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
1e7e3d7172ceb335216874576ca5691dc1ae2138
2,810
// Copyright 2017 Frank Rehwinkel. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import AppKit // Things to figure out the view hierarchy and frames. // Entry is myview() below. func labelView(title: String) -> NSTextField { let label = NSTextField(frame: NSRect(x: 0, y: 0, width: 0, height: 0)) label.stringValue = title label.isBezeled = false label.isBordered = false label.drawsBackground = false label.isEditable = false label.isSelectable = false label.sizeToFit() return label } extension NSView { func addSubviews(_ views: [NSView]) { for view in views { self.addSubview(view) } } } extension NSSplitView { func smartAddSubviews(_ views: [NSView]) { if self.frame.size == CGSize(width: 0, height: 0) { var size = self.frame.size for view in views { let viewSize = view.frame.size if self.isVertical { size.width += viewSize.width + self.dividerThickness if size.height < viewSize.height { size.height = viewSize.height } } else { size.height += viewSize.height + self.dividerThickness if size.width < viewSize.width { size.width = viewSize.width } } } self.frame.size = size } for view in views { self.addSubview(view) } } } func container(title: String) -> NSView { // TBD why doesn't the split view resize to wider when super view gets wider? let container = NSSplitView() container.isVertical = true let label1 = labelView(title: title) let label2 = labelView(title: title+"2") let label3 = labelView(title: title+"3") label1.printframe(label: "label1") label2.printframe(label: "label2") label3.printframe(label: "label3") //container.frame.size = CGSize(width: 100, height: 100) //container.autoresizesSubviews = true container.smartAddSubviews([label1, label2, label3]) print("after") label1.printframe(label: "label1") label2.printframe(label: "label2") label3.printframe(label: "label3") container.printframe(label: "container") return container } #if false // 10.12 or higher func label2(title: String) -> NSTextField { return NSTextField(labelWithString: title) } func label3(title: String) -> NSTextField { //return NSTextField(labelWithAttributedString: NSAttributedString) return NSTextField(wrappingLabelWithString: title) } #endif func myview() -> NSView { return container(title: "Container Title") }
29.270833
81
0.616726
7974a5283e9f6b23256678509915a3154559c5a6
2,045
// // ButtonCell.swift // NearbyWeather // // Created by Erik Maximilian Martens on 12.02.18. // Copyright © 2018 Erik Maximilian Martens. All rights reserved. // import UIKit class ButtonCell: UITableViewCell { @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var leftButton: UIButton! @IBOutlet weak var rightButton: UIButton! private var leftButtonHandler: ((UIButton) -> ())? private var rightButtonHandler: ((UIButton) -> ())? @objc private func leftButtonPressed(_ sender: UIButton) { leftButtonHandler?(sender) } @objc private func rightButtonPressed(_ sender: UIButton) { rightButtonHandler?(sender) } override func prepareForReuse() { super.prepareForReuse() leftButtonHandler = nil leftButton.removeTarget(self, action: #selector(ButtonCell.leftButtonPressed(_:)), for: .touchUpInside) rightButtonHandler = nil rightButton.removeTarget(self, action: #selector(ButtonCell.rightButtonPressed(_:)), for: .touchUpInside) } public func configure(withTitle title: String, leftButtonTitle: String, rightButtonTitle: String, leftButtonHandler: @escaping ((UIButton) -> ()), rightButtonHandler: @escaping ((UIButton) -> ())) { contentLabel.text = title self.rightButtonHandler = rightButtonHandler self.leftButtonHandler = leftButtonHandler leftButton.setTitle(leftButtonTitle, for: .normal) leftButton.addTarget(self, action: #selector(ButtonCell.leftButtonPressed(_:)), for: .touchUpInside) rightButton.setTitle(rightButtonTitle, for: .normal) rightButton.addTarget(self, action: #selector(ButtonCell.rightButtonPressed(_:)), for: .touchUpInside) [rightButton, leftButton].forEach { $0?.layer.cornerRadius = 5.0 $0?.layer.borderColor = UIColor.nearbyWeatherStandard.cgColor $0?.layer.borderWidth = 1.0 } } }
35.258621
202
0.65868
720fe909f15be0b361ba8d7742ab9b583a52006a
4,034
// // CreateOrderInteractor.swift // CleanStorePractice // // Created by 조경진 on 2020/02/18. // Copyright (c) 2020 조경진. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit //MARK: BusinessLogic Protocol protocol CreateOrderBusinessLogic { var shippingMethods: [String] { get } var orderToEdit: Order? { get } func formatExpirationDate(request: CreateOrder.FormatExpirationDate.Request) func createOrder(request: CreateOrder.CreateOrder.Request) func showOrderToEdit(request: CreateOrder.EditOrder.Request) func updateOrder(request: CreateOrder.UpdateOrder.Request) } protocol CreateOrderDataStore { var orderToEdit: Order? { get set } } class CreateOrderInteractor: CreateOrderBusinessLogic, CreateOrderDataStore { var presenter: CreateOrderPresentationLogic? var ordersWorker = OrdersWorker(ordersStore: OrdersMemStore()) var orderToEdit: Order? var shippingMethods = [ ShipmentMethod(speed: .Standard).toString(), ShipmentMethod(speed: .OneDay).toString(), ShipmentMethod(speed: .TwoDay).toString() ] //BusinessLogic protocol // MARK: - Expiration date // request받은걸 response로 바꾸어서 presenter에게 전달 func formatExpirationDate(request: CreateOrder.FormatExpirationDate.Request) { let response = CreateOrder.FormatExpirationDate.Response(date: request.date) presenter?.presentExpirationDate(response: response) } // MARK: - Create order func createOrder(request: CreateOrder.CreateOrder.Request) { let orderToCreate = buildOrderFromOrderFormFields(request.orderFormFields) ordersWorker.createOrder(orderToCreate: orderToCreate) { (order: Order?) in self.orderToEdit = order let response = CreateOrder.CreateOrder.Response(order: order) self.presenter?.presentCreatedOrder(response: response) } } // MARK: - Edit order func showOrderToEdit(request: CreateOrder.EditOrder.Request) { if let orderToEdit = orderToEdit { let response = CreateOrder.EditOrder.Response(order: orderToEdit) presenter?.presentOrderToEdit(response: response) } } // MARK: - Update order func updateOrder(request: CreateOrder.UpdateOrder.Request) { let orderToUpdate = buildOrderFromOrderFormFields(request.orderFormFields) ordersWorker.updateOrder(orderToUpdate: orderToUpdate) { (order) in self.orderToEdit = order let response = CreateOrder.UpdateOrder.Response(order: order) self.presenter?.presentUpdatedOrder(response: response) } } // MARK: - Helper function private func buildOrderFromOrderFormFields(_ orderFormFields: CreateOrder.OrderFormFields) -> Order { let billingAddress = Address(street1: orderFormFields.billingAddressStreet1, street2: orderFormFields.billingAddressStreet2, city: orderFormFields.billingAddressCity, state: orderFormFields.billingAddressState, zip: orderFormFields.billingAddressZIP) let paymentMethod = PaymentMethod(creditCardNumber: orderFormFields.paymentMethodCreditCardNumber, expirationDate: orderFormFields.paymentMethodExpirationDate, cvv: orderFormFields.paymentMethodCVV) let shipmentAddress = Address(street1: orderFormFields.shipmentAddressStreet1, street2: orderFormFields.shipmentAddressStreet2, city: orderFormFields.shipmentAddressCity, state: orderFormFields.shipmentAddressState, zip: orderFormFields.shipmentAddressZIP) let shipmentMethod = ShipmentMethod(speed: ShipmentMethod.ShippingSpeed(rawValue: orderFormFields.shipmentMethodSpeed)!) return Order(firstName: orderFormFields.firstName, lastName: orderFormFields.lastName, phone: orderFormFields.phone, email: orderFormFields.email, billingAddress: billingAddress, paymentMethod: paymentMethod, shipmentAddress: shipmentAddress, shipmentMethod: shipmentMethod, id: orderFormFields.id, date: orderFormFields.date, total: orderFormFields.total) } }
38.788462
360
0.774417
1c629cc85f07238fb6245a24fea80e4c952cf877
1,216
// // UniversalPlayerView.swift // vimeo // // Created by Andrii Momot on 3/28/19. // Copyright © 2019 Andrii Momot. All rights reserved. // import UIKit protocol UniversalPlayerViewDelegate: NSObjectProtocol { func youtubeAction() func vimeoAction() } protocol UniversalPlayerViewProtocol: NSObjectProtocol { var delegate: UniversalPlayerViewDelegate? { get set } var videoPlayerView: VideoPlayer! { get } func setThumbnail(_ image: UIImage?) } class UniversalPlayerView: UIView, UniversalPlayerViewProtocol{ @IBOutlet weak var thumbnailImageView: UIImageView! @IBOutlet weak var videoPlayerView: VideoPlayer! // MARK: - UniversalPlayerView interface methods weak public var delegate: UniversalPlayerViewDelegate? func setThumbnail(_ image: UIImage?) { thumbnailImageView.image = image } // MARK: - Overrided methods override public func awakeFromNib() { super.awakeFromNib() } // MARK: - IBActions @IBAction func youtubeButtonAction(_ sender: Any) { delegate?.youtubeAction() } @IBAction func vimeoButtonAction(_ sender: Any) { delegate?.vimeoAction() } }
23.384615
63
0.685033
d72a114b88343d75e0b019f638dd6a9b4c50ad7d
808
// // Guitarist.swift // Guitar // // Created by Gabrielle Miller-Messner on 4/13/16. // Copyright © 2016 Gabrielle Miller-Messner. All rights reserved. // import Cocoa class Guitarist: NSObject { let guitar:Guitar = Guitar(frets: [Fret()], strings: [GuitarString()]) func perform(_ notes: [Note]) { for note in notes { do { try guitar.playNote(note) } catch GuitarStringError.broken { print("Quick, replace the string!") break } catch GuitarStringError.outOfTune { print("Uh oh! Tuning break.") break } catch { print("Oh well, guess it's time to crowd surf!") break } } } }
24.484848
74
0.506188
1c09788655f913480b93024ddbb14285d4749241
3,413
// The MIT License (MIT) // // Copyright (c) 2020–2022 Alexander Grebenyuk (github.com/kean). #if os(iOS) import UIKit import SwiftUI import PulseCore import UniformTypeIdentifiers @available(iOS 13.0, *) final class DocumentBrowserViewController: UIDocumentPickerViewController, UIDocumentPickerDelegate, UIDocumentBrowserViewControllerDelegate { // This key is used to encode the bookmark data of the URL of the opened document as part of the state restoration data. static let bookmarkDataKey = "bookmarkData" override func viewDidLoad() { super.viewDidLoad() delegate = self view.tintColor = .systemBlue } // MARK: UIDocumentPickerDelegate func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { // Do nothing } func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { // Do nothing } // MARK: UIDocumentBrowserViewControllerDelegate func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentsAt documentURLs: [URL]) { guard let sourceURL = documentURLs.first else { return } // When the user has chosen an existing document, a new `DocumentViewController` is presented for the first document that was picked. presentDocument(at: sourceURL) } func documentBrowser(_ controller: UIDocumentBrowserViewController, didImportDocumentAt sourceURL: URL, toDestinationURL destinationURL: URL) { // When a new document has been imported by the `UIDocumentBrowserViewController`, a new `DocumentViewController` is presented as well. presentDocument(at: destinationURL) } func documentBrowser(_ controller: UIDocumentBrowserViewController, failedToImportDocumentAt documentURL: URL, error: Error?) { // Make sure to handle the failed import appropriately, e.g., by presenting an error message to the user. } func documentBrowser(_ controller: UIDocumentBrowserViewController, applicationActivitiesForDocumentURLs documentURLs: [URL]) -> [UIActivity] { // Whenever one or more items are being shared by the user, the default activities of the `UIDocumentBrowserViewController` can be augmented // with custom ones. In this case, no additional activities are added. return [] } // MARK: Document Presentation func presentDocument(at documentURL: URL, animated: Bool = true) { guard documentURL.startAccessingSecurityScopedResource() else { return } do { let store = try LoggerStore(storeURL: documentURL) let vc = UIHostingController(rootView: MainView(store: store, onDismiss: { [weak self] in self?.dismiss(animated: true, completion: nil) })) vc.onDeinit { documentURL.stopAccessingSecurityScopedResource() } vc.modalPresentationStyle = .fullScreen present(vc, animated: true, completion: nil) } catch { documentURL.stopAccessingSecurityScopedResource() let vc = UIAlertController(title: "Failed to open store", message: error.localizedDescription, preferredStyle: .alert) vc.addAction(.init(title: "Ok", style: .cancel, handler: nil)) present(vc, animated: true, completion: nil) } } } #endif
38.784091
148
0.701729
d5fcf22767e7100f049e0e3ff88e4157826959e6
4,802
// // GiftVM.swift // AgoraLive // // Created by CavanSu on 2020/4/9. // Copyright © 2020 Agora. All rights reserved. // import UIKit import RxSwift import RxRelay import AlamoClient enum Gift: Int { case smallBell = 0, iceCream, wine, cake, ring, watch, crystal, rocket var description: String { switch self { case .smallBell: return NSLocalizedString("Small_Bell") case .iceCream: return NSLocalizedString("Ice_Cream") case .wine: return NSLocalizedString("Wine") case .cake: return NSLocalizedString("Cake") case .ring: return NSLocalizedString("Ring") case .watch: return NSLocalizedString("Watch") case .crystal: return NSLocalizedString("Crystal") case .rocket: return NSLocalizedString("Rocket") } } var image: UIImage { switch self { case .smallBell: return UIImage(named: "gift-dang")! case .iceCream: return UIImage(named: "gift-icecream")! case .wine: return UIImage(named: "gift-wine")! case .cake: return UIImage(named: "gift-cake")! case .ring: return UIImage(named: "gift-ring")! case .watch: return UIImage(named: "gift-watch")! case .crystal: return UIImage(named: "gift-diamond")! case .rocket: return UIImage(named: "gift-rocket")! } } var price: Int { switch self { case .smallBell: return 20 case .iceCream: return 30 case .wine: return 40 case .cake: return 50 case .ring: return 60 case .watch: return 70 case .crystal: return 80 case .rocket: return 90 } } var hasGIF: Bool { switch self { case .smallBell: return true case .iceCream: return true case .wine: return true case .cake: return true case .ring: return true case .watch: return true case .crystal: return true case .rocket: return true } } var gifFileName: String { switch self { case .smallBell: return "SuperBell" case .iceCream: return "SuperIcecream" case .wine: return "SuperWine" case .cake: return "SuperCake" case .ring: return "SuperRing" case .watch: return "SuperWatch" case .crystal: return "SuperDiamond" case .rocket: return "SuperRocket" } } static var list: [Gift] = [.smallBell, .iceCream, .wine, .cake, .ring, .watch, .crystal, .rocket] } class GiftVM: RTMObserver { private var room: Room var received = PublishRelay<(userName:String, gift:Gift)>() init(room: Room) { self.room = room super.init() observe() } deinit { #if !RELEASE print("deinit GiftVM") #endif } func present(gift: Gift, fail: Completion) { let client = ALCenter.shared().centerProvideRequestHelper() let local = ALCenter.shared().centerProvideLocalUser() let event = RequestEvent(name: "present-gift") let url = URLGroup.receivedGift(roomId: room.roomId) let task = RequestTask(event: event, type: .http(.post, url: url), timeout: .medium, header: ["token": ALKeys.ALUserToken], parameters: ["giftId": gift.rawValue, "count": 1]) client.request(task: task, success: ACResponse.blank({ [weak self] in self?.received.accept((local.info.value.name, gift)) })) } } private extension GiftVM { func observe() { let rtm = ALCenter.shared().centerProvideRTMHelper() rtm.addReceivedChannelMessage(observer: self.address) { [weak self] (json) in guard let cmd = try? json.getEnum(of: "cmd", type: ALChannelMessage.AType.self) else { return } guard cmd == .gift else { return } let data = try json.getDataObject() let gift = try data.getEnum(of: "giftId", type: Gift.self) let userId = try data.getStringValue(of: "fromUserId") let userName = try data.getStringValue(of: "fromUserName") guard let user = ALCenter.shared().liveSession?.role.value else { return } guard user.info.userId != userId else { return } self?.received.accept((userName, gift)) } } }
32.228188
98
0.539775
5b37705e18e5cc6de3d3503a3777ac6e3a244cab
1,006
// // DoubleConvertible.swift // Swiftest // // Created by Brian Strobach on 12/14/18. // public protocol DoubleConvertible { var double: Double { get } } public protocol DoubleInitializable { init(_ double: Double) } extension Double: DoubleConvertible, DoubleInitializable { public var double: Double { return self } } extension Float: DoubleConvertible, DoubleInitializable { public var double: Double { return Double(self) } } extension Int: DoubleConvertible, DoubleInitializable { public var double: Double { return Double(self) } } #if canImport(CoreGraphics) import CoreGraphics extension CGFloat: DoubleConvertible, DoubleInitializable { public var double: Double { return Double(self) } } #endif public protocol OptionalDoubleConvertible { var double: Double? { get } } extension String: OptionalDoubleConvertible, DoubleInitializable { public var double: Double? { return Double(self) } }
19.72549
66
0.696819
2fc6ea9b7d32a18acdeb0bfbe24efb21866ae809
296
// // FetchLoggedUserMock.swift // ShowDetails-Unit-Tests // // Created by Jeans Ruiz on 8/4/20. // @testable import ShowDetails @testable import Shared class FetchLoggedUserMock: FetchLoggedUser { var account: AccountDomain? func execute() -> AccountDomain? { return account } }
16.444444
44
0.716216
fec67d5658142f1709bc18e931cd435fdd3b3b92
2,373
// // AppDelegate.swift // BigcommerceApi // // Created by William Welbes on 07/07/2015. // Copyright (c) 2015 William Welbes. 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. //Set the NSURLCache to not be used let sharedCache = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil) URLCache.shared = sharedCache return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.634615
285
0.743363
e2628bad80971e86ebc45654422c4213e7582e70
481
// // InputValidation.swift // CryptoMessages // // Created by Giorgio Natili on 5/8/17. // Copyright © 2017 Giorgio Natili. All rights reserved. // import Foundation import SwiftValidators class InputValidation: ValidateInput { func validEmail(email: String) -> Bool { return Validator.isEmail().apply(email) } func passwordNotEmpty(password: String) -> Bool { return !Validator.isEmpty().apply(password) } }
19.24
57
0.642412
ebd49267d74800a23d8c58d4e03cf7be00f91620
14,739
// // CRTFilter.swift // Filterpedia // // CRT filter and VHS Tracking Lines // // Created by Simon Gladman on 20/01/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // import CoreImage class VHSTrackingLines: CIFilter { var inputImage: CIImage? var inputTime: CGFloat = 0 var inputSpacing: CGFloat = 50 var inputStripeHeight: CGFloat = 0.5 var inputBackgroundNoise: CGFloat = 0.05 override func setDefaults() { inputSpacing = 50 inputStripeHeight = 0.5 inputBackgroundNoise = 0.05 } override func setValue(_ value: Any?, forKey key: String) { switch key { case "inputImage": inputImage = value as? CIImage case "inputSpacing": inputSpacing = value as! CGFloat case "inputStripeHeight": inputStripeHeight = value as! CGFloat case "inputBackgroundNoise": inputBackgroundNoise = value as! CGFloat default: log.error("Invalid key: \(key)") } } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "VHS Tracking Lines", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputTime": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 8, kCIAttributeDisplayName: "Time", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 2048, kCIAttributeType: kCIAttributeTypeScalar], "inputSpacing": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 50, kCIAttributeDisplayName: "Spacing", kCIAttributeMin: 20, kCIAttributeSliderMin: 20, kCIAttributeSliderMax: 200, kCIAttributeType: kCIAttributeTypeScalar], "inputStripeHeight": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.5, kCIAttributeDisplayName: "Stripe Height", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputBackgroundNoise": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.05, kCIAttributeDisplayName: "Background Noise", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 0.25, kCIAttributeType: kCIAttributeTypeScalar] ] } override var outputImage: CIImage? { guard let inputImage = inputImage else { return nil } let tx = NSValue(cgAffineTransform: CGAffineTransform(translationX: CGFloat(drand48() * 100), y: CGFloat(drand48() * 100))) let noise = CIFilter(name: "CIRandomGenerator")!.outputImage! .applyingFilter("CIAffineTransform", parameters: [kCIInputTransformKey: tx]) .applyingFilter("CILanczosScaleTransform", parameters: [kCIInputAspectRatioKey: 5]) .cropped(to: inputImage.extent) let kernel = CIColorKernel(source: "kernel vec4 thresholdFilter(__sample image, __sample noise, float time, float spacing, float stripeHeight, float backgroundNoise)" + "{" + " vec2 uv = destCoord();" + " float stripe = smoothstep(1.0 - stripeHeight, 1.0, sin((time + uv.y) / spacing)); " + " return image + (noise * noise * stripe) + (noise * backgroundNoise);" + "}" )! let extent = inputImage.extent let arguments = [inputImage, noise, inputTime, inputSpacing, inputStripeHeight, inputBackgroundNoise] as [Any] let final = kernel.apply(extent: extent, arguments: arguments)? //.imageByApplyingFilter("CIPhotoEffectNoir", withInputParameters: nil) .applyingFilter("CIPhotoEffectNoir") return final } } class CRTFilter: CIFilter { var inputImage : CIImage? var inputPixelWidth: CGFloat = 8 var inputPixelHeight: CGFloat = 12 var inputBend: CGFloat = 3.2 override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "CRT Filter", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputPixelWidth": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 8, kCIAttributeDisplayName: "Pixel Width", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], "inputPixelHeight": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 12, kCIAttributeDisplayName: "Pixel Height", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], "inputBend": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 3.2, kCIAttributeDisplayName: "Bend", kCIAttributeMin: 0.5, kCIAttributeSliderMin: 0.5, kCIAttributeSliderMax: 10, kCIAttributeType: kCIAttributeTypeScalar] ] } let crtWarpFilter = CRTWarpFilter() let crtColorFilter = CRTColorFilter() let vignette = CIFilter(name: "CIVignette", parameters: [ kCIInputIntensityKey: 1.5, kCIInputRadiusKey: 2])! override func setDefaults() { inputPixelWidth = 8 inputPixelHeight = 12 inputBend = 3.2 } override func setValue(_ value: Any?, forKey key: String) { switch key { case "inputImage": inputImage = value as? CIImage case "inputPixelWidth": inputPixelWidth = value as! CGFloat case "inputPixelHeight": inputPixelHeight = value as! CGFloat case "inputBend": inputBend = value as! CGFloat default: log.error("Invalid key: \(key)") } } override var outputImage: CIImage! { guard let inputImage = inputImage else { return nil } crtColorFilter.setValue(inputImage, forKey: "inputImage") crtColorFilter.setValue(inputPixelHeight, forKey: "inputPixelHeight") crtColorFilter.setValue(inputPixelHeight, forKey: "inputPixelWidth") crtWarpFilter.setValue(inputImage, forKey: "inputImage") crtWarpFilter.setValue(inputBend, forKey: "inputBend") let crtimage = crtColorFilter.outputImage guard crtimage != nil else { log.error("NIL CRT image returned from CRTColorFilter") return nil } vignette.setValue(crtimage, forKey: kCIInputImageKey) let vimage = vignette.outputImage guard vimage != nil else { log.error("NIL image returned from Vignette Filter") return nil } crtWarpFilter.inputImage = vimage! return crtWarpFilter.outputImage } class CRTColorFilter: CIFilter { var inputImage : CIImage? var inputPixelWidth: CGFloat = 8.0 var inputPixelHeight: CGFloat = 12.0 override func setValue(_ value: Any?, forKey key: String) { switch key { case "inputImage": inputImage = value as? CIImage case "inputPixelWidth": inputPixelWidth = value as! CGFloat case "inputPixelHeight": inputPixelHeight = value as! CGFloat default: log.error("Invalid key: \(key)") } } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "CRT Color Filter", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputPixelWidth": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 8, kCIAttributeDisplayName: "Pixel Width", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], "inputPixelHeight": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 12, kCIAttributeDisplayName: "Pixel Height", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar] ] } //let crtColorKernel = CIColorKernel(source: let crtKernel = CIKernel(source: "kernel vec4 crtColor(sampler image, float pixelWidth, float pixelHeight) \n" + "{ \n" + " int columnIndex = int(mod(samplerCoord(image).x / pixelWidth, 3.0)); \n" + " int rowIndex = int(mod(samplerCoord(image).y, pixelHeight)); \n" + " float scanlineMultiplier = (rowIndex == 0 || rowIndex == 1) ? 0.3 : 1.0;\n" + " float red = (columnIndex == 0) ? sample(image, samplerCoord(image)).r : sample(image, samplerCoord(image)).r * ((columnIndex == 2) ? 0.3 : 0.2); \n" + " float green = (columnIndex == 1) ? sample(image, samplerCoord(image)).g : sample(image, samplerCoord(image)).g * ((columnIndex == 2) ? 0.3 : 0.2); \n" + " float blue = (columnIndex == 2) ? sample(image, samplerCoord(image)).b : sample(image, samplerCoord(image)).b * 0.2; \n" + " return vec4(red * scanlineMultiplier, green * scanlineMultiplier, blue * scanlineMultiplier, 1.0); \n" + "}" ) override var outputImage: CIImage! { if let inputImage = inputImage, //let crtColorKernel = crtColorKernel let crtKernel = crtKernel { let dod = inputImage.extent //let args = [inputImage, inputPixelWidth, inputPixelHeight] as [Any] let args = [inputImage, inputPixelWidth, inputPixelHeight] as [Any] //return crtKernel.apply(extent: dod, arguments: args) return crtKernel.apply(extent: dod, roiCallback: { (index, rect) in return rect }, arguments: args) } return nil } } class CRTWarpFilter: CIFilter { var inputImage : CIImage? var inputBend: CGFloat = 3.2 override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "CRT Warp Filter", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputBend": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 3.2, kCIAttributeDisplayName: "Bend", kCIAttributeMin: 0.5, kCIAttributeSliderMin: 0.5, kCIAttributeSliderMax: 10, kCIAttributeType: kCIAttributeTypeScalar] ] } override func setValue(_ value: Any?, forKey key: String) { switch key { case "inputImage": inputImage = value as? CIImage case "inputBend": inputBend = value as! CGFloat default: log.error("Invalid key: \(key)") } } let crtWarpKernel = CIWarpKernel(source: "kernel vec2 crtWarp(vec2 extent, float bend)" + "{" + " vec2 coord = ((destCoord() / extent) - 0.5) * 2.0;" + " coord.x *= 1.0 + pow((abs(coord.y) / bend), 2.0);" + " coord.y *= 1.0 + pow((abs(coord.x) / bend), 2.0);" + " coord = ((coord / 2.0) + 0.5) * extent;" + " return coord;" + "}" ) override var outputImage : CIImage! { if let inputImage = inputImage, let crtWarpKernel = crtWarpKernel { let arguments = [CIVector(x: inputImage.extent.size.width, y: inputImage.extent.size.height), inputBend] as [Any] let extent = inputImage.extent.insetBy(dx: -1, dy: -1) return crtWarpKernel.apply(extent: extent, roiCallback: { (index, rect) in return rect }, image: inputImage, arguments: arguments) } return nil } } }
38.685039
172
0.521949
ed4521bae027ad27697423caf7dcd95190e76fee
582
// // EmojiTableViewCell.swift // EmojiDictionary // // Created by Kaden Kim on 2020-05-02. // Copyright © 2020 CICCC. All rights reserved. // import UIKit class EmojiTableViewCell: UITableViewCell { @IBOutlet var symbolLabel: UILabel! @IBOutlet var nameLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } func update(with emoji: Emoji) { symbolLabel.text = emoji.symbol nameLabel.text = emoji.name descriptionLabel.text = emoji.description } }
20.785714
49
0.666667
b9b774f4e165fb27301455e3b57e0b2dbee9eb94
1,658
// // Copyright (c) 2021 Related Code - https://relatedcode.com // // 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 Menu1Cell1: UICollectionViewCell { @IBOutlet var viewMenu: UIView! @IBOutlet var labelMenu: UILabel! //------------------------------------------------------------------------------------------------------------------------------------------- override func awakeFromNib() { super.awakeFromNib() viewMenu.layer.borderWidth = 1 viewMenu.layer.borderColor = AppColor.Border.cgColor } //------------------------------------------------------------------------------------------------------------------------------------------- func bindData(menu: String) { labelMenu.text = menu.uppercased() } //------------------------------------------------------------------------------------------------------------------------------------------- func set(isSelected: Bool) { viewMenu.backgroundColor = isSelected ? AppColor.Theme : UIColor.systemBackground labelMenu.textColor = isSelected ? UIColor.white : UIColor.label } }
40.439024
145
0.492159
615223ff8d9a7978974b159a49cc4c96e615a0dc
831
import Foundation protocol ServiceProtocol { func performTask(with request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) } struct Service: ServiceProtocol { private let session: SessionProtocol private let dispatcher: Dispatcher init(session: SessionProtocol = Session(), dispatcher: Dispatcher = DefaultDispatcher()) { self.session = session self.dispatcher = dispatcher } func performTask(with request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) { session.dataTask(with: request) { (responseData, urlResponse, responseError) in self.dispatcher.dispatch { completion(responseData, urlResponse, responseError) } } } }
30.777778
87
0.636582
dd00c135dd2d2e2fddd9b31113fcf690b7f199c9
1,299
// // Created by Eugene Kazaev on 05/02/2018. // import Foundation import UIKit /// the case resolver for `SwitcherStep` public protocol StepCaseResolver { /// THE Method to be called by a `SwitcherStep` at the moment when it will try to find a previous step for the `Router`. /// /// - Parameter destination: A `RoutingDestination` instance that been passed to the `Router` /// - Returns: A `RoutingStep` to be made by `Router`, nil if resolver could not decide when step should be previous func resolve<D: RoutingDestination>(for destination: D) -> RoutingStep? } class SwitcherStep: RoutingStep, ChainableStep, PerformableStep { private(set) public var previousStep: RoutingStep? = nil private var resolvers: [StepCaseResolver] func perform<D: RoutingDestination>(for destination: D) -> StepResult { previousStep = nil resolvers.forEach({ resolver in guard previousStep == nil, let step = resolver.resolve(for: destination) else { return } previousStep = step }) guard let _ = previousStep else { return .failure } return .continueRouting(nil) } public init(resolvers: [StepCaseResolver]) { self.resolvers = resolvers } }
29.522727
124
0.657429
2807af2ddcb6eff334b6557547c8eb011eb7fcfc
1,005
// // AudioKitAudioIOTests.swift // AudioKitAudioIOTests // // Created by Sam Meech-Ward on 2018-01-07. // Copyright © 2018 meech-ward. All rights reserved. // import XCTest @testable import AudioKitAudioIO class AudioKitAudioIOTests: 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. } } }
27.162162
111
0.643781
ffebdba10235ce20f8207b3378542b26819af668
549
// // AuthViewController.swift // CoordinateDemo // // Created by Dariel on 2019/5/29. // Copyright © 2019 Dariel. All rights reserved. // import UIKit protocol AuthViewControllerDelegate: AnyObject { func signIn() } class AuthViewController: UIViewController { weak var delegate: AuthViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() } @IBAction func signInTouch(_ sender: Any) { delegate?.signIn() } deinit { print("AuthViewController销毁") } }
17.15625
50
0.652095
f7cebaee52e7c149ac06e813a3ba6085565d5aac
564
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol A { func f: A? { return " } protocol b { protocol a { protocol a { } (T) { protocol P { enum A { } } } } typealias B : B) private class A { } class func ^(.
20.142857
79
0.703901
266669a4b61325ec85d917643b7354bbd0711739
19,078
import Foundation // swiftlint:disable type_body_length class PBXObjects: Equatable { // MARK: - Properties private let lock = NSRecursiveLock() private var _projects: [PBXObjectReference: PBXProject] = [:] var projects: [PBXObjectReference: PBXProject] { return lock.whileLocked { _projects } } private var _referenceProxies: [PBXObjectReference: PBXReferenceProxy] = [:] var referenceProxies: [PBXObjectReference: PBXReferenceProxy] { return lock.whileLocked { _referenceProxies } } // File elements private var _fileReferences: [PBXObjectReference: PBXFileReference] = [:] var fileReferences: [PBXObjectReference: PBXFileReference] { return lock.whileLocked { _fileReferences } } private var _versionGroups: [PBXObjectReference: XCVersionGroup] = [:] var versionGroups: [PBXObjectReference: XCVersionGroup] { return lock.whileLocked { _versionGroups } } private var _variantGroups: [PBXObjectReference: PBXVariantGroup] = [:] var variantGroups: [PBXObjectReference: PBXVariantGroup] { return lock.whileLocked { _variantGroups } } private var _groups: [PBXObjectReference: PBXGroup] = [:] var groups: [PBXObjectReference: PBXGroup] { return lock.whileLocked { _groups } } // Configuration private var _buildConfigurations: [PBXObjectReference: XCBuildConfiguration] = [:] var buildConfigurations: [PBXObjectReference: XCBuildConfiguration] { return lock.whileLocked { _buildConfigurations } } private var _configurationLists: [PBXObjectReference: XCConfigurationList] = [:] var configurationLists: [PBXObjectReference: XCConfigurationList] { return lock.whileLocked { _configurationLists } } // Targets private var _legacyTargets: [PBXObjectReference: PBXLegacyTarget] = [:] var legacyTargets: [PBXObjectReference: PBXLegacyTarget] { return lock.whileLocked { _legacyTargets } } private var _aggregateTargets: [PBXObjectReference: PBXAggregateTarget] = [:] var aggregateTargets: [PBXObjectReference: PBXAggregateTarget] { return lock.whileLocked { _aggregateTargets } } private var _nativeTargets: [PBXObjectReference: PBXNativeTarget] = [:] var nativeTargets: [PBXObjectReference: PBXNativeTarget] { return lock.whileLocked { _nativeTargets } } private var _targetDependencies: [PBXObjectReference: PBXTargetDependency] = [:] var targetDependencies: [PBXObjectReference: PBXTargetDependency] { return lock.whileLocked { _targetDependencies } } private var _containerItemProxies: [PBXObjectReference: PBXContainerItemProxy] = [:] var containerItemProxies: [PBXObjectReference: PBXContainerItemProxy] { return lock.whileLocked { _containerItemProxies } } private var _buildRules: [PBXObjectReference: PBXBuildRule] = [:] var buildRules: [PBXObjectReference: PBXBuildRule] { return lock.whileLocked { _buildRules } } // Build Phases private var _buildFiles: [PBXObjectReference: PBXBuildFile] = [:] var buildFiles: [PBXObjectReference: PBXBuildFile] { return lock.whileLocked { _buildFiles } } private var _copyFilesBuildPhases: [PBXObjectReference: PBXCopyFilesBuildPhase] = [:] var copyFilesBuildPhases: [PBXObjectReference: PBXCopyFilesBuildPhase] { return lock.whileLocked { _copyFilesBuildPhases } } private var _shellScriptBuildPhases: [PBXObjectReference: PBXShellScriptBuildPhase] = [:] var shellScriptBuildPhases: [PBXObjectReference: PBXShellScriptBuildPhase] { return lock.whileLocked { _shellScriptBuildPhases } } private var _resourcesBuildPhases: [PBXObjectReference: PBXResourcesBuildPhase] = [:] var resourcesBuildPhases: [PBXObjectReference: PBXResourcesBuildPhase] { return lock.whileLocked { _resourcesBuildPhases } } private var _frameworksBuildPhases: [PBXObjectReference: PBXFrameworksBuildPhase] = [:] var frameworksBuildPhases: [PBXObjectReference: PBXFrameworksBuildPhase] { return lock.whileLocked { _frameworksBuildPhases } } private var _headersBuildPhases: [PBXObjectReference: PBXHeadersBuildPhase] = [:] var headersBuildPhases: [PBXObjectReference: PBXHeadersBuildPhase] { return lock.whileLocked { _headersBuildPhases } } private var _sourcesBuildPhases: [PBXObjectReference: PBXSourcesBuildPhase] = [:] var sourcesBuildPhases: [PBXObjectReference: PBXSourcesBuildPhase] { return lock.whileLocked { _sourcesBuildPhases } } private var _carbonResourcesBuildPhases: [PBXObjectReference: PBXRezBuildPhase] = [:] var carbonResourcesBuildPhases: [PBXObjectReference: PBXRezBuildPhase] { return lock.whileLocked { _carbonResourcesBuildPhases } } /// Initializes the project objects container /// /// - Parameters: /// - objects: project objects init(objects: [PBXObject] = []) { objects.forEach { _ = self.add(object: $0) } } // MARK: - Equatable public static func == (lhs: PBXObjects, rhs: PBXObjects) -> Bool { return lhs.buildFiles == rhs.buildFiles && lhs.legacyTargets == rhs.legacyTargets && lhs.aggregateTargets == rhs.aggregateTargets && lhs.containerItemProxies == rhs.containerItemProxies && lhs.copyFilesBuildPhases == rhs.copyFilesBuildPhases && lhs.groups == rhs.groups && lhs.configurationLists == rhs.configurationLists && lhs.buildConfigurations == rhs.buildConfigurations && lhs.variantGroups == rhs.variantGroups && lhs.targetDependencies == rhs.targetDependencies && lhs.sourcesBuildPhases == rhs.sourcesBuildPhases && lhs.shellScriptBuildPhases == rhs.shellScriptBuildPhases && lhs.resourcesBuildPhases == rhs.resourcesBuildPhases && lhs.frameworksBuildPhases == rhs.frameworksBuildPhases && lhs.headersBuildPhases == rhs.headersBuildPhases && lhs.nativeTargets == rhs.nativeTargets && lhs.fileReferences == rhs.fileReferences && lhs.projects == rhs.projects && lhs.versionGroups == rhs.versionGroups && lhs.referenceProxies == rhs.referenceProxies && lhs.carbonResourcesBuildPhases == rhs.carbonResourcesBuildPhases && lhs.buildRules == rhs.buildRules } // MARK: - Helpers /// Add a new object. /// /// - Parameters: /// - object: object. func add(object: PBXObject) { lock.lock() defer { lock.unlock() } let objectReference: PBXObjectReference = object.reference objectReference.objects = self switch object { // subclasses of PBXGroup; must be tested before PBXGroup case let object as PBXVariantGroup: _variantGroups[objectReference] = object case let object as XCVersionGroup: _versionGroups[objectReference] = object // everything else case let object as PBXBuildFile: _buildFiles[objectReference] = object case let object as PBXAggregateTarget: _aggregateTargets[objectReference] = object case let object as PBXLegacyTarget: _legacyTargets[objectReference] = object case let object as PBXContainerItemProxy: _containerItemProxies[objectReference] = object case let object as PBXCopyFilesBuildPhase: _copyFilesBuildPhases[objectReference] = object case let object as PBXGroup: _groups[objectReference] = object case let object as XCConfigurationList: _configurationLists[objectReference] = object case let object as XCBuildConfiguration: _buildConfigurations[objectReference] = object case let object as PBXTargetDependency: _targetDependencies[objectReference] = object case let object as PBXSourcesBuildPhase: _sourcesBuildPhases[objectReference] = object case let object as PBXShellScriptBuildPhase: _shellScriptBuildPhases[objectReference] = object case let object as PBXResourcesBuildPhase: _resourcesBuildPhases[objectReference] = object case let object as PBXFrameworksBuildPhase: _frameworksBuildPhases[objectReference] = object case let object as PBXHeadersBuildPhase: _headersBuildPhases[objectReference] = object case let object as PBXNativeTarget: _nativeTargets[objectReference] = object case let object as PBXFileReference: _fileReferences[objectReference] = object case let object as PBXProject: _projects[objectReference] = object case let object as PBXReferenceProxy: _referenceProxies[objectReference] = object case let object as PBXRezBuildPhase: _carbonResourcesBuildPhases[objectReference] = object case let object as PBXBuildRule: _buildRules[objectReference] = object default: fatalError("Unhandled PBXObject type for \(object), this is likely a bug / todo") } } /// Deletes the object with the given reference. /// /// - Parameter reference: referenc of the object to be deleted. /// - Returns: the deleted object. // swiftlint:disable:next function_body_length Note: SwiftLint doesn't disable if @discardable and the function are on different lines. @discardableResult func delete(reference: PBXObjectReference) -> PBXObject? { lock.lock() if let index = buildFiles.index(forKey: reference) { return _buildFiles.remove(at: index).value } else if let index = aggregateTargets.index(forKey: reference) { return _aggregateTargets.remove(at: index).value } else if let index = legacyTargets.index(forKey: reference) { return _legacyTargets.remove(at: index).value } else if let index = containerItemProxies.index(forKey: reference) { return _containerItemProxies.remove(at: index).value } else if let index = groups.index(forKey: reference) { return _groups.remove(at: index).value } else if let index = configurationLists.index(forKey: reference) { return _configurationLists.remove(at: index).value } else if let index = buildConfigurations.index(forKey: reference) { return _buildConfigurations.remove(at: index).value } else if let index = variantGroups.index(forKey: reference) { return _variantGroups.remove(at: index).value } else if let index = targetDependencies.index(forKey: reference) { return _targetDependencies.remove(at: index).value } else if let index = nativeTargets.index(forKey: reference) { return _nativeTargets.remove(at: index).value } else if let index = fileReferences.index(forKey: reference) { return _fileReferences.remove(at: index).value } else if let index = projects.index(forKey: reference) { return _projects.remove(at: index).value } else if let index = versionGroups.index(forKey: reference) { return _versionGroups.remove(at: index).value } else if let index = referenceProxies.index(forKey: reference) { return _referenceProxies.remove(at: index).value } else if let index = copyFilesBuildPhases.index(forKey: reference) { return _copyFilesBuildPhases.remove(at: index).value } else if let index = shellScriptBuildPhases.index(forKey: reference) { return _shellScriptBuildPhases.remove(at: index).value } else if let index = resourcesBuildPhases.index(forKey: reference) { return _resourcesBuildPhases.remove(at: index).value } else if let index = frameworksBuildPhases.index(forKey: reference) { return _frameworksBuildPhases.remove(at: index).value } else if let index = headersBuildPhases.index(forKey: reference) { return _headersBuildPhases.remove(at: index).value } else if let index = sourcesBuildPhases.index(forKey: reference) { return _sourcesBuildPhases.remove(at: index).value } else if let index = carbonResourcesBuildPhases.index(forKey: reference) { return _carbonResourcesBuildPhases.remove(at: index).value } else if let index = buildRules.index(forKey: reference) { return _buildRules.remove(at: index).value } lock.unlock() return nil } /// It returns the object with the given reference. /// /// - Parameter reference: Xcode reference. /// - Returns: object. // swiftlint:disable:next function_body_length func get(reference: PBXObjectReference) -> PBXObject? { // This if-let expression is used because the equivalent chain of `??` separated lookups causes, // with Swift 4, this compiler error: // Expression was too complex to be solved in reasonable time; // consider breaking up the expression into distinct sub-expressions if let object = buildFiles[reference] { return object } else if let object = aggregateTargets[reference] { return object } else if let object = legacyTargets[reference] { return object } else if let object = containerItemProxies[reference] { return object } else if let object = groups[reference] { return object } else if let object = configurationLists[reference] { return object } else if let object = buildConfigurations[reference] { return object } else if let object = variantGroups[reference] { return object } else if let object = targetDependencies[reference] { return object } else if let object = nativeTargets[reference] { return object } else if let object = fileReferences[reference] { return object } else if let object = projects[reference] { return object } else if let object = versionGroups[reference] { return object } else if let object = referenceProxies[reference] { return object } else if let object = copyFilesBuildPhases[reference] { return object } else if let object = shellScriptBuildPhases[reference] { return object } else if let object = resourcesBuildPhases[reference] { return object } else if let object = frameworksBuildPhases[reference] { return object } else if let object = headersBuildPhases[reference] { return object } else if let object = sourcesBuildPhases[reference] { return object } else if let object = carbonResourcesBuildPhases[reference] { return object } else if let object = buildRules[reference] { return object } else { return nil } } } // MARK: - Public extension PBXObjects { /// Returns all the targets with the given name. /// /// - Parameters: /// - name: target name. /// - Returns: targets with the given name. func targets(named name: String) -> [PBXTarget] { var targets: [PBXTarget] = [] let filter = { (targets: [PBXObjectReference: PBXTarget]) -> [PBXTarget] in targets.values.filter { $0.name == name } } targets.append(contentsOf: filter(nativeTargets)) targets.append(contentsOf: filter(legacyTargets)) targets.append(contentsOf: filter(aggregateTargets)) return targets } /// Invalidates all the objects references. func invalidateReferences() { forEach { $0.reference.invalidate() } } // MARK: - Computed Properties var buildPhases: [PBXObjectReference: PBXBuildPhase] { var phases: [PBXObjectReference: PBXBuildPhase] = [:] phases.merge(copyFilesBuildPhases as [PBXObjectReference: PBXBuildPhase], uniquingKeysWith: { first, _ in first }) phases.merge(sourcesBuildPhases as [PBXObjectReference: PBXBuildPhase], uniquingKeysWith: { first, _ in first }) phases.merge(shellScriptBuildPhases as [PBXObjectReference: PBXBuildPhase], uniquingKeysWith: { first, _ in first }) phases.merge(resourcesBuildPhases as [PBXObjectReference: PBXBuildPhase], uniquingKeysWith: { first, _ in first }) phases.merge(headersBuildPhases as [PBXObjectReference: PBXBuildPhase], uniquingKeysWith: { first, _ in first }) phases.merge(carbonResourcesBuildPhases as [PBXObjectReference: PBXBuildPhase], uniquingKeysWith: { first, _ in first }) phases.merge(frameworksBuildPhases as [PBXObjectReference: PBXBuildPhase], uniquingKeysWith: { first, _ in first }) return phases } // This dictionary is used to quickly get a connection between the build phase and the build files of this phase. // This is used to decode build files. (we need the name of the build phase) // Otherwise, we would have to go through all the build phases for each file. var buildPhaseFile: [PBXObjectReference: PBXBuildPhaseFile] { let values: [[PBXBuildPhaseFile]] = buildPhases.values.map { buildPhase in let files = buildPhase.files let buildPhaseFile: [PBXBuildPhaseFile] = files?.compactMap { (file: PBXBuildFile) -> PBXBuildPhaseFile in PBXBuildPhaseFile( buildFile: file, buildPhase: buildPhase ) } ?? [] return buildPhaseFile } return Dictionary(values.flatMap { $0 }.map { ($0.buildFile.reference, $0) }, uniquingKeysWith: { first, _ in return first }) } /// Runs the given closure for each of the objects that are part of the project. /// /// - Parameter closure: closure to be run. func forEach(_ closure: (PBXObject) -> Void) { buildFiles.values.forEach(closure) legacyTargets.values.forEach(closure) aggregateTargets.values.forEach(closure) containerItemProxies.values.forEach(closure) groups.values.forEach(closure) configurationLists.values.forEach(closure) versionGroups.values.forEach(closure) buildConfigurations.values.forEach(closure) variantGroups.values.forEach(closure) targetDependencies.values.forEach(closure) nativeTargets.values.forEach(closure) fileReferences.values.forEach(closure) projects.values.forEach(closure) referenceProxies.values.forEach(closure) buildRules.values.forEach(closure) copyFilesBuildPhases.values.forEach(closure) shellScriptBuildPhases.values.forEach(closure) resourcesBuildPhases.values.forEach(closure) frameworksBuildPhases.values.forEach(closure) headersBuildPhases.values.forEach(closure) sourcesBuildPhases.values.forEach(closure) carbonResourcesBuildPhases.values.forEach(closure) } }
47.106173
139
0.68199
8748440c6aabf535466ebf05eb1ce0229b7f9688
1,729
//===--- WriteBackMutableSlice.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 // //===----------------------------------------------------------------------===// internal func _writeBackMutableSlice<C, Slice_>( _ self_: inout C, bounds: Range<C.Index>, slice: Slice_ ) where C : MutableCollection, Slice_ : Collection, C._Element == Slice_.Iterator.Element, C.Index == Slice_.Index { self_._failEarlyRangeCheck(bounds, bounds: self_.startIndex..<self_.endIndex) // FIXME(performance): can we use // _withUnsafeMutableBufferPointerIfSupported? Would that create inout // aliasing violations if the newValue points to the same buffer? var selfElementIndex = bounds.lowerBound let selfElementsEndIndex = bounds.upperBound var newElementIndex = slice.startIndex let newElementsEndIndex = slice.endIndex while selfElementIndex != selfElementsEndIndex && newElementIndex != newElementsEndIndex { self_[selfElementIndex] = slice[newElementIndex] self_.formIndex(after: &selfElementIndex) slice.formIndex(after: &newElementIndex) } _precondition( selfElementIndex == selfElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a smaller size") _precondition( newElementIndex == newElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a larger size") }
36.020833
83
0.699826
1ea70781daa3d2e95382d93d51425f017b7ce07b
248
// // 🦠 Corona-Warn-App // import Foundation extension String { var localized: String { self.localized(tableName: nil) } func localized(tableName: String? = nil) -> String { NSLocalizedString(self, tableName: tableName, comment: "") } }
15.5
60
0.685484
283c2e7da678162680369ec99a076cb4bf1ebc8c
8,010
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import FBSimulatorControl @testable import FBSimulatorControlKit import XCTest /** * FakeDesc * * Fake, probe-able ParserDescription */ struct FakeDesc: ParserDescription { public let summary: String public let isDelimited: Bool public let children: [ParserDescription] public let isNormalised: Bool init(summary: String, isDelimited: Bool, children: [ParserDescription], isNormalised: Bool) { self.summary = summary self.isDelimited = isDelimited self.children = children self.isNormalised = isNormalised } init(_ n: Int, WithChildren children: [ParserDescription]) { self.init(summary: "fake-desc-" + String(n), isDelimited: false, children: children, isNormalised: false) } init(_ n: Int) { self.init(n, WithChildren: []) } public var normalised: ParserDescription { return FakeDesc(summary: summary, isDelimited: isDelimited, children: children.map { $0.normalised }, isNormalised: true) } } /** * AssertCast<U, T>(_ obj: U, _ tests: (T) -> Void) * * Check whether `obj : U` can be dynamically cast to a value of type `T`, and * if it can, pass it on to a continuation for potential further testing. */ func AssertCast<U, T>(_ obj: U, _ tests: (T) -> Void) { switch obj { case let casted as T: tests(casted) default: XCTFail("AssertCast: Could not dynamically cast value") } } /** * AssertEqualDesc(_ lhs: ParserDescription, _ rhs: ParserDescription) * * Check whether the descriptions `lhs` and `rhs` are observationally * equivalent. */ func AssertEqualDesc(_ lhs: ParserDescription, _ rhs: ParserDescription) { XCTAssertEqual(lhs.summary, rhs.summary) XCTAssertEqual(lhs.delimitedSummary, rhs.delimitedSummary) XCTAssertEqual(lhs.isDelimited, rhs.isDelimited) XCTAssertEqual(lhs.description, rhs.description) let lcs = lhs.children let rcs = rhs.children XCTAssertEqual(lcs.count, rcs.count) for (l, r) in zip(lcs, rcs) { AssertEqualDesc(l, r) } } class NormalisationTests: XCTestCase { func testPrimitive() { let prim = PrimitiveDesc(name: "name", desc: "desc") AssertEqualDesc(prim, prim.normalised) } func testFlag() { let flag = FlagDesc(name: "name", desc: "desc") AssertEqualDesc(flag, flag.normalised) } func testCmd() { let cmd = CmdDesc(cmd: "cmd") AssertEqualDesc(cmd, cmd.normalised) } func testSection() { let sect = SectionDesc(tag: "tag", name: "name", desc: "desc", child: FakeDesc(1)) let norm = sect.normalised AssertEqualDesc(sect, norm) AssertCast(norm) { (norm: SectionDesc) in AssertCast(norm.child) { (child: FakeDesc) in XCTAssertTrue(child.isNormalised) } } } func testAtleast() { let atleast = AtleastDesc(lowerBound: 1, child: FakeDesc(1)) let norm = atleast.normalised AssertEqualDesc(atleast, norm) AssertCast(norm) { (norm: AtleastDesc) in AssertCast(norm.child) { (child: FakeDesc) in XCTAssertTrue(child.isNormalised) } } } func testOptional() { let opt = OptionalDesc(child: FakeDesc(1)) AssertEqualDesc(opt, opt.normalised) } func testOptionalNonEmptyFlattening() { let nonEmpty = AtleastDesc(lowerBound: 1, child: FakeDesc(1), sep: FakeDesc(2)) let opt = OptionalDesc(child: nonEmpty) let expected = AtleastDesc(lowerBound: 0, child: nonEmpty.child, sep: nonEmpty.sep) AssertEqualDesc(opt.normalised, expected) } func testOptionalAtleastPreserve() { let atleast = AtleastDesc(lowerBound: 2, child: FakeDesc(1), sep: FakeDesc(2)) let opt = OptionalDesc(child: atleast) AssertEqualDesc(opt, opt.normalised) } func testSequenceDiscarding() { let fake = FakeDesc(1) let seq = SequenceDesc(children: [fake]) let norm = seq.normalised AssertEqualDesc(fake, norm) AssertCast(norm) { (actual: FakeDesc) in XCTAssertTrue(actual.isNormalised) } } func testSequenceFlattening() { let seq = SequenceDesc(children: [ FakeDesc(1), FakeDesc(2), SequenceDesc(children: [ FakeDesc(3), SequenceDesc(children: [ FakeDesc(4), ]), ]), FakeDesc(5, WithChildren: [ SequenceDesc(children: [ FakeDesc(6), ]), FakeDesc(7), ]), ]) let expected = SequenceDesc(children: [ FakeDesc(1), FakeDesc(2), FakeDesc(3), FakeDesc(4), FakeDesc(5, WithChildren: [ FakeDesc(6), FakeDesc(7), ]), ]) AssertEqualDesc(expected, seq.normalised) } func testSequenceEmpty() { let seq = SequenceDesc(children: []) AssertEqualDesc(seq, seq.normalised) } func testChoiceDiscarding() { let fake = FakeDesc(1) let choices = ChoiceDesc(children: [fake]) let norm = choices.normalised AssertEqualDesc(fake, norm) AssertCast(norm) { (actual: FakeDesc) in XCTAssertTrue(actual.isNormalised) } } func testChoiceFlattening() { let choices = ChoiceDesc(children: [ FakeDesc(1), FakeDesc(2), ChoiceDesc(children: [ FakeDesc(3), ChoiceDesc(children: [ FakeDesc(4), ]), ]), FakeDesc(5, WithChildren: [ ChoiceDesc(children: [ FakeDesc(6), ]), FakeDesc(7), ]), ]) let expected = ChoiceDesc(children: [ FakeDesc(1), FakeDesc(2), FakeDesc(3), FakeDesc(4), FakeDesc(5, WithChildren: [ FakeDesc(6), FakeDesc(7), ]), ]) AssertEqualDesc(expected, choices.normalised) } func testChoiceEmpty() { let choice = ChoiceDesc(children: []) AssertEqualDesc(choice, choice.normalised) } func testPreservesExpandednessOfChoice() { let choice = ChoiceDesc(children: [FakeDesc(1), FakeDesc(2)]).expanded AssertEqualDesc(choice, choice.normalised) } } class DelimitedSummaryTest: XCTestCase { func testNotDelimited() { let fake = FakeDesc(summary: "summary", isDelimited: false, children: [], isNormalised: false) XCTAssertEqual("{{ summary }}", fake.delimitedSummary) } func testDelimited() { let fake = FakeDesc(summary: "summary", isDelimited: true, children: [], isNormalised: false) XCTAssertEqual("summary", fake.delimitedSummary) } } class FindAllTests: XCTestCase { func testSingleton() { let fake = FakeDesc(1) var fakes = [FakeDesc]() fake.findAll(&fakes) XCTAssertEqual(0, fakes.count) } func testNested() { let fake4 = FakeDesc(4) let fake3 = FakeDesc(3, WithChildren: [fake4]) let fake2 = FakeDesc(2) let fake1 = FakeDesc(1, WithChildren: [fake2, fake3]) let expectedFakes = [fake2, fake3, fake4] var actualFakes = [FakeDesc]() fake1.findAll(&actualFakes) XCTAssertEqual(expectedFakes.count, actualFakes.count) for fake in expectedFakes { XCTAssert(actualFakes.contains { $0.summary == fake.summary }) } } func testHiddenBySect() { let fake2 = FakeDesc(2) let fake1 = FakeDesc(1, WithChildren: [ fake2, SectionDesc(tag: "tag", name: "name", desc: "desc", child: FakeDesc(3)), ]) var actualFakes = [FakeDesc]() fake1.findAll(&actualFakes) XCTAssertEqual(1, actualFakes.count) AssertEqualDesc(fake2, actualFakes.first!) } }
25.509554
78
0.613483
397377c127f40a87522661b88f08677c2a7cd724
4,383
// The MIT License (MIT) // // Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). import XCTest @testable import Nuke class ImageDecoderTests: XCTestCase { func testDecodingProgressiveJPEG() { let data = Test.data(name: "progressive", extension: "jpeg") let decoder = ImageDecoder() // Just before the Start Of Frame XCTAssertNil(decoder.decode(data: data[0...358], isFinal: false)) XCTAssertNil(decoder.isProgressive) XCTAssertEqual(decoder.numberOfScans, 0) // Right after the Start Of Frame XCTAssertNil(decoder.decode(data: data[0...359], isFinal: false)) XCTAssertTrue(decoder.isProgressive!) XCTAssertEqual(decoder.numberOfScans, 0) // still haven't finished the first scan // Just before the first Start Of Scan XCTAssertNil(decoder.decode(data: data[0...438], isFinal: false)) XCTAssertEqual(decoder.numberOfScans, 0) // still haven't finished the first scan // Found the first Start Of Scan XCTAssertNil(decoder.decode(data: data[0...439], isFinal: false)) XCTAssertEqual(decoder.numberOfScans, 1) // Found the second Start of Scan let scan1 = decoder.decode(data: data[0...2952], isFinal: false) XCTAssertNotNil(scan1) #if os(macOS) XCTAssertEqual(scan1!.size.width, 450) XCTAssertEqual(scan1!.size.height, 300) #else XCTAssertEqual(scan1!.size.width * scan1!.scale, 450) XCTAssertEqual(scan1!.size.height * scan1!.scale, 300) #endif XCTAssertEqual(decoder.numberOfScans, 2) // Feed all data and see how many scans are there // In practice the moment we finish receiving data we call // `decode(data: data, isFinal: true)` so we might not scan all the // of the bytes and encounter all of the scans (e.g. the final chunk // of data that we receive contains multiple scans). XCTAssertNotNil(decoder.decode(data: data, isFinal: false)) XCTAssertEqual(decoder.numberOfScans, 10) } func testDecodingGIFs() { XCTAssertFalse(ImagePipeline.Configuration.isAnimatedImageDataEnabled) let data = Test.data(name: "cat", extension: "gif") XCTAssertNil(ImageDecoder().decode(data: data, isFinal: true)?.animatedImageData) ImagePipeline.Configuration.isAnimatedImageDataEnabled = true XCTAssertNotNil(ImageDecoder().decode(data: data, isFinal: true)?.animatedImageData) ImagePipeline.Configuration.isAnimatedImageDataEnabled = false } } class ImageFormatTests: XCTestCase { // MARK: PNG func testDetectPNG() { let data = Test.data(name: "fixture", extension: "png") XCTAssertNil(ImageFormat.format(for: data[0..<1])) XCTAssertNil(ImageFormat.format(for: data[0..<7])) XCTAssertEqual(ImageFormat.format(for: data[0..<8]), .png) XCTAssertEqual(ImageFormat.format(for: data), .png) } // MARK: GIF func testDetectGIF() { let data = Test.data(name: "cat", extension: "gif") XCTAssertEqual(ImageFormat.format(for: data), .gif) } // MARK: JPEG func testDetectBaselineJPEG() { let data = Test.data(name: "baseline", extension: "jpeg") XCTAssertNil(ImageFormat.format(for: data[0..<1])) XCTAssertNil(ImageFormat.format(for: data[0..<2])) XCTAssertEqual(ImageFormat.format(for: data[0..<3]), .jpeg(isProgressive: nil)) XCTAssertEqual(ImageFormat.format(for: data), .jpeg(isProgressive: false)) } func testDetectProgressiveJPEG() { let data = Test.data(name: "progressive", extension: "jpeg") // Not enough data XCTAssertNil(ImageFormat.format(for: Data())) XCTAssertNil(ImageFormat.format(for: data[0..<2])) // Enough to determine image format XCTAssertEqual(ImageFormat.format(for: data[0..<3]), .jpeg(isProgressive: nil)) XCTAssertEqual(ImageFormat.format(for: data[0...30]), .jpeg(isProgressive: nil)) // Just before the first scan XCTAssertEqual(ImageFormat.format(for: data[0...358]), .jpeg(isProgressive: nil)) XCTAssertEqual(ImageFormat.format(for: data[0...359]), .jpeg(isProgressive: true)) // Full image XCTAssertEqual(ImageFormat.format(for: data), .jpeg(isProgressive: true)) } }
39.845455
92
0.660735
72d3e4a4de196971b0752fa13525161d5b0e3992
4,364
// // Database.swift // lyrum // // Created by Josh Arnold on 9/18/20. // import Parse import SVProgressHUD func does_user_exist(user_id:String, completion: @escaping (_ exists:Bool) -> ()) { let query = PFQuery(className: PFUser().parseClassName) query.whereKey("username", equalTo: user_id) query.getFirstObjectInBackground { (obj, error) in if error == nil { completion(true) }else{ completion(false) } } } func sign_up_user(user_id:String, completion: @escaping (_ success:Bool) -> ()) { let user = PFUser() user.username = user_id user.password = user_id user["name"] = SpotifyConstants.DISPLAY_NAME user.signUpInBackground { (success, error) in completion(success) } } func login_user(user_id:String, completion: @escaping (_ success:Bool) -> ()) { guard PFUser.current() == nil else { completion(true) return } PFUser.logInWithUsername(inBackground: user_id, password: user_id) { (user, error) in if error == nil { // temp // user!["name"] = SpotifyConstants.DISPLAY_NAME // user?.saveInBackground() completion(true) }else{ completion(false) } } } func create_post(song_title:String, song_id:String, artist:String, user:PFUser, preview_link:String, stream_link:String, artwork_url:String, tag:String, completion: @escaping (_ success:Bool) -> ()) { SVProgressHUD.show() let obj = PFObject(className: "Post") obj["songId"] = song_id obj["songTitle"] = song_title obj["artist"] = artist obj["user"] = user obj["preview_link"] = preview_link obj["stream_link"] = stream_link obj["artwork_url"] = artwork_url obj["tag"] = tag obj["likes"] = [] obj["numComments"] = 0 obj.saveInBackground { (done, error) in SVProgressHUD.dismiss() if error == nil { completion(true) }else{ completion(false) } } } enum QueryPreference { case NEW case HOT } func query_for_posts(pref:QueryPreference = QueryPreference.HOT, completion: @escaping (_ success:Bool, _ objects: [PFObject]) -> ()) { let query = PFQuery(className: "Post") if (pref == QueryPreference.NEW) { query.order(byDescending: "createdAt") }else if (pref == QueryPreference.HOT) { query.order(byDescending: "likes") } query.findObjectsInBackground { (obj, error) in if error == nil { completion(true, obj!) }else{ completion(false, []) } } } func likePost(obj:PFObject) { obj.addUniqueObject(PFUser.current()!.objectId!, forKey: "likes") obj.saveInBackground() } func unlikePost(obj:PFObject) { obj.removeObjects(in: [PFUser.current()!.objectId!], forKey: "likes") obj.saveInBackground() } func commentPost(post:PFObject, text:String, user:PFUser, completion: @escaping (_ success: Bool) -> ()) { // Actually save obj post.incrementKey("numComments") post.saveInBackground() let comment = PFObject(className: "Comment") comment["post"] = post comment["user"] = user comment["text"] = text comment.saveInBackground { (done, error) in if error == nil { completion(true) }else{ completion(false) } } } func pfobj_to_song(obj:PFObject) -> Song { let song = Song() song.title = obj.object(forKey: "songTitle") as! String song.id = obj.object(forKey: "songId") as! String song.artist = obj.object(forKey: "artist") as! String song.artwork = obj.object(forKey: "artwork_url") as! String song.tag = obj.object(forKey: "tag") as! String song.preview = obj.object(forKey: "preview_link") as! String song.uri = obj.object(forKey: "stream_link") as! String return song } func query_comments(post:PFObject, completion: @escaping (_ success:Bool, _ objects: [PFObject]) -> ()) { let query = PFQuery(className: "Comment") query.includeKey("user") query.whereKey("post", equalTo: post) query.findObjectsInBackground { (obj, error) in if error == nil { completion(true, obj!) }else{ completion(false, []) } } }
26.289157
200
0.606324
09109df47744fab2b3d6a47bd5dba37f80fe2eaf
1,776
// Copyright (c) 2020 Razeware LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, // distribute, sublicense, create a derivative work, and/or sell copies of the // Software in any work that is designed, intended, or marketed for pedagogical or // instructional purposes related to programming, coding, application development, // or information technology. Permission for such use, copying, modification, // merger, publication, distribution, sublicensing, creation of derivative works, // or sale is expressly withheld. // // 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. extension Comparable { func clamped(to limits: ClosedRange<Self>) -> Self { min(max(self, limits.lowerBound), limits.upperBound) } }
52.235294
82
0.765203
d62cfe88df61f6cc66adf3df06c4f08ef5b88399
4,208
// // BSNavgationController.swift // BSBuDeJie // // Created by mh on 16/4/19. // Copyright © 2016年 BS. All rights reserved. // import UIKit class BSNavgationController: UINavigationController { override class func initialize() { let bar:UINavigationBar = UINavigationBar.appearance() bar.setBackgroundImage(UIImage(named: "navigationbarBackgroundWhite"), forBarMetrics: UIBarMetrics.Default) let item:UIBarButtonItem = UIBarButtonItem.appearance() item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.whiteColor()], forState: UIControlState.Normal) item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orangeColor()], forState: UIControlState.Highlighted) item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor(red: 154.0/255.0, green: 154.0/255.0, blue: 154.0/255.0, alpha: 0.8)], forState: UIControlState.Disabled) } override func viewDidLoad() { super.viewDidLoad() //MARK: - 添加全屏返回手势 addGestureRecognizer() } private func addGestureRecognizer(){ let pan : UIPanGestureRecognizer = UIPanGestureRecognizer.init(target: self.interactivePopGestureRecognizer?.delegate, action: NSSelectorFromString("handleNavigationTransition:")) pan.delegate = self view.addGestureRecognizer(pan) } //MARK: -系统方法 override func pushViewController(viewController: UIViewController, animated: Bool) { if childViewControllers.count > 0 {//非根控制器 viewController.hidesBottomBarWhenPushed = true viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.itemWithTarget(self, action: Selector("back"), image: "navigationButtonReturn", highlightImage: "navigationButtonReturnClick") viewController.navigationItem.rightBarButtonItem = UIBarButtonItem.itemWithTarget(self, action: Selector("moreClick"), image: "cellmorebtnnormal", highlightImage: "cellmorebtnclick") viewController.navigationController?.navigationBar.shadowImage = UIImage(named: "cell-content-line") } super.pushViewController(viewController, animated: animated) } func back(){ popViewControllerAnimated(true) } func moreClick(){ popViewControllerAnimated(true) } } extension BSNavgationController: UIGestureRecognizerDelegate{ func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if childViewControllers.count == 1 { return false } return true } } extension UIBarButtonItem { class func itemWithTarget(target: AnyObject?, action: Selector, image: String, highlightImage: String) -> UIBarButtonItem { let btn : UIButton = UIButton(type: UIButtonType.Custom) btn.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside) btn.setBackgroundImage(UIImage(named: image), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: highlightImage), forState: UIControlState.Highlighted) btn.bounds.size = (btn.currentBackgroundImage?.size)! btn.adjustsImageWhenHighlighted = false //用uiview包装后位置会产生偏移 let newViwe : UIView = UIView.init(frame: btn.bounds) // newViwe.addSubview(btn) return UIBarButtonItem.init(customView: btn) } class func itemWithTarget(target: AnyObject?, action: Selector, image: String, seletedImage: String) -> UIBarButtonItem { let btn : UIButton = UIButton(type: UIButtonType.Custom) btn.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside) btn.setBackgroundImage(UIImage(named: image), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: seletedImage), forState: UIControlState.Selected) btn.bounds.size = (btn.currentBackgroundImage?.size)! btn.adjustsImageWhenHighlighted = false //用uiview包装后位置会产生偏移 // newViwe.addSubview(btn) return UIBarButtonItem.init(customView: btn) } }
43.833333
204
0.706511
d6286d49f910f87a0682a6753651bd8a63cca44d
3,883
import Cocoa import Influence extension NSColor { static var darkRed: NSColor { return NSColor(red: 0.5, green: 0, blue: 0, alpha: 1) } static var lightRed: NSColor { return NSColor(red: 0.75, green: 0.3, blue: 0.3, alpha: 1) } } private func *(lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x * rhs.x, y: lhs.y * rhs.y) } class BoardView: NSView { override var isFlipped: Bool { return true } var board: Board! = nil { didSet { moves = [] pegCountX = board.pegs.reduce(1) { max($0, $1.position.x) } + 1 pegCountY = board.pegs.reduce(1) { max($0, $1.position.y) } + 1 boardLines = board.lines .map { (a, b) in (board.peg(a).position, board.peg(b).position)} setNeedsDisplay(bounds) } } var moves: [String] = [] { didSet { setNeedsDisplay(bounds) } } var pegCountX: CGFloat = 0 var pegCountY: CGFloat = 0 var boardLines: [(CGPoint, CGPoint)] = [] override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) NSColor.white.setFill() NSRectFill(bounds) guard let context = NSGraphicsContext.current()?.cgContext else { return } drawBoard(context: context) } func drawBoard(context: CGContext) { let scaleX = bounds.size.width / pegCountX let scaleY = bounds.size.height / pegCountY let scale = CGPoint(x: scaleX, y: scaleY) let scaledLines = boardLines.map { (a: CGPoint, b: CGPoint) -> (CGPoint, CGPoint) in (a * scale, b * scale) } context.setLineWidth(2) context.setStrokeColor(NSColor.lightGray.cgColor) for (lineStart, lineEnd) in scaledLines { let path = CGMutablePath() path.move(to: lineStart) path.addLine(to: lineEnd) context.addPath(path) } context.drawPath(using: .stroke) func draw(pegs: [Peg], radius: CGFloat, color: NSColor) { for peg in pegs { context.setFillColor(color.cgColor) context.addArc( center: peg.position * scale, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true) context.fillPath() } } func draw(outlinedPegs pegs: [Peg], radius: CGFloat, color: NSColor) { draw(pegs: pegs, radius: radius + 3, color: NSColor.white) draw(pegs: pegs, radius: radius, color: color) } draw(outlinedPegs: board.pegs.filter { !$0.state }, radius: 10, color: NSColor.lightGray) draw(outlinedPegs: board.pegs.filter { $0.state }, radius: 12, color: NSColor.lightRed) let movePegs = moves.map({ board.peg($0) }) draw(outlinedPegs: movePegs, radius: 15, color: NSColor.darkRed) let moveAttrs = [ NSFontAttributeName: NSFont.systemFont(ofSize: 16, weight: NSFontWeightRegular), NSForegroundColorAttributeName: NSColor.white] for (index, peg) in moves.map({ board.peg($0) }).enumerated() { let pegCenter = CGPoint( x: CGFloat(peg.position.x) * scaleX, y: CGFloat(peg.position.y) * scaleY) let pegStr = String(describing: index) let strSize = (pegStr as NSString).size(withAttributes: moveAttrs) pegStr.draw( with: CGRect( x: pegCenter.x - strSize.width / 2, y: pegCenter.y - strSize.height / 2, width: strSize.width, height: strSize.height), options: .usesLineFragmentOrigin, attributes: moveAttrs, context: nil) } } }
30.100775
117
0.55112
760f5800a9e16a6c5e55fd3d906d5d116230cd15
919
// // Tests.swift // Tests // // Created by devedbox on 2017/4/19. // Copyright © 2017年 devedbox. All rights reserved. // import XCTest 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. // 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. } } }
25.527778
111
0.618063
9b48beb13e46e796b76fcaf1ceb26282a66c27f0
3,901
// // LoginInteractor.swift // TripStory // // Created by Gon on 2021/01/17. // import Foundation import Combine protocol LoginInteractor { func login(username: String, password: String) func validationState(username: Published<String>.Publisher) -> AnyPublisher<UsernameState, Never> func validationState(password: Published<String>.Publisher) -> AnyPublisher<PasswordState, Never> func isLoginable(with username: Published<String>.Publisher, _ password: Published<String>.Publisher ) -> AnyPublisher<Bool, Never> } struct DefaultLoginInteractor: LoginInteractor { let appState: Store<AppState> let authService: AuthenticationService let cancelBag = CancelBag() func login(username: String, password: String) { appState[\.loginState] = .isInProgress authService.login(username: username, password: password) .sink(receiveValue: { appState[\.loginState] = $0}) .store(in: cancelBag) } func validationState(username: Published<String>.Publisher) -> AnyPublisher<UsernameState, Never> { isEmpty(username) .map { isEmpty in guard !isEmpty else { return UsernameState.empty } return UsernameState.valid } .removeDuplicates() .eraseToAnyPublisher() } func validationState(password: Published<String>.Publisher) -> AnyPublisher<PasswordState, Never> { isEmpty(password) .map { isEmpty in guard !isEmpty else { return PasswordState.empty} return PasswordState.valid } .removeDuplicates() .eraseToAnyPublisher() } func isLoginable(with username: Published<String>.Publisher, _ password: Published<String>.Publisher ) -> AnyPublisher<Bool, Never> { Publishers.CombineLatest(validationState(username: username), validationState(password: password)) .map { $0.0 == .valid && $0.1 == .valid } .removeDuplicates() .eraseToAnyPublisher() } private func isEmpty(_ string: Published<String>.Publisher) -> AnyPublisher<Bool, Never> { string .debounce(for: 0.2, scheduler: RunLoop.main) .removeDuplicates() .map { $0 == "" } .eraseToAnyPublisher() } } #if DEBUG struct StubLoginInteractor: LoginInteractor { func login(username: String, password: String) { // } func validationState(username: Published<String>.Publisher) -> AnyPublisher<UsernameState, Never> { isEmpty(username) .map { isEmpty in guard !isEmpty else { return UsernameState.empty } return UsernameState.valid } .removeDuplicates() .eraseToAnyPublisher() } func validationState(password: Published<String>.Publisher) -> AnyPublisher<PasswordState, Never> { isEmpty(password) .map { isEmpty in guard !isEmpty else { return PasswordState.empty} return PasswordState.valid } .removeDuplicates() .eraseToAnyPublisher() } func isLoginable(with username: Published<String>.Publisher, _ password: Published<String>.Publisher ) -> AnyPublisher<Bool, Never> { Publishers.CombineLatest(validationState(username: username), validationState(password: password)) .map { $0.0 == .valid && $0.1 == .valid } .removeDuplicates() .eraseToAnyPublisher() } private func isEmpty(_ string: Published<String>.Publisher) -> AnyPublisher<Bool, Never> { string .debounce(for: 0.2, scheduler: RunLoop.main) .removeDuplicates() .map { $0 == "" } .eraseToAnyPublisher() } } #endif
33.62931
106
0.613432
fcf6897b72bd7aa37aee309cd582e0bed8aa8f18
38
public struct True_Empty: Codable { }
12.666667
35
0.763158
f4ec92d6a24f3796e0c1924cf740e50124a05415
416
// // NotesProtocol.swift // MyNotes // // Created by Hall, Adrian on 8/24/18. // Copyright © 2018 Hall, Adrian. All rights reserved. // struct Note { var id: String? = nil var title: String? = nil var content: String? = nil } protocol NotesProtocol { func getNote(noteId: String) func loadNotes() func createNote() func updateNote(note: Note) func deleteNote(noteId: String) }
18.909091
55
0.649038
693a56ee0b640ffad8ad443ab2b383ae561cca2c
1,608
import Foundation public struct ChordFormatter { public var style: Style public init(style: Style = .full) { self.style = style } /// Produce a string representation of a chord /// - Parameter chord: The chord to describe /// - Returns: A string description of a chord public func string(from chord: Chord) -> String { chord.root.description + spacer + chord.voicing.description(for: style) } private var spacer: String { style == .short ? "" : " " } } extension ChordFormatter { public enum Style { /// Specifies a short style, such as "C", "Cm", "Cº", "C+". case short /// Specifies a medium style, with abbreviated text such as /// "C maj", "C min", "C dim", "C aug". case medium /// Specifies a full written style such as /// "C major", "C minor", "C diminished", "C augmented". case full } } private extension ChordVoicing { func description(for style: ChordFormatter.Style) -> String { switch (self, style) { case (.major, .short): return "" case (.major, .medium): return "maj" case (.minor, .short): return "m" case (.minor, .medium): return "min" case (.diminished, .short): return "º" case (.diminished, .medium): return "dim" case (.augmented, .short): return "+" case (.augmented, .medium): return "aug" case (_, .full): return self.rawValue } } }
26.360656
79
0.536692
721596de108bd389221479881dd683e04646dadd
1,292
// // Copyright (c) 2019-Present Umobi - https://github.com/umobi // // 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 SwiftUI public protocol RawWindowAnimation { func animate<Content>(_ view: Content) -> AnyView where Content: View }
44.551724
80
0.762384
e684b97bd850321ffe2bb27f0449eba2b9c1e5fc
1,696
// // GoodToGo // // Created by Ricardo Santos // Copyright © 2020 Ricardo P Santos. All rights reserved. // import Foundation import UIKit // import RxCocoa import RxSwift import DevTools import PointFreeFunctions // import Extensions open class BaseGenericViewControllerVIP<T: StylableView>: BaseViewControllerVIP { deinit { if genericView != nil { genericView.removeFromSuperview() } } public var genericView: T! open override func loadView() { super.loadView() // Setup Generic View setup() genericView = T() view.addSubview(genericView) genericView.autoLayout.edgesToSuperview() setupViewUIRx() } open func setup() { DevTools.Log.warning("\(self.className) : \(DevTools.Strings.overrideMe.rawValue)") } open override func viewDidLoad() { super.viewDidLoad() setupViewIfNeed() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNavigationUIRx() } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.executeWithDelay(delay: 0.1) { [weak self] in self?.firstAppearance = false } } open func setupViewIfNeed() { DevTools.Log.warning("\(self.className) : \(DevTools.Strings.overrideMe.rawValue)") } open func setupNavigationUIRx() { DevTools.Log.warning("\(self.className) : \(DevTools.Strings.overrideMe.rawValue)") } open func setupViewUIRx() { DevTools.Log.warning("\(self.className) : \(DevTools.Strings.overrideMe.rawValue)") } }
23.887324
91
0.645637
3961f33733f176fb31f7afd9dafc0855226aa3b1
442
// // ContentView.swift // Shopping List // // Created by John Edwin Guerrero Ayala on 8/12/19. // Copyright © 2019 John Edwin Guerrero Ayala. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { ShopListView(availableItems: ShopItem.generateFake(withQuantity: 30)) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
20.090909
77
0.687783
f970d5d6a7ecac64dd845669af9932ecfb4c8db8
2,122
// // Statio // Varun Santhanam // import Analytics import Foundation import NeedleFoundation import ShortRibs protocol BatteryDependency: Dependency { var analyticsManager: AnalyticsManaging { get } var batteryLevelStream: BatteryLevelStreaming { get } var batteryStateStream: BatteryStateStreaming { get } } class BatteryComponent: Component<BatteryDependency> { // MARK: - Internal Dependencies fileprivate var colllectionView: BatteryCollectionView { shared { BatteryCollectionView() } } fileprivate var dataSource: BatteryDataSource { shared { BatteryCollectionViewDataSource(collectionView: colllectionView) } } } /// @CreateMock protocol BatteryInteractable: PresentableInteractable {} typealias BatteryDynamicBuildDependency = ( BatteryListener ) /// @CreateMock protocol BatteryBuildable: AnyObject { func build(withListener listener: BatteryListener) -> PresentableInteractable } final class BatteryBuilder: ComponentizedBuilder<BatteryComponent, PresentableInteractable, BatteryDynamicBuildDependency, Void>, BatteryBuildable { // MARK: - ComponentizedBuilder override final func build(with component: BatteryComponent, _ dynamicBuildDependency: BatteryDynamicBuildDependency) -> PresentableInteractable { let listener = dynamicBuildDependency let viewController = BatteryViewController(analyticsManager: component.analyticsManager, collectionView: component.colllectionView, dataSource: component.dataSource) let interactor = BatteryInteractor(presenter: viewController, batteryLevelStream: component.batteryLevelStream, batteryStateStream: component.batteryStateStream) interactor.listener = listener return interactor } // MARK: - BatteryBuildable func build(withListener listener: BatteryListener) -> PresentableInteractable { build(withDynamicBuildDependency: listener) } }
32.151515
149
0.707823
618e47803a4e2ad59b0ff181e738af0054e06766
77
import Foundation enum Result<T, E> { case value(T) case error(E) }
11
19
0.623377
89cb6b353c31fcbd7adc0d17c8ca7587ce6cf109
1,951
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import MaterialComponents private func randomFloat() -> CGFloat { return CGFloat(arc4random()) / CGFloat(UInt32.max) } private func generateRandomPalettes(_ count: Int) -> [(name: String, palette: MDCPalette)] { var palettes = [(name: String, palette: MDCPalette)]() for _ in 1...count { let rgb = [randomFloat(), randomFloat(), randomFloat()] let name = String(format: "Generated from #%2X%2X%2X", Int(rgb[0] * 255), Int(rgb[1] * 255), Int(rgb[2] * 255)) let color = UIColor.init(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: 1) palettes.append((name, MDCPalette.init(generatedFrom: color))) } return palettes } class PalettesGeneratedExampleViewController: PalettesExampleViewController { fileprivate let numPalettes = 10 convenience init() { self.init(style: .grouped) self.palettes = generateRandomPalettes(numPalettes) } } // MARK: Catalog by convention extension PalettesGeneratedExampleViewController { class func catalogBreadcrumbs() -> [String] { return ["Palettes", "Generated Palettes"] } class func catalogDescription() -> String { return "The Palettes component provides sets of reference colors that work well together." } class func catalogIsPrimaryDemo() -> Bool { return false } }
32.516667
94
0.708867
fedcd8546fa1b4a6f028e261acaf2f1b4b2f06f4
135
import Foundation extension MGlobalPlan { struct Constants { static let projectsDirectory:String = "projects" } }
13.5
56
0.674074
e40b62a84dcfc3cd05bf26bb96efa74d5b456bbc
41,228
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2015 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import CoreFoundation import Security public protocol WebSocketDelegate: class { func websocketDidConnect(socket: WebSocket) func websocketDidDisconnect(socket: WebSocket, error: NSError?) func websocketDidReceiveMessage(socket: WebSocket, text: String) func websocketDidReceiveData(socket: WebSocket, data: NSData) } public protocol WebSocketPongDelegate: class { func websocketDidReceivePong(socket: WebSocket) } public class WebSocket : NSObject, NSStreamDelegate { enum OpCode : UInt8 { case ContinueFrame = 0x0 case TextFrame = 0x1 case BinaryFrame = 0x2 //3-7 are reserved. case ConnectionClose = 0x8 case Ping = 0x9 case Pong = 0xA //B-F reserved. } public enum CloseCode : UInt16 { case Normal = 1000 case GoingAway = 1001 case ProtocolError = 1002 case ProtocolUnhandledType = 1003 // 1004 reserved. case NoStatusReceived = 1005 //1006 reserved. case Encoding = 1007 case PolicyViolated = 1008 case MessageTooBig = 1009 } public static let ErrorDomain = "WebSocket" enum InternalErrorCode : UInt16 { // 0-999 WebSocket status codes not used case OutputStreamWriteError = 1 } //Where the callback is executed. It defaults to the main UI thread queue. public var queue = dispatch_get_main_queue() var optionalProtocols : [String]? //Constant Values. let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 class WSResponse { var isFin = false var code: OpCode = .ContinueFrame var bytesLeft = 0 var frameCount = 0 var buffer: NSMutableData? } public weak var delegate: WebSocketDelegate? public weak var pongDelegate: WebSocketPongDelegate? public var onConnect: ((Void) -> Void)? public var onDisconnect: ((NSError?) -> Void)? public var onText: ((String) -> Void)? public var onData: ((NSData) -> Void)? public var onPong: ((Void) -> Void)? public var headers = [String: String]() public var voipEnabled = false public var selfSignedSSL = false private var security: SSLSecurity? public var enabledSSLCipherSuites: [SSLCipherSuite]? public var origin: String? public var isConnected :Bool { return connected } public var currentURL: NSURL {return url} private var url: NSURL private var inputStream: NSInputStream? private var outputStream: NSOutputStream? private var connected = false private var isCreated = false private var writeQueue = NSOperationQueue() private var readStack = [WSResponse]() private var inputQueue = [NSData]() private var fragBuffer: NSData? private var certValidated = false private var didDisconnect = false private var readyToWrite = false private let mutex = NSLock() private var canDispatch: Bool { mutex.lock() let canWork = readyToWrite mutex.unlock() return canWork } //the shared processing queue used for all websocket private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL) //used for setting protocols. public init(url: NSURL, protocols: [String]? = nil) { self.url = url self.origin = url.absoluteString writeQueue.maxConcurrentOperationCount = 1 optionalProtocols = protocols } ///Connect to the websocket server on a background thread public func connect() { guard !isCreated else { return } didDisconnect = false isCreated = true createHTTPRequest() isCreated = false } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. */ public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) { switch forceTimeout { case .Some(let seconds) where seconds > 0: dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [unowned self] in self.disconnectStream(nil) } fallthrough case .None: writeError(CloseCode.Normal.rawValue) default: self.disconnectStream(nil) break } } ///write a string to the websocket. This sends it as a text frame. public func writeString(str: String) { guard isConnected else { return } dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame) } ///write binary data to the websocket. This sends it as a binary frame. public func writeData(data: NSData) { guard isConnected else { return } dequeueWrite(data, code: .BinaryFrame) } //write a ping to the websocket. This sends it as a control frame. //yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s public func writePing(data: NSData) { guard isConnected else { return } dequeueWrite(data, code: .Ping) } //private method that starts the connection private func createHTTPRequest() { let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET", url, kCFHTTPVersion1_1).takeRetainedValue() var port = url.port if port == nil { if ["wss", "https"].contains(url.scheme) { port = 443 } else { port = 80 } } addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue) addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue) if let protocols = optionalProtocols { addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(",")) } addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue) addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey()) if let origin = origin { addHeader(urlRequest, key: headerOriginName, val: origin) } addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)") for (key,value) in headers { addHeader(urlRequest, key: key, val: value) } if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) { let serializedRequest = cfHTTPMessage.takeRetainedValue() initStreamsWithData(serializedRequest, Int(port!)) } } //Add a header to the CFHTTPMessage by using the NSString bridges to CFString private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) { CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val) } //generate a websocket key as needed in rfc private func generateWebSocketKey() -> String { var key = "" let seed = 16 for _ in 0..<seed { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni))" } let data = key.dataUsingEncoding(NSUTF8StringEncoding) let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) return baseKey! } //Start the stream connection and write the data to the output stream private func initStreamsWithData(data: NSData, _ port: Int) { //higher level API we will cut over to at some point //NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h: NSString = url.host! CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if ["wss", "https"].contains(url.scheme) { inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey) outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey) } else { certValidated = true //not a https session, so no need to check SSL pinning } if voipEnabled { inStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) } if selfSignedSSL { let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull] inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String) outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String) } if let cipherSuites = self.enabledSSLCipherSuites { if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?, sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? { let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) if resIn != errSecSuccess { let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn)) disconnectStream(error) return } if resOut != errSecSuccess { let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut)) disconnectStream(error) return } } } CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue) CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue) inStream.open() outStream.open() self.mutex.lock() self.readyToWrite = true self.mutex.unlock() let bytes = UnsafePointer<UInt8>(data.bytes) var timeout = 5000000 //wait 5 seconds before giving up writeQueue.addOperationWithBlock { [unowned self] in while !outStream.hasSpaceAvailable { usleep(100) //wait until the socket is ready timeout -= 100 if timeout < 0 { self.cleanupStream() self.doDisconnect(self.errorWithDetail("write wait timed out", code: 2)) return } else if outStream.streamError != nil { return //disconnectStream will be called. } } outStream.write(bytes, maxLength: data.length) } } //delegate for the stream methods. Processes incoming bytes public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) { if let sec = security where !certValidated && [.HasBytesAvailable, .HasSpaceAvailable].contains(eventCode) { let possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as String) if let trust: AnyObject = possibleTrust { let domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as String) if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) { certValidated = true } else { let error = errorWithDetail("Invalid SSL certificate", code: 1) disconnectStream(error) return } } } if eventCode == .HasBytesAvailable { if aStream == inputStream { processInputStream() } } else if eventCode == .ErrorOccurred { disconnectStream(aStream.streamError) } else if eventCode == .EndEncountered { disconnectStream(nil) } } //disconnect the stream object private func disconnectStream(error: NSError?) { writeQueue.waitUntilAllOperationsAreFinished() cleanupStream() doDisconnect(error) } private func cleanupStream() { outputStream?.delegate = nil inputStream?.delegate = nil if let stream = inputStream { CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } outputStream = nil inputStream = nil } ///handles the incoming bytes and sending them to the proper processing method private func processInputStream() { let buf = NSMutableData(capacity: BUFFER_MAX) let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes) let length = inputStream!.read(buffer, maxLength: BUFFER_MAX) guard length > 0 else { return } var process = false if inputQueue.count == 0 { process = true } inputQueue.append(NSData(bytes: buffer, length: length)) if process { dequeueInput() } } ///dequeue the incoming input so it is processed in order private func dequeueInput() { guard !inputQueue.isEmpty else { return } let data = inputQueue[0] var work = data if let fragBuffer = fragBuffer { let combine = NSMutableData(data: fragBuffer) combine.appendData(data) work = combine self.fragBuffer = nil } let buffer = UnsafePointer<UInt8>(work.bytes) let length = work.length if !connected { processTCPHandshake(buffer, bufferLen: length) } else { processRawMessage(buffer, bufferLen: length) } inputQueue = inputQueue.filter{$0 != data} dequeueInput() } //handle checking the inital connection status private func processTCPHandshake(buffer: UnsafePointer<UInt8>, bufferLen: Int) { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: connected = true guard canDispatch else {return} dispatch_async(queue) { [weak self] in guard let s = self else { return } s.onConnect?() s.delegate?.websocketDidConnect(s) } case -1: fragBuffer = NSData(bytes: buffer, length: bufferLen) break //do nothing, we are going to collect more data default: doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code))) } } ///Finds the HTTP Packet in the TCP stream, by looking for the CRLF. private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for i in 0..<bufferLen { if buffer[i] == CRLFBytes[k] { k++ if k == 3 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { let code = validateResponse(buffer, bufferLen: totalSize) if code != 0 { return code } totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessage((buffer+totalSize),bufferLen: restSize) } return 0 //success } return -1 //was unable to find the full TCP header } ///validates the HTTP is a 101 as per the RFC spec private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() CFHTTPMessageAppendBytes(response, buffer, bufferLen) let code = CFHTTPMessageGetResponseStatusCode(response) if code != 101 { return code } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let headers = cfHeaders.takeRetainedValue() as NSDictionary if let acceptKey = headers[headerWSAcceptName] as? NSString { if acceptKey.length > 0 { return 0 } } } return -1 } ///read a 16 bit big endian value from a buffer private static func readUint16(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 { return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) } ///read a 64 bit big endian value from a buffer private static func readUint64(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(buffer[offset + i]) } return value } ///write a 16 bit big endian value to a buffer private static func writeUint16(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) { buffer[offset + 0] = UInt8(value >> 8) buffer[offset + 1] = UInt8(value & 0xff) } ///write a 64 bit big endian value to a buffer private static func writeUint64(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } ///process the websocket data private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) { let response = readStack.last if response != nil && bufferLen < 2 { fragBuffer = NSData(bytes: buffer, length: bufferLen) return } if let response = response where response.bytesLeft > 0 { var len = response.bytesLeft var extra = bufferLen - response.bytesLeft if response.bytesLeft > bufferLen { len = bufferLen extra = 0 } response.bytesLeft -= len response.buffer?.appendData(NSData(bytes: buffer, length: len)) processResponse(response) let offset = bufferLen - extra if extra > 0 { processExtra((buffer+offset), bufferLen: extra) } return } else { let isFin = (FinMask & buffer[0]) let receivedOpcode = OpCode(rawValue: (OpCodeMask & buffer[0])) let isMasked = (MaskMask & buffer[1]) let payloadLen = (PayloadLenMask & buffer[1]) var offset = 2 if (isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != .Pong { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode)) writeError(errCode) return } let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping) if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame && receivedOpcode != .TextFrame && receivedOpcode != .Pong) { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)) writeError(errCode) return } if isControlFrame && isFin == 0 { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode)) writeError(errCode) return } if receivedOpcode == .ConnectionClose { var code = CloseCode.Normal.rawValue if payloadLen == 1 { code = CloseCode.ProtocolError.rawValue } else if payloadLen > 1 { code = WebSocket.readUint16(buffer, offset: offset) if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) { code = CloseCode.ProtocolError.rawValue } offset += 2 } if payloadLen > 2 { let len = Int(payloadLen-2) if len > 0 { let bytes = UnsafePointer<UInt8>((buffer+offset)) let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding) if str == nil { code = CloseCode.ProtocolError.rawValue } } } doDisconnect(errorWithDetail("connection closed by server", code: code)) writeError(code) return } if isControlFrame && payloadLen > 125 { writeError(CloseCode.ProtocolError.rawValue) return } var dataLength = UInt64(payloadLen) if dataLength == 127 { dataLength = WebSocket.readUint64(buffer, offset: offset) offset += sizeof(UInt64) } else if dataLength == 126 { dataLength = UInt64(WebSocket.readUint16(buffer, offset: offset)) offset += sizeof(UInt16) } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = NSData(bytes: buffer, length: bufferLen) return } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } var data: NSData! if len < 0 { len = 0 data = NSData() } else { data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len)) } if receivedOpcode == .Pong { if canDispatch { dispatch_async(queue) { [weak self] in guard let s = self else { return } s.onPong?() s.pongDelegate?.websocketDidReceivePong(s) } } let step = Int(offset+numericCast(len)) let extra = bufferLen-step if extra > 0 { processRawMessage((buffer+step), bufferLen: extra) } return } var response = readStack.last if isControlFrame { response = nil //don't append pings } if isFin == 0 && receivedOpcode == .ContinueFrame && response == nil { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode)) writeError(errCode) return } var isNew = false if response == nil { if receivedOpcode == .ContinueFrame { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("first frame can't be a continue frame", code: errCode)) writeError(errCode) return } isNew = true response = WSResponse() response!.code = receivedOpcode! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == .ContinueFrame { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame", code: errCode)) writeError(errCode) return } response!.buffer!.appendData(data) } if let response = response { response.bytesLeft -= Int(len) response.frameCount++ response.isFin = isFin > 0 ? true : false if isNew { readStack.append(response) } processResponse(response) } let step = Int(offset+numericCast(len)) let extra = bufferLen-step if extra > 0 { processExtra((buffer+step), bufferLen: extra) } } } ///process the extra of a buffer private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) { if bufferLen < 2 { fragBuffer = NSData(bytes: buffer, length: bufferLen) } else { processRawMessage(buffer, bufferLen: bufferLen) } } ///process the finished response of a buffer private func processResponse(response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .Ping { let data = response.buffer! //local copy so it is perverse for writing dequeueWrite(data, code: OpCode.Pong) } else if response.code == .TextFrame { let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding) if str == nil { writeError(CloseCode.Encoding.rawValue) return false } if canDispatch { dispatch_async(queue) { [weak self] in guard let s = self else { return } s.onText?(str! as String) s.delegate?.websocketDidReceiveMessage(s, text: str! as String) } } } else if response.code == .BinaryFrame { if canDispatch { let data = response.buffer! //local copy so it is perverse for writing dispatch_async(queue) { [weak self] in guard let s = self else { return } s.onData?(data) s.delegate?.websocketDidReceiveData(s, data: data) } } } readStack.removeLast() return true } return false } ///Create an error private func errorWithDetail(detail: String, code: UInt16) -> NSError { var details = [String: String]() details[NSLocalizedDescriptionKey] = detail return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details) } ///write a an error to the socket private func writeError(code: UInt16) { let buf = NSMutableData(capacity: sizeof(UInt16)) let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes) WebSocket.writeUint16(buffer, offset: 0, value: code) dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose) } ///used to write things to the stream private func dequeueWrite(data: NSData, code: OpCode) { writeQueue.addOperationWithBlock { [weak self] in //stream isn't ready, let's wait guard let s = self else { return } var offset = 2 let bytes = UnsafeMutablePointer<UInt8>(data.bytes) let dataLength = data.length let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize) let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes) buffer[0] = s.FinMask | code.rawValue if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) offset += sizeof(UInt16) } else { buffer[1] = 127 WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) offset += sizeof(UInt64) } buffer[1] |= s.MaskMask let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey) offset += sizeof(UInt32) for i in 0..<dataLength { buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)] offset += 1 } var total = 0 while true { guard let outStream = s.outputStream else { break } let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total) let len = outStream.write(writeBuffer, maxLength: offset-total) if len < 0 { var error: NSError? if let streamError = outStream.streamError { error = streamError } else { let errCode = InternalErrorCode.OutputStreamWriteError.rawValue error = s.errorWithDetail("output stream error during write", code: errCode) } s.doDisconnect(error) break } else { total += len } if total >= offset { break } } } } ///used to preform the disconnect delegate private func doDisconnect(error: NSError?) { guard !didDisconnect else { return } didDisconnect = true connected = false guard canDispatch else {return} dispatch_async(queue) { [weak self] in guard let s = self else { return } s.onDisconnect?(error) s.delegate?.websocketDidDisconnect(s, error: error) } } deinit { mutex.lock() readyToWrite = false mutex.unlock() cleanupStream() } } private class SSLCert { var certData: NSData? var key: SecKeyRef? /** Designated init for certificates - parameter data: is the binary data of the certificate - returns: a representation security object to be used with */ init(data: NSData) { self.certData = data } /** Designated init for public keys - parameter key: is the public key to be used - returns: a representation security object to be used with */ init(key: SecKeyRef) { self.key = key } } private class SSLSecurity { var validatedDN = true //should the domain name be validated? var isReady = false //is the key processing done? var certificates: [NSData]? //the certificates var pubKeys: [SecKeyRef]? //the public keys var usePublicKeys = false //use public keys or certificate validation? /** Use certs from main app bundle - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ convenience init(usePublicKeys: Bool = false) { let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".") let certs = paths.reduce([SSLCert]()) { (var certs: [SSLCert], path: String) -> [SSLCert] in if let data = NSData(contentsOfFile: path) { certs.append(SSLCert(data: data)) } return certs } self.init(certs: certs, usePublicKeys: usePublicKeys) } /** Designated init - parameter keys: is the certificates or public keys to use - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ init(certs: [SSLCert], usePublicKeys: Bool) { self.usePublicKeys = usePublicKeys if self.usePublicKeys { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) { let pubKeys = certs.reduce([SecKeyRef]()) { (var pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in if let data = cert.certData where cert.key == nil { cert.key = self.extractPublicKey(data) } if let key = cert.key { pubKeys.append(key) } return pubKeys } self.pubKeys = pubKeys self.isReady = true } } else { let certificates = certs.reduce([NSData]()) { (var certificates: [NSData], cert: SSLCert) -> [NSData] in if let data = cert.certData { certificates.append(data) } return certificates } self.certificates = certificates self.isReady = true } } /** Valid the trust and domain name. - parameter trust: is the serverTrust to validate - parameter domain: is the CN domain to validate - returns: if the key was successfully validated */ func isValid(trust: SecTrustRef, domain: String?) -> Bool { var tries = 0 while(!self.isReady) { usleep(1000) tries += 1 if tries > 5 { return false //doesn't appear it is going to ever be ready... } } var policy: SecPolicyRef if self.validatedDN { policy = SecPolicyCreateSSL(true, domain) } else { policy = SecPolicyCreateBasicX509() } SecTrustSetPolicies(trust,policy) if self.usePublicKeys { if let keys = self.pubKeys { let serverPubKeys = publicKeyChainForTrust(trust) for serverKey in serverPubKeys as [AnyObject] { for key in keys as [AnyObject] { if serverKey.isEqual(key) { return true } } } } } else if let certs = self.certificates { let serverCerts = certificateChainForTrust(trust) var collect = [SecCertificate]() for cert in certs { collect.append(SecCertificateCreateWithData(nil,cert)!) } SecTrustSetAnchorCertificates(trust,collect) var result: SecTrustResultType = 0 SecTrustEvaluate(trust,&result) let r = Int(result) if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed { var trustedCount = 0 for serverCert in serverCerts { for cert in certs { if cert == serverCert { trustedCount++ break } } } if trustedCount == serverCerts.count { return true } } } return false } /** Get the public key from a certificate data - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKey(data: NSData) -> SecKeyRef? { guard let cert = SecCertificateCreateWithData(nil, data) else { return nil } return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509()) } /** Get the public key from a certificate - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? { var possibleTrust: SecTrust? SecTrustCreateWithCertificates(cert, policy, &possibleTrust) guard let trust = possibleTrust else { return nil } var result: SecTrustResultType = 0 SecTrustEvaluate(trust, &result) return SecTrustCopyPublicKey(trust) } /** Get the certificate chain for the trust - parameter trust: is the trust to lookup the certificate chain for - returns: the certificate chain for the trust */ func certificateChainForTrust(trust: SecTrustRef) -> [NSData] { let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (var certificates: [NSData], index: Int) -> [NSData] in let cert = SecTrustGetCertificateAtIndex(trust, index) certificates.append(SecCertificateCopyData(cert!)) return certificates } return certificates } /** Get the public key chain for the trust - parameter trust: is the trust to lookup the certificate chain and extract the public keys - returns: the public keys from the certifcate chain for the trust */ func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] { let policy = SecPolicyCreateBasicX509() let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (var keys: [SecKeyRef], index: Int) -> [SecKeyRef] in let cert = SecTrustGetCertificateAtIndex(trust, index) if let key = extractPublicKeyFromCert(cert!, policy: policy) { keys.append(key) } return keys } return keys } }
39.528284
226
0.567551
2055c78f63ededec81a520b3786b470dc06b7bc4
1,990
// // SettingsViewController.swift // TipCal // // Created by Pujita Ravada on 3/9/17. // Copyright © 2017 Pujita Ravada. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var DefaultTipController: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() let defaults = UserDefaults.standard self.DefaultTipController.selectedSegmentIndex = defaults.integer(forKey: "default_Percentage") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // sets the selected segment in memory @IBAction func DefaultTipControllerPressed(_ sender: AnyObject) { if(DefaultTipController.selectedSegmentIndex == 0) { let DefaultTipController = UserDefaults.standard DefaultTipController.set(0, forKey: "default_Percentage") } if(DefaultTipController.selectedSegmentIndex == 1) { let DefaultTipController = UserDefaults.standard DefaultTipController.set(1, forKey : "default_Percentage") } else if(DefaultTipController.selectedSegmentIndex == 2) { let DefaultTipController = UserDefaults.standard DefaultTipController.set(2, forKey: "default_Percentage") } UserDefaults.standard.synchronize() } /* // 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. } */ }
23.975904
106
0.621608
e28bff9aa558eade5f9bb410cb7a7bddfd89cb59
2,612
// // AppDelegate.swift // memoirs // // Created by Alejandro Ravasio on 18/03/2019. // Copyright © 2019 Alejandro Ravasio. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { //Testing Requests. // API.getUser(id: 1, completion: { user in // print(user?.username ?? "nil user") // }) // // API.getAlbums(for: 1, completion: { albums in // albums.forEach { print("Album: \($0.title)") } // }) // // API.getPhotos(for: 1, completion: { photos in // photos.forEach { print("Photo: \($0.title)") } // }) // 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:. } }
42.819672
285
0.707121
fec7f01c81fbefdd5eac13f02de71a05f52176b6
921
// // MotionImageViewTests.swift // MotionImageViewTests // // Created by Cem Olcay on 03/03/15. // Copyright (c) 2015 Cem Olcay. All rights reserved. // import UIKit import XCTest class MotionImageViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.891892
111
0.62215
3939a8059db05efa7b09e7f4ddcf7c429d43e54b
803
/* * Test that we can define new work types and use them for foreign * functions. */ import io; pragma worktypedef a_new_work_type; @dispatch=a_new_work_type (void o) f1(int i) "turbine" "0.0" [ "puts \"f1(<<i>>) ran on $turbine::mode ([ adlb::comm_rank ])\"" ]; // Should not be case-sensitive @dispatch=A_NEW_WORK_TYPE (void o) f2(int i) "turbine" "0.0" [ "puts \"f2(<<i>>) ran on $turbine::mode ([ adlb::comm_rank ])\"" ]; @dispatch=WORKER (void o) f3(int i) "turbine" "0.0" [ "puts \"f3(<<i>>) ran on $turbine::mode ([ adlb::comm_rank ])\"" ]; main () { foreach i in [0:100] { f1(i); f2(i); f3(i); } // Try to trick into running in wrong context f1(-1) => f2(-1) => f3(-1); f3(-2) => f1(-2) => f2(-2); f1(-3) => f3(-3) => f2(-3); }
17.085106
66
0.549191
d7ac2b6d715254dbd3f69fd6687a031e5472dbc2
529
// // ViewController.swift // iosstarter // // Created by Manu Rink on 12.11.17. // Copyright © 2017 byteroyal. All rights reserved. // import UIKit import GameplayKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.346154
80
0.667297
69294e0e378f0980b1f246d7d190f2efd6c56f55
1,052
/* * Copyright 2019, Undefined Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import OpenTelemetryApi @testable import OpenTelemetrySdk struct DistributedContextTestUtil { static func listToDistributedContext(entries: [Entry]) -> DistributedContextSdk { let builder = DistributedContextSdk.contextBuilder() for entry in entries { builder.put(key: entry.key, value: entry.value, metadata: entry.metadata) } return builder.build() as! DistributedContextSdk } }
35.066667
85
0.730989
7ada8d8b10e5757a6bdc7b009a42c9b3a54986a8
8,341
import CoreData import Crashlytics import FirebaseAnalytics import FirebaseAuth import GoogleSignIn import MyTBAKit import Photos import PureLayout import TBAData import TBAKit import UIKit import UserNotifications class MyTBAViewController: ContainerViewController { private let myTBA: MyTBA private let pasteboard: UIPasteboard? private let photoLibrary: PHPhotoLibrary? private let statusService: StatusService private let urlOpener: URLOpener private(set) var signInViewController: MyTBASignInViewController = MyTBASignInViewController() private(set) var favoritesViewController: MyTBATableViewController<Favorite, MyTBAFavorite> private(set) var subscriptionsViewController: MyTBATableViewController<Subscription, MyTBASubscription> private var signInView: UIView! { return signInViewController.view } private lazy var signOutBarButtonItem: UIBarButtonItem = { return UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(logoutTapped)) }() private var signOutActivityIndicatorBarButtonItem = UIBarButtonItem.activityIndicatorBarButtonItem() var isLoggingOut: Bool = false { didSet { DispatchQueue.main.async { self.updateInterface() } } } private var isLoggedIn: Bool { return myTBA.isAuthenticated } init(myTBA: MyTBA, pasteboard: UIPasteboard? = nil, photoLibrary: PHPhotoLibrary? = nil, statusService: StatusService, urlOpener: URLOpener, persistentContainer: NSPersistentContainer, tbaKit: TBAKit, userDefaults: UserDefaults) { self.myTBA = myTBA self.pasteboard = pasteboard self.photoLibrary = photoLibrary self.statusService = statusService self.urlOpener = urlOpener favoritesViewController = MyTBATableViewController<Favorite, MyTBAFavorite>(myTBA: myTBA, persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults) subscriptionsViewController = MyTBATableViewController<Subscription, MyTBASubscription>(myTBA: myTBA, persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults) super.init(viewControllers: [favoritesViewController, subscriptionsViewController], segmentedControlTitles: ["Favorites", "Subscriptions"], persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults) title = "myTBA" tabBarItem.image = UIImage.starIcon favoritesViewController.delegate = self subscriptionsViewController.delegate = self GIDSignIn.sharedInstance()?.presentingViewController = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // TODO: Fix the white status bar/white UINavigationController during sign in // https://github.com/the-blue-alliance/the-blue-alliance-ios/issues/180 // modalPresentationCapturesStatusBarAppearance = true styleInterface() myTBA.authenticationProvider.add(observer: self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Analytics.logEvent("mytba", parameters: nil) } // MARK: - Private Methods private func styleInterface() { addChild(signInViewController) view.addSubview(signInView) for edge in [ALEdge.top, ALEdge.bottom] { signInView.autoPinEdge(toSuperviewSafeArea: edge) } for edge in [ALEdge.leading, ALEdge.trailing] { signInView.autoPinEdge(toSuperviewEdge: edge) } updateInterface() } private func updateInterface() { if isLoggingOut { rightBarButtonItems = [signOutActivityIndicatorBarButtonItem] } else { rightBarButtonItems = isLoggedIn ? [signOutBarButtonItem] : [] } // Disable interaction with our view while logging out view.isUserInteractionEnabled = !isLoggingOut signInView.isHidden = isLoggedIn } private func logout() { let signOutOperation = myTBA.unregister { [weak self] (_, error) in self?.isLoggingOut = false if let error = error as? MyTBAError, error.code != 404 { Crashlytics.sharedInstance().recordError(error) self?.showErrorAlert(with: "Unable to sign out of myTBA - \(error.localizedDescription)") } else { // Run on main thread, since we delete our Core Data objects on the main thread. DispatchQueue.main.async { self?.logoutSuccessful() } } } guard let op = signOutOperation else { return } isLoggingOut = true OperationQueue.main.addOperation(op) } private func logoutSuccessful() { GIDSignIn.sharedInstance().signOut() try! Auth.auth().signOut() // Cancel any ongoing requests for vc in [favoritesViewController, subscriptionsViewController] as! [Refreshable] { vc.cancelRefresh() } // Remove all locally stored myTBA data removeMyTBAData() } func removeMyTBAData() { persistentContainer.viewContext.deleteAllObjectsForEntity(entity: Favorite.entity()) persistentContainer.viewContext.deleteAllObjectsForEntity(entity: Subscription.entity()) // Clear notifications persistentContainer.viewContext.performSaveOrRollback(errorRecorder: Crashlytics.sharedInstance()) } // MARK: - Interface Methods @objc func logoutTapped() { let signOutAlertController = UIAlertController(title: "Log Out?", message: "Are you sure you want to sign out of myTBA?", preferredStyle: .alert) signOutAlertController.addAction(UIAlertAction(title: "Log Out", style: .default, handler: { (_) in self.logout() })) signOutAlertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(signOutAlertController, animated: true, completion: nil) } } extension MyTBAViewController: MyTBATableViewControllerDelegate { func eventSelected(_ event: Event) { let viewController = EventViewController(event: event, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults) let navigationController = UINavigationController(rootViewController: viewController) self.navigationController?.showDetailViewController(navigationController, sender: nil) } func teamSelected(_ team: Team) { let viewController = TeamViewController(team: team, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults) let navigationController = UINavigationController(rootViewController: viewController) self.navigationController?.showDetailViewController(navigationController, sender: nil) } func matchSelected(_ match: Match) { let viewController = MatchViewController(match: match, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults) let navigationController = UINavigationController(rootViewController: viewController) self.navigationController?.showDetailViewController(navigationController, sender: nil) } } extension MyTBAViewController: MyTBAAuthenticationObservable { @objc func authenticated() { if let viewController = currentViewController() { viewController.refresh() } updateInterfaceMain() } @objc func unauthenticated() { updateInterfaceMain() } func updateInterfaceMain() { DispatchQueue.main.async { [weak self] in self?.updateInterface() } } }
38.086758
266
0.699077
7638370945df899c58c18066887a231281e89a74
3,336
import Foundation enum CoinType { case bitcoin case bitcoinCash case dash case ethereum case erc20(address: String, fee: Decimal, gasLimit: Int?, minimumRequiredBalance: Decimal, minimumSpendableAmount: Decimal?) case eos(token: String, symbol: String) case binance(symbol: String) init(erc20Address: String, fee: Decimal = 0, gasLimit: Int? = nil, minimumRequiredBalance: Decimal = 0, minimumSpendableAmount: Decimal? = nil) { self = .erc20(address: erc20Address, fee: fee, gasLimit: gasLimit, minimumRequiredBalance: minimumRequiredBalance, minimumSpendableAmount: minimumSpendableAmount) } func canSupport(accountType: AccountType) -> Bool { switch self { case .bitcoin, .bitcoinCash, .dash, .ethereum, .erc20: if case let .mnemonic(words, salt) = accountType, words.count == 12, salt == nil { return true } return false case .eos: if case .eos = accountType { return true } return false case .binance: if case let .mnemonic(words, salt) = accountType, words.count == 24, salt == nil { return true } return false } } var predefinedAccountType: PredefinedAccountType { switch self { case .bitcoin, .bitcoinCash, .dash, .ethereum, .erc20: return .standard case .eos: return .eos case .binance: return .binance } } var blockchainType: String? { switch self { case .erc20: return "ERC20" case .eos(let token, _): if token != "eosio.token" { return "EOSIO" } case .binance(let symbol): if symbol != "BNB" { return "BEP2" } default: () } return nil } var settings: [CoinSetting] { switch self { case .bitcoin: return [.derivation, .syncMode] case .bitcoinCash: return [.syncMode] case .dash: return [.syncMode] default: return [] } } var restoreUrl: String { switch self { case .bitcoin: return "https://btc.horizontalsystems.xyz/apg" case .bitcoinCash: return "https://blockdozer.com" case .dash: return "https://dash.horizontalsystems.xyz" default: return "" } } } extension CoinType: Equatable { public static func ==(lhs: CoinType, rhs: CoinType) -> Bool { switch (lhs, rhs) { case (.bitcoin, .bitcoin): return true case (.bitcoinCash, .bitcoinCash): return true case (.dash, .dash): return true case (.ethereum, .ethereum): return true case (.erc20(let lhsAddress, let lhsFee, let lhsGasLimit, _, _), .erc20(let rhsAddress, let rhsFee, let rhsGasLimit, _, _)): return lhsAddress == rhsAddress && lhsFee == rhsFee && lhsGasLimit == rhsGasLimit case (.eos(let lhsToken, let lhsSymbol), .eos(let rhsToken, let rhsSymbol)): return lhsToken == rhsToken && lhsSymbol == rhsSymbol case (.binance(let lhsSymbol), .binance(let rhsSymbol)): return lhsSymbol == rhsSymbol default: return false } } } typealias CoinSettings = [CoinSetting: Any] enum CoinSetting { case derivation case syncMode }
32.076923
170
0.594724
5decb358371daca9420eaca491db4b66a10108b0
1,649
// // JZRowHeader.swift // JZCalendarWeekView // // Created by Jeff Zhang on 28/3/18. // Copyright © 2018 Jeff Zhang. All rights reserved. // import UIKit /// Header for each row (every hour) in collectionView (Supplementary View) open class JZRowHeader: UICollectionReusableView { public var lblTime = UILabel() public var dateFormatter = DateFormatter() public override init(frame: CGRect) { super.init(frame: .zero) setupLayout() setupBasic() } private func setupLayout() { self.addSubview(lblTime) // This one is used to support iPhone X Landscape state because of notch status bar // If you want to customise the RowHeader, please keep the similar contraints with this one (vertically center and a value to trailing anchor) // If you want to change rowHeaderWidth and font size, you can change the trailing value to make it horizontally center in normal state, but keep the trailing anchor lblTime.setAnchorCenterVerticallyTo(view: self, trailingAnchor: (self.trailingAnchor, -5)) } open func setupBasic() { // Hide all content when colum header height equals 0 // self.clipsToBounds = true dateFormatter.dateFormat = "HH:mm" lblTime.textColor = JZWeekViewColors.rowHeaderTime lblTime.font = UIFont.systemFont(ofSize: 8) lblTime.textAlignment = .center } public func updateView(date: Date) { lblTime.text = dateFormatter.string(from: date) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
32.98
173
0.682232
bbcec3ccdf25a6e456679beaafad2245050d31c6
181
// // Copyright © 2018 SCENEE. All rights reserved. // import Foundation public class SampleUtils: NSObject { @objc public func sayHello() { print("Hello!") } }
15.083333
49
0.629834
dee60852ece529c287d748e841f1a9cc53196927
2,446
@testable import KsApi @testable import Library import Prelude import ReactiveExtensions_TestHelpers import XCTest final class ErroredBackingViewViewModelTests: TestCase { private let vm: ErroredBackingViewViewModelType = ErroredBackingViewViewModel() private let finalCollectionDateText = TestObserver<String, Never>() private let notifyDelegateManageButtonTapped = TestObserver<ProjectAndBackingEnvelope, Never>() private let projectName = TestObserver<String, Never>() override func setUp() { super.setUp() self.vm.outputs.finalCollectionDateText.observe(self.finalCollectionDateText.observer) self.vm.outputs.notifyDelegateManageButtonTapped.observe(self.notifyDelegateManageButtonTapped.observer) self.vm.outputs.projectName.observe(self.projectName.observer) } func testNotifyDelegateManageButtonTapped_Emits_WhenButtonIsTapped() { let env = ProjectAndBackingEnvelope.template self.vm.inputs.configure(with: env) self.notifyDelegateManageButtonTapped.assertDidNotEmitValue() self.vm.inputs.manageButtonTapped() self.notifyDelegateManageButtonTapped.assertValue(env) } func testErroredBackings() { let date = AppEnvironment.current.calendar.date(byAdding: DateComponents(day: 4), to: MockDate().date) let project = Project.template |> \.name .~ "Awesome tabletop collection" |> \.dates.finalCollectionDate .~ date?.timeIntervalSince1970 let env = ProjectAndBackingEnvelope.template |> \.project .~ project self.projectName.assertDidNotEmitValue() self.finalCollectionDateText.assertDidNotEmitValue() self.vm.inputs.configure(with: env) self.projectName.assertValue("Awesome tabletop collection") self.finalCollectionDateText.assertValue("4 days left") } func testErroredBackings_lessThanAnHour() { let date = AppEnvironment.current.calendar.date(byAdding: DateComponents(minute: 48), to: MockDate().date) let project = Project.template |> \.name .~ "Awesome tabletop collection" |> \.dates.finalCollectionDate .~ date?.timeIntervalSince1970 let env = ProjectAndBackingEnvelope.template |> \.project .~ project self.projectName.assertDidNotEmitValue() self.finalCollectionDateText.assertDidNotEmitValue() self.vm.inputs.configure(with: env) self.projectName.assertValue("Awesome tabletop collection") self.finalCollectionDateText.assertValue("1 hour left") } }
33.972222
110
0.771055
5dfd75b69141c4e7b25029da5e71d50740d7c9e5
288
// // ArtGalleryApp.swift // ArtGallery // // Created by Kim Egenvall on 2021-05-23. // import SwiftUI @main struct ArtGalleryApp: App { private let factory = AppViewFactory() var body: some Scene { WindowGroup { factory.build(.gallery) } } }
15.157895
42
0.604167
23ea4adcce7a5e4d30673f391f3bd9c16965a281
5,676
// // JiroTextField.swift // TextFieldEffects // // Created by Raúl Riera on 24/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit /** A JiroTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the background of the control. */ @IBDesignable open class JiroTextField: TextFieldEffects { /** The color of the border. This property applies a color to the lower edge of the control. The default value for this property is a clear color. */ @IBInspectable open dynamic var borderColor: UIColor? { didSet { updateBorder() } } /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable open dynamic var placeholderColor: UIColor = .black { didSet { updatePlaceholder() } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable open dynamic var placeholderFontScale: CGFloat = 0.65 { didSet { updatePlaceholder() } } override open var placeholder: String? { didSet { updatePlaceholder() } } override open var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: CGFloat = 2 private let placeholderInsets = CGPoint(x: 8, y: 8) private let textFieldInsets = CGPoint(x: 8, y: 12) private let borderLayer = CALayer() // MARK: - TextFieldEffects override open func drawViewsForRect(_ rect: CGRect) { let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = frame.insetBy(dx: placeholderInsets.x, dy: placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateBorder() updatePlaceholder() layer.insertSublayer(borderLayer, at: 0) addSubview(placeholderLabel) } override open func animateViewsForTextEntry() { borderLayer.frame.origin = CGPoint(x: 0, y: font!.lineHeight) UIView.animate(withDuration: 0.2, delay: 0.3, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: .beginFromCurrentState, animations: ({ self.placeholderLabel.frame.origin = CGPoint(x: self.placeholderInsets.x, y: self.borderLayer.frame.origin.y - self.placeholderLabel.bounds.height) self.borderLayer.frame = self.rectForBorder(self.borderThickness, isFilled: true) }), completion: { _ in self.animationCompletionHandler?(.textEntry) }) } override open func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animate(withDuration: 0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .beginFromCurrentState, animations: ({ self.layoutPlaceholderInTextRect() self.placeholderLabel.alpha = 1 }), completion: { _ in self.animationCompletionHandler?(.textDisplay) }) borderLayer.frame = rectForBorder(borderThickness, isFilled: false) } } // MARK: - Private private func updateBorder() { borderLayer.frame = rectForBorder(borderThickness, isFilled: false) borderLayer.backgroundColor = borderColor?.cgColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder || text!.isNotEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(_ font: UIFont) -> UIFont! { let smallerFont = UIFont(descriptor: font.fontDescriptor, size: font.pointSize * placeholderFontScale) return smallerFont } private func rectForBorder(_ thickness: CGFloat, isFilled: Bool) -> CGRect { if isFilled { return CGRect(origin: CGPoint(x: 0, y: placeholderLabel.frame.origin.y + placeholderLabel.font.lineHeight), size: CGSize(width: frame.width, height: frame.height)) } else { return CGRect(origin: CGPoint(x: 0, y: frame.height - thickness), size: CGSize(width: frame.width, height: thickness)) } } private func layoutPlaceholderInTextRect() { if text!.isNotEmpty { return } let textRect = self.textRect(forBounds: bounds) var originX = textRect.origin.x switch textAlignment { case .center: originX += textRect.size.width / 2 - placeholderLabel.bounds.width / 2 case .right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: textRect.size.height / 2, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } // MARK: - Overrides override open func editingRect(forBounds bounds: CGRect) -> CGRect { bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y) } override open func textRect(forBounds bounds: CGRect) -> CGRect { bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y) } }
34.192771
176
0.648696
2841fd367ea84b6ec35923766cd83d7b1d618f12
451
// // Created by 李智慧 on 16/07/2017. // Copyright (c) 2017 李智慧. All rights reserved. // import Foundation import PCCWFoundationSwift import RxCocoa import Moya import Result protocol IBLRootAction: PFSViewAction { } class IBLRootViewModel: PFSViewModel<IBLRootViewController, IBLRootDomain> { var school: IBLSchool? func cachedSchool() -> IBLSchool? { self.school = PFSDomain.cachedSchool() return self.school } }
18.04
76
0.716186
e0a3758089f2d8696e4b11eb63501dd7e43589fd
2,014
import XCTest import AsyncKit final class FutureMiscellaneousTests: XCTestCase { func testGuard() { let future1 = eventLoop.makeSucceededFuture(1) let guardedFuture1 = future1.guard({ $0 == 1 }, else: TestError.notEqualTo1) XCTAssertNoThrow(try guardedFuture1.wait()) let future2 = eventLoop.makeSucceededFuture("foo") let guardedFuture2 = future2.guard({ $0 == "bar" }, else: TestError.notEqualToBar) XCTAssertThrowsError(try guardedFuture2.wait()) } func testTryThrowing() { let future1: EventLoopFuture<String> = eventLoop.tryFuture { return "Hello" } let future2: EventLoopFuture<String> = eventLoop.tryFuture { throw TestError.notEqualTo1 } var value: String = "" try XCTAssertNoThrow(value = future1.wait()) XCTAssertEqual(value, "Hello") try XCTAssertThrowsError(future2.wait()) } func testTryFutureThread() throws { // There is a known bug in Swift 5.2 and earlier that causes this result. // Skip check because it's been resolved in later versions and there's // not a lot we can do about it. #if swift(<5.3) try XCTSkipIf(true, "Thread.current.name is broken in Swift 5.2") #endif let future = self.eventLoop.tryFuture { Thread.current.name } let name = try XCTUnwrap(future.wait()) XCTAssert(name.starts(with: "NIO-ELT"), "'\(name)' is not a valid NIO ELT name") } var group: EventLoopGroup! var eventLoop: EventLoop { self.group.next() } override func setUpWithError() throws { try super.setUpWithError() self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1) } override func tearDownWithError() throws { try self.group.syncShutdownGracefully() self.group = nil try super.tearDownWithError() } override class func setUp() { super.setUp() XCTAssertTrue(isLoggingConfigured) } }
34.724138
98
0.646475
eb5034da675f8cd2062b3535f3c8dd856c15ccf1
1,263
// // TimelineSortOrderView.swift // Multiplatform macOS // // Created by Maurice Parker on 7/12/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import SwiftUI struct TimelineSortOrderView: View { @EnvironmentObject var settings: AppDefaults @State var selection: Int = 1 var body: some View { Menu { Button { settings.timelineSortDirection = true } label: { HStack { Text("Newest to Oldest") if settings.timelineSortDirection { Spacer() AppAssets.checkmarkImage } } } Button { settings.timelineSortDirection = false } label: { HStack { Text("Oldest to Newest") if !settings.timelineSortDirection { Spacer() AppAssets.checkmarkImage } } } Divider() Button { settings.timelineGroupByFeed.toggle() } label: { HStack { Text("Group by Feed") if settings.timelineGroupByFeed { Spacer() AppAssets.checkmarkImage } } } } label : { if settings.timelineSortDirection { Text("Sort Newest to Oldest") } else { Text("Sort Oldest to Newest") } } .font(.subheadline) .frame(width: 150) .padding(.top, 8).padding(.leading) .menuStyle(BorderlessButtonMenuStyle()) } }
19.430769
60
0.633413
33ba8512823405bb251894e301ce91b65eab8e83
712
// // SplashController.swift // FinansCase // // Created by Erdem on 7.03.2022. // import Foundation import UIKit class SplashController: UIViewController { // MARK: - Properties var coordinator: SplashCoordinator? private var viewModel = SplashViewModel() // MARK: - View Elements private lazy var view_ = SplashView(self) // MARK: - Constructor Methods override func loadView() { super.loadView() view = view_ delay(1) { self.coordinator?.coordinateToSearch() } } // MARK: - Custom Methods } // MARK: - Extension / SplashView Protocol extension SplashController: SplashViewProtocol { }
19.243243
50
0.617978
480ded300d6b103076257a0b89f0fad5b9935e62
3,302
// // AppDelegate.swift // Fletch // // Created by Rob Bishop on 7/13/20. // Copyright © 2020 Boring Software. All rights reserved. // import Cocoa import Dispatch import SwiftUI @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! var preferencesWindow: NSWindow! @objc func openPreferencesWindow() { if nil == preferencesWindow { // create once !! let preferencesView = LineChartView().environmentObject(LineChartData(6)) // Create the preferences window and set content preferencesWindow = NSWindow( contentRect: NSRect(x: 20, y: 20, width: 480, height: 300), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) preferencesWindow.center() preferencesWindow.setFrameAutosaveName("Preferences") preferencesWindow.isReleasedWhenClosed = false preferencesWindow.contentView = NSHostingView(rootView: preferencesView) } preferencesWindow.makeKeyAndOrderFront(nil) } func applicationDidFinishLaunching(_ aNotification: Notification) { // Count initial frame let newFrame: NSRect let aspectRatioOfRobsMacbookPro: CGFloat = 2880 / 1800 if let screenFrame = NSScreen.main?.visibleFrame { // We got the screen dimensions, count the frame from them // visibleFrame is the screen size excluding menu bar (on top of the screen) // and dock (by default on bottom) let newWidth = screenFrame.width * 0.85 let newHeight = newWidth / aspectRatioOfRobsMacbookPro let newSize = NSSize(width: newWidth, height: newHeight) let newOrigin = CGPoint(x: screenFrame.origin.x + (screenFrame.width - newSize.width), y: screenFrame.origin.y + (screenFrame.height - newSize.height)) newFrame = NSRect(origin: newOrigin, size: newSize) } else { // We have no clue about scren dimensions, set static size newFrame = NSRect(origin: NSPoint(x: 50, y: 100), size: NSSize(width: 1500, height: 850)) } ArkoniaLayout.SeasonFactorView.bgFrameHeight = newFrame.height ArkoniaLayout.SeasonFactorView.stickGrooveFrameHeight = newFrame.height // Create the SwiftUI view that provides the window contents. let contentView = ContentView() .frame(width: newFrame.width, height: newFrame.height) .environmentObject(AKRandomNumberFakerator.shared) // Create the window and set the content view. window = NSWindow( contentRect: newFrame, styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false ) window.center() window.title = "Arkonia" window.setFrameAutosaveName("Arkonia") window.contentView = NSHostingView(rootView: contentView) window.makeKeyAndOrderFront(nil) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
40.765432
101
0.647789
f8bbdd3f1946a566ceae84e392775f6064492449
6,685
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest @testable import Amplify @testable import AmplifyTestCommon class DefaultHubPluginTests: XCTestCase { var plugin: HubCategoryPlugin { guard let plugin = try? Amplify.Hub.getPlugin(for: "awsHubPlugin"), plugin.key == "awsHubPlugin" else { fatalError("Could not access AWSHubPlugin") } return plugin } override func setUp() { Amplify.reset() // This test suite will have a lot of in-flight messages at the time of the `reset`. Give them time to finis // being delivered before moving to the next step. Thread.sleep(forTimeInterval: 1.0) let config = AmplifyConfiguration() do { try Amplify.configure(config) } catch { XCTFail("Error setting up Amplify: \(error)") } } override func tearDown() { Amplify.reset() } /// Given: An Amplify system configured with default values /// When: I invoke Amplify.configure() /// Then: I have access to the framework-provided Hub plugin func testDefaultPluginAssigned() throws { let plugin = try? Amplify.Hub.getPlugin(for: "awsHubPlugin") XCTAssertNotNil(plugin) XCTAssertEqual(plugin?.key, "awsHubPlugin") } /// Given: The default Hub plugin /// When: I invoke listen() /// Then: I receive an unsubscription token func testDefaultPluginListen() throws { let unsubscribe = plugin.listen(to: .storage, isIncluded: nil) { _ in } XCTAssertNotNil(unsubscribe) } /// Given: The default Hub plugin /// When: I invoke listen(to:eventName:) /// Then: I receive messages with that event name func testDefaultPluginListenEventName() throws { let expectedMessageReceived = expectation(description: "Message was received as expected") let unsubscribeToken = plugin.listen(to: .storage, eventName: "TEST_EVENT") { _ in expectedMessageReceived.fulfill() } guard try HubListenerTestUtilities.waitForListener(with: unsubscribeToken, plugin: plugin, timeout: 0.5) else { XCTFail("Token with \(unsubscribeToken.id) was not registered") return } plugin.dispatch(to: .storage, payload: HubPayload(eventName: "TEST_EVENT")) wait(for: [expectedMessageReceived], timeout: 0.5) } /// Given: The default Hub plugin with a registered listener /// When: I dispatch a message /// Then: My listener is invoked with the message func testDefaultPluginDispatches() throws { let messageReceived = expectation(description: "Message was received") // We have other tests for multiple message delivery, and since Amplify.reset() is known to leave in-process // messages going, we'll let this test's expectation pass as long as it fulfills at least once messageReceived.assertForOverFulfill = false let token = plugin.listen(to: .storage, isIncluded: nil) { _ in messageReceived.fulfill() } guard try HubListenerTestUtilities.waitForListener(with: token, plugin: plugin, timeout: 0.5) else { XCTFail("Token with \(token.id) was not registered") return } plugin.dispatch(to: .storage, payload: HubPayload(eventName: "TEST_EVENT")) waitForExpectations(timeout: 0.5) } /// Given: A subscription token from a previous call to the default Hub plugin's `listen` method /// When: I invoke removeListener() /// Then: My listener is removed, and I receive no more events func testDefaultPluginRemoveListener() throws { let expectedMessageReceived = expectation(description: "Message was received as expected") let unexpectedMessageReceived = expectation(description: "Message was received after removing listener") unexpectedMessageReceived.isInverted = true var isStillRegistered = true let unsubscribeToken = plugin.listen(to: .storage, isIncluded: nil) { hubPayload in if isStillRegistered { // Ignore system-generated notifications (e.g., "configuration finished"). After we `removeListener` // though, we don't expect to receive any message, so we only check for the message name if we haven't // yet unsubscribed. guard hubPayload.eventName == "TEST_EVENT" else { return } expectedMessageReceived.fulfill() } else { unexpectedMessageReceived.fulfill() } } guard try HubListenerTestUtilities.waitForListener(with: unsubscribeToken, plugin: plugin, timeout: 0.5) else { XCTFail("Token with \(unsubscribeToken.id) was not registered") return } plugin.dispatch(to: .storage, payload: HubPayload(eventName: "TEST_EVENT")) wait(for: [expectedMessageReceived], timeout: 0.5) plugin.removeListener(unsubscribeToken) isStillRegistered = try HubListenerTestUtilities.waitForListener(with: unsubscribeToken, plugin: plugin, timeout: 0.5) XCTAssertFalse(isStillRegistered, "Should not be registered after removeListener") plugin.dispatch(to: .storage, payload: HubPayload(eventName: "TEST_EVENT")) wait(for: [unexpectedMessageReceived], timeout: 0.5) } /// Given: The default Hub plugin /// When: I invoke listen() for a specified channel and subsequently dispatch a message to a different channel /// Then: My listener is not invoked func testMessagesAreDeliveredOnlyToSpecifiedChannel() { let messageShouldNotBeReceived = expectation(description: "Message should not be received") messageShouldNotBeReceived.isInverted = true _ = plugin.listen(to: .storage, isIncluded: nil) { hubPayload in // Ignore system-generated notifications (e.g., "configuration finished") guard hubPayload.eventName == "TEST_EVENT" else { return } messageShouldNotBeReceived.fulfill() } plugin.dispatch(to: .custom("DifferentChannel"), payload: HubPayload(eventName: "TEST_EVENT")) waitForExpectations(timeout: 0.5) } }
41.78125
119
0.632012
d5fe0e200cc7c8b2ccf3de8f22c4474811d7c96b
1,791
// // Copyright (c) 2018 KxCoding <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /*: # Replacing Substrings */ var str = "Hello, Objective-C" if let range = str.range(of: "Objective-C"){ str.replaceSubrange(range, with: "Swift") } // 범위를 먼저 받아오고 그 다음에 대치하는 것임 str if let range = str.range(of: "Hello"){ let s = str.replacingCharacters(in: range, with: "Hi") // ing 가 있는 메소드는 원본을 변경하지 않고 작업을 진행한다. print(s) str } var s = str.replacingOccurrences(of: "swift", with: "Awesome Swift") // 만약에 of 에 해당하는 것을 찾지 못한다면 그냥 그 값을 리턴해 버림 s = str.replacingOccurrences(of: "swift", with: "Awesome Swift", options: [.caseInsensitive]) // 이 옵션을 추가하게 되면 대소문자를 구분하지 않고 검색을 하게 된다. //: [Next](@next)
36.55102
93
0.717476
2fafb930146f5fc473c4014d16181d52e1393276
618
// // SubjectModel.swift // TiwallSwiftSDK // // Created by PFOREX on 1/8/18. // import Foundation public class SubjectModel{ public var id : Int? public var urn : String? public var parent_id : Int? static func parse(rawJson: Dictionary<String,Any>)->SubjectModel{ let model = SubjectModel() if let temp = rawJson["id"] as? Int{ model.id = temp } if let temp = rawJson["urn"] as? String{ model.urn = temp } if let temp = rawJson["parent_id"] as? Int{ model.parent_id = temp } return model } }
22.888889
69
0.564725
1438b8556039a42887177b894eea34afb59c04ad
4,556
//// // 🦠 Corona-Warn-App // import UIKit import OpenCombine class CheckinCellModel: EventCellModel { // MARK: - Init init( checkin: Checkin, eventProvider: EventProviding, onUpdate: @escaping () -> Void ) { self.checkin = checkin self.onUpdate = onUpdate updateForActiveState() scheduleUpdateTimer() } // MARK: - Internal var checkin: Checkin var isInactiveIconHiddenPublisher = CurrentValueSubject<Bool, Never>(true) var isActiveContainerViewHiddenPublisher = CurrentValueSubject<Bool, Never>(true) var isButtonHiddenPublisher = CurrentValueSubject<Bool, Never>(true) var durationPublisher = CurrentValueSubject<String?, Never>(nil) var timePublisher = CurrentValueSubject<String?, Never>(nil) var isActiveIconHidden: Bool = true var isDurationStackViewHidden: Bool = false var date: String? { DateFormatter.localizedString(from: checkin.checkinStartDate, dateStyle: .short, timeStyle: .none) } var title: String { checkin.traceLocationDescription } var address: String { checkin.traceLocationAddress } var buttonTitle: String = AppStrings.Checkins.Overview.checkoutButtonTitle func update(with checkin: Checkin) { guard checkin != self.checkin else { return } self.checkin = checkin updateForActiveState() onUpdate() } // MARK: - Private private let onUpdate: () -> Void private var subscriptions = Set<AnyCancellable>() private var updateTimer: Timer? private func updateForActiveState() { isInactiveIconHiddenPublisher.value = !checkin.checkinCompleted isActiveContainerViewHiddenPublisher.value = checkin.checkinCompleted isButtonHiddenPublisher.value = checkin.checkinCompleted if checkin.checkinCompleted { let dateFormatter = DateIntervalFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short timePublisher.value = dateFormatter.string(from: checkin.checkinStartDate, to: checkin.checkinEndDate) } else { let formattedCheckinTime = DateFormatter.localizedString(from: checkin.checkinStartDate, dateStyle: .none, timeStyle: .short) let dateComponentsFormatter = DateComponentsFormatter() dateComponentsFormatter.allowedUnits = [.hour, .minute] dateComponentsFormatter.unitsStyle = .short if let formattedAutomaticCheckoutDuration = dateComponentsFormatter.string(from: checkin.checkinEndDate.timeIntervalSince(checkin.checkinStartDate)) { timePublisher.value = String(format: AppStrings.Checkins.Overview.checkinTimeTemplate, formattedCheckinTime, formattedAutomaticCheckoutDuration) } else { timePublisher.value = formattedCheckinTime } } let duration = Date().timeIntervalSince(checkin.checkinStartDate) let dateComponentsFormatter = DateComponentsFormatter() dateComponentsFormatter.allowedUnits = [.hour, .minute] dateComponentsFormatter.unitsStyle = .positional dateComponentsFormatter.zeroFormattingBehavior = .pad durationPublisher.value = dateComponentsFormatter.string(from: duration) } private func scheduleUpdateTimer() { updateTimer?.invalidate() NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) guard !checkin.checkinCompleted else { return } // Schedule new timer. NotificationCenter.default.addObserver(self, selector: #selector(invalidateUpdatedTimer), name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(refreshUpdateTimerAfterResumingFromBackground), name: UIApplication.didBecomeActiveNotification, object: nil) let now = Date() let currentSeconds = Calendar.current.component(.second, from: now) let checkinSeconds = Calendar.current.component(.second, from: checkin.checkinStartDate) let timeToNextCheckinSeconds = (60 - (currentSeconds - checkinSeconds)) % 60 let firstFireDate = now.addingTimeInterval(TimeInterval(timeToNextCheckinSeconds)) updateTimer = Timer(fireAt: firstFireDate, interval: 60, target: self, selector: #selector(updateFromTimer), userInfo: nil, repeats: true) guard let updateTimer = updateTimer else { return } RunLoop.current.add(updateTimer, forMode: .common) } @objc private func invalidateUpdatedTimer() { updateTimer?.invalidate() } @objc private func refreshUpdateTimerAfterResumingFromBackground() { scheduleUpdateTimer() } @objc private func updateFromTimer() { updateForActiveState() onUpdate() } }
31.42069
176
0.782704
14a4deea2b77aa3bde12e4c50f99ae491c4c438a
712
// // Annotation.swift // Callisto // // Created by Patrick Kladek on 08.08.19. // Copyright © 2019 IdeasOnCanvas. All rights reserved. // import Foundation struct Annotation: Codable { enum Level: String, Codable { case notice case warning case failure } let path: String let startLine: Int let endLine: Int let level: Level let message: String let title: String? let details: String? enum CodingKeys: String, CodingKey { case path case startLine = "start_line" case endLine = "end_line" case level = "annotation_level" case message case title case details = "raw_details" } }
18.736842
56
0.610955
f587e0b2dd5a6849547678695643c40b240d7a09
11,499
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import DSWaveformImage enum VoiceMessageAttachmentCacheManagerError: Error { case invalidEventId case invalidAttachmentType case decryptionError(Error) case preparationError(Error) case conversionError(Error) case invalidNumberOfSamples case samplingError } /** Swift optimizes the callbacks to be the same instance. Wrap them so we can store them in an array. */ private class CompletionWrapper { let completion: (Result<VoiceMessageAttachmentCacheManagerLoadResult, Error>) -> Void init(_ completion: @escaping (Result<VoiceMessageAttachmentCacheManagerLoadResult, Error>) -> Void) { self.completion = completion } } private struct CompletionCallbackKey: Hashable { let eventIdentifier: String let requiredNumberOfSamples: Int } struct VoiceMessageAttachmentCacheManagerLoadResult { let eventIdentifier: String let url: URL let duration: TimeInterval let samples: [Float] } class VoiceMessageAttachmentCacheManager { static let sharedManager = VoiceMessageAttachmentCacheManager() private var completionCallbacks = [CompletionCallbackKey: [CompletionWrapper]]() private var samples = [String: [Int: [Float]]]() private var durations = [String: TimeInterval]() private var finalURLs = [String: URL]() private let workQueue: DispatchQueue private init() { workQueue = DispatchQueue(label: "io.element.VoiceMessageAttachmentCacheManager.queue", qos: .userInitiated) } func loadAttachment(_ attachment: MXKAttachment, numberOfSamples: Int, completion: @escaping (Result<VoiceMessageAttachmentCacheManagerLoadResult, Error>) -> Void) { guard attachment.type == MXKAttachmentTypeVoiceMessage else { completion(Result.failure(VoiceMessageAttachmentCacheManagerError.invalidAttachmentType)) return } guard let identifier = attachment.eventId else { completion(Result.failure(VoiceMessageAttachmentCacheManagerError.invalidEventId)) return } guard numberOfSamples > 0 else { completion(Result.failure(VoiceMessageAttachmentCacheManagerError.invalidNumberOfSamples)) return } workQueue.async { // Run this in the work queue to preserve order if let finalURL = self.finalURLs[identifier], let duration = self.durations[identifier], let samples = self.samples[identifier]?[numberOfSamples] { MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished task - using cached results") let result = VoiceMessageAttachmentCacheManagerLoadResult(eventIdentifier: identifier, url: finalURL, duration: duration, samples: samples) DispatchQueue.main.async { completion(Result.success(result)) } return } self.enqueueLoadAttachment(attachment, identifier: identifier, numberOfSamples: numberOfSamples, completion: completion) } } private func enqueueLoadAttachment(_ attachment: MXKAttachment, identifier: String, numberOfSamples: Int, completion: @escaping (Result<VoiceMessageAttachmentCacheManagerLoadResult, Error>) -> Void) { MXLog.debug("[VoiceMessageAttachmentCacheManager] Started task") let callbackKey = CompletionCallbackKey(eventIdentifier: identifier, requiredNumberOfSamples: numberOfSamples) if var callbacks = completionCallbacks[callbackKey] { MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished task - cached completion callback") callbacks.append(CompletionWrapper(completion)) completionCallbacks[callbackKey] = callbacks return } else { completionCallbacks[callbackKey] = [CompletionWrapper(completion)] } if let finalURL = finalURLs[identifier], let duration = durations[identifier] { sampleFileAtURL(finalURL, duration: duration, numberOfSamples: numberOfSamples, identifier: identifier) return } DispatchQueue.main.async { // These don't behave accordingly if called from a background thread if attachment.isEncrypted { attachment.decrypt(toTempFile: { filePath in self.workQueue.async { self.convertFileAtPath(filePath, numberOfSamples: numberOfSamples, identifier: identifier) } }, failure: { error in // A nil error in this case is a cancellation on the MXMediaLoader if let error = error { MXLog.error("Failed decrypting attachment with error: \(String(describing: error))") self.invokeFailureCallbacksForIdentifier(identifier, error: VoiceMessageAttachmentCacheManagerError.decryptionError(error)) } }) } else { attachment.prepare({ self.workQueue.async { self.convertFileAtPath(attachment.cacheFilePath, numberOfSamples: numberOfSamples, identifier: identifier) } }, failure: { error in // A nil error in this case is a cancellation on the MXMediaLoader if let error = error { MXLog.error("Failed preparing attachment with error: \(String(describing: error))") self.invokeFailureCallbacksForIdentifier(identifier, error: VoiceMessageAttachmentCacheManagerError.preparationError(error)) } }) } } } private func convertFileAtPath(_ path: String?, numberOfSamples: Int, identifier: String) { guard let filePath = path else { return } let temporaryDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let newURL = temporaryDirectoryURL.appendingPathComponent(ProcessInfo().globallyUniqueString).appendingPathExtension("m4a") VoiceMessageAudioConverter.convertToMPEG4AAC(sourceURL: URL(fileURLWithPath: filePath), destinationURL: newURL) { result in MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished converting voice message") self.workQueue.async { switch result { case .success: self.finalURLs[identifier] = newURL VoiceMessageAudioConverter.mediaDurationAt(newURL) { result in self.workQueue.async { MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished retrieving media duration") switch result { case .success: if let duration = try? result.get() { self.durations[identifier] = duration self.sampleFileAtURL(newURL, duration: duration, numberOfSamples: numberOfSamples, identifier: identifier) } else { MXLog.error("[VoiceMessageAttachmentCacheManager] Failed retrieving media duration") } case .failure(let error): MXLog.error("[VoiceMessageAttachmentCacheManager] Failed retrieving audio duration with error: \(error)") } } } case .failure(let error): MXLog.error("[VoiceMessageAttachmentCacheManager] Failed decoding audio message with error: \(error)") self.invokeFailureCallbacksForIdentifier(identifier, error: VoiceMessageAttachmentCacheManagerError.conversionError(error)) } } } } private func sampleFileAtURL(_ url: URL, duration: TimeInterval, numberOfSamples: Int, identifier: String) { let analyser = WaveformAnalyzer(audioAssetURL: url) analyser?.samples(count: numberOfSamples, completionHandler: { samples in self.workQueue.async { guard let samples = samples else { MXLog.debug("[VoiceMessageAttachmentCacheManager] Failed sampling voice message") self.invokeFailureCallbacksForIdentifier(identifier, error: VoiceMessageAttachmentCacheManagerError.samplingError) return } MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished sampling voice message") if var existingSamples = self.samples[identifier] { existingSamples[numberOfSamples] = samples self.samples[identifier] = existingSamples } else { self.samples[identifier] = [numberOfSamples: samples] } self.invokeSuccessCallbacksForIdentifier(identifier, url: url, duration: duration, samples: samples) } }) } private func invokeSuccessCallbacksForIdentifier(_ identifier: String, url: URL, duration: TimeInterval, samples: [Float]) { let callbackKey = CompletionCallbackKey(eventIdentifier: identifier, requiredNumberOfSamples: samples.count) guard let callbacks = completionCallbacks[callbackKey] else { return } let result = VoiceMessageAttachmentCacheManagerLoadResult(eventIdentifier: identifier, url: url, duration: duration, samples: samples) let copy = callbacks.map { $0 } DispatchQueue.main.async { for wrapper in copy { wrapper.completion(Result.success(result)) } } self.completionCallbacks[callbackKey] = nil MXLog.debug("[VoiceMessageAttachmentCacheManager] Successfully finished task") } private func invokeFailureCallbacksForIdentifier(_ identifier: String, error: Error) { let callbackKey = CompletionCallbackKey(eventIdentifier: identifier, requiredNumberOfSamples: samples.count) guard let callbacks = completionCallbacks[callbackKey] else { return } let copy = callbacks.map { $0 } DispatchQueue.main.async { for wrapper in copy { wrapper.completion(Result.failure(error)) } } self.completionCallbacks[callbackKey] = nil MXLog.debug("[VoiceMessageAttachmentCacheManager] Failed task with error: \(error)") } }
45.630952
204
0.628576
f5e600f1e01994c4385b55291cc24c19bb9d0dbc
821
// // tip_calculatorUITestsLaunchTests.swift // tip calculatorUITests // // Created by Leonardo Langgeng on 2/4/22. // import XCTest class tip_calculatorUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
24.878788
88
0.680877
725552495b8af8b4b13ca81e40083900842c9661
607
// // AnchorGroupModel.swift // DouYuWL // // Created by dinpay on 2017/7/24. // Copyright © 2017年 apple. All rights reserved. // import UIKit class AnchorGroupModel : BaseGameModel { // 1.改组中房间对应的信息 var room_list : [[String : NSObject]]? { didSet { guard let room_list = room_list else { return } for dict in room_list { anchors.append(AnchorModel(dict:dict)) } } } // 2.组显示的图标 var icon_name : String = "home_header_normal" // 3.定义主播的模型对象数组 lazy var anchors : [AnchorModel] = [AnchorModel]() }
21.678571
59
0.581549
879805c0738ec3883949497e321b4de30c8cf282
1,759
// // TextInputCellProtocol.swift // Clark // // Created by Vladislav Zagorodnyuk on 8/2/17. // Copyright © 2017 Clark. All rights reserved. // import UIKit import Foundation protocol TextInputCellProtocol { /// Title label var titleLabel: UILabel { get set } /// Text field var textField: UITextField { get set } } extension TextInputCellProtocol where Self: UICollectionViewCell { /// Generate title label func generateTitleLabel()-> UILabel { let label = UILabel() label.numberOfLines = 1 label.font = UIFont.defaultFont() label.textAlignment = .left return label } /// Generate form input func generateTextInput(placeholder: String)-> UITextField { let input = UITextField() input.textAlignment = .left input.font = UIFont.defaultFont(size: 18) input.placeholder = placeholder return input } /// Layout func textInputLayout() { /// Title label addSubview(titleLabel) /// Form input addSubview(textField) /// Title label layout titleLabel.snp.updateConstraints { maker in maker.left.equalTo(self).offset(24) maker.right.equalTo(self).offset(-24) maker.top.equalTo(self).offset(26) maker.height.equalTo(self).offset(17) } /// Text field layout textField.snp.updateConstraints { maker in maker.left.equalTo(self).offset(24) maker.right.equalTo(self).offset(-24) maker.top.equalTo(titleLabel.bottom).offset(11) maker.bottom.equalTo(self).offset(-22) } } }
25.128571
66
0.587834
1a7b5b2d4f51fa2ef137579f7727152c9ec81987
2,289
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ // This file was auto-autogenerated by scripts and templates at http://github.com/AudioKit/AudioKitDevTools/ import AVFoundation /// White noise generator public class WhiteNoise: Node, AudioUnitContainer, Tappable, Toggleable { /// Unique four-letter identifier "wnoz" public static let ComponentDescription = AudioComponentDescription(generator: "wnoz") /// Internal type of audio unit for this node public typealias AudioUnitType = InternalAU /// Internal audio unit public private(set) var internalAU: AudioUnitType? // MARK: - Parameters /// Specification details for amplitude public static let amplitudeDef = NodeParameterDef( identifier: "amplitude", name: "Amplitude", address: akGetParameterAddress("WhiteNoiseParameterAmplitude"), range: 0.0 ... 1.0, unit: .generic, flags: .default) /// Amplitude. (Value between 0-1). @Parameter public var amplitude: AUValue // MARK: - Audio Unit /// Internal Audio Unit for WhiteNoise public class InternalAU: AudioUnitBase { /// Get an array of the parameter definitions /// - Returns: Array of parameter definitions public override func getParameterDefs() -> [NodeParameterDef] { [WhiteNoise.amplitudeDef] } /// Create the DSP Refence for this node /// - Returns: DSP Reference public override func createDSP() -> DSPRef { akCreateDSP("WhiteNoiseDSP") } } // MARK: - Initialization /// Initialize this noise node /// /// - Parameters: /// - amplitude: Amplitude. (Value between 0-1). /// public init( amplitude: AUValue = 1 ) { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit guard let audioUnit = avAudioUnit.auAudioUnit as? AudioUnitType else { fatalError("Couldn't create audio unit") } self.internalAU = audioUnit self.stop() self.amplitude = amplitude } } }
30.118421
108
0.637396
8fa70dab34bc43e30a0f1de2f7196f15d0a42395
293
// // ArticleListClient.swift // WikiApp // // Created by tiking on 2021/10/30. // import Combine struct ArticlelistClient { let bookID: Int func getArticleList() -> AnyPublisher<ArticleList, Error> { APIClient.GetArticleList(bookID: bookID).getArticlelist() } }
17.235294
65
0.672355
1ec062cf7f58174e26abebe4825f8e37851a5bf3
222
// // AppDependecies.swift // RickAndMortyFlexx // // Created by Даниил on 28.03.2021. // import Foundation typealias HasDependecies = HasRMService struct AppDependecies: HasDependecies { let rmService: RMService }
15.857143
39
0.752252
5dad0a938dce8b4e17fc2d22162ec8e9fafe44d6
2,015
// // Advent // Copyright © 2020 David Jennes // import Algorithms import Common private struct Path { typealias Point = Vector2<Int> private let points: [Point] init<T: StringProtocol>(instructions: Line<T>) { points = instructions.csvWords.reduce(into: []) { points, movement in points.append(contentsOf: Self.trace(movement: movement, from: points.last ?? .zero)) } } private static func trace(movement: Word, from point: Point) -> [Point] { let distance = Int(movement.raw.dropFirst()) ?? 0 switch movement.characters[0] { case "U": return (point.y..<(point.y + distance)).map { Point(x: point.x, y: $0 + 1) } case "D": return ((point.y - distance + 1)...point.y).reversed().map { Point(x: point.x, y: $0 - 1) } case "R": return (point.x..<(point.x + distance)).map { Point(x: $0 + 1, y: point.y) } case "L": return ((point.x - distance + 1)...point.x).reversed().map { Point(x: $0 - 1, y: point.y) } default: preconditionFailure("Uknown direction \(movement)") } } // we need to add 1 to count the origin func stepsTaken(for point: Point) -> Int { (points.firstIndex(of: point) ?? .max) + 1 } func intersections(with path: Path) -> Set<Point> { Set(points).intersection(Set(path.points)) } } struct Day03: Day { static let name = "Crossed Wires" private let paths: [Path] private var intersections: Set<Path.Point> = [] init(input: Input) { paths = input.lines.map(Path.init(instructions:)) } } // MARK: - Part 1 extension Day03 { mutating func part1() -> Any { logPart("What is the Manhattan distance from the central port to the closest intersection?") intersections = paths[0].intersections(with: paths[1]) return intersections.map(\.manhattanLength).min() ?? 0 } } // MARK: - Part 2 extension Day03 { mutating func part2() -> Any { logPart("What is the fewest combined steps the wires must take to reach an intersection?") return intersections .map { point in paths.map { $0.stepsTaken(for: point) }.sum } .min() ?? .max } }
27.22973
103
0.660546
5643f62b5159fa234a40507b83002ff02722b019
5,132
//////////////////////////////////////////////////////////////////////////// // // Copyright 2018 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import UIKit import RealmSwift // Configure the permissions on the Realm and each model class. // This will only succeed the first time that this code is executed. Subsequent attempts // will silently fail due to `canSetPermissions` having already been removed. // // NOTE: This initial configuration of permissions would typically be done by an admin via // Realm Studio or a dedicated script, not as part of your app's logic. We show it here // solely to demonstrate a more advanced use of the Swift API. func initializeRealmPermissions(_ realm: Realm) { // Ensure that class-level permissions cannot be modified by anyone but admin users. // The Project type can be queried, while Item cannot. This means that the only Item // objects that will be synchronized are those associated with our Projects. // Additionally, we prevent roles from being modified to avoid malicious users // from gaining access to other user's projects by adding themselves as members // of that user's private role. let queryable = [Project.className(): true, Item.className(): false, PermissionRole.className(): true] let updateable = [Project.className(): true, Item.className(): true, PermissionRole.className(): false] for cls in [Project.self, Item.self, PermissionRole.self] { let everyonePermission = realm.permissions(forType: cls).findOrCreate(forRoleNamed: "everyone") everyonePermission.canQuery = queryable[cls.className()]! everyonePermission.canUpdate = updateable[cls.className()]! everyonePermission.canSetPermissions = false } // Ensure that the schema and Realm-level permissions cannot be modified by anyone but admin users. let everyonePermission = realm.permissions.findOrCreate(forRoleNamed: "everyone") everyonePermission.canModifySchema = false // `canSetPermissions` must be disabled last, as it would otherwise prevent other permission changes // from taking effect. everyonePermission.canSetPermissions = false } // Initialize the default permissions of the Realm. // This is done asynchronously, as we must first wait for the Realm to download from the server // to ensure that we don't end up with the same user being added to a role multiple times. func initializePermissions(_ user: SyncUser, completion: @escaping (Error?) -> Void) { let config = SyncUser.current!.configuration() Realm.asyncOpen(configuration: config) { (realm, error) in guard let realm = realm else { completion(error) return } try! realm.write { initializeRealmPermissions(realm) } completion(nil) } } class WelcomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) title = "Welcome" if let _ = SyncUser.current { // We have already logged in here! self.navigationController?.viewControllers = [ProjectsViewController()] } else { let alertController = UIAlertController(title: "Login to Realm Cloud", message: "Supply a nice nickname!", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Login", style: .default) { [weak self] _ in let textField = alertController.textFields![0] let creds = SyncCredentials.nickname(textField.text!) SyncUser.logIn(with: creds, server: Constants.AUTH_URL) { [weak self](user, error) in guard let user = user else { fatalError(error!.localizedDescription) } initializePermissions(user) { error in if let error = error { fatalError(error.localizedDescription) } self?.navigationController?.viewControllers = [ProjectsViewController()] } } }) alertController.addTextField() { textField in textField.placeholder = "A Name for your user" } self.present(alertController, animated: true, completion: nil) } } }
43.863248
142
0.647506
9086f7dfae55a7328b4a4cd76aa1141988114955
887
// RUN: %target-swift-frontend -O %s -parse-as-library -emit-sil | %FileCheck %s public class BaseClass<T> { func doSomething(_ value: T) -> Int { return 1 } } public class DerivedClass: BaseClass<Double> { // Don't eliminate this public method, which is called via a thunk public override func doSomething(_ value: Double) -> Int { return 1 } } // CHECK: sil_vtable BaseClass { // CHECK: #BaseClass.doSomething!1: <T> (BaseClass<T>) -> (T) -> Int : @$S23alive_method_with_thunk9BaseClassC11doSomethingySixF // BaseClass.doSomething(_:) // CHECK: } // CHECK: sil_vtable DerivedClass { // CHECK: #BaseClass.doSomething!1: <T> (BaseClass<T>) -> (T) -> Int : public @$S23alive_method_with_thunk12DerivedClassC11doSomethingySiSdFAA04BaseF0CADySixFTV [override] // vtable thunk for BaseClass.doSomething(_:) dispatching to DerivedClass.doSomething(_:) // CHECK: }
35.48
263
0.713641
726bdee58c2f34897caf36ae75781fd314046020
280
import SpriteKit public class BasicNode: SKShapeNode { override init() { super.init() blendMode = .replace isAntialiased = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
18.666667
59
0.617857
90731c1c7184f283e5113e94cf32990f7571024d
3,346
import XCTest import SwiftUI import Combine @testable import ViewInspector // MARK: - Tap Gesture Tests @available(iOS 13.0, macOS 10.15, *) @available(tvOS, unavailable) final class TapGestureTests: XCTestCase { var tapValue: TapGesture.Value? var gestureTests: CommonGestureTests<TapGesture>? override func setUpWithError() throws { tapValue = TapGesture.Value() gestureTests = CommonGestureTests<TapGesture>(testCase: self, gesture: TapGesture(), value: tapValue!, assert: assertTapValue) } override func tearDownWithError() throws { tapValue = nil gestureTests = nil } func testCreateTapGestureValue() throws { let value: TapGesture.Value = try XCTUnwrap(tapValue) assertTapValue(value) } func testTapGestureMask() throws { try gestureTests!.maskTest() } func testTapGesture() throws { let sut = EmptyView().gesture(TapGesture(count: 2)) let tapGesture = try sut.inspect().emptyView().gesture(TapGesture.self).actualGesture() XCTAssertEqual(tapGesture.count, 2) } func testTapGestureWithUpdatingModifier() throws { try gestureTests!.propertiesWithUpdatingModifierTest() } func testTapGestureWithOnEndedModifier() throws { try gestureTests!.propertiesWithOnEndedModifierTest() } #if os(macOS) func testTapGestureWithModifiers() throws { try gestureTests!.propertiesWithModifiersTest() } #endif func testTapGestureFailure() throws { try gestureTests!.propertiesFailureTest("TapGesture") } func testTapGestureCallUpdating() throws { try gestureTests!.callUpdatingTest() } func testTapGestureCallUpdatingNotFirst() throws { try gestureTests!.callUpdatingNotFirstTest() } func testTapGestureCallUpdatingMultiple() throws { try gestureTests!.callUpdatingMultipleTest() } func testTapGestureCallUpdatingFailure() throws { try gestureTests!.callUpdatingFailureTest() } func testTapGestureCallOnEnded() throws { try gestureTests!.callOnEndedTest() } func testTapGestureCallOnEndedNotFirst() throws { try gestureTests!.callOnEndedNotFirstTest() } func testTapGestureCallOnEndedMultiple() throws { try gestureTests!.callOnEndedMultipleTest() } func testTapGestureCallOnEndedFailure() throws { try gestureTests!.callOnEndedFailureTest() } #if os(macOS) func testTapGestureModifiers() throws { try gestureTests!.modifiersTest() } func testTapGestureModifiersNotFirst() throws { try gestureTests!.modifiersNotFirstTest() } func testTapGestureModifiersMultiple() throws { try gestureTests!.modifiersMultipleTest() } func testTapGestureModifiersNone() throws { try gestureTests!.modifiersNoneTest() } #endif func assertTapValue( _ value: TapGesture.Value, file: StaticString = #filePath, line: UInt = #line) { XCTAssertTrue(value == ()) } }
27.883333
95
0.635983
2876a1e0f2e971ab8f0f9bede92fe9f7c4697ab4
600
// // STPPaymentMethodBancontactParams.swift // StripeiOS // // Created by Vineet Shah on 4/29/20. // Copyright © 2020 Stripe, Inc. All rights reserved. // import Foundation /// An object representing parameters used to create a Bancontact Payment Method public class STPPaymentMethodBancontactParams: NSObject, STPFormEncodable { public var additionalAPIParameters: [AnyHashable: Any] = [:] public class func rootObjectName() -> String? { return "bancontact" } public class func propertyNamesToFormFieldNamesMapping() -> [String: String] { return [:] } }
26.086957
82
0.71
26a7c3cde2ff39f4df7d620318d0c62fcf9bb8cb
512
// // ViewController.swift // Swift-OC-3rd // // Created by zhangjinwei on 09/29/2021. // Copyright (c) 2021 zhangjinwei. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.48
80
0.671875
5d5ef7f4559a76d1c29888c9c13cea915f43c74f
932
// Copyright 2018-2020 Tokamak contributors // // 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. // // Created by Carson Katri on 9/9/20. // import TokamakCore extension Link: ViewDeferredToRenderer { @_spi(TokamakCore) public var deferredBody: AnyView { let proxy = _LinkProxy(self) return AnyView(HTML("a", ["href": proxy.destination.absoluteString, "class": "_tokamak-link"]) { proxy.label }) } }
32.137931
100
0.723176
ab54e5013e6c64b93c625e77f4a27140f524894b
1,379
// // Offset.swift // MusicXML // // Created by James Bean on 5/28/19. // /// An offset is represented in terms of divisions, and indicates where the direction will appear /// relative to the current musical location. This affects the visual appearance of the direction. /// If an element within a direction includes a default-x attribute, the offset value will be /// ignored when determining the appearance of that element. public struct Offset { // MARK: - Instance Properties // MARK: Attributes public let sound: Bool? // MARK: Value public let value: Divisions // MARK: - Initializers public init(_ value: Divisions, sound: Bool? = nil) { self.value = value self.sound = sound } } extension Offset: Equatable {} extension Offset: Codable { // MARK: - Codable enum CodingKeys: String, CodingKey { case value = "" case sound } } extension Offset: ExpressibleByIntegerLiteral { // MARK: - ExpressibleByIntegerLiteral public init(integerLiteral value: Int) { self.init(value) } } import XMLCoder extension Offset: DynamicNodeEncoding { public static func nodeEncoding(for key: CodingKey) -> XMLEncoder.NodeEncoding { switch key { case CodingKeys.value: return .element default: return .attribute } } }
22.983333
98
0.656273
dba789f1851394097bedec808e2024e2dca046ea
1,530
// // FullScreenPhotoViewController.swift // tumblR // // Created by Barbara Ristau on 1/22/17. // Copyright © 2017 FeiLabs. All rights reserved. // import UIKit import AFNetworking class FullScreenPhotoViewController: UIViewController, UIScrollViewDelegate { var post: NSDictionary! @IBOutlet weak var fullScreenPhotoImage: UIImageView! @IBOutlet weak var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() scrollView.delegate = self if let photos = post.value(forKeyPath: "photos") as? [NSDictionary] { let imageUrlString = photos[0].value(forKeyPath: "original_size.url") as? String let imageUrl = URL(string: imageUrlString!) fullScreenPhotoImage.setImageWith(imageUrl!) scrollView.contentSize = fullScreenPhotoImage.image!.size } } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return fullScreenPhotoImage } @IBAction func closeScreen(_ sender: UIButton) { print("Tapped close button") self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24.285714
106
0.670588
ebf607757b8d5e9e8dbd9ea17065225e5a766ffa
8,631
// // ViewController.swift // MobileAzureDevDays // // Created by Colby Williams on 9/22/17. // Copyright © 2017 Colby Williams. All rights reserved. // import UIKit class ViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var sentimentTextView: UITextView! @IBOutlet weak var sentimentTextContainer: UIView! @IBOutlet weak var sentimentTextPlaceholder: UILabel! @IBOutlet weak var submitButton: UIButton! @IBOutlet weak var crashButton: UIButton! @IBOutlet weak var eventButton: UIButton! @IBOutlet weak var colorButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var activityLabel: UILabel! @IBOutlet weak var emojiLabel: UILabel! let submit = "Submit" let reset = "Reset" override func viewDidLoad() { super.viewDidLoad() setupBorders() submitButton.isEnabled = false SentimentClient.shared.obtainKey(){keyResponse in if let document = keyResponse { SentimentClient.shared.apiKey = document.key SentimentClient.shared.region = document.region } else { self.showApiKeyAlert() } DispatchQueue.main.async { self.submitButton.isEnabled = true } } } @IBAction func submitButtonTouchUpInside(_ sender: Any) { if submitButton.currentTitle == submit { if !sentimentTextView.hasText { showErrorAlert("Hold up", message: "Gotta add some text first.", dismiss: "Got it"); return } setActivity(true) SentimentClient.shared.determineSentiment(sentimentTextView.text) { sentimentResponse in self.setActivity(false) if let response = sentimentResponse, let document = response.documents.first { self.setSentiment(Sentiment.getSentiment(document.score)) } else { self.showErrorAlert("Error \(sentimentResponse?.errorStatusCode ?? -1)", message: sentimentResponse?.errorMessage ?? "", dismiss: "Okay") } } } else if submitButton.currentTitle == reset { setSentiment(nil) resetTextView() } } @IBAction func crashButtonTapped(_: UIButton) { presentCrashAlert() } // - MARK: Alert Functions func presentCrashAlert() { let alert = UIAlertController(title: "The app will close", message: "A crash report will be sent when you reopen the app.", preferredStyle: UIAlertControllerStyle.alert) // Cancel Button alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { _ in alert.dismiss(animated: true, completion: nil) })) // Crash App button alert.addAction(UIAlertAction(title: "Crash app", style: UIAlertActionStyle.destructive, handler: { _ in alert.dismiss(animated: true, completion: nil) // generate test crash fatalError() })) present(alert, animated: true, completion: nil) } func showErrorAlert(_ title:String, message:String, dismiss:String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: dismiss, style: .default) { a in self.dismiss(animated: true) { } }); present(alertController, animated: true) {} } @IBAction func analyticsButtonTapped(_ sender: UIButton) { switch sender { case eventButton: print("send a custom alert via Cocoapods") presentCustomEventAlert() case colorButton: print("custom color property button pressed") presentColorPropertyAlert() default: break } } // - MARK: Alert Functions func presentCustomEventAlert() { let alert = UIAlertController(title: "Event sent", message: "", preferredStyle: .alert) // OK Button alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in alert.dismiss(animated: true, completion: nil) })) present(alert, animated: true, completion: nil) } func presentColorPropertyAlert() { let alert = UIAlertController(title: "Choose a color", message: "", preferredStyle: .alert) alert.view.tintColor = UIColor.black // Yellow button alert.addAction(UIAlertAction(title: "💛 Yellow", style: .default, handler: { _ in alert.dismiss(animated: true, completion: nil) })) // Blue button alert.addAction(UIAlertAction(title: "💙 Blue", style: .default, handler: { _ in alert.dismiss(animated: true, completion: nil) })) // Red button alert.addAction(UIAlertAction(title: "❤️ Red", style: .default, handler: { _ in alert.dismiss(animated: true, completion: nil) })) present(alert, animated: true, completion: nil) } func setSentiment(_ sentiment:Sentiment?) { emojiLabel.text = sentiment?.emoji view.backgroundColor = sentiment?.color ?? #colorLiteral(red: 1, green: 0.4352941176, blue: 0.4117647059, alpha: 1) submitButton.setTitle(sentiment == nil ? submit : reset, for: .normal) } func resetTextView() { sentimentTextView.text = nil sentimentTextPlaceholder.isHidden = false sentimentTextView.isEditable = true } func setActivity(_ activity: Bool) { activityLabel.isHidden = !activity activityIndicator.isHidden = !activity sentimentTextView.isEditable = !activity submitButton.isUserInteractionEnabled = !activity if activity && !activityIndicator.isAnimating { activityIndicator.startAnimating() } } func setupBorders() { sentimentTextContainer.layer.borderWidth = 1 sentimentTextContainer.layer.borderColor = #colorLiteral(red: 0.6078431373, green: 0.6078431373, blue: 0.6078431373, alpha: 1) sentimentTextContainer.layer.cornerRadius = 8 submitButton.layer.borderWidth = 1.5 submitButton.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK - UITextViewDelegate func textViewDidChange(_ textView: UITextView) { sentimentTextPlaceholder.isHidden = textView.hasText } func showApiKeyAlert() { if SentimentClient.shared.apiKey == nil || SentimentClient.shared.apiKey!.isEmpty { let alertController = UIAlertController(title: "Configure App", message: "Enter a Text Analytics API Subscription Key. Or add the key in code in `didFinishLaunchingWithOptions`", preferredStyle: .alert) alertController.addTextField() { textField in textField.placeholder = "Subscription Key" textField.returnKeyType = .done } alertController.addAction(UIAlertAction(title: "Get Key", style: .default) { a in if let getKeyUrl = URL(string: "https://portal.azure.com/#blade/HubsExtension/BrowseResourceBlade/resourceType/Microsoft.CognitiveServices%2Faccounts") { UIApplication.shared.open(getKeyUrl, options: [:]) { opened in print("Opened GetKey url successfully: \(opened)") } } }) alertController.addAction(UIAlertAction(title: "Done", style: .default) { a in if alertController.textFields?.first?.text == nil || alertController.textFields!.first!.text!.isEmpty { self.showApiKeyAlert() } else { SentimentClient.shared.apiKey = alertController.textFields!.first!.text } }) present(alertController, animated: true) { } } } }
33.453488
214
0.591704
e4d9f0c8ebb22f460b6c971699efe3201d8a57d0
2,478
// // Created by Timofey on 3/12/18. // Copyright (c) 2018 CocoaPods. All rights reserved. // import Nimble import Quick @testable import Web3Swift final class BigEndianNumberHexTests: XCTestCase { func testHexConversionFromBytes() { Array< Array<UInt8> >( [ [0x01], [0x03, 0xff], [0xff, 0xff, 0xff, 0xff] ] ).forEach{ bytes in expect{ try BigEndianNumber( bytes: SimpleBytes( bytes: bytes ) ).hex().value() }.to( equal( Data( bytes: bytes ) ), description: "Hex of a number from bytes is expected to persist" ) } } //TODO: This is not an exact test because set neglects order. We need to test for ending overlap func testHexConversionFromUInt() { Array< ( Array<UInt8>, UInt ) >( [ ([0x01], 1), ([0x03, 0xff], 1023), ([0xff, 0xff, 0xff, 0xff], 4294967295) ] ).forEach{ bytes, uint in expect{ try Set<UInt8>( BigEndianNumber( uint: uint ).hex().value() ).isSuperset(of: Set<UInt8>(bytes)) }.to( equal(true), description: "Hex of a number from uint is expected to persist" ) } } func testHexConversionFromString() { Array< ( String, Array<UInt8> ) >( [ ("0x01", [0x01]), ("0x03ff", [0x03, 0xff]), ("0xffffffff", [0xff, 0xff, 0xff, 0xff]) ] ).forEach{ hex, bytes in expect{ try BigEndianNumber( hex: SimpleString( string: hex ) ).hex().value() }.to( equal( Data( bytes: bytes ) ), description: "Hex of a number from hex string is expected to persist" ) } } }
25.8125
100
0.377724
11ff90a9d61c66857e40e9a8749f73abc3ba8a15
1,254
// // Colors.swift // Demo // // Created by Motoki on 2015/12/22. // Copyright © 2015年 MotokiNarita. All rights reserved. // import UIKit extension UIColor { class func midnight() -> UIColor { return UIColor(red: 44.0/255.0, green: 62.0/255.0, blue: 80.0/255.0, alpha: 1.0) } class func cloud() -> UIColor { return UIColor(red: 236.0/255.0, green: 240.0/255.0, blue: 241.0/255.0, alpha: 1.0) } class func alizarin() -> UIColor { return UIColor(red: 231.0/255.0, green: 76.0/255.0, blue: 60.0/255.0, alpha: 1.0) } class func carrot() -> UIColor { return UIColor(red: 231.0/255.0, green: 126.0/255.0, blue: 34.0/255.0, alpha: 1.0) } class func sunflower() -> UIColor { return UIColor(red: 241.0/255.0, green: 196.0/255.0, blue: 15.0/255.0, alpha: 1.0) } class func turquoize() -> UIColor { return UIColor(red: 26.0/255.0, green: 188.0/255.0, blue: 156.0/255.0, alpha: 1.0) } class func river() -> UIColor { return UIColor(red: 52.0/255.0, green: 152.0/255.0, blue: 219.0/255.0, alpha: 1.0) } class func amethyst() -> UIColor { return UIColor(red: 155.0/255.0, green: 89.0/255.0, blue: 182.0/255.0, alpha: 1.0) } }
27.866667
91
0.585327
390d6248f72e1dc067c410a30a5570cc013c7aa0
663
// // CaesarCipherTests.swift // WhiteBoardCodingChallenges // // Created by William Boles on 10/05/2016. // Copyright © 2016 Boles. All rights reserved. // import XCTest class CaesarCipherTests: XCTestCase { // MARK: Tests func test_caesarCipherA() { let encryptedString = CaesarCipher.encrypt(originalString: "middle-Outz", rotate: 2) XCTAssertEqual("okffng-Qwvb", encryptedString) } func test_caesarCipherB() { let encryptedString = CaesarCipher.encrypt(originalString: "www.abc.xy", rotate: 87) XCTAssertEqual("fff.jkl.gh", encryptedString) } }
22.1
92
0.636501
b9be7ef6ec7ab9ccf6967d8c1402ef49aa11f1a2
501
// // AppDelegate.swift // DirtyWords for Xcode // // Created by 杨萧玉 on 2018/12/20. // Copyright © 2018 杨萧玉. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
18.555556
71
0.708583
db0651eb00e464e3b887649a229cf278277b2e17
12,714
/* This source file is part of the Swift System open source project Copyright (c) 2020 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ internal struct _ParsedWindowsRoot { var rootEnd: SystemString.Index // TODO: Remove when I normalize to always (except `C:`) // have trailing separator var relativeBegin: SystemString.Index var drive: SystemChar? var fullyQualified: Bool var deviceSigil: SystemChar? var host: Range<SystemString.Index>? var volume: Range<SystemString.Index>? } extension _ParsedWindowsRoot { static func traditional( drive: SystemChar?, fullQualified: Bool, endingAt idx: SystemString.Index ) -> _ParsedWindowsRoot { _ParsedWindowsRoot( rootEnd: idx, relativeBegin: idx, drive: drive, fullyQualified: fullQualified, deviceSigil: nil, host: nil, volume: nil) } static func unc( deviceSigil: SystemChar?, server: Range<SystemString.Index>, share: Range<SystemString.Index>, endingAt end: SystemString.Index, relativeBegin relBegin: SystemString.Index ) -> _ParsedWindowsRoot { _ParsedWindowsRoot( rootEnd: end, relativeBegin: relBegin, drive: nil, fullyQualified: true, deviceSigil: deviceSigil, host: server, volume: share) } static func device( deviceSigil: SystemChar, volume: Range<SystemString.Index>, endingAt end: SystemString.Index, relativeBegin relBegin: SystemString.Index ) -> _ParsedWindowsRoot { _ParsedWindowsRoot( rootEnd: end, relativeBegin: relBegin, drive: nil, fullyQualified: true, deviceSigil: deviceSigil, host: nil, volume: volume) } } struct _Lexer { var slice: Slice<SystemString> init(_ str: SystemString) { self.slice = str[...] } var backslash: SystemChar { .backslash } // Try to eat a backslash, returns false if nothing happened mutating func eatBackslash() -> Bool { slice._eat(.backslash) != nil } // Try to consume a drive letter and subsequent `:`. mutating func eatDrive() -> SystemChar? { let copy = slice if let d = slice._eat(if: { $0.isLetter }), slice._eat(.colon) != nil { return d } // Restore slice slice = copy return nil } // Try to consume a device sigil (stand-alone . or ?) mutating func eatSigil() -> SystemChar? { let copy = slice guard let sigil = slice._eat(.question) ?? slice._eat(.dot) else { return nil } // Check for something like .hidden or ?question guard isEmpty || slice.first == backslash else { slice = copy return nil } return sigil } // Try to consume an explicit "UNC" directory mutating func eatUNC() -> Bool { slice._eatSequence("UNC".unicodeScalars.lazy.map { SystemChar(ascii: $0) }) != nil } // Eat everything up to but not including a backslash or null mutating func eatComponent() -> Range<SystemString.Index> { let backslash = self.backslash let component = slice._eatWhile({ $0 != backslash }) ?? slice[slice.startIndex ..< slice.startIndex] return component.indices } var isEmpty: Bool { return slice.isEmpty } var current: SystemString.Index { slice.startIndex } mutating func clear() { // TODO: Intern empty system string self = _Lexer(SystemString()) } mutating func reset(to: SystemString, at: SystemString.Index) { self.slice = to[at...] } } internal struct WindowsRootInfo { // The "volume" of a root. For UNC paths, this is also known as the "share". internal enum Volume: Equatable { /// No volume specified /// /// * Traditional root relative to the current drive: `\`, /// * Omitted volume from other forms: `\\.\`, `\\.\UNC\server\\`, `\\server\\` case empty /// A specified drive. /// /// * Traditional disk: `C:\`, `C:` /// * Device disk: `\\.\C:\`, `\\?\C:\` /// * UNC: `\\server\e:\`, `\\?\UNC\server\e:\` /// /// TODO: NT paths? Admin paths using `$`? case drive(Character) /// A volume with a GUID in a non-traditional path /// /// * UNC: `\\host\Volume{0000-...}\`, `\\.\UNC\host\Volume{0000-...}\` /// * Device roots: `\\.\Volume{0000-...}\`, `\\?\Volume{000-...}\` /// /// TODO: GUID type? case guid(String) // TODO: Legacy DOS devices, such as COM1? /// Device object or share name /// /// * Device roots: `\\.\BootPartition\` /// * UNC: `\\host\volume\` case volume(String) // TODO: Should legacy DOS devices be detected and/or converted at construction time? // TODO: What about NT paths: `\??\` } /// Represents the syntactic form of the path internal enum Form: Equatable { /// Traditional DOS roots: `C:\`, `C:`, and `\` case traditional(fullyQualified: Bool) // `C:\`, `C:`, `\` /// UNC syntactic form: `\\server\share\` case unc /// DOS device syntactic form: `\\?\BootPartition`, `\\.\C:\`, `\\?\UNC\server\share` case device(sigil: Character) // TODO: NT? } /// The host for UNC paths, else `nil`. internal var host: String? /// The specified volume (or UNC share) for the root internal var volume: Volume /// The syntactic form the root is in internal var form: Form init(host: String?, volume: Volume, form: Form) { self.host = host self.volume = volume self.form = form checkInvariants() } } extension _ParsedWindowsRoot { fileprivate func volumeInfo(_ root: SystemString) -> WindowsRootInfo.Volume { if let d = self.drive { return .drive(Character(d.asciiScalar!)) } guard let vol = self.volume, !vol.isEmpty else { return .empty } // TODO: check for GUID // TODO: check for drive return .volume(root[vol].string) } } extension WindowsRootInfo { internal init(_ root: SystemString, _ parsed: _ParsedWindowsRoot) { self.volume = parsed.volumeInfo(root) if let host = parsed.host { self.host = root[host].string } else { self.host = nil } if let sig = parsed.deviceSigil { self.form = .device(sigil: Character(sig.asciiScalar!)) } else if parsed.host != nil { assert(parsed.volume != nil) self.form = .unc } else { self.form = .traditional(fullyQualified: parsed.fullyQualified) } } } extension WindowsRootInfo { /// NOT `\foo\bar` nor `C:foo\bar` internal var isFullyQualified: Bool { return form != .traditional(fullyQualified: false) } /// /// `\\server\share\foo\bar.exe`, `\\.\UNC\server\share\foo\bar.exe` internal var isUNC: Bool { host != nil } /// /// `\foo\bar.exe` internal var isTraditionalRooted: Bool { form == .traditional(fullyQualified: false) && volume == .empty } /// /// `C:foo\bar.exe` internal var isTraditionalDriveRelative: Bool { switch (form, volume) { case (.traditional(fullyQualified: false), .drive(_)): return true default: return false } } // TODO: Should this be component? func formPath() -> FilePath { fatalError("Unimplemented") } // static func traditional( // drive: Character?, fullyQualified: Bool // ) -> WindowsRootInfo { // let vol: Volume // if let d = Character { // vol = .drive(d) // } else { // vol = .relative // } // // return WindowsRootInfo( // volume: .relative, form: .traditional(fullyQualified: false)) // } internal func checkInvariants() { switch form { case .traditional(let qual): precondition(host == nil) switch volume { case .empty: precondition(!qual) break case .drive(_): break default: preconditionFailure() } case .unc: precondition(host != nil) case .device(_): break } } } extension SystemString { // TODO: Or, should I always inline this to remove some of the bookeeping? private func _parseWindowsRootInternal() -> _ParsedWindowsRoot? { assert(_windowsPaths) /* Windows root: device or UNC or DOS device: (`\\.` or `\\?`) `\` (drive or guid or UNC-link) drive: letter `:` guid: `Volume{` (hex-digit or `-`)* `}` UNC-link: `UNC\` UNC-volume UNC: `\\` UNC-volume UNC-volume: server `\` share DOS: fully-qualified or legacy-device or drive or `\` full-qualified: drive `\` TODO: What is \\?\server1\e:\utilities\\filecomparer\ from the docs? TODO: What about admin use of `$` instead of `:`? E.g. \\system07\C$\ NOTE: Legacy devices are not handled by System at a library level, but are deferred to the relevant syscalls. */ var lexer = _Lexer(self) // Helper to parse a UNC root func parseUNC(deviceSigil: SystemChar?) -> _ParsedWindowsRoot { let serverRange = lexer.eatComponent() guard lexer.eatBackslash() else { fatalError("expected normalized root to contain backslash") } let shareRange = lexer.eatComponent() let rootEnd = lexer.current _ = lexer.eatBackslash() return .unc( deviceSigil: deviceSigil, server: serverRange, share: shareRange, endingAt: rootEnd, relativeBegin: lexer.current) } // `C:` or `C:\` if let d = lexer.eatDrive() { // `C:\` - fully qualified let fullyQualified = lexer.eatBackslash() return .traditional( drive: d, fullQualified: fullyQualified, endingAt: lexer.current) } // `\` or else it's just a rootless relative path guard lexer.eatBackslash() else { return nil } // `\\` or else it's just a current-drive rooted traditional path guard lexer.eatBackslash() else { return .traditional( drive: nil, fullQualified: false, endingAt: lexer.current) } // `\\.` or `\\?` (device paths) or else it's just UNC guard let sigil = lexer.eatSigil() else { return parseUNC(deviceSigil: nil) } _ = sigil // suppress warnings guard lexer.eatBackslash() else { fatalError("expected normalized root to contain backslash") } if lexer.eatUNC() { guard lexer.eatBackslash() else { fatalError("expected normalized root to contain backslash") } return parseUNC(deviceSigil: sigil) } let device = lexer.eatComponent() let rootEnd = lexer.current _ = lexer.eatBackslash() return .device( deviceSigil: sigil, volume: device, endingAt: rootEnd, relativeBegin: lexer.current) } @inline(never) internal func _parseWindowsRoot() -> ( rootEnd: SystemString.Index, relativeBegin: SystemString.Index ) { guard let parsed = _parseWindowsRootInternal() else { return (startIndex, startIndex) } return (parsed.rootEnd, parsed.relativeBegin) } } extension SystemString { // UNC and device roots can have multiple repeated roots that are meaningful, // and extra backslashes may need to be inserted for partial roots (e.g. empty // volume). // // Returns the point where `_normalizeSeparators` should resume. internal mutating func _prenormalizeWindowsRoots() -> Index { assert(_windowsPaths) assert(!self.contains(.slash), "only valid after separator conversion") var lexer = _Lexer(self) // Only relevant for UNC or device paths guard lexer.eatBackslash(), lexer.eatBackslash() else { return lexer.current } // Parse a backslash, inserting one if needed func expectBackslash() { if lexer.eatBackslash() { return } // A little gross, but we reset the lexer because the lexer // holds a strong reference to `self`. // // TODO: Intern the empty SystemString. Right now, this is // along an uncommon/pathological case, but we want to in // general make empty strings without allocation let idx = lexer.current lexer.clear() self.insert(.backslash, at: idx) lexer.reset(to: self, at: idx) let p = lexer.eatBackslash() assert(p) } // Parse a component and subsequent backslash, insering one if needed func expectComponent() { _ = lexer.eatComponent() expectBackslash() } // Check for `\\.` style paths if lexer.eatSigil() != nil { expectBackslash() if lexer.eatUNC() { expectBackslash() expectComponent() expectComponent() return lexer.current } expectComponent() return lexer.current } expectComponent() expectComponent() return lexer.current } }
27.283262
89
0.628362
aba2ae677ca3232d1cd560c14b6ea1c52d5f1f70
9,108
// // ColorPaleteControl.swift // FlexColorPicker // // Created by Rastislav Mirek on 27/5/18. // // MIT License // Copyright (c) 2018 Rastislav Mirek // // 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 let minimumDistanceForInBoundsTouchFromValidPoint: CGFloat = 44 let defaultSelectedColor = UIColor.white.hsbColor /// Color control that allows to select color by tapping or panning a palette that displays available color options. /// /// Any subvies must be added to `contentView` only for this to work correctly inside `UIScrollView` and iOS 13 modal view controllers. @IBDesignable open class ColorPaletteControl: ColorControlWithThumbView { /// The image view providing preview of color option for each particular point. Its image might be e.g. hue/saturation map. public let foregroundImageView = UIImageView() /// Background image view that holds image which blends with image displayed by `foregroundImageView` when its alpha is less then 1, providing more accurate color options preview. E.g. black image that blends with hue/saturation map in foreground to show color map adjusted for brightness . public let backgroundImageView = UIImageView() /// A delegate that specifies what pallete color options look like (image of the palette) and how selecting a point on the palette is interpreted. It also specifies tappable region of the palette. open var paletteDelegate: ColorPaletteDelegate = RadialHSBPaletteDelegate() { didSet { updatePaletteImagesAndThumb(isInteractive: false) } } open override var bounds: CGRect { didSet { guard oldValue != bounds else { return } updatePaletteImagesAndThumb(isInteractive: false) } } open override var contentMode: UIView.ContentMode { didSet { updateContentMode() updateThumbPosition(position: paletteDelegate.positionAndAlpha(for: selectedHSBColor).position) } } open override func commonInit() { super.commonInit() contentView.addAutolayoutFillingSubview(backgroundImageView) backgroundImageView.addAutolayoutFillingSubview(foregroundImageView) updateContentMode() contentView.addSubview(thumbView) updatePaletteImagesAndThumb(isInteractive: false) } open override func setSelectedHSBColor(_ hsbColor: HSBColor, isInteractive interactive: Bool) { let hasChanged = selectedHSBColor != hsbColor super.setSelectedHSBColor(hsbColor, isInteractive: interactive) if hasChanged { thumbView.setColor(hsbColor.toUIColor(), animateBorderColor: interactive) let (position, foregroundAlpha) = paletteDelegate.positionAndAlpha(for: hsbColor) updateThumbPosition(position: position) foregroundImageView.alpha = foregroundAlpha } } /// Updates palette foreground and backround images and thumb view to reflect current state of this control (e.g. values of `selectedHSBColor` and `paletteDelegate`). Call this only if update of visual state of the pallete is necessary as this call has performance implications - new images are requested from palette delegate. /// /// Override this if you need update palette visual state differently on state change. /// /// - Parameter interactive: Whether the change originated from user interaction or is programatic. This can be used to determine if certain animations should be played. open func updatePaletteImagesAndThumb(isInteractive interactive: Bool) { layoutIfNeeded() //force subviews layout to update their bounds - bounds of subviews are not automatically updated paletteDelegate.size = foregroundImageView.bounds.size //cannot use self.bounds as that is extended compared to foregroundImageView.bounds when AdjustedHitBoxColorControl.hitBoxInsets are non-zero foregroundImageView.image = paletteDelegate.foregroundImage() backgroundImageView.image = paletteDelegate.backgroundImage() assert(foregroundImageView.image!.size.width <= paletteDelegate.size.width && foregroundImageView.image!.size.height <= paletteDelegate.size.height, "Size of rendered image must be smaller or equal specified palette size") assert(backgroundImageView.image == nil || foregroundImageView.image?.size == backgroundImageView.image?.size, "foreground and background images rendered must have same size") updateContentMode() updateThumbPosition(position: paletteDelegate.positionAndAlpha(for: selectedHSBColor).position) thumbView.setColor(selectedColor, animateBorderColor: interactive) } /// Translates a point from given coordinate space to coordinate space of foreground image. Image coordinate space is used by the palette delegate. /// - Note: This translates from the coordiate space of the image itself not the coordinate space of its image view. Those can be different and the translation between them is dependent on current value of image view's `contentMode`. /// /// - Parameters: /// - point: The point to translate. /// - coordinateSpace: Source (current) coordinate space of the point to translate from. /// - Returns: Corresponding point in image coordinate space. open func imageCoordinates(point: CGPoint, fromCoordinateSpace coordinateSpace: UICoordinateSpace) -> CGPoint { return foregroundImageView.convertToImageSpace(point: foregroundImageView.convert(point, from: coordinateSpace)) } /// Translates a point from coordinate space of foreground image to given coordinate space. Image coordinate space is used by the palette delegate. /// - Note: This translates to the coordiate space of the image itself not the coordinate space of its image view. Those can be different and the translation between them is dependent on current value of image view's `contentMode`. /// /// - Parameters: /// - point: The point to translate. /// - coordinateSpace: Target (destination) coordinate space to translate to. /// - Returns: Corresponding point in target coordinate space. open func imageCoordinates(point: CGPoint, toCoordinateSpace coordinateSpace: UICoordinateSpace) -> CGPoint { return foregroundImageView.convert(foregroundImageView.convertFromImageSpace(point: point), to: coordinateSpace) } open override func updateSelectedColor(at point: CGPoint, isInteractive: Bool) { let pointInside = paletteDelegate.closestValidPoint(to: imageCoordinates(point: point, fromCoordinateSpace: contentView)) setSelectedHSBColor(paletteDelegate.modifiedColor(from: selectedHSBColor, with: pointInside), isInteractive: isInteractive) updateThumbPosition(position: pointInside) sendActions(for: .valueChanged) } open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let maxTouchDistance = max(hitBoxInsets.bottom, hitBoxInsets.top, hitBoxInsets.left, hitBoxInsets.right, minimumDistanceForInBoundsTouchFromValidPoint) if imageCoordinates(point: paletteDelegate.closestValidPoint(to: imageCoordinates(point: point, fromCoordinateSpace: self)), toCoordinateSpace: self).distance(to: point) > maxTouchDistance { return nil } return super.hitTest(point, with: event) } private func updateThumbPosition(position: CGPoint) { thumbView.frame = CGRect(center: imageCoordinates(point: position, toCoordinateSpace: contentView), size: thumbView.intrinsicContentSize) } private func updateContentMode() { let contentMode = paletteDelegate.supportedContentMode(for: self.contentMode) backgroundImageView.contentMode = contentMode foregroundImageView.contentMode = contentMode } } extension ColorPaletteControl { open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return !(gestureRecognizer is UIPanGestureRecognizer) } }
58.384615
331
0.746157
e89dd277be351290096fc175f8c9593c71618236
1,195
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import Foundation /// Environment argument wrapped value. /// /// **Usage:** /// /// ```swift /// enum Arguments { /// @EnvironmentArgument("referral") /// static var referral: String? /// /// @EnvironmentArgument("skipOnboarding", default: false) /// static var skipOnboarding: Bool /// } /// ``` @propertyWrapper public struct EnvironmentArgument<Value> { private let argument: ProcessInfo.Argument private let defaultValue: (() -> Value)? public init(_ argument: ProcessInfo.Argument, default defaultValue: @autoclosure @escaping () -> Value) { self.argument = argument self.defaultValue = defaultValue } public var wrappedValue: Value { get { argument.get(default: defaultValue!()) } set { argument.set(newValue) } } } extension EnvironmentArgument where Value: ExpressibleByNilLiteral { public init(_ argument: ProcessInfo.Argument) { self.argument = argument self.defaultValue = nil } public var wrappedValue: Value? { get { argument.get() } set { argument.set(newValue) } } }
24.387755
109
0.647699
0aab532ed3aa99a4fe2e06e06abfd669b24937e0
722
import PlaygroundSupport import AsyncDisplayKit public protocol ASPlayground: class { func display(inRect: CGRect) } extension ASPlayground { public func display(inRect rect: CGRect) { var rect = rect if rect.size == .zero { rect.size = CGSize(width: 400, height: 400) } guard let nodeSelf = self as? ASDisplayNode else { assertionFailure("Class inheriting ASPlayground must be an ASDisplayNode") return } let constrainedSize = ASSizeRange(min: rect.size, max: rect.size) _ = ASCalculateRootLayout(nodeSelf, constrainedSize) nodeSelf.frame = rect PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = nodeSelf.view } }
26.740741
80
0.720222
f50a3b34fe3bc32709953b3f156bd5d2309a56d7
8,213
// SnapshotfileProtocol.swift // Copyright (c) 2021 FastlaneTools public protocol SnapshotfileProtocol: class { /// Path the workspace file var workspace: String? { get } /// Path the project file var project: String? { get } /// Pass additional arguments to xcodebuild for the test phase. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS="-ObjC -lstdc++" var xcargs: String? { get } /// Use an extra XCCONFIG file to build your app var xcconfig: String? { get } /// A list of devices you want to take the screenshots from var devices: [String]? { get } /// A list of languages which should be used var languages: [String] { get } /// A list of launch arguments which should be used var launchArguments: [String] { get } /// The directory where to store the screenshots var outputDirectory: String { get } /// If the logs generated by the app (e.g. using NSLog, perror, etc.) in the Simulator should be written to the output_directory var outputSimulatorLogs: Bool { get } /// By default, the latest version should be used automatically. If you want to change it, do it here var iosVersion: String? { get } /// Don't open the HTML summary after running _snapshot_ var skipOpenSummary: Bool { get } /// Do not check for most recent SnapshotHelper code var skipHelperVersionCheck: Bool { get } /// Enabling this option will automatically clear previously generated screenshots before running snapshot var clearPreviousScreenshots: Bool { get } /// Enabling this option will automatically uninstall the application before running it var reinstallApp: Bool { get } /// Enabling this option will automatically erase the simulator before running the application var eraseSimulator: Bool { get } /// Enabling this option will prevent displaying the simulator window var headless: Bool { get } /// Enabling this option will automatically override the status bar to show 9:41 AM, full battery, and full reception var overrideStatusBar: Bool { get } /// Fully customize the status bar by setting each option here. See `xcrun simctl status_bar --help` var overrideStatusBarArguments: String? { get } /// Enabling this option will configure the Simulator's system language var localizeSimulator: Bool { get } /// Enabling this option will configure the Simulator to be in dark mode (false for light, true for dark) var darkMode: Bool? { get } /// The bundle identifier of the app to uninstall (only needed when enabling reinstall_app) var appIdentifier: String? { get } /// A list of photos that should be added to the simulator before running the application var addPhotos: [String]? { get } /// A list of videos that should be added to the simulator before running the application var addVideos: [String]? { get } /// A path to screenshots.html template var htmlTemplate: String? { get } /// The directory where to store the build log var buildlogPath: String { get } /// Should the project be cleaned before building it? var clean: Bool { get } /// Test without building, requires a derived data path var testWithoutBuilding: Bool? { get } /// The configuration to use when building the app. Defaults to 'Release' var configuration: String? { get } /// Additional xcpretty arguments var xcprettyArgs: String? { get } /// The SDK that should be used for building the application var sdk: String? { get } /// The scheme you want to use, this must be the scheme for the UI Tests var scheme: String? { get } /// The number of times a test can fail before snapshot should stop retrying var numberOfRetries: Int { get } /// Should snapshot stop immediately after the tests completely failed on one device? var stopAfterFirstError: Bool { get } /// The directory where build products and other derived data will go var derivedDataPath: String? { get } /// Should an Xcode result bundle be generated in the output directory var resultBundle: Bool { get } /// The name of the target you want to test (if you desire to override the Target Application from Xcode) var testTargetName: String? { get } /// Separate the log files per device and per language var namespaceLogFiles: String? { get } /// Take snapshots on multiple simulators concurrently. Note: This option is only applicable when running against Xcode 9 var concurrentSimulators: Bool { get } /// Disable the simulator from showing the 'Slide to type' prompt var disableSlideToType: Bool { get } /// Sets a custom path for Swift Package Manager dependencies var clonedSourcePackagesPath: String? { get } /// Skips resolution of Swift Package Manager dependencies var skipPackageDependenciesResolution: Bool { get } /// Prevents packages from automatically being resolved to versions other than those recorded in the `Package.resolved` file var disablePackageAutomaticUpdates: Bool { get } /// The testplan associated with the scheme that should be used for testing var testplan: String? { get } /// Array of strings matching Test Bundle/Test Suite/Test Cases to run var onlyTesting: String? { get } /// Array of strings matching Test Bundle/Test Suite/Test Cases to skip var skipTesting: String? { get } /// Disable xcpretty formatting of build var disableXcpretty: Bool? { get } /// Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path var suppressXcodeOutput: Bool? { get } /// Lets xcodebuild use system's scm configuration var useSystemScm: Bool { get } } public extension SnapshotfileProtocol { var workspace: String? { return nil } var project: String? { return nil } var xcargs: String? { return nil } var xcconfig: String? { return nil } var devices: [String]? { return nil } var languages: [String] { return ["en-US"] } var launchArguments: [String] { return [""] } var outputDirectory: String { return "screenshots" } var outputSimulatorLogs: Bool { return false } var iosVersion: String? { return nil } var skipOpenSummary: Bool { return false } var skipHelperVersionCheck: Bool { return false } var clearPreviousScreenshots: Bool { return false } var reinstallApp: Bool { return false } var eraseSimulator: Bool { return false } var headless: Bool { return true } var overrideStatusBar: Bool { return false } var overrideStatusBarArguments: String? { return nil } var localizeSimulator: Bool { return false } var darkMode: Bool? { return nil } var appIdentifier: String? { return nil } var addPhotos: [String]? { return nil } var addVideos: [String]? { return nil } var htmlTemplate: String? { return nil } var buildlogPath: String { return "~/Library/Logs/snapshot" } var clean: Bool { return false } var testWithoutBuilding: Bool? { return nil } var configuration: String? { return nil } var xcprettyArgs: String? { return nil } var sdk: String? { return nil } var scheme: String? { return nil } var numberOfRetries: Int { return 1 } var stopAfterFirstError: Bool { return false } var derivedDataPath: String? { return nil } var resultBundle: Bool { return false } var testTargetName: String? { return nil } var namespaceLogFiles: String? { return nil } var concurrentSimulators: Bool { return true } var disableSlideToType: Bool { return false } var clonedSourcePackagesPath: String? { return nil } var skipPackageDependenciesResolution: Bool { return false } var disablePackageAutomaticUpdates: Bool { return false } var testplan: String? { return nil } var onlyTesting: String? { return nil } var skipTesting: String? { return nil } var disableXcpretty: Bool? { return nil } var suppressXcodeOutput: Bool? { return nil } var useSystemScm: Bool { return false } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.70]
40.259804
149
0.699379
4bd7800272119aa8cf8ce0be372f4e5fc20c7175
519
// // UIStoryboard+InstantiateViewController.swift // TheMeal // // Created by Gastón Sobrevilla on 26/09/2020. // Copyright © 2020 Gastón Sobrevilla. All rights reserved. // import Foundation import UIKit extension UIStoryboard { static func instantiate(viewController viewControllerName: String, from appStoryboard: AppStoryboard) -> UIViewController { return UIStoryboard(name: appStoryboard.storyboardName, bundle: .main).instantiateViewController(withIdentifier: viewControllerName) } }
28.833333
140
0.768786
4afbf8e4895fc16dd043b4ce8b2946d49087ffeb
735
// // CellStyle.swift // UnsplashApiApp // // Created by Berta Devant on 12/08/2019. // Copyright © 2019 Berta Devant. All rights reserved. // import Foundation import UIKit struct CellStyle { let reuseIdentifier: String let insets: UIEdgeInsets let itemsPerRow: CGFloat } extension CellStyle { static var iphone = CellStyle(reuseIdentifier: "ImageCell", insets: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), itemsPerRow: 1) static var ipad = CellStyle(reuseIdentifier: "ImageCell", insets: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), itemsPerRow: 2) }
27.222222
97
0.586395
61483999f03199abafaf369ad763243967b13fba
14,406
// // ZipTask.swift // YUKTask // // Created by Ruslan Lutfullin on 2/2/20. // import Foundation // //@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *) //extension Tasks { // //public final class Zip<T1: ProducerTaskProtocol, T2: ProducerTaskProtocol>: // GroupProducerTask<(T1.Output, T2.Output), T1.Failure> // where T1.Failure == T2.Failure //{ // // MARK: // public init( // tasks: (T1, T2) // ) { // let name = String(describing: Self.self) // // let maxQos = // QualityOfService(rawValue: max(tasks.0.qualityOfService.rawValue, tasks.1.qualityOfService.rawValue))! // let maxPriority = // Operation.QueuePriority(rawValue: max(tasks.0.queuePriority.rawValue, tasks.1.queuePriority.rawValue))! // // let zip = // BlockProducerTask<(T1.Output, T2.Output), T1.Failure>( // name: "\(name).Zip", // qos: maxQos, // priority: maxPriority // ) { (task, finish) in // guard !task.isCancelled else { // finish(.failure(.internal(ProducerTaskError.executionFailure))) // return // } // // guard let consumed1 = tasks.0.produced, // let consumed2 = tasks.1.produced else // { // finish(.failure(.internal(ConsumerProducerTaskError.producingFailure))) // return // } // // if case let .success(value1) = consumed1, // case let .success(value2) = consumed2 // { // finish(.success((value1, value2))) // } else if case let .failure(error) = consumed1 { // finish(.failure(error)) // } else if case let .failure(error) = consumed2 { // finish(.failure(error)) // } // } // .addDependency(tasks.0) // .addDependency(tasks.1) // // super.init( // name: name, // qos: maxQos, // priority: maxPriority, // underlyingQueue: (tasks.0 as? TaskQueueContainable)?.innerQueue.underlyingQueue, // tasks: (tasks.0, tasks.1, zip), // produced: zip // ) // } //} // // //public final class Zip3<T1: ProducerTaskProtocol, T2: ProducerTaskProtocol, T3: ProducerTaskProtocol>: // GroupProducerTask<(T1.Output, T2.Output, T3.Output), T1.Failure> // where T1.Failure == T2.Failure, // T2.Failure == T3.Failure //{ // // MARK: // public init( // tasks: (T1, T2, T3), // underlyingQueue: DispatchQueue? = nil // ) { // let name = String(describing: Self.self) // // let maxQos = // QualityOfService( // rawValue: max( // tasks.0.qualityOfService.rawValue, // tasks.1.qualityOfService.rawValue, // tasks.2.qualityOfService.rawValue))! // let maxPriority = // Operation.QueuePriority( // rawValue: max( // tasks.0.queuePriority.rawValue, // tasks.1.queuePriority.rawValue, // tasks.2.queuePriority.rawValue))! // // let zip = // BlockProducerTask<(T1.Output, T2.Output, T3.Output), T1.Failure>( // name: "\(name).Zip", // qos: maxQos, // priority: maxPriority // ) { (task, finish) in // guard !task.isCancelled else { // finish(.failure(.internal(ProducerTaskError.executionFailure))) // return // } // // guard let consumed1 = tasks.0.produced, // let consumed2 = tasks.1.produced, // let consumed3 = tasks.2.produced else // { // finish(.failure(.internal(ConsumerProducerTaskError.producingFailure))) // return // } // // if case let .success(value1) = consumed1, // case let .success(value2) = consumed2, // case let .success(value3) = consumed3 // { // finish(.success((value1, value2, value3))) // } else if case let .failure(error) = consumed1 { // finish(.failure(error)) // } else if case let .failure(error) = consumed2 { // finish(.failure(error)) // } else if case let .failure(error) = consumed3 { // finish(.failure(error)) // } // } // .addDependency(tasks.0) // .addDependency(tasks.1) // .addDependency(tasks.2) // // super.init( // name: name, // qos: maxQos, // priority: maxPriority, // underlyingQueue: (tasks.0 as? TaskQueueContainable)?.innerQueue.underlyingQueue, // tasks: (tasks.0, tasks.1, tasks.2, zip), // produced: zip // ) //} //} // // //public final class Zip4<T1: ProducerTaskProtocol, // T2: ProducerTaskProtocol, // T3: ProducerTaskProtocol, // T4: ProducerTaskProtocol>: // GroupProducerTask<(T1.Output, T2.Output, T3.Output, T4.Output), T1.Failure> // where T1.Failure == T2.Failure, // T2.Failure == T3.Failure, // T3.Failure == T4.Failure //{ // // MARK: // public init( // tasks: (T1, T2, T3, T4), // underlyingQueue: DispatchQueue? = nil // ) { // let name = String(describing: Self.self) // // let maxQos = // QualityOfService( // rawValue: max( // tasks.0.qualityOfService.rawValue, // tasks.1.qualityOfService.rawValue, // tasks.2.qualityOfService.rawValue, // tasks.3.qualityOfService.rawValue))! // let maxPriority = // Operation.QueuePriority( // rawValue: max( // tasks.0.queuePriority.rawValue, // tasks.1.queuePriority.rawValue, // tasks.2.queuePriority.rawValue, // tasks.3.queuePriority.rawValue))! // // let zip = // BlockProducerTask<(T1.Output, T2.Output, T3.Output, T4.Output), T1.Failure>( // name: "\(name).Zip", // qos: maxQos, // priority: maxPriority // ) { (task, finish) in // guard !task.isCancelled else { // finish(.failure(.internal(ProducerTaskError.executionFailure))) // return // } // // guard let consumed1 = tasks.0.produced, // let consumed2 = tasks.1.produced, // let consumed3 = tasks.2.produced, // let consumed4 = tasks.3.produced else // { // finish(.failure(.internal(ConsumerProducerTaskError.producingFailure))) // return // } // // if case let .success(value1) = consumed1, // case let .success(value2) = consumed2, // case let .success(value3) = consumed3, // case let .success(value4) = consumed4 // { // finish(.success((value1, value2, value3, value4))) // } else if case let .failure(error) = consumed1 { // finish(.failure(error)) // } else if case let .failure(error) = consumed2 { // finish(.failure(error)) // } else if case let .failure(error) = consumed3 { // finish(.failure(error)) // } else if case let .failure(error) = consumed4 { // finish(.failure(error)) // } // } // .addDependency(tasks.0) // .addDependency(tasks.1) // .addDependency(tasks.2) // .addDependency(tasks.3) // // super.init( // name: name, // qos: maxQos, // priority: maxPriority, // underlyingQueue: (tasks.0 as? TaskQueueContainable)?.innerQueue.underlyingQueue, // tasks: (tasks.0, tasks.1, tasks.2, tasks.3, zip), // produced: zip // ) // } //} // // //public final class Zip5<T1: ProducerTaskProtocol, // T2: ProducerTaskProtocol, // T3: ProducerTaskProtocol, // T4: ProducerTaskProtocol, // T5: ProducerTaskProtocol>: // GroupProducerTask<(T1.Output, T2.Output, T3.Output, T4.Output, T5.Output), T1.Failure> // where T1.Failure == T2.Failure, // T2.Failure == T3.Failure, // T3.Failure == T4.Failure, // T4.Failure == T5.Failure //{ // // MARK: // public init( // tasks: (T1, T2, T3, T4, T5), // underlyingQueue: DispatchQueue? = nil // ) { // let name = String(describing: Self.self) // // let maxQos = // QualityOfService( // rawValue: max( // tasks.0.qualityOfService.rawValue, // tasks.1.qualityOfService.rawValue, // tasks.2.qualityOfService.rawValue, // tasks.3.qualityOfService.rawValue, // tasks.4.qualityOfService.rawValue))! // let maxPriority = // Operation.QueuePriority( // rawValue: max( // tasks.0.queuePriority.rawValue, // tasks.1.queuePriority.rawValue, // tasks.2.queuePriority.rawValue, // tasks.3.queuePriority.rawValue, // tasks.4.queuePriority.rawValue))! // // let zip = // BlockProducerTask<(T1.Output, T2.Output, T3.Output, T4.Output, T5.Output), T1.Failure>( // name: "\(name).Zip", // qos: maxQos, // priority: maxPriority // ) { (task, finish) in // guard !task.isCancelled else { // finish(.failure(.internal(ProducerTaskError.executionFailure))) // return // } // // guard let consumed1 = tasks.0.produced, // let consumed2 = tasks.1.produced, // let consumed3 = tasks.2.produced, // let consumed4 = tasks.3.produced, // let consumed5 = tasks.4.produced else // { // finish(.failure(.internal(ConsumerProducerTaskError.producingFailure))) // return // } // // if case let .success(value1) = consumed1, // case let .success(value2) = consumed2, // case let .success(value3) = consumed3, // case let .success(value4) = consumed4, // case let .success(value5) = consumed5 // { // finish(.success((value1, value2, value3, value4, value5))) // } else if case let .failure(error) = consumed1 { // finish(.failure(error)) // } else if case let .failure(error) = consumed2 { // finish(.failure(error)) // } else if case let .failure(error) = consumed3 { // finish(.failure(error)) // } else if case let .failure(error) = consumed4 { // finish(.failure(error)) // } else if case let .failure(error) = consumed5 { // finish(.failure(error)) // } // } // .addDependency(tasks.0) // .addDependency(tasks.1) // .addDependency(tasks.2) // .addDependency(tasks.3) // .addDependency(tasks.4) // // super.init( // name: name, // qos: maxQos, // priority: maxPriority, // underlyingQueue: (tasks.0 as? TaskQueueContainable)?.innerQueue.underlyingQueue, // tasks: (tasks.0, tasks.1, tasks.2, tasks.3, tasks.4, zip), // produced: zip // ) // } //} // // //public final class Zip6<T1: ProducerTaskProtocol, // T2: ProducerTaskProtocol, // T3: ProducerTaskProtocol, // T4: ProducerTaskProtocol, // T5: ProducerTaskProtocol, // T6: ProducerTaskProtocol>: // GroupProducerTask<(T1.Output, T2.Output, T3.Output, T4.Output, T5.Output, T6.Output), T1.Failure> // where T1.Failure == T2.Failure, // T2.Failure == T3.Failure, // T3.Failure == T4.Failure, // T4.Failure == T5.Failure, // T5.Failure == T6.Failure //{ // // MARK: // public init( // tasks: (T1, T2, T3, T4, T5, T6), // underlyingQueue: DispatchQueue? = nil // ) { // let name = String(describing: Self.self) // // let maxQos = // QualityOfService( // rawValue: max( // tasks.0.qualityOfService.rawValue, // tasks.1.qualityOfService.rawValue, // tasks.2.qualityOfService.rawValue, // tasks.3.qualityOfService.rawValue, // tasks.4.qualityOfService.rawValue, // tasks.5.qualityOfService.rawValue))! // let maxPriority = // Operation.QueuePriority( // rawValue: max( // tasks.0.queuePriority.rawValue, // tasks.1.queuePriority.rawValue, // tasks.2.queuePriority.rawValue, // tasks.3.queuePriority.rawValue, // tasks.4.queuePriority.rawValue, // tasks.5.queuePriority.rawValue))! // // let zip = // BlockProducerTask<(T1.Output, T2.Output, T3.Output, T4.Output, T5.Output, T6.Output), T1.Failure>( // name: "\(name).Zip", // qos: maxQos, // priority: maxPriority // ) { (task, finish) in // guard !task.isCancelled else { // finish(.failure(.internal(ProducerTaskError.executionFailure))) // return // } // // guard let consumed1 = tasks.0.produced, // let consumed2 = tasks.1.produced, // let consumed3 = tasks.2.produced, // let consumed4 = tasks.3.produced, // let consumed5 = tasks.4.produced, // let consumed6 = tasks.5.produced else // { // finish(.failure(.internal(ConsumerProducerTaskError.producingFailure))) // return // } // // if case let .success(value1) = consumed1, // case let .success(value2) = consumed2, // case let .success(value3) = consumed3, // case let .success(value4) = consumed4, // case let .success(value5) = consumed5, // case let .success(value6) = consumed6 // { // finish(.success((value1, value2, value3, value4, value5, value6))) // } else if case let .failure(error) = consumed1 { // finish(.failure(error)) // } else if case let .failure(error) = consumed2 { // finish(.failure(error)) // } else if case let .failure(error) = consumed3 { // finish(.failure(error)) // } else if case let .failure(error) = consumed4 { // finish(.failure(error)) // } else if case let .failure(error) = consumed5 { // finish(.failure(error)) // } else if case let .failure(error) = consumed6 { // finish(.failure(error)) // } // } // .addDependency(tasks.0) // .addDependency(tasks.1) // .addDependency(tasks.2) // .addDependency(tasks.3) // .addDependency(tasks.4) // .addDependency(tasks.5) // // super.init( // name: name, // qos: maxQos, // priority: maxPriority, // underlyingQueue: (tasks.0 as? TaskQueueContainable)?.innerQueue.underlyingQueue, // tasks: (tasks.0, tasks.1, tasks.2, tasks.3, tasks.4, tasks.5, zip), // produced: zip // ) // } //} // //}
34.056738
111
0.562335
22fc03807ecc2c777658488c829f38355738a642
98
public protocol DocumentBodyPrinting { func print(from node: Node, base: String) -> String }
19.6
55
0.72449
b96519d028a49d0fdeb5b85e4cd0b1a6d5d72e71
4,239
// Copyright (c) 2015 Felix Jendrusch. All rights reserved. import UIKit public enum CalculationMode: Equatable { case Linear case Discrete case Paced case Cubic case CubicPaced public var name: String { switch self { case .Linear: return kCAAnimationLinear case .Discrete: return kCAAnimationDiscrete case .Paced: return kCAAnimationPaced case .Cubic: return kCAAnimationCubic case .CubicPaced: return kCAAnimationCubicPaced } } } public func == (lhs: CalculationMode, rhs: CalculationMode) -> Bool { return lhs.name == rhs.name } public enum RotationMode: Equatable { case Auto case AutoReverse public var name: String { switch self { case .Auto: return kCAAnimationRotateAuto case .AutoReverse: return kCAAnimationRotateAutoReverse } } } public func == (lhs: RotationMode, rhs: RotationMode) -> Bool { return lhs.name == rhs.name } public class KeyframeAnimation<T>: PropertyAnimation<T, CAKeyframeAnimation> { public var values: [T]? = nil public var path: CGPath? = nil public var keyTimes: [Float]? = nil public var timingFunctions: [MediaTimingFunction]? = nil public var calculationMode: CalculationMode = .Linear public var tensionValues: [Float]? = nil public var continuityValues: [Float]? = nil public var biasValues: [Float]? = nil public var rotationMode: RotationMode? = nil public override init() {} public init(keyFrames: [(Float, T)], duration aDuration: CFTimeInterval? = nil) { super.init() let (keyTimes, values) = unzip(keyFrames) self.values = values self.keyTimes = keyTimes if let duration = aDuration { self.duration = duration } } public init(path: CGPath, duration aDuration: CFTimeInterval? = nil) { super.init() self.path = path if let duration = aDuration { self.duration = duration } } internal override func animationForProperty(property: Property<T>) -> CAKeyframeAnimation! { var animation = CAKeyframeAnimation() populateAnimation(animation, forProperty: property) return animation } internal override func populateAnimation(animation: CAKeyframeAnimation, forProperty property: Property<T>) { super.populateAnimation(animation, forProperty: property) animation.values = values?.map(property.pack) animation.path = path animation.keyTimes = keyTimes animation.timingFunctions = timingFunctions?.map { $0.function() } animation.calculationMode = calculationMode.name animation.tensionValues = tensionValues animation.continuityValues = continuityValues animation.biasValues = biasValues animation.rotationMode = rotationMode?.name } } private func animation<T>(keyFrames: [(Float, T)]) -> KeyframeAnimation<T> { return KeyframeAnimation(keyFrames: keyFrames) } private func animation(path: CGPath) -> KeyframeAnimation<CGPoint> { return KeyframeAnimation(path: path) } infix operator ~ { associativity none precedence 131 } public func ~ <T>(lhs: [(Float, T)], rhs: MediaTimingFunction) -> KeyframeAnimation<T> { return animation(lhs) ~ rhs } public func ~ (lhs: CGPath, rhs: MediaTimingFunction) -> KeyframeAnimation<CGPoint> { return animation(lhs) ~ rhs } public func ~ <T>(lhs: KeyframeAnimation<T>, rhs: [MediaTimingFunction]) -> KeyframeAnimation<T> { lhs.timingFunctions = rhs return lhs } public func ~ <T>(lhs: [(Float, T)], rhs: [MediaTimingFunction]) -> KeyframeAnimation<T> { return animation(lhs) ~ rhs } public func ~ (lhs: CGPath, rhs: [MediaTimingFunction]) -> KeyframeAnimation<CGPoint> { return animation(lhs) ~ rhs } infix operator ~= { associativity none precedence 130 } public func ~= <T>(lhs: Property<T>, rhs: [(Float, T)]) -> CAKeyframeAnimation { return lhs ~= animation(rhs) } public func ~= (lhs: Property<CGPoint>, rhs: CGPath) -> CAKeyframeAnimation { return lhs ~= animation(rhs) }
27.705882
113
0.658174
d7297323e3f0e1e8362c2e42691fa793503d86bb
9,821
import Foundation import CoreLocation public class Location: NSObject, NSSecureCoding { private static let NON_UNIQUE_NAMES = ["Hauptbahnhof", "Hbf", "Hbf.", "HB", "Bahnhof", "Bf", "Bf.", "Bhf", "Bhf.", "Busbahnhof", "Südbahnhof", "ZOB", "Schiffstation", "Schiffst.", "Zentrum", "Markt", "Dorf", "Kirche", "Nord", "Ost", "Süd", "West", "Airport", "Flughafen", "Talstation"] public static var supportsSecureCoding: Bool = true public let type: LocationType public let id: String? public let coord: LocationPoint? public let place: String? public let name: String? public let products: [Product]? lazy var distanceFormatter: NumberFormatter = { let numberFormatter = NumberFormatter() numberFormatter.maximumFractionDigits = 2 return numberFormatter }() public init?(type: LocationType, id: String?, coord: LocationPoint?, place: String?, name: String?, products: [Product]?) { if let id = id, id.isEmpty { return nil } if let _ = place, name == nil { return nil } if type == .any { if id != nil { return nil } } else if type == .coord && coord == nil { return nil } self.type = type self.id = id; self.coord = coord self.place = place self.name = name self.products = products } public init(id: String) { self.type = .station self.id = id self.coord = nil self.place = nil self.name = nil self.products = nil } public init(anyName: String?) { self.type = .any self.id = nil self.coord = nil self.place = nil self.name = anyName self.products = nil } public init(lat: Int, lon: Int) { self.type = .coord self.id = nil self.coord = LocationPoint(lat: lat, lon: lon) self.place = nil self.name = nil self.products = nil } convenience public init?(type: LocationType, id: String?, coord: LocationPoint?, place: String?, name: String?) { self.init(type: type, id: id, coord: coord, place: place, name: name, products: nil) } convenience public init?(type: LocationType, id: String) { self.init(type: type, id: id, coord: nil, place: nil, name: nil) } required convenience public init?(coder aDecoder: NSCoder) { guard let type = LocationType(rawValue: aDecoder.decodeInteger(forKey: PropertyKey.locationTypeKey)) else { print("Location type could not be decoded") return nil } let id = aDecoder.decodeObject(of: NSString.self, forKey: PropertyKey.locationIdKey) as String? let coord: LocationPoint? if aDecoder.containsValue(forKey: PropertyKey.locationLatKey) && aDecoder.containsValue(forKey: PropertyKey.locationLonKey) { let lat = aDecoder.decodeInteger(forKey: PropertyKey.locationLatKey) let lon = aDecoder.decodeInteger(forKey: PropertyKey.locationLonKey) coord = LocationPoint(lat: lat, lon: lon) } else { coord = nil } let place = aDecoder.decodeObject(of: NSString.self, forKey: PropertyKey.locationPlaceKey) as String? let name = aDecoder.decodeObject(of: NSString.self, forKey: PropertyKey.locationNameKey) as String? self.init(type: type, id: id, coord: coord, place: place, name: name) } public func encode(with aCoder: NSCoder) { aCoder.encode(type.rawValue, forKey: PropertyKey.locationTypeKey) aCoder.encode(id, forKey: PropertyKey.locationIdKey) if let coord = coord { aCoder.encode(coord.lat, forKey: PropertyKey.locationLatKey) aCoder.encode(coord.lon, forKey: PropertyKey.locationLonKey) } aCoder.encode(place, forKey: PropertyKey.locationPlaceKey) aCoder.encode(name, forKey: PropertyKey.locationNameKey) } public func hasLocation() -> Bool { return coord != nil } public func hasName() -> Bool { return name != nil || place != nil } public func getUniqueShortName() -> String { if let place = self.place, !place.isEmpty, let name = self.name, !name.contains(place) && (Location.NON_UNIQUE_NAMES.contains(name) || name.split(separator: " ").first(where: {Location.NON_UNIQUE_NAMES.contains(String($0))}) != nil || name.split(separator: ",").first(where: {Location.NON_UNIQUE_NAMES.contains(String($0))}) != nil) { return place + ", " + name } else if let name = self.name { return name } else if let id = self.id, id != "" { return id } else if let coord = coord { return "\(Double(coord.lat) / 1e6):\(Double(coord.lon) / 1e6)" } else { return type.displayName } } public func getUniqueLongName() -> String { var result = "" if let name = name { result += name } if let place = place, !result.contains(place) { if !result.isEmpty { result += ", " } result += place } if result.isEmpty { if let coord = coord { result = "\(Double(coord.lat) / 1e6):\(Double(coord.lon) / 1e6)" } else { result = type.displayName } } return result } public func getMultilineLabel() -> String { var result = "" if let place = place { result += place } if let name = name { if !result.isEmpty { result += "\n" } result += name } if result.isEmpty { if let coord = coord { result = "\(Double(coord.lat) / 1e6):\(Double(coord.lon) / 1e6)" } else { result = type.displayName } } return result } public func getDistanceText(_ location: CLLocation, maximumFractionDigits: Int = 2) -> String { let distance = getDistance(from: location) distanceFormatter.maximumFractionDigits = maximumFractionDigits if distance > 1000 { return "\(distanceFormatter.string(from: (distance / 1000) as NSNumber) ?? String(format: "%.2f", distance / 1000))\u{00a0}km" } else { return "\(Int(distance))\u{00a0}m" } } public func getDistance(from location: CLLocation) -> CLLocationDistance { let distance: CLLocationDistance if let coord = coord { distance = location.distance(from: CLLocation(latitude: Double(coord.lat) / 1000000.0, longitude: Double(coord.lon) / 1000000.0)) } else { distance = 0 } return distance } public func isIdentified() -> Bool { if type == .station { return id != nil && id != "" } if type == .poi { return true } if type == .address || type == .coord { return hasLocation() } return false } override public var description: String { return getUniqueLongName() } public override func isEqual(_ object: Any?) -> Bool { guard let other = object as? Location else { return false } if self === other { return true } if self.type != other.type { return false } if let id = self.id { return id == other.id ?? "" } if coord != nil && other.coord != nil && coord == other.coord { return true } if self.place != other.place { return false } if self.name != other.name { return false } return true } public override var hash: Int { get { if let id = id { return id.hash } else { if let coord = coord { return "\(coord.lat):\(coord.lon)".hashValue } return type.hashValue } } } struct PropertyKey { static let locationTypeKey = "type" static let locationIdKey = "id" static let locationLatKey = "lat" static let locationLonKey = "lon" static let locationPlaceKey = "place" static let locationNameKey = "name" } } public enum LocationType: Int { /** Location can represent any of the below. Mainly meant for user input. */ case any, /** Location represents a station or stop. */ station, /** Location represents a point of interest. */ poi, /** Location represents a postal address. */ address, /** Location represents a just a plain coordinate, e.g. acquired by GPS. */ coord public static let ALL: [LocationType] = [.any, .station, .poi, .address, .coord] private static let stringValues: [LocationType: String] = [.any: "any", .station: "station", .poi: "poi", .address: "address", .coord: "coord"] public var stringValue: String { return LocationType.stringValues[self]! } public var displayName: String { switch self { case .any: return "Ort" case .station: return "Haltestelle" case .poi: return "Point Of Interest" case .address: return "Adresse" case .coord: return "Adresse" } } public static func from(string: String) -> LocationType? { return stringValues.first(where: {$1 == string})?.key } }
33.179054
342
0.553304
f75f397737be3b509dd938f41bfe8cbc236dfe07
24,083
// // AffineMatrix.swift // LlamaCore // // Created by Thomas Roughton on 3/08/18. // import RealModule /// A matrix that can represent 3D affine transformations. /// Internally, the data is stored in row-major format for size reasons; /// however, all operations treat it as a column-major type /// It's conceptually a Matrix4x3f but happens to be stored as a 3x4f. public struct AffineMatrix<Scalar: SIMDScalar & BinaryFloatingPoint>: Hashable, Codable, CustomStringConvertible { public var r0 : SIMD4<Scalar> public var r1 : SIMD4<Scalar> public var r2 : SIMD4<Scalar> @inlinable public init() { self.init(diagonal: SIMD3(repeating: 1.0)) } @inlinable public init(diagonal: SIMD3<Scalar>) { self.r0 = SIMD4(diagonal.x, 0, 0, 0) self.r1 = SIMD4(0, diagonal.y, 0, 0) self.r2 = SIMD4(0, 0, diagonal.z, 0) } /// Creates an instance with the specified columns /// /// - parameter c0: a vector representing column 0 /// - parameter c1: a vector representing column 1 /// - parameter c2: a vector representing column 2 /// - parameter c3: a vector representing column 3 @inlinable public init(_ c0: SIMD4<Scalar>, _ c1: SIMD4<Scalar>, _ c2: SIMD4<Scalar>, _ c3: SIMD4<Scalar>) { self.r0 = SIMD4(c0.x, c1.x, c2.x, c3.x) self.r1 = SIMD4(c0.y, c1.y, c2.y, c3.y) self.r2 = SIMD4(c0.z, c1.z, c2.z, c3.z) assert(SIMD4(c0.w, c1.w, c2.w, c3.w) == SIMD4(0, 0, 0, 1), "Columns cannot be represented as an affine transform.") } @inlinable public init(rows r0: SIMD4<Scalar>, _ r1: SIMD4<Scalar>, _ r2: SIMD4<Scalar>) { self.r0 = r0 self.r1 = r1 self.r2 = r2 } @inlinable public init(_ matrix: Matrix4x4<Scalar>) { let transpose = matrix.transpose assert(transpose[3] == SIMD4<Scalar>(0, 0, 0, 1)) self.init(rows: transpose[0], transpose[1], transpose[2]) } @inlinable public init(_ matrix: Matrix3x3<Scalar>) { self.init(rows: SIMD4<Scalar>(matrix[0].x, matrix[1].x, matrix[2].x, 0), SIMD4<Scalar>(matrix[0].y, matrix[1].y, matrix[2].y, 0), SIMD4<Scalar>(matrix[0].z, matrix[1].z, matrix[2].z, 0)) } /// Access the `col`th column vector @inlinable public subscript(col: Int) -> SIMD4<Scalar> { get { switch col { case 0: return SIMD4(r0.x, r1.x, r2.x, 0) case 1: return SIMD4(r0.y, r1.y, r2.y, 0) case 2: return SIMD4(r0.z, r1.z, r2.z, 0) case 3: return SIMD4(r0.w, r1.w, r2.w, 1) default: preconditionFailure("Index out of bounds") } } set { switch col { case 0: self.r0.x = newValue.x; self.r1.x = newValue.y; self.r2.x = newValue.z; assert(newValue.w == 0) case 1: self.r0.y = newValue.x; self.r1.y = newValue.y; self.r2.y = newValue.z; assert(newValue.w == 0) case 2: self.r0.z = newValue.x; self.r1.z = newValue.y; self.r2.z = newValue.z; assert(newValue.w == 0) case 3: self.r0.w = newValue.x; self.r1.w = newValue.y; self.r2.w = newValue.z; assert(newValue.w == 1) default: preconditionFailure("Index out of bounds") } } } @inlinable @inline(__always) public subscript(row row: Int) -> SIMD4<Scalar> { get { switch row { case 0: return self.r0 case 1: return self.r1 case 2: return self.r2 case 3: return SIMD4(0, 0, 0, 1) default: preconditionFailure("Index out of bounds") } } set { switch row { case 0: self.r0 = newValue case 1: self.r1 = newValue case 2: self.r2 = newValue case 3: assert(newValue == SIMD4(0, 0, 0, 1)) default: preconditionFailure("Index out of bounds") } } } @inlinable @inline(__always) public subscript(row: Int, col: Int) -> Scalar { get { switch row { case 0: return self.r0[col] case 1: return self.r1[col] case 2: return self.r2[col] case 3: return SIMD4<Scalar>(0, 0, 0, 1)[col] default: preconditionFailure("Index out of bounds") } } set { switch row { case 0: self.r0[col] = newValue case 1: self.r1[col] = newValue case 2: self.r2[col] = newValue case 3: break default: preconditionFailure("Index out of bounds") } } } @inlinable public var inverse : AffineMatrix { // https://lxjk.github.io/2017/09/03/Fast-4x4-Matrix-Inverse-with-SSE-SIMD-Explained.html#_general_matrix_inverse var result = AffineMatrix() // transpose 3x3, we know m30 = m31 = m32 = 0 let t0 = SIMD4(lowHalf: self.r0.lowHalf, highHalf: self.r1.lowHalf) let t1 = SIMD4(self.r0.z, 0.0, self.r1.z, 0.0) result.r0 = SIMD4(lowHalf: t0.evenHalf, highHalf: SIMD2(self.r2.x, 0.0)) result.r1 = SIMD4(lowHalf: t0.oddHalf, highHalf: SIMD2(self.r2.y, 0.0)) result.r2 = SIMD4(lowHalf: t1.evenHalf, highHalf: SIMD2(self.r2.z, 0.0)) // (SizeSqr(mVec[0]), SizeSqr(mVec[1]), SizeSqr(mVec[2]), 0) var sizeSqr = self.r0.xyz * self.r0.xyz sizeSqr.addProduct(self.r1.xyz, self.r1.xyz) sizeSqr.addProduct(self.r2.xyz, self.r2.xyz) // optional test to avoid divide by 0 // for each component, if(sizeSqr < SMALL_NUMBER) sizeSqr = 1; let rSizeSqr = (1.0 / sizeSqr).replacing(with: 1.0, where: sizeSqr .< 1.0e-8) result.r0 *= rSizeSqr.x result.r1 *= rSizeSqr.y result.r2 *= rSizeSqr.z // translation = -(result * self.translation) var translation = SIMD3(result.r0.x, result.r1.x, result.r2.x) * self.r0.w translation.addProduct(SIMD3(result.r0.y, result.r1.y, result.r2.y), self.r1.w) translation.addProduct(SIMD3(result.r0.z, result.r1.z, result.r2.z), self.r2.w) result.r0.w = -translation.x result.r1.w = -translation.y result.r2.w = -translation.z return result } @inlinable public var inverseNoScale : AffineMatrix { var result = AffineMatrix() // Transpose the 3x3 matrix. let t0 = SIMD4(lowHalf: self.r0.lowHalf, highHalf: self.r1.lowHalf) let t1 = SIMD4(self.r0.z, 0.0, self.r1.z, 0.0) result.r0 = SIMD4(lowHalf: t0.evenHalf, highHalf: SIMD2(self.r2.x, 0.0)) result.r1 = SIMD4(lowHalf: t0.oddHalf, highHalf: SIMD2(self.r2.y, 0.0)) result.r2 = SIMD4(lowHalf: t1.evenHalf, highHalf: SIMD2(self.r2.z, 0.0)) // translation = -(result * self.translation) var translation = SIMD3(result.r0.x, result.r1.x, result.r2.x) * self.r0.w translation.addProduct(SIMD3(result.r0.y, result.r1.y, result.r2.y), self.r1.w) translation.addProduct(SIMD3(result.r0.z, result.r1.z, result.r2.z), self.r2.w) result.r0.w = -translation.x result.r1.w = -translation.y result.r2.w = -translation.z return result } /// Returns the maximum scale along any axis. @inlinable public var maximumScale : Scalar { let s0 = SIMD3<Scalar>(self.r0.x, self.r1.x, self.r2.x).lengthSquared let s1 = SIMD3<Scalar>(self.r0.y, self.r1.y, self.r2.y).lengthSquared let s2 = SIMD3<Scalar>(self.r0.z, self.r1.z, self.r2.z).lengthSquared return max(s0, max(s1, s2)).squareRoot() } public var description : String { return """ AffineMatrix( \(self.r0.x), \(self.r0.y), \(self.r0.z), \(self.r0.w), \(self.r1.x), \(self.r1.y), \(self.r1.z), \(self.r1.w), \(self.r2.x), \(self.r2.y), \(self.r2.z), \(self.r2.w) ) """ } } extension AffineMatrix { @inlinable public static func *(lhs: AffineMatrix, rhs: AffineMatrix) -> AffineMatrix { var r0 = SIMD4(0, 0, 0, lhs.r0.w) r0.addProduct(SIMD4(repeating: lhs.r0.x), rhs.r0) r0.addProduct(SIMD4(repeating: lhs.r0.y), rhs.r1) r0.addProduct(SIMD4(repeating: lhs.r0.z), rhs.r2) var r1 = SIMD4(0, 0, 0, lhs.r1.w) r1.addProduct(SIMD4(repeating: lhs.r1.x), rhs.r0) r1.addProduct(SIMD4(repeating: lhs.r1.y), rhs.r1) r1.addProduct(SIMD4(repeating: lhs.r1.z), rhs.r2) var r2 = SIMD4(0, 0, 0, lhs.r2.w) r2.addProduct(SIMD4(repeating: lhs.r2.x), rhs.r0) r2.addProduct(SIMD4(repeating: lhs.r2.y), rhs.r1) r2.addProduct(SIMD4(repeating: lhs.r2.z), rhs.r2) return AffineMatrix(rows: r0, r1, r2) } @inlinable public static func *(lhs: Matrix4x4<Scalar>, rhs: AffineMatrix) -> Matrix4x4<Scalar> { return lhs * Matrix4x4(rhs) } @inlinable public static func *(lhs: AffineMatrix, rhs: SIMD4<Scalar>) -> SIMD4<Scalar> { var result = SIMD3(lhs.r0.x, lhs.r1.x, lhs.r2.x) * SIMD3(repeating: rhs.x) result.addProduct(SIMD3(lhs.r0.y, lhs.r1.y, lhs.r2.y), SIMD3(repeating: rhs.y)) result.addProduct(SIMD3(lhs.r0.z, lhs.r1.z, lhs.r2.z), SIMD3(repeating: rhs.z)) result.addProduct(SIMD3(lhs.r0.w, lhs.r1.w, lhs.r2.w), SIMD3(repeating: rhs.w)) return SIMD4(result, rhs.w) } @inlinable public func transform(point: SIMD3<Scalar>) -> SIMD3<Scalar> { let lhs = self let rhs = point var result = SIMD3(lhs.r0.w, lhs.r1.w, lhs.r2.w) result.addProduct(SIMD3(lhs.r0.x, lhs.r1.x, lhs.r2.x), SIMD3(repeating: rhs.x)) result.addProduct(SIMD3(lhs.r0.y, lhs.r1.y, lhs.r2.y), SIMD3(repeating: rhs.y)) result.addProduct(SIMD3(lhs.r0.z, lhs.r1.z, lhs.r2.z), SIMD3(repeating: rhs.z)) return result } @inlinable public func transform(direction: SIMD3<Scalar>) -> SIMD3<Scalar> { let lhs = self let rhs = direction var result = SIMD3(lhs.r0.x, lhs.r1.x, lhs.r2.x) * SIMD3(repeating: rhs.x) result.addProduct(SIMD3(lhs.r0.y, lhs.r1.y, lhs.r2.y), SIMD3(repeating: rhs.y)) result.addProduct(SIMD3(lhs.r0.z, lhs.r1.z, lhs.r2.z), SIMD3(repeating: rhs.z)) return result } } extension Matrix3x3 { @inlinable public init(_ affineMatrix: AffineMatrix<Scalar>) { self.init(SIMD3(affineMatrix.r0.x, affineMatrix.r1.x, affineMatrix.r2.x), SIMD3(affineMatrix.r0.y, affineMatrix.r1.y, affineMatrix.r2.y), SIMD3(affineMatrix.r0.z, affineMatrix.r1.z, affineMatrix.r2.z)) } } extension Matrix4x4 { @inlinable public init(_ affineMatrix: AffineMatrix<Scalar>) { self.init(SIMD4<Scalar>(affineMatrix.r0.x, affineMatrix.r1.x, affineMatrix.r2.x, 0), SIMD4<Scalar>(affineMatrix.r0.y, affineMatrix.r1.y, affineMatrix.r2.y, 0), SIMD4<Scalar>(affineMatrix.r0.z, affineMatrix.r1.z, affineMatrix.r2.z, 0), SIMD4<Scalar>(affineMatrix.r0.w, affineMatrix.r1.w, affineMatrix.r2.w, 1)) } } extension AffineMatrix { /// Returns the identity matrix @inlinable public static var identity : AffineMatrix { return AffineMatrix(diagonal: SIMD3<Scalar>(repeating: 1.0)) } //MARK: matrix operations @inlinable public static func lookAt(eye: SIMD3<Scalar>, at: SIMD3<Scalar>, up: SIMD3<Scalar> = SIMD3(0, 1, 0)) -> AffineMatrix { return lookAtLH(eye: eye, at: at, up: up) } @inlinable public static func lookAtLH(eye: SIMD3<Scalar>, at: SIMD3<Scalar>, up: SIMD3<Scalar> = SIMD3(0, 1, 0)) -> AffineMatrix { let view = normalize(at - eye) return lookAtLH(eye: eye, forward: view, up: up) } @inlinable public static func lookAtLH(eye: SIMD3<Scalar>, forward view: SIMD3<Scalar>, up: SIMD3<Scalar> = SIMD3(0, 1, 0)) -> AffineMatrix { var up = up if abs(dot(up, view)) > 0.99 { up = SIMD3<Scalar>(0, 0, 1) } let right = normalize(cross(up, view)) let u = cross(view, right) return AffineMatrix(rows: SIMD4<Scalar>(right, -dot(right, eye)), SIMD4<Scalar>(u, -dot(u, eye)), SIMD4<Scalar>(view, -dot(view, eye)) ) } @inlinable public static func lookAtInv(eye: SIMD3<Scalar>, at: SIMD3<Scalar>, up: SIMD3<Scalar> = SIMD3(0, 1, 0)) -> AffineMatrix { let view = normalize(at - eye) return lookAtInv(eye: eye, forward: view, up: up) } @inlinable public static func lookAtInv(eye: SIMD3<Scalar>, forward view: SIMD3<Scalar>, up: SIMD3<Scalar> = SIMD3(0, 1, 0)) -> AffineMatrix { var up = up if abs(dot(up, view)) > 0.99 { up = SIMD3<Scalar>(0, 0, 1) } let right = normalize(cross(up, view)) let u = cross(view, right) return AffineMatrix(rows: SIMD4<Scalar>(right.x, u.x, view.x, eye.x), SIMD4<Scalar>(right.y, u.y, view.y, eye.y), SIMD4<Scalar>(right.z, u.z, view.z, eye.z) ) } @inlinable public static func lookAt(forward: SIMD3<Scalar>) -> AffineMatrix { var up = SIMD3<Scalar>(0, 1, 0) if abs(dot(up, forward)) > 0.99 { up = SIMD3<Scalar>(0, 0, 1) } let right = normalize(cross(up, forward)) let u = cross(forward, right) return AffineMatrix(rows: SIMD4<Scalar>(right.x, u.x, forward.x, 0), SIMD4<Scalar>(right.y, u.y, forward.y, 0), SIMD4<Scalar>(right.z, u.z, forward.z, 0) ) } //MARK: matrix operations @inlinable public static func scale(by s: SIMD3<Scalar>) -> AffineMatrix { return AffineMatrix.scale(sx: s.x, sy: s.y, sz: s.z) } @inlinable public static func scale(sx: Scalar, sy: Scalar, sz: Scalar) -> AffineMatrix { return AffineMatrix(diagonal: SIMD3<Scalar>(sx, sy, sz)) } @inlinable public static func translate(by t: SIMD3<Scalar>) -> AffineMatrix { return AffineMatrix.translate(tx: t.x, ty: t.y, tz: t.z) } @inlinable public static func translate(tx: Scalar, ty: Scalar, tz: Scalar) -> AffineMatrix { return AffineMatrix(rows: SIMD4<Scalar>(1, 0, 0, tx), SIMD4<Scalar>(0, 1, 0, ty), SIMD4<Scalar>(0, 0, 1, tz)) } } extension AffineMatrix where Scalar : Real { @inlinable public init(_ q: Quaternion<Scalar>) { self.init(quaternion: q) } @inlinable public init(quaternion q: Quaternion<Scalar>) { self.init() let sqw : Scalar = q.w*q.w let sqx : Scalar = q.x*q.x let sqy : Scalar = q.y*q.y let sqz : Scalar = q.z*q.z let n : Scalar = sqx + sqy + sqz + sqw let s : Scalar = n == 0 ? 0 : 2.0 / n let wx = s * q.w * q.x let wy = s * q.w * q.y let wz = s * q.w * q.z let xx = s * sqx let xy = s * q.x * q.y let xz = s * q.x * q.z let yy = s * sqy let yz = s * q.y * q.z let zz = s * sqz self[0,0] = 1.0 - (yy + zz) self[0,1] = xy - wz self[0,2] = xz + wy self[1,0] = xy + wz self[1,1] = 1.0 - (xx + zz) self[1,2] = yz - wx self[2,0] = xz - wy self[2,1] = yz + wx self[2,2] = 1.0 - (xx + yy) } @inlinable public static func rotate(_ quaternion: Quaternion<Scalar>) -> AffineMatrix { return AffineMatrix(quaternion: quaternion) } /// Create a matrix with rotates clockwise around the x axis @inlinable public static func rotate(x: Angle<Scalar>) -> AffineMatrix { let (sin: sx, cos: cx) = Angle<Scalar>.sincos(x) var r = AffineMatrix() r[0, 0] = 1.0 r[1, 1] = cx r[1, 2] = sx r[2, 1] = -sx r[2, 2] = cx return r } /// Returns a transformation matrix that rotates clockwise around the y axis @inlinable public static func rotate(y: Angle<Scalar>) -> AffineMatrix { let (sin: sy, cos: cy) = Angle<Scalar>.sincos(y) var r = AffineMatrix() r[0,0] = cy r[0,2] = -sy r[1,1] = 1.0 r[2,0] = sy r[2,2] = cy return r } /// Returns a transformation matrix that rotates clockwise around the z axis @inlinable public static func rotate(z: Angle<Scalar>) -> AffineMatrix { let (sin: sz, cos: cz) = Angle<Scalar>.sincos(z) var r = AffineMatrix() r[0,0] = cz r[0,1] = sz r[1,0] = -sz r[1,1] = cz r[2,2] = 1.0 return r } /// Returns a transformation matrix that rotates clockwise around the given axis @inlinable public static func rotate(angle: Angle<Scalar>, axis: SIMD3<Scalar>) -> AffineMatrix { let (sin: st, cos: ct) = Angle<Scalar>.sincos(angle) let oneMinusCT = 1.0 - ct var r = AffineMatrix() r[0,0] = (axis.x * axis.x * oneMinusCT as Scalar) + (ct as Scalar) r[0,1] = (axis.x * axis.y * oneMinusCT as Scalar) + (axis.z * st as Scalar) r[0,2] = (axis.x * axis.z * oneMinusCT as Scalar) - (axis.y * st as Scalar) r[1,0] = (axis.x * axis.y * oneMinusCT as Scalar) - (axis.z * st as Scalar) r[1,1] = (axis.y * axis.y * oneMinusCT as Scalar) + (ct as Scalar) r[1,2] = (axis.y * axis.z * oneMinusCT as Scalar) + (axis.x * st as Scalar) r[2,0] = (axis.x * axis.z * oneMinusCT as Scalar) + (axis.y * st as Scalar) r[2,1] = (axis.y * axis.z * oneMinusCT as Scalar) - (axis.x * st as Scalar) r[2,2] = (axis.z * axis.z * oneMinusCT as Scalar) + (ct as Scalar) return r } /// Returns a transformation matrix that rotates clockwise around the x and then y axes @inlinable public static func rotate(x: Angle<Scalar>, y: Angle<Scalar>) -> AffineMatrix { // TODO: optimize. return AffineMatrix.rotate(y: y) * AffineMatrix.rotate(x: x) } /// Returns a transformation matrix that rotates clockwise around the x, y, and then z axes @inlinable public static func rotate(x: Angle<Scalar>, y: Angle<Scalar>, z: Angle<Scalar>) -> AffineMatrix { // TODO: optimize. return AffineMatrix.rotate(z: z) * AffineMatrix.rotate(y: y) * AffineMatrix.rotate(x: x) } /// Returns a transformation matrix that rotates clockwise around the y, x, and then z axes @inlinable public static func rotate(y: Angle<Scalar>, x: Angle<Scalar>, z: Angle<Scalar>) -> AffineMatrix { // TODO: optimize. return AffineMatrix.rotate(z: z) * AffineMatrix.rotate(x: x) * AffineMatrix.rotate(y: y) } /// Returns a transformation matrix that rotates clockwise around the z, y, and then x axes @inlinable public static func rotate(z: Angle<Scalar>, y: Angle<Scalar>, x: Angle<Scalar>) -> AffineMatrix { let (sx, cx) = Angle<Scalar>.sincos(x) let (sy, cy) = Angle<Scalar>.sincos(y) let (sz, cz) = Angle<Scalar>.sincos(z) var r = AffineMatrix() r[0,0] = (cy * cz) as Scalar r[1,0] = (cz * sx * sy) as Scalar - (cx * sz) as Scalar r[2,0] = (cx * cz * sy) as Scalar + (sx * sz) as Scalar r[0,1] = (cy * sz) as Scalar r[1,1] = (cx * cz) as Scalar + (sx * sy * sz) as Scalar r[2,1] = -(cz * sx) as Scalar + (cx * sy * sz) as Scalar r[0,2] = -sy as Scalar r[1,2] = (cy * sx) as Scalar r[2,2] = (cx * cy) as Scalar return r } /// Returns a transformation matrix which can be used to scale, rotate and translate vectors @inlinable public static func scaleRotateTranslate(scale: SIMD3<Scalar>, rotation: Quaternion<Scalar>, translation: SIMD3<Scalar>) -> AffineMatrix { let sqw : Scalar = rotation.w * rotation.w let sqx : Scalar = rotation.x * rotation.x let sqy : Scalar = rotation.y * rotation.y let sqz : Scalar = rotation.z * rotation.z var r0 = SIMD4<Scalar>(repeating: 0) var r1 = SIMD4<Scalar>(repeating: 0) var r2 = SIMD4<Scalar>(repeating: 0) r0.x = ( sqx - sqy - sqz + sqw) // since sqw + sqx + sqy + sqz =1/invs*invs r1.y = (-sqx + sqy - sqz + sqw) r2.z = (-sqx - sqy + sqz + sqw) var tmp1 : Scalar = rotation.x * rotation.y var tmp2 : Scalar = rotation.z * rotation.w r1.x = 2.0 * (tmp1 + tmp2) r0.y = 2.0 * (tmp1 - tmp2) tmp1 = rotation.x * rotation.z tmp2 = rotation.y * rotation.w r2.x = 2.0 * (tmp1 - tmp2) r0.z = 2.0 * (tmp1 + tmp2) tmp1 = rotation.y * rotation.z tmp2 = rotation.x * rotation.w r2.y = 2.0 * (tmp1 + tmp2) r1.z = 2.0 * (tmp1 - tmp2) let sqLength : Scalar = sqx + sqy + sqz + sqw let scale = scale / sqLength r0.xyz *= scale r1.xyz *= scale r2.xyz *= scale r0.w = translation.x r1.w = translation.y r2.w = translation.z return AffineMatrix(rows: r0, r1, r2) } @inlinable public var decomposed : (translation: SIMD3<Scalar>, rotation: Quaternion<Scalar>, scale: SIMD3<Scalar>) { var currentTransform = self let translation = currentTransform[3].xyz currentTransform[3] = SIMD4<Scalar>(0, 0, 0, 1) var scale = SIMD3<Scalar>(currentTransform[0].xyz.length, currentTransform[1].xyz.length, currentTransform[2].xyz.length) let tempZ = cross(currentTransform[0].xyz, currentTransform[1].xyz) if dot(tempZ, currentTransform[2].xyz) < 0 { scale.x *= -1 } currentTransform[0] /= max(scale.x, .leastNormalMagnitude) currentTransform[1] /= max(scale.y, .leastNormalMagnitude) currentTransform[2] /= max(scale.z, .leastNormalMagnitude) let rotation = Quaternion(currentTransform) return (translation, rotation, scale) } } extension AffineMatrix { @inlinable public var right : SIMD3<Scalar> { get { return SIMD3<Scalar>(r0.x, r1.x, r2.x) } set { self.r0.x = newValue.x self.r1.x = newValue.y self.r2.x = newValue.z } } @inlinable public var up : SIMD3<Scalar> { get { return SIMD3<Scalar>(r0.y, r1.y, r2.y) } set { self.r0.y = newValue.x self.r1.y = newValue.y self.r2.y = newValue.z } } @inlinable public var forward : SIMD3<Scalar> { get { return SIMD3<Scalar>(r0.z, r1.z, r2.z) } set { self.r0.z = newValue.x self.r1.z = newValue.y self.r2.z = newValue.z } } @inlinable public var translation : SIMD4<Scalar> { get { return SIMD4<Scalar>(r0.w, r1.w, r2.w, 1.0) } set { self.r0.w = newValue.x self.r1.w = newValue.y self.r2.w = newValue.z assert(newValue.w == 1.0) } } }
35.891207
194
0.547191
f882dacddb44158c81df4ff241e386050106c49b
3,509
import Foundation import Logging /// Allows to extend with custom `log` method which automatically captures current type (class name). internal protocol Loggable: Any { } internal extension Loggable { /// Automatically captures current type (class name) to ``Logger.Metadata`` func log(_ message: Logger.Message? = nil, _ level: Logger.Level = .debug, file: String = #file, type type_: Any.Type? = nil, function: String = #function, line: UInt = #line) { logger.log(message ?? "", level, file: file, type: type_ ?? type(of: self), function: function, line: line) } } internal extension Logger { /// Adds `type` param to capture current type (usually class) func log(_ message: @autoclosure () -> Logger.Message, _ level: Logger.Level = .debug, source: @autoclosure () -> String? = nil, file: String = #file, type: Any.Type, function: String = #function, line: UInt = #line) { let metadata: Logger.Metadata = [ "type": .string(String(describing: type)) ] log(level: level, message(), metadata: metadata, source: source(), file: file, function: function, line: line) } } /// ``LogHandler`` which formats log output preferred for debugging the LiveKit SDK. public struct LiveKitLogHandler: LogHandler { public let label: String public let timeStampFormat = "%Y-%m-%dT%H:%M:%S%z" public var logLevel: Logger.Level public var metadata = Logger.Metadata() public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { get { self.metadata[metadataKey] } set { self.metadata[metadataKey] = newValue } } public init(label: String, level: Logger.Level = .debug) { self.label = label self.logLevel = level } public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt) { var elements: [String] = [ label.padding(toLength: 10, withPad: " ", startingAt: 0), // longest level string is `critical` which is 8 characters String(describing: level).uppercased().padding(toLength: 8, withPad: " ", startingAt: 0) ] // append type (usually class name) if available if case .string(let type) = metadata?["type"] { elements.append("\(type).\(function)".padding(toLength: 40, withPad: " ", startingAt: 0)) } let str = String(describing: message) if !str.isEmpty { elements.append(str) } // join all elements with a space in between print(elements.joined(separator: " ")) } private func timestamp() -> String { var buffer = [Int8](repeating: 0, count: 255) var timestamp = time(nil) let localTime = localtime(&timestamp) strftime(&buffer, buffer.count, timeStampFormat, localTime) return buffer.withUnsafeBufferPointer { $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } } } }
31.330357
101
0.554004
fb0ad8c2d5a7dbb698f5c848e35c0671116cac0c
12,905
// // FormattableInput.swift // FormattableTextView // // Created by Михаил Мотыженков on 21.07.2018. // Copyright © 2018 Михаил Мотыженков. All rights reserved. // import Foundation import UIKit /// A way to draw the mask /// /// - leftOnly: draw mask elements from the left side of inputed symbols /// - leftAndRight: draw mask elements from the left side of inputed symbols and draw next mask element from the right side if current input area is finished /// - whole: draw all mask elements; in this case it is your responsibility to set the same *monospaced* font in maskAttributes and inputAttributes public enum MaskAppearance { case leftOnly case leftAndRight case whole(placeholders: [Character: Character]) fileprivate var isWhole: Bool { switch self { case .whole(_): return true default: return false } } } internal enum MaskState { case mask case input } internal struct MaskLayersDiff { var layersToAdd: [Int: CALayer] var layersToDelete: [Int] var layersToChangeFrames: [Int: CGPoint] } internal enum ActionForLayer { case change case add } internal enum ProcessAttributesResult { case withoutFormat case notAllowed case allowed(attributedString: NSAttributedString, numberOfDeletedSymbols: Int, maskLayersDiff: MaskLayersDiff) } public protocol FormattableInput: class, UITextInput { var format: String? { get set } var maskAppearance: FormattableTextView.MaskAppearance { get set } /// Input symbols will be drawn with these attributes var inputAttributes: [NSAttributedString.Key : Any] { get set } /// Non-input symbols will be drawn with these attributes var maskAttributes: [NSAttributedString.Key : Any]! { get set } var formatSymbols: [Character : CharacterSet] { get set } /// x inset for input text and placeholders, may be set by user var insetX: CGFloat { get set } var keyboardType: UIKeyboardType { get set } } internal protocol FormattableInputInternal: FormattableInput where Self: UIView { var internalAttributedText: NSAttributedString { get set } var format: String? { get } var formatInputChars: Set<Character>! { get } var formatSymbols: [Character: CharacterSet] { get } var maskAttributes: [NSAttributedString.Key: Any]! { get } var inputAttributes: [NSAttributedString.Key: Any] { get } var maskAppearance: MaskAppearance { get } /// Non-input elements of format which will be drawn in separate layers var maskLayers: [Int: CALayer] { get set } var maskPlaceholders: [CALayer] { get set } var backgroundColor: UIColor? { get } /// real x inset for input text var internalInsetX: CGFloat { get set } /// real y inset for input text var internalInsetY: CGFloat { get set } func updateInsetY() func processAttributesForTextAndMask(range: NSRange, replacementText: String) -> ProcessAttributesResult func setAttributedTextAndTextPosition(attributedString: NSAttributedString, location: Int, offset: Int, maskLayersDiff: MaskLayersDiff) } extension FormattableInputInternal { fileprivate func getOrCreateCurrentLayer(maskLayers: [Int: CALayer], maskAttributes: [NSAttributedString.Key: Any], key: Int, prevFormat: String) -> (action: ActionForLayer, layer: CALayer) { if let layer = maskLayers[key] { return (action: .change, layer: layer) } else { let layer = CALayer(text: prevFormat, attributes: maskAttributes) layer.edgeAntialiasingMask = .layerTopEdge return (action: .add, layer: layer) } } @discardableResult fileprivate func fillMaskLayersDiffAndIncrementDx(maskLayersDiff: inout MaskLayersDiff, maskLayers: [Int: CALayer], key: Int, prevFormat: String, dx: inout CGFloat) -> CGFloat { let currentLayerResult = getOrCreateCurrentLayer(maskLayers: maskLayers, maskAttributes: maskAttributes, key: key, prevFormat: prevFormat) let layer = currentLayerResult.layer guard let inputFont = inputAttributes[NSAttributedString.Key.font] as? UIFont, let maskFont = maskAttributes[NSAttributedString.Key.font] as? UIFont else { return 0 } let dy = internalInsetY.rounded() - (maskFont.lineHeight-inputFont.lineHeight)/2 switch currentLayerResult.action { case .add: layer.frame.origin.x = dx layer.frame.origin.y = dy maskLayersDiff.layersToAdd[key] = layer case .change: var position = layer.frame.origin position.x = dx position.y = dy maskLayersDiff.layersToChangeFrames[key] = position } let offset = layer.bounds.width dx += offset return offset } fileprivate func calculateDx(dx: inout CGFloat, format: String, formatCurrentIndex: String.Index, inputString: String, lastInputStartIndex: String.Index, inputIndex: String.Index) { if maskAppearance.isWhole { let prevInput = String(format[format.startIndex..<formatCurrentIndex]) let size = (prevInput as NSString).size(withAttributes: self.inputAttributes) dx = self.insetX + size.width } else { let prevInput = String(inputString[lastInputStartIndex..<inputIndex]) let size = (prevInput as NSString).size(withAttributes: self.inputAttributes) dx += size.width } } fileprivate func addMaskPlaceholder(_ newMaskPlaceholders: inout [CALayer], _ char: Character, _ maskSymbolNumber: Int, _ symbolWidth: CGFloat) { switch maskAppearance { case .whole(let placeholders): guard let inputFont = inputAttributes[NSAttributedString.Key.font] as? UIFont, let maskFont = maskAttributes[NSAttributedString.Key.font] as? UIFont else { return } if let placeholderChar = placeholders[char] { let layer = CALayer(text: String(placeholderChar), attributes: maskAttributes) layer.frame.origin.y = internalInsetY.rounded() - (maskFont.lineHeight-inputFont.lineHeight)/2 layer.frame.origin.x = insetX + CGFloat(maskSymbolNumber) * symbolWidth newMaskPlaceholders.append(layer) } default: break } } func processAttributesForTextAndMask(range: NSRange, replacementText: String) -> ProcessAttributesResult { guard let format = self.format else { return .withoutFormat } var numberOfDeletedSymbols = 0 var state = MaskState.mask var formatCurrentStartIndex = format.startIndex let mutableAttributedString = NSMutableAttributedString(string: (self.internalAttributedText.string as NSString).replacingCharacters(in: range, with: replacementText), attributes: self.inputAttributes) var inputSymbolNumber = 0 var maskSymbolNumber = 0 var inputIndex = mutableAttributedString.string.startIndex var formatCurrentIndex = format.startIndex var lastInputStartIndex = format.startIndex let maskLayers = self.maskLayers var dx: CGFloat = self.insetX var isFirstInputSymbol = true var shouldEnd = false var maskLayersDiff = MaskLayersDiff(layersToAdd: [Int: CALayer](), layersToDelete: [Int](), layersToChangeFrames: [Int: CGPoint]()) let symbolWidth = format.isEmpty ? 0 : (String(format.first!) as NSString).size(withAttributes: inputAttributes).width var newMaskPlaceholders = [CALayer]() updateInsetY() for char in format { var allowIncrementingInputSymbolIndex = (inputIndex != mutableAttributedString.string.endIndex) let prevFormat = String(format[formatCurrentStartIndex..<formatCurrentIndex]) let isUserSymbol = self.formatInputChars.contains(char) if state == .mask && isUserSymbol { state = .input lastInputStartIndex = inputIndex if isFirstInputSymbol { isFirstInputSymbol = false if !prevFormat.isEmpty { fillMaskLayersDiffAndIncrementDx(maskLayersDiff: &maskLayersDiff, maskLayers: maskLayers, key: formatCurrentStartIndex.encodedOffset, prevFormat: prevFormat, dx: &dx) } } else { let width = fillMaskLayersDiffAndIncrementDx(maskLayersDiff: &maskLayersDiff, maskLayers: maskLayers, key: formatCurrentStartIndex.encodedOffset, prevFormat: prevFormat, dx: &dx) if (maskAppearance.isWhole && allowIncrementingInputSymbolIndex || !maskAppearance.isWhole) && !mutableAttributedString.string.isEmpty { mutableAttributedString.addAttribute(NSAttributedString.Key.kern, value: width, range: NSMakeRange(inputSymbolNumber-1, 1)) } } if shouldEnd { break } } else if state == .input && !isUserSymbol { state = .mask calculateDx(dx: &dx, format: format, formatCurrentIndex: formatCurrentIndex, inputString: mutableAttributedString.string, lastInputStartIndex: lastInputStartIndex, inputIndex: inputIndex) formatCurrentStartIndex = formatCurrentIndex } if state == .input { if shouldEnd || (mutableAttributedString.string.isEmpty && !maskAppearance.isWhole) { break } // Check if current area of input string starts with a tail of previous mask area. In that case delete those characters. // It is useful in situation when user pastes text with mask symbols. if allowIncrementingInputSymbolIndex { if !self.formatSymbols[char]!.contains(mutableAttributedString.string[inputIndex].unicodeScalars.first!) { let prevFormat = String(format[formatCurrentStartIndex..<formatCurrentIndex]) if prevFormat.isEmpty { return .notAllowed } // Delete mask characters from input string. // TODO: better implementation for formatChar in prevFormat { if mutableAttributedString.string[inputIndex] == formatChar { mutableAttributedString.deleteCharacters(in: NSMakeRange(inputSymbolNumber, 1)) numberOfDeletedSymbols += 1 allowIncrementingInputSymbolIndex = false if inputIndex == mutableAttributedString.string.endIndex { break } } else { return .notAllowed } } } inputSymbolNumber += 1 if inputIndex != mutableAttributedString.string.endIndex { inputIndex = mutableAttributedString.string.index(after: inputIndex) } } if maskAppearance.isWhole && !allowIncrementingInputSymbolIndex { addMaskPlaceholder(&newMaskPlaceholders, char, maskSymbolNumber, symbolWidth) } } if inputIndex == mutableAttributedString.string.endIndex && !mutableAttributedString.string.isEmpty && !shouldEnd { var shouldBreak = false switch maskAppearance { case .leftOnly: shouldBreak = true case .leftAndRight: shouldEnd = true case .whole: break // exit from switch statement } if shouldBreak { break // exit from loop } } formatCurrentIndex = format.index(after: formatCurrentIndex) maskSymbolNumber += 1 } // A condition which prevents user from inserting too many symbols if inputIndex < mutableAttributedString.string.endIndex { return .notAllowed } maskPlaceholders.forEach { $0.removeFromSuperlayer() } newMaskPlaceholders.forEach { self.layer.addSublayer($0) } maskPlaceholders = newMaskPlaceholders let indicesToAdd = Set(maskLayersDiff.layersToAdd.map { $0.key }) let indicesToChange = Set(maskLayersDiff.layersToChangeFrames.map { $0.key }) maskLayersDiff.layersToDelete = self.maskLayers.map { $0.key }.filter { !indicesToAdd.contains($0) && !indicesToChange.contains($0) } return .allowed(attributedString: mutableAttributedString, numberOfDeletedSymbols: numberOfDeletedSymbols, maskLayersDiff: maskLayersDiff) } func setAttributedTextAndTextPosition(attributedString: NSAttributedString, location: Int, offset: Int, maskLayersDiff: MaskLayersDiff) { self.internalAttributedText = attributedString for key in maskLayersDiff.layersToDelete { let layer = self.maskLayers.removeValue(forKey: key) layer?.removeFromSuperlayer() } for (key, value) in maskLayersDiff.layersToAdd { self.maskLayers[key] = value self.layer.addSublayer(value) } for (key, value) in maskLayersDiff.layersToChangeFrames { let layer = self.maskLayers[key] layer?.frame.origin = value } if let pos = self.position(from: self.beginningOfDocument, offset: location+offset) { self.selectedTextRange = self.textRange(from: pos, to: pos) } } func updateInsetY() { if let inputFont = self.inputAttributes[NSAttributedString.Key.font] as? UIFont { internalInsetY = (self.bounds.height - inputFont.lineHeight)/2 } } }
41.495177
209
0.698334