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
297874ab06d3177f1438ed623f8529f4b30bb4fc
3,592
// // ReceiptListViewController.swift // ReceiptSaver // // Created by Umut SERIFLER on 19/04/2021. // import UIKit class ReceiptListViewController: UITableViewController { private(set) var viewModel: ReceiptListViewModel? /// Initialised Method /// - Parameter tableView: TableView will be used to show saved receipts init(_ viewModel: ReceiptListViewModel = ReceiptListViewModel(), _ tableView: UITableView = BaseTableView(cellArray: [ReceiptTableViewCell.self])) { super.init(nibName: nil, bundle: nil) self.viewModel = viewModel self.tableView = tableView self.title = Constants.receiptsListTitle } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) initViewModel() self.tableView?.reloadData() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewReceipt)) } func initViewModel() { viewModel?.reloadTableViewClosure = { [weak self] in DispatchQueue.main.async { self?.tableView.reloadData() } } viewModel?.updateLoadingStatusClosure = { [weak self] (deletions,insertions,updates) in DispatchQueue.main.async { self?.tableView.reloadData() } } viewModel?.showAlertClosure = { [weak self] errorMessage in guard let errorMessage = errorMessage else { return } self?.showAlert(with: errorMessage) } } @objc func addNewReceipt() { self.navigationController?.pushViewController(ReceiptSaveViewController(delegation: self), animated: true) } } extension ReceiptListViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel?.retrieveNumberOfItems() ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let receiptCell : ReceiptTableViewCell = tableView.dequeueReusableCell(withIdentifier: ReceiptTableViewCell.identifier, for: indexPath) as? ReceiptTableViewCell, let receipt: Receipt = self.viewModel?.getData(at: indexPath) as? Receipt { receiptCell.receipt = receipt return receiptCell } return UITableViewCell() } } extension ReceiptListViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let receiptCell: ReceiptTableViewCell = tableView.cellForRow(at: indexPath) as? ReceiptTableViewCell { guard let receipt = receiptCell.receipt else { return } DispatchQueue.main.async { [weak self] in self?.navigationController?.pushViewController(ReceiptSaveViewController(receipt.tranformsToReceiptModel(), delegation: self), animated: true) } } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } } extension ReceiptListViewController: ReceiptSaveViewControllerDelegate { func saveUpdateReceipt(with data: Any) { if let receipt = (data as? ReceiptModel)?.transformToRealmObject() { viewModel?.saveUpdate(with: receipt) } } }
34.209524
248
0.659521
f9ff38664e6fee09740bc28ba45845939ba21967
938
//: [Previous](@previous) import Foundation import GameplayKit //Random from 0 to N - 1 let r1 = rand() % 100 //let r2 = random() % 100 let r3 = arc4random() % 100 let r4 = arc4random_uniform(100) //N GKARC4RandomSource().nextUniform() GKARC4RandomSource().nextInt() GKARC4RandomSource().nextIntWithUpperBound(100) let random = GKRandomDistribution(lowestValue: 0, highestValue: 100).nextInt() let ints = [1,2,3,4,5,6,7,8,9,10] let shuffledArray = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(ints) let normal = GKGaussianDistribution(randomSource: GKARC4RandomSource(), lowestValue: 0, highestValue: 100).nextInt() func generateUniqueSequence(lowestValue: Int, highestValue: Int) -> [Int] { var ints: [Int] = [] ints += lowestValue...highestValue return GKARC4RandomSource.sharedRandom().arrayByShufflingObjectsInArray(ints) as! [Int] } generateUniqueSequence(2, highestValue: 15) //: [Next](@next)
28.424242
116
0.744136
7a6a21c26ef5c3653a1652d0827b863c84bc6ee6
989
// // 🦠 Corona-Warn-App // import XCTest @testable import ENA final class DynamicTypeLabelTests: CWATestCase { func testDesignatedInitializer() { XCTAssertNotNil(DynamicTypeLabel()) } func testBoldWeight() { let sut = DynamicTypeLabel() sut.dynamicTypeWeight = "bold" // swiftlint:disable:next force_cast let traits = sut.font.fontDescriptor.object(forKey: .traits) as! [UIFontDescriptor.TraitKey: AnyObject] let weight = traits[.weight] as? NSNumber ?? NSNumber(-1) XCTAssertEqual(CGFloat(weight.doubleValue), UIFont.Weight.bold.rawValue, accuracy: 0.001) } func testSemboldWeight() { let sut = DynamicTypeLabel() sut.dynamicTypeWeight = "semibold" // swiftlint:disable:next force_cast let traits = sut.font.fontDescriptor.object(forKey: .traits) as! [UIFontDescriptor.TraitKey: AnyObject] let weight = traits[.weight] as? NSNumber ?? NSNumber(-1) XCTAssertEqual(CGFloat(weight.doubleValue), UIFont.Weight.semibold.rawValue, accuracy: 0.001) } }
31.903226
105
0.745197
fe3564d83da9d2f3a2c21557135734366f30807e
522
// // LineChartDataProvider.swift // Charts // // Created by Daniel Cohen Gindi on 27/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics @objc public protocol LineChartDataProvider: BarLineScatterCandleBubbleChartDataProvider { var lineData: LineChartData? { get } func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis }
22.695652
82
0.741379
fc26a2336f3bfbd880252cb94bef76443bdf676b
600
// // Messages.swift // tl2swift // // Generated automatically. Any changes will be lost! // Based on TDLib 1.8.0-fa8feefe // https://github.com/tdlib/td/tree/fa8feefe // import Foundation /// Contains a list of messages public struct Messages: Codable, Equatable { /// List of messages; messages may be null public let messages: [Message]? /// Approximate total count of messages found public let totalCount: Int public init( messages: [Message]?, totalCount: Int ) { self.messages = messages self.totalCount = totalCount } }
18.75
54
0.648333
cc10670044d58f8e419db31bf79f090605821d3b
141
import PackageDescription let package = Package( dependencies: [ .Package(url: "../dep1", versions: "1.1.0"..<"2.0.0"), ] )
17.625
62
0.574468
335f6b148c27b9e047c124209fceb4e3259c2d7f
3,648
// // AppDelegate.swift // flat // // Created by xuyunshi on 2021/10/12. // Copyright © 2021 agora.io. All rights reserved. // import UIKit import IQKeyboardManagerSwift import Kingfisher import Fastboard var globalLaunchCoordinator: LaunchCoordinator? { if #available(iOS 13.0, *) { return (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.launch } else { return (UIApplication.shared.delegate as? AppDelegate)?.launch } } @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var launch: LaunchCoordinator? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { ApiProvider.shared.startEmptyRequestForWakingUpNetworkAlert() processMethodExchange() configAppearance() registerThirdPartSDK() if #available(iOS 13, *) { // SceneDelegate } else { let url = launchOptions?[.url] as? URL window = UIWindow(frame: UIScreen.main.bounds) launch = LaunchCoordinator(window: window!, authStore: AuthStore.shared, defaultLaunchItems: [JoinRoomLaunchItem(), FileShareLaunchItem()]) launch?.start(withLaunchUrl: url) } #if DEBUG DispatchQueue.main.asyncAfter(deadline: .now() + 1) { guard AuthStore.shared.isLogin else { return } // Cancel all the previous upload task, for old task will block the new upload ApiProvider.shared.request(fromApi: CancelUploadRequest(fileUUIDs: [])) { _ in } } #endif return true } func registerThirdPartSDK() { WXApi.registerApp(Env().wechatAppId, universalLink: "https://flat-api.whiteboard.agora.io") } func configAppearance() { IQKeyboardManager.shared.enable = true IQKeyboardManager.shared.enableAutoToolbar = false IQKeyboardManager.shared.shouldResignOnTouchOutside = true IQKeyboardManager.shared.keyboardDistanceFromTextField = 10 } func processMethodExchange() { methodExchange(cls: UIViewController.self, originalSelector: #selector(UIViewController.traitCollectionDidChange(_:)), swizzledSelector: #selector(UIViewController.exchangedTraitCollectionDidChange(_:))) methodExchange(cls: UIView.self, originalSelector: #selector(UIView.traitCollectionDidChange(_:)), swizzledSelector: #selector(UIView.exchangedTraitCollectionDidChange(_:))) } // MARK: UISceneSession Lifecycle @available(iOS 13.0, *) func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { launch?.start(withLaunchUrl: url) return true } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { let _ = launch?.start(withLaunchUserActivity: userActivity) return true } func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { .all } }
38.808511
179
0.682292
71b3dffe89f88546af6a9b9cf703de320464354d
2,714
// // FiindFriendViewController.swift // Loustagram // // Created by Kiet on 12/4/17. // Copyright © 2017 Kiet. All rights reserved. // import UIKit import Foundation import AsyncDisplayKit class FindFriendViewController: ASViewController<ASTableNode> { var users = [User]() init() { super.init(node: ASTableNode()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Find Friends" node.view.separatorInset.left = 0.0 node.allowsSelection = false node.leadingScreensForBatching = 3.0 node.delegate = self node.dataSource = self node.view.tableFooterView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UserService.usersExcludingCurrentUser { [unowned self] (users) in self.users = users DispatchQueue.main.async { self.node.reloadData() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension FindFriendViewController: ASTableDelegate, ASTableDataSource { func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int { return users.count } func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode { let cell = FindFriendCell() cell.delegate = self configureCell(cell: cell, indexPath: indexPath) return cell } func configureCell(cell: FindFriendCell, indexPath: IndexPath) { let user = users[indexPath.row] cell.usernameNode.attributedText = NSAttributedString(string: user.username) cell.followButton.isSelected = user.isFollowed } } extension FindFriendViewController: FindFriendCellDelegate { func didTapOnCell(_ followButton: ASButtonNode, on cell: FindFriendCell) { guard let indexPath = node.indexPath(for: cell) else { return } followButton.isUserInteractionEnabled = false let followee = users[indexPath.row] FollowService.setIsFollowing(!followee.isFollowed, fromCurrentUserTo: followee) { (success) in defer { followButton.isUserInteractionEnabled = true } guard success else { return } followee.isFollowed = !followee.isFollowed self.node.reloadRows(at: [indexPath], with: .none) } } }
23.6
102
0.628224
507ef4eb2ff8a2e52c63c0a01b29de0d0d026d1a
606
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ extension AKComputedParameter { /// Add a delay to an incoming signal with optional feedback. /// /// - Parameters: /// - time: Delay time, in seconds. (Default: 1.0, Range: 0 - 10) /// - feedback: Feedback amount. (Default: 0.0, Range: 0 - 1) /// public func delay( time: Double = 1.0, feedback: AKParameter = 0.0 ) -> AKOperation { return AKOperation(module: "delay", inputs: toMono(), feedback, time) } }
31.894737
100
0.582508
1cb99944970665cbddf5edf877a6f009d9bb6418
1,450
// // AppDelegate.swift // SwiftUIMagnificationGestureTutorial // // Created by Arthur Knopper on 14/10/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
38.157895
179
0.753103
1e134d5fc70af207c686b2fc303ad5d3fe2c973f
10,306
// // BaseViewController.swift // Proverbs // // Created by Yevhenii Zozulia on 4/11/18. // Copyright © 2018 Yevhenii Zozulia. All rights reserved. // import UIKit import Reachability import NVActivityIndicatorView class BaseViewController: UIViewController, ViewControllerConstructor, NavigationBarDelegate, NVActivityIndicatorViewable { static var storyboardType: StoryboardType { return self._storyboardType } class var _storyboardType: StoryboardType { return .Main } // MARK: - IBOutlets @IBOutlet weak var internalNavigationBar: NavigationBar? @IBOutlet weak var backgroundImageView: UIImageView? // MARK: - Properties fileprivate var shareHelper: ContentShareHelper? let notificaionCenter = NotificationCenter.default let reachabilityManager = ReachabilityManager.shared var isKeyboardVisible = false var activityIndicator: NVActivityIndicatorView? var statusBarStyle: UIStatusBarStyle = .default { didSet { if oldValue != statusBarStyle { self.setNeedsStatusBarAppearanceUpdate() } } } var statusBarHidden = false { didSet { if oldValue != statusBarHidden { self.setNeedsStatusBarAppearanceUpdate() } } } var isVisible: Bool { return self.viewIfLoaded?.window != nil } // MARK: - Life cycle methods override func viewDidLoad() { super.viewDidLoad() self.setupViews() self.setupLocalization() self.addNotificationsObserver() self.setNeedsStatusBarAppearanceUpdate() self.internalNavigationBar?.viewController = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setNeedsStatusBarAppearanceUpdate() self.setupViewsWithReachability(self.reachabilityManager.isReachable) self.addKeyboardNotificationsObserver() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.removeKeyboardNotificationsObserver() } deinit { self.removeNotificationsObserver() } override var preferredStatusBarStyle : UIStatusBarStyle { return self.statusBarStyle } override var prefersStatusBarHidden : Bool { return self.statusBarHidden } // MARK: - Notifications Methods func addNotificationsObserver() { self.notificaionCenter.addObserver(self, selector: #selector(BaseViewController.reachabilityChangedNotification(_:)), name: Notification.Name.reachabilityChanged, object: nil) } func removeNotificationsObserver() { self.notificaionCenter.removeObserver(self) } func addKeyboardNotificationsObserver() { self.notificaionCenter.addObserver(self, selector: #selector(BaseViewController.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) self.notificaionCenter.addObserver(self, selector: #selector(BaseViewController.keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil) self.notificaionCenter.addObserver(self, selector: #selector(BaseViewController.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) self.notificaionCenter.addObserver(self, selector: #selector(BaseViewController.keyboardDidHide(_:)), name: UIResponder.keyboardDidHideNotification, object: nil) } func removeKeyboardNotificationsObserver() { self.notificaionCenter.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) self.notificaionCenter.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil) self.notificaionCenter.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) self.notificaionCenter.removeObserver(self, name: UIResponder.keyboardDidHideNotification, object: nil) } // MARK: - Keyboard methods @objc func hideKeyboard() { self.view.endEditing(true) self.view.window?.endEditing(true) } @objc func keyboardWillShow(_ notif: Notification) { self.isKeyboardVisible = true } @objc func keyboardDidShow(_ notif: Notification) { } @objc func keyboardWillHide(_ notif: Notification) { self.isKeyboardVisible = false } @objc func keyboardDidHide(_ notif: Notification) { } // MARK: - Reachability Methods func setupViewsWithReachability(_ isReachable: Bool) { } @objc func reachabilityChangedNotification(_ notif: Notification) { self.setupViewsWithReachability(self.reachabilityManager.isReachable) } func showNetworkErrorNotificationView() { } func checkAndShowOfflineAlert() -> Bool { if self.reachabilityManager.isReachable == false { } return !self.reachabilityManager.isReachable } // MARK: - Views Methods func setupViews() { } func setupLocalization() { } func showElementView(_ view: UIView, show: Bool, animated: Bool) { let newAlpha: CGFloat = show ? 1.0 : 0.0 if view.alpha == newAlpha { return } let showClosure = { view.alpha = newAlpha } if animated { UIView.animate(withDuration: 0.3, animations: showClosure) } else { showClosure() } } func view(block: Bool) { self.navigationController?.navigationBar.isUserInteractionEnabled = !block self.tabBarController?.tabBar.isUserInteractionEnabled = !block } // MARK: - Activity Indicator Methods func activityIndicator(show: Bool, blockView: Bool = false) { if show && self.activityIndicator == nil { self.activityIndicator = self.createActivityIndicatorView() self.view.addSubview(self.activityIndicator!) self.activityIndicator?.startAnimating() self.view.isUserInteractionEnabled = blockView ? false : true } else if !show && self.activityIndicator != nil { self.activityIndicator?.stopAnimating() self.activityIndicator = nil self.view.isUserInteractionEnabled = true } } func createActivityIndicatorView() -> NVActivityIndicatorView { var frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0) frame = CGRect.makeCenter(forRect: frame, atView: self.view) return NVActivityIndicatorView(frame: frame, type: NVActivityIndicatorType.ballScaleRippleMultiple) } // MARK: - NavigationBarDelegate func leftbuttonPushed(_ navigationBar: NavigationBar) { } func rightbuttonPushed(_ navigationBar: NavigationBar) { } } // MARK: Share extension BaseViewController: ContentShareHelperDelegate { func makeShareActionSheet(withDelegate viewController: ContentShareHelper.Delegate, proverb: Proverb) -> ActionSheetViewController? { guard let actionSheet = ActionSheetViewController.make(withTitle: "Share via") else { return nil } let share = { guard let helper = self.shareHelper else { return } helper.share() } let facebookAction = ActionSheetItem(type: .select, title: "Facebook", color: UIColor.appFacebookButton) { _ in self.shareHelper = ContentShareHelper.createShareHelper(withServiceType: .facebook, proverb: proverb, delegate: viewController) share() } let twitterAction = ActionSheetItem(type: .select, title: "Twitter", color: UIColor.appTwitterButton) { _ in self.shareHelper = ContentShareHelper.createShareHelper(withServiceType: .twitter, proverb: proverb, delegate: viewController) share() } let clipboardAction = ActionSheetItem(type: .select, title: "Copy Link") { _ in self.shareHelper = ContentShareHelper.createShareHelper(withServiceType: .clipboard, proverb: proverb, delegate: viewController) share() } let cancelAction = ActionSheetItem(type: .destructive, title: "Cancel") actionSheet.addItem(facebookAction) actionSheet.addItem(twitterAction) actionSheet.addItem(clipboardAction) actionSheet.addItem(cancelAction) return actionSheet } func contentShareHelperDidShare(_ helper: ContentShareHelper) { defer { self.shareHelper = nil } if IAPController.shared.isPurchased { return } if helper.serviceType == .facebook || helper.serviceType == .twitter { ShareToUnlock.shared.checkAndChangeCounter(completion: { (result) in if !result { return } if ShareToUnlock.shared.isUnlocked { self.showCongratulationAlert() } else { self.showLeftDaysAlert() } }) } } func contentShareHelperDidCancelShare(_ helper: ContentShareHelper) { self.shareHelper = nil } func contentShareHelperDidFailToShare(_ helper: ContentShareHelper, error: Error?) { DLog("Error: \(String(describing: error))") self.shareHelper = nil } } // MARK: Share To Unlock Alerts extension BaseViewController { func showLeftDaysAlert() { let daysLeftToUnlock = ShareToUnlock.shared.daysLeftToUnlock var message = "Great! \(daysLeftToUnlock) days left to unlock the list of all Proverbs for free." if daysLeftToUnlock == 1 { message = "Great! \(daysLeftToUnlock) day left to unlock the list of all Proverbs for free." } after(0.5) { UIAlertController.show(message: message) } } func showCongratulationAlert() { after(0.5) { UIAlertController.show(message: "Congratulations! List of all Proverbs has been unlocked!") } } }
34.353333
186
0.654085
283c2ffef83be6dc5800867fdc8d4588f0dceb1b
1,085
// // Copyright (c) 2020 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation import UIKit /// Handles opening third party apps. /// :nodoc: public protocol AnyAppLauncher { func openCustomSchemeUrl(_ url: URL, completion: ((Bool) -> Void)?) func openUniversalAppUrl(_ url: URL, completion: ((Bool) -> Void)?) } /// Handles opening third party apps. /// :nodoc: public struct AppLauncher: AnyAppLauncher { /// :nodoc: public init() { /* Empty initializer */ } /// :nodoc: public func openCustomSchemeUrl(_ url: URL, completion: ((Bool) -> Void)?) { UIApplication.shared.open(url, options: [:], completionHandler: completion) } /// :nodoc: public func openUniversalAppUrl(_ url: URL, completion: ((Bool) -> Void)?) { UIApplication.shared.open(url, options: [UIApplication.OpenExternalURLOptionsKey.universalLinksOnly: true], completionHandler: completion) } }
29.324324
110
0.628571
fc172fd0aa5447e90e4e041265b1adf4efdb6139
3,077
// // KeyEventHandling.swift // Theatrical Trailers // // Created by Christoph Parstorfer on 13.12.21. // import AppKit import Carbon.HIToolbox import SwiftUI struct KeyEventHandling: NSViewRepresentable { var onEnter: (() -> ())? = nil var onUpArrow: (() -> ())? = nil var onDownArrow: (() -> ())? = nil var onEsc: (() -> ())? = nil var onQuit: (() -> ())? = nil class Coordinator: NSObject { var parent: KeyEventHandling var keyHandler: Any? = nil init(_ parent: KeyEventHandling) { self.parent = parent super.init() keyHandler = NSEvent.addLocalMonitorForEvents(matching: [.keyDown]) { event in if self.handleKeyDown(with: event) { /// we handled it, don't send it to the system return nil } else { /// not handled, send back to event system return event } } } deinit { if let keyHandler = keyHandler { NSEvent.removeMonitor(keyHandler) } keyHandler = nil } func handleKeyDown(with event: NSEvent) -> Bool { let fixedFlagMask = event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue let modifierFlags: NSEvent.ModifierFlags = NSEvent.ModifierFlags(rawValue: fixedFlagMask) let arrowKeyModifierFlag: NSEvent.ModifierFlags = [.numericPad, .function] if modifierFlags == [] || modifierFlags == arrowKeyModifierFlag || modifierFlags == .numericPad { switch Int(event.keyCode) { case kVK_Return, kVK_ANSI_KeypadEnter: parent.onEnter?() break case kVK_UpArrow: parent.onUpArrow?() break case kVK_DownArrow: parent.onDownArrow?() break case kVK_Escape: parent.onEsc?() break default: return false } return true } else /// `cmd-q` ? if modifierFlags == NSEvent.ModifierFlags.command && Int(event.keyCode) == kVK_ANSI_Q { parent.onQuit?() return true } else { return false } } } class KeyView: NSView {} func makeNSView(context: Context) -> KeyView { let view = KeyView() DispatchQueue.main.asyncAfter(1) { // wait till next event cycle view.window?.makeFirstResponder(view) } updateNSView(view, context: context) return view } func makeCoordinator() -> Coordinator { Coordinator(self) } func updateNSView(_ nsView: KeyView, context: Context) { context.coordinator.parent = self } }
31.397959
120
0.509262
08971e419a2890857f17bdd64a5ca232ff97d5a7
5,799
import TinkoffASDKCore import TinkoffASDKUI @objc(AsdkTinkoff) class AsdkTinkoff: NSObject { var promiseResolve: RCTPromiseResolveBlock? = nil var promiseReject: RCTPromiseRejectBlock? = nil var sdk:AcquiringSdk? = nil var ui:AcquiringUISDK? = nil func Configure(json:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) { promiseResolve = resolve promiseReject = reject struct Config: Decodable { let TerminalKey: String let Password: String let PublicKey: String } let cfg = try! JSONDecoder().decode(Config.self, from: json.data(using: .utf8)!) let configuration = AcquiringSdkConfiguration( credential: AcquiringSdkCredential( terminalKey: cfg.TerminalKey, password: cfg.Password, publicKey: cfg.PublicKey ), server: .prod ) sdk = try? AcquiringSdk.init(configuration: configuration) ui = try? AcquiringUISDK.init(configuration: configuration) } // MARK - Pay @objc(Pay:withResolver:withRejecter:) func Pay(json:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { Configure(json:json, resolve:resolve, reject:reject) let data = try! JSONDecoder().decode(PaymentInitData.self, from: json.data(using: .utf8)!) let viewConfigration = AcquiringViewConfiguration.init() viewConfigration.localizableInfo = AcquiringViewConfiguration.LocalizableInfo(lang: "ru") self.ui?.presentPaymentView(on: (UIApplication.shared.delegate?.window!?.rootViewController)!, paymentData: data, configuration: viewConfigration) { (res) in switch res { case .success(let success): self.promiseResolve?(try! success.encode2JSONObject()) case .failure(let error): self.promiseReject?(nil, nil, error) } } } // MARK - ApplePay @objc(ApplePay:merchant:withResolver:withRejecter:) func ApplePay(json:String, merchant:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { Configure(json:json, resolve:resolve, reject:reject) let data = try! JSONDecoder().decode(PaymentInitData.self, from: json.data(using: .utf8)!) var paymentConfiguration = AcquiringUISDK.ApplePayConfiguration.init() paymentConfiguration.merchantIdentifier = merchant self.ui?.presentPaymentApplePay( on: (UIApplication.shared.delegate?.window!?.rootViewController)!, paymentData: data, viewConfiguration: .init(), paymentConfiguration: paymentConfiguration) { (res) in switch res { case .success(let success): self.promiseResolve?(try! success.encode2JSONObject()) case .failure(let error): self.promiseReject?(nil, nil, error) } } } // MARK - ApplePayAvailable @objc(ApplePayAvailable:merchant:withResolver:withRejecter:) func ApplePayAvailable(json:String, merchant:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { Configure(json:json, resolve:resolve, reject:reject) var paymentConfiguration = AcquiringUISDK.ApplePayConfiguration.init() paymentConfiguration.merchantIdentifier = merchant let result = self.ui?.canMakePaymentsApplePay(with: paymentConfiguration) resolve(result ?? false) } // // MARK - Init // // @objc(Init:withResolver:withRejecter:) // func Init(json:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { // // Configure(json:json, resolve:resolve, reject:reject) // // let paymentData = try! JSONDecoder().decode(PaymentInitData.self, from: json.data(using: .utf8)!) // // _ = sdk?.paymentInit(data: paymentData) { (res) in // switch res { // case .success(let success): // self.promiseResolve?(try! success.encode2JSONObject()) // case .failure(let error): // self.promiseReject?(nil, nil, error) // } // } // } // // // MARK - FinishAuthorize // // @objc(Finish:withResolver:withRejecter:) // func Finish(json:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { // // Configure(json:json, resolve:resolve, reject:reject) // // let data = try! JSONDecoder().decode(PaymentFinishRequestData.self, from: json.data(using: .utf8)!) // // _ = sdk?.paymentFinish(data: data) { (res) in // switch res { // case .success(let success): // self.promiseResolve?(try! success.encode2JSONObject()) // case .failure(let error): // self.promiseReject?(nil, nil, error) // } // } // } }
42.328467
169
0.561649
9b622a7805ba807aafb4eab529bdcee867a31e86
4,816
import XCTest @testable import Apollo class GraphQLInputValueEncodingTests: XCTestCase { static var allTests : [(String, (GraphQLInputValueEncodingTests) -> () throws -> Void)] { return [ ("testEncodeValue", testEncodeValue), ("testEncodeOptionalValue", testEncodeOptionalValue), ("testEncodeNilValue", testEncodeNilValue), ("testEncodeNullValue", testEncodeNilValue), ("testEncodeEnumValue", testEncodeEnumValue), ("testEncodeMap", testEncodeMap), ("testEncodeOptionalMap", testEncodeOptionalMap), ("testEncodeNilMap", testEncodeNilMap), ("testEncodeList", testEncodeList), ("testEncodeOptionalList", testEncodeOptionalList), ("testEncodeNilList", testEncodeNilList), ("testEncodeInputObject", testEncodeInputObject), ("testEncodeInputObjectWithExplicitOptionalValue", testEncodeInputObjectWithExplicitOptionalValue), ("testEncodeInputObjectWithoutOptionalValue", testEncodeInputObjectWithoutOptionalValue), ("testEncodeInputObjectWithExplicitNilValue", testEncodeInputObjectWithExplicitNilValue), ("testEncodeInputObjectWithNestedInputObject", testEncodeInputObjectWithNestedInputObject), ] } private func serializeAndDeserialize(value: GraphQLInputValue) -> NSDictionary { let data = try! JSONSerializationFormat.serialize(value: value) return try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary } func testEncodeValue() { let map: GraphQLMap = ["name": "Luke Skywalker"] XCTAssertEqual(serializeAndDeserialize(value: map), ["name": "Luke Skywalker"]) } func testEncodeOptionalValue() { let map: GraphQLMap = ["name": "Luke Skywalker" as String?] XCTAssertEqual(serializeAndDeserialize(value: map), ["name": "Luke Skywalker"]) } func testEncodeNilValue() { let map: GraphQLMap = ["name": nil as String?] XCTAssertEqual(serializeAndDeserialize(value: map), [:]) } func testEncodeNullValue() { let map: GraphQLMap = ["name": NSNull()] XCTAssertEqual(serializeAndDeserialize(value: map), ["name": NSNull()]) } func testEncodeEnumValue() { let map: GraphQLMap = ["favoriteEpisode": Episode.jedi] XCTAssertEqual(serializeAndDeserialize(value: map), ["favoriteEpisode": "JEDI"]) } func testEncodeMap() { let map: GraphQLMap = ["hero": ["name": "Luke Skywalker"]] XCTAssertEqual(serializeAndDeserialize(value: map), ["hero": ["name": "Luke Skywalker"]]) } func testEncodeOptionalMap() { let map: GraphQLMap = ["hero": ["name": "Luke Skywalker"] as GraphQLMap?] XCTAssertEqual(serializeAndDeserialize(value: map), ["hero": ["name": "Luke Skywalker"]]) } func testEncodeNilMap() { let map: GraphQLMap = ["hero": nil as GraphQLMap?] XCTAssertEqual(serializeAndDeserialize(value: map), [:]) } func testEncodeList() { let map: GraphQLMap = ["appearsIn": [.jedi, .empire] as [Episode]] XCTAssertEqual(serializeAndDeserialize(value: map), ["appearsIn": ["JEDI", "EMPIRE"]]) } func testEncodeOptionalList() { let map: GraphQLMap = ["appearsIn": [.jedi, .empire] as [Episode]?] XCTAssertEqual(serializeAndDeserialize(value: map), ["appearsIn": ["JEDI", "EMPIRE"]]) } func testEncodeNilList() { let map: GraphQLMap = ["appearsIn": nil as [Episode]?] XCTAssertEqual(serializeAndDeserialize(value: map), [:]) } func testEncodeInputObject() { let review = ReviewInput(stars: 5, commentary: "This is a great movie!") let map: GraphQLMap = ["review": review] XCTAssertEqual(serializeAndDeserialize(value: map), ["review": ["stars": 5, "commentary": "This is a great movie!"]]) } func testEncodeInputObjectWithExplicitOptionalValue() { let review = ReviewInput(stars: 5, commentary: "This is a great movie!" as String?) let map: GraphQLMap = ["review": review] XCTAssertEqual(serializeAndDeserialize(value: map), ["review": ["stars": 5, "commentary": "This is a great movie!"]]) } func testEncodeInputObjectWithoutOptionalValue() { let review = ReviewInput(stars: 5) let map: GraphQLMap = ["review": review] XCTAssertEqual(serializeAndDeserialize(value: map), ["review": ["stars": 5]]) } func testEncodeInputObjectWithExplicitNilValue() { let review = ReviewInput(stars: 5, commentary: nil) let map: GraphQLMap = ["review": review] XCTAssertEqual(serializeAndDeserialize(value: map), ["review": ["stars": 5]]) } func testEncodeInputObjectWithNestedInputObject() { let review = ReviewInput(stars: 5, favoriteColor: ColorInput(red: 0, green: 0, blue: 0)) let map: GraphQLMap = ["review": review] XCTAssertEqual(serializeAndDeserialize(value: map), ["review": ["stars": 5, "favoriteColor": ["red": 0, "blue": 0, "green": 0]]]) } }
41.517241
133
0.698713
e2dddb107884f198e5af5fdcb75ab36d1e77e4d1
456
// // HairlineConstant.swift // SampleProject // // Created by danube83 on 2017. 2. 1.. // Copyright © 2017년 danube83. All rights reserved. // import UIKit @IBDesignable extension NSLayoutConstraint { @IBInspectable var hairLineConstraint: Int { get { return Int(self.constant * UIScreen.main.scale) } set { self.constant = CGFloat(integerLiteral: newValue) / UIScreen.main.scale } } }
20.727273
83
0.629386
2891c80e4dbad4d15e15d0001856af29ec501ca0
315
// // FILE.swift // MarkdownBuilder // // Created by Helge Heß on 15.10.21. // #if swift(>=5.1) import Markdown public extension Paragraph { // BlockMarkup, BasicInlineContainer @inlinable init(@InlineContentBuilder content: () -> [ InlineMarkup ]) { self.init(content()) } } #endif // swift(>=5.1)
16.578947
65
0.653968
f7cdf4dd2b4fb1cfb8f65b446b83092f4a7e83c2
874
/// The path of type-erased coding keys taken to get to a point in decoding. /// /// The use of `[AnyCodingKey]` allows this type to be used as a dictionary key (ie. it can conform to `Hashable`) where `[CodingKey]` cannot. public struct CodingPath: Hashable { /// The elements of the `CodingPath` as type-erased coding keys. public let elements: [AnyCodingKey] init(_ codingPath: [CodingKey]) { self.elements = codingPath.map(AnyCodingKey.init) } } extension CodingPath: ExpressibleByArrayLiteral { /// See `ExpressibleByArrayLiteral`. public init(arrayLiteral elements: AnyCodingKey...) { self.elements = elements } } public extension CodingPath { /// A representation of the `CodingPath` as the path elements separated by `.`. var dotPath: String { elements.map(\.description).joined(separator: ".") } }
33.615385
142
0.687643
dd29a394643b4bdb67d924054e49443b740f638d
5,349
// // BKLog.swift // BoundlessKit // // Created by Akash Desai on 3/14/18. // import Foundation open class BKLogPreferences { static var printEnabled = true static var debugEnabled = false } internal class BKLog { /// This function sends debug messages if "-D DEBUG" flag is added in 'Build Settings' > 'Swift Compiler - Custom Flags' /// /// - parameters: /// - message: The debug message. /// - filePath: Used to get filename of bug. Do not use this parameter. Defaults to #file. /// - function: Used to get function name of bug. Do not use this parameter. Defaults to #function. /// - line: Used to get the line of bug. Do not use this parameter. Defaults to #line. /// @objc public class func print(_ message: String, filePath: String = #file, function: String = #function, line: Int = #line) { guard BKLogPreferences.printEnabled else { return } var functionSignature:String = function if let parameterNames = functionSignature.range(of: "\\((.*?)\\)", options: .regularExpression) { functionSignature.replaceSubrange(parameterNames, with: "()") } let fileName = NSString(string: filePath).lastPathComponent Swift.print("[\(fileName):\(line):\(functionSignature)] - \(message)") } /// This function sends debug messages if "-D DEBUG" flag is added in 'Build Settings' > 'Swift Compiler - Custom Flags' /// /// - parameters: /// - message: The debug message. /// - filePath: Used to get filename of bug. Do not use this parameter. Defaults to #file. /// - function: Used to get function name of bug. Do not use this parameter. Defaults to #function. /// - line: Used to get the line of bug. Do not use this parameter. Defaults to #line. /// @objc public class func debug(_ message: String, filePath: String = #file, function: String = #function, line: Int = #line) { guard BKLogPreferences.printEnabled && BKLogPreferences.debugEnabled else { return } var functionSignature:String = function if let parameterNames = functionSignature.range(of: "\\((.*?)\\)", options: .regularExpression) { functionSignature.replaceSubrange(parameterNames, with: "()") } let fileName = NSString(string: filePath).lastPathComponent Swift.print("[\(fileName):\(line):\(functionSignature)] - \(message)") } /// This function sends debug messages if "-D DEBUG" flag is added in 'Build Settings' > 'Swift Compiler - Custom Flags' /// /// - parameters: /// - message: The confirmation message. /// - filePath: Used to get filename. Do not use this parameter. Defaults to #file. /// - function: Used to get function name. Do not use this parameter. Defaults to #function. /// - line: Used to get the line. Do not use this parameter. Defaults to #line. /// @objc public class func debug(confirmed message: String, filePath: String = #file, function: String = #function, line: Int = #line) { guard BKLogPreferences.printEnabled && BKLogPreferences.debugEnabled else { return } var functionSignature:String = function if let parameterNames = functionSignature.range(of: "\\((.*?)\\)", options: .regularExpression) { functionSignature.replaceSubrange(parameterNames, with: "()") } let fileName = NSString(string: filePath).lastPathComponent Swift.print("[\(fileName):\(line):\(functionSignature)] - ✅ \(message)") } /// This function sends debug messages if "-D DEBUG" flag is added in 'Build Settings' > 'Swift Compiler - Custom Flags' /// /// - parameters: /// - message: The debug message. /// - filePath: Used to get filename of bug. Do not use this parameter. Defaults to #file. /// - function: Used to get function name of bug. Do not use this parameter. Defaults to #function. /// - line: Used to get the line of bug. Do not use this parameter. Defaults to #line. /// @objc public class func debug(error message: String, visual: Bool = false, filePath: String = #file, function: String = #function, line: Int = #line) { guard BKLogPreferences.printEnabled && BKLogPreferences.debugEnabled else { return } var functionSignature:String = function if let parameterNames = functionSignature.range(of: "\\((.*?)\\)", options: .regularExpression) { functionSignature.replaceSubrange(parameterNames, with: "()") } let fileName = NSString(string: filePath).lastPathComponent Swift.print("[\(fileName):\(line):\(functionSignature)] - ❌ \(message)") if BKLogPreferences.debugEnabled && visual { alert(message: "🚫 \(message)", title: "☠️") } } private static func alert(message: String, title: String) { guard BKLogPreferences.printEnabled else { return } DispatchQueue.main.async { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) UIWindow.presentTopLevelAlert(alertController: alertController) } } }
52.441176
156
0.643298
2f695c843f0d431bfafa03f9c1b2789304ba1a3b
1,562
/* * 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 UIKit protocol RemoveCellDelegate: class { func removeCellDidTapButton(_ cell: RemoveCell) } final class RemoveCell: UICollectionViewCell { weak var delegate: RemoveCellDelegate? private lazy var label: UILabel = { let label = UILabel() label.backgroundColor = .clear self.contentView.addSubview(label) return label }() fileprivate lazy var button: UIButton = { let button = UIButton(type: .custom) button.setTitle("Remove", for: UIControl.State()) button.setTitleColor(.blue, for: UIControl.State()) button.backgroundColor = .clear button.addTarget(self, action: #selector(RemoveCell.onButton(_:)), for: .touchUpInside) self.contentView.addSubview(button) return button }() var text: String? { get { return label.text } set { label.text = newValue } } override func layoutSubviews() { super.layoutSubviews() contentView.backgroundColor = .white let bounds = contentView.bounds let divide = bounds.divided(atDistance: 100, from: .maxXEdge) label.frame = divide.slice.insetBy(dx: 15, dy: 0) button.frame = divide.remainder } @objc func onButton(_ button: UIButton) { delegate?.removeCellDidTapButton(self) } }
26.931034
95
0.637644
0e4319a44b1c38afbde11133503178a6a14b590e
3,080
// // S3+ObjectInfo.swift // S3 // // Created by Ondrej Rafaj on 12/05/2018. // import Foundation import Vapor import S3Signer // Helper S3 extension for working with buckets public extension S3 { // MARK: Buckets /// Get acl file information (ACL) /// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETacl.html public func get(acl file: LocationConvertible, headers: [String: String], on container: Container) throws -> Future<File.Info> { fatalError("Not implemented") } /// Get acl file information /// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETacl.html func get(acl file: LocationConvertible, on container: Container) throws -> Future<File.Info> { return try get(fileInfo: file, headers: [:], on: container) } /// Get file information (HEAD) /// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html public func get(fileInfo file: LocationConvertible, headers: [String: String], on container: Container) throws -> Future<File.Info> { let builder = urlBuilder(for: container) let url = try builder.url(file: file) let headers = try signer.headers(for: .HEAD, urlString: url.absoluteString, headers: headers, payload: .none) return try make(request: url, method: .HEAD, headers: headers, data: emptyData(), on: container).map(to: File.Info.self) { response in try self.check(response) let bucket = file.bucket ?? self.defaultBucket let region = file.region ?? self.signer.config.region let mime = response.http.headers.string(File.Info.CodingKeys.mime.rawValue) let size = response.http.headers.int(File.Info.CodingKeys.size.rawValue) let server = response.http.headers.string(File.Info.CodingKeys.server.rawValue) let etag = response.http.headers.string(File.Info.CodingKeys.etag.rawValue) let expiration = response.http.headers.date(File.Info.CodingKeys.expiration.rawValue) let created = response.http.headers.date(File.Info.CodingKeys.created.rawValue) let modified = response.http.headers.date(File.Info.CodingKeys.modified.rawValue) let versionId = response.http.headers.string(File.Info.CodingKeys.versionId.rawValue) let storageClass = response.http.headers.string(File.Info.CodingKeys.storageClass.rawValue) let info = File.Info(bucket: bucket, region: region, path: file.path, access: .authenticatedRead, mime: mime, size: size, server: server, etag: etag, expiration: expiration, created: created, modified: modified, versionId: versionId, storageClass: storageClass) return info } } /// Get file information (HEAD) /// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html func get(fileInfo file: LocationConvertible, on container: Container) throws -> Future<File.Info> { return try get(fileInfo: file, headers: [:], on: container) } }
48.125
273
0.677922
1c45df6d403bd332ae19cab409f7046184f08912
538
// // File.swift // // // Created by everis on 3/28/20. // import Foundation import ConsoleKit let console: Console = Terminal() var input = CommandInput(arguments: CommandLine.arguments) var context = CommandContext(console: console, input: input) var commands = Commands(enableAutocomplete: true) commands.use(ScanCommand(), as: ScanCommand.name, isDefault: true) do { let group = commands.group(help: "Interact with your TODOs") try console.run(group, input: input) } catch { console.error("\(error)") exit(1) }
19.925926
66
0.708178
1a0afb227183732ef91929f2788724de0d3026d5
5,905
// // AddRecipeView.swift // My Favourite Recipes // // Created by Chris Barker on 20/12/2019. // Copyright © 2019 Packt. All rights reserved. // import SwiftUI struct AddRecipeView: View { @State internal var recipeName: String = "" @State internal var ingredient: String = "" @State internal var ingredients = [String]() @State internal var recipeDetails: String = "" @State internal var showingImagePicker = false @State private var libraryImage: UIImage? @State private var selectedCountry = 0 @Environment(\.presentationMode) var presentationMode @EnvironmentObject var appData: AppData internal var countries = Helper.getCountries() var body: some View { NavigationView { Form { Button(action: { self.showingImagePicker.toggle() }) { Image(uiImage: self.libraryImage ?? (UIImage(named: "placeholder-add-image") ?? UIImage())) .resizable() .aspectRatio(contentMode: .fit) .clipShape(Circle()) .overlay(Circle().stroke(Color.purple, lineWidth: 3).shadow(radius: 10)) .frame(maxWidth: .infinity, maxHeight: 230) .padding(6) } .sheet(isPresented: $showingImagePicker) { ImagePicker(image: self.$libraryImage) }.buttonStyle(PlainButtonStyle()) Section(header: Text("Add Recipe Name:")) { TextField("enter recipe name", text: $recipeName) } Section(header: Text("Add Ingredient:")) { TextField("enter ingredient name", text: $ingredient) .modifier(AddButton(text: $ingredient, ingredients: $ingredients)) } if ingredients.count > 0 { Section(header: Text("Current Ingredients:")) { List(ingredients, id: \.self) { item in Button(action: { self.ingredients.removeAll { $0 == item } }) { Image(systemName: "minus") .foregroundColor(Color(UIColor.opaqueSeparator)) } .padding(.trailing, 8) Text(item) } } } Section(header: Text("Details")) { TextView(text: $recipeDetails) .frame(height: 220) } Section(header: Text("Country of Origin:")) { Picker(selection: $selectedCountry, label: Text("Country")) { ForEach(0 ..< countries.count) { Text(self.countries[$0]).tag($0) .font(.headline) } } } } // Closing Form Brace .navigationBarTitle("Add Recipe") .navigationBarItems(leading: Button(action: { self.getRandomImage() }) { Text("Random Image") }, trailing: Button(action: { self.saveRecipe() self.presentationMode.wrappedValue.dismiss() }) { Text("Save") } ) } } private func getRandomImage() { guard let url = URL(string: "https://source.unsplash.com/300x200/?food") else { return } NetworkHelper.loadData(url: url) { (image) in self.libraryImage = image } } private func saveRecipe() { var recipeImage = UIImage() if let libImage = libraryImage { recipeImage = libImage } let country = countries[selectedCountry] let newRecipe = RecipeModel(id: UUID(), name: recipeName, origin: country, countryCode: Helper.getCountryCode(country: country), favourite: false, ingredients: ingredients, recipe: recipeDetails, imageData: recipeImage.jpegData(compressionQuality: 0.3) ?? Data()) // Update Local Saved Data self.appData.recipes.append(newRecipe) Helper.saveRecipes(recipes: self.appData.recipes) } } struct AddButton: ViewModifier { @Binding var text: String @Binding var ingredients: [String] public func body(content: Content) -> some View { ZStack(alignment: .trailing) { content Button(action: { if self.text != "" { self.ingredients.append(self.text) self.text = "" } }) { Image(systemName: "plus") .foregroundColor(Color(UIColor.opaqueSeparator)) } .padding(.trailing, 8) } } } struct AddRecipeView_Previews: PreviewProvider { static var previews: some View { let recipe = Helper.mockRecipes().first! return AddRecipeView(recipeName: recipe.name, ingredient: recipe.ingredients.first ?? "", ingredients: recipe.ingredients, recipeDetails: recipe.recipe) } }
34.331395
160
0.461304
fb7c2b234dfebc25e494c9f970427252049ee124
2,544
// // BottomSheetView.swift // WBikes // // Created by Diego on 16/10/2020. // import UIKit class BottomSheetView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var bikesLabel: UILabel! @IBOutlet weak var slotsLabel: UILabel! @IBOutlet weak var buttomDirections: UIButton! @IBOutlet weak var favoriteButton: UIButton! var id: String? = nil var buttonDirectionsAction: (()->Void)? var buttonFavoriteAction: (()->Void)? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSubviews() } override init(frame: CGRect) { super.init(frame: frame) initSubviews() } func initSubviews() { // standard initialization logic let nib = UINib(nibName: "BottomSheetView", bundle: nil) nib.instantiate(withOwner: self, options: nil) contentView.frame = bounds buttomDirections.layer.cornerRadius = 5 addSubview(contentView) } func updateData(station: Station){ clearData() self.id = station.id if let address = station.address ?? station.name { self.addressLabel.text = address } self.bikesLabel.text = "\(station.freeBikes)" self.slotsLabel.text = "\(station.emptySlots)" setFavorite(station.isFavorite) } func setFavorite(_ isFavorite: Bool){ self.favoriteButton.setImage( isFavorite ? UIImage( named: "favorite_fill") : UIImage( named: "favorite"), for: .normal) } func clearData(){ self.addressLabel.text = "" self.bikesLabel.text = "" self.slotsLabel.text = "" setFavorite(false) } func animated(x: CGFloat, y: CGFloat) { UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: { self.frame = CGRect(x: x, y: y , width: self.frame.width, height: self.frame.height) }, completion: nil) } func setRoundCorners(radius: CGFloat) { contentView.roundCorners(corners: [.topLeft, .topRight], radius: radius) } @IBAction func buttomLike(_ sender: Any) { buttonFavoriteAction?() } @IBAction func buttomDirections(_ sender: Any) { buttonDirectionsAction?() } @IBAction func closeAction(_ sender: Any) { animated(x: 0, y: UIScreen.main.bounds.size.height ) } }
27.956044
148
0.621069
87cc3058ac71960088111d324213db049a15a3f2
400
import Foundation public enum Feature: String { case nativeCheckout = "ios_native_checkout" case nativeCheckoutPledgeView = "ios_native_checkout_pledge_view" } extension Feature: CustomStringConvertible { public var description: String { switch self { case .nativeCheckout: return "Native Checkout" case .nativeCheckoutPledgeView: return "Native Checkout Pledge View" } } }
25
72
0.765
dbb3fcde6a52a18b2a3df386d02553d484b5fe94
4,543
// // AppDelegate.swift // lokinet // // Copyright © 2019 Loki. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "lokinet") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
48.849462
285
0.686551
61a4baf1f2c215d1d65756b76317c97f55754aa5
1,872
// // ViewController.swift // Swift-Sample-UICollectionView-zoom // // Created by nobuy on 2020/03/21. // Copyright © 2020 A10 Lab Inc. All rights reserved. // import UIKit class ViewController: UIViewController { private let imageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "sample1.jpg")) imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.isUserInteractionEnabled = true return imageView }() // MARk: - Lifc Cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true imageView.widthAnchor.constraint(equalToConstant: 200).isActive = true imageView.heightAnchor.constraint(equalToConstant: 200).isActive = true let gesture = UITapGestureRecognizer() gesture.addTarget(self, action: #selector(onTapped(_:))) imageView.addGestureRecognizer(gesture) } // MARK: - Handle Event @objc private func onTapped(_ sender: Any?) { let vc = FullScreenImagesViewController(images: images) vc.modalPresentationStyle = .fullScreen vc.modalTransitionStyle = .crossDissolve present(vc, animated: true, completion: nil) } let images = [ UIImage(named: "sample1.jpg")!, UIImage(named: "sample2.jpg")!, UIImage(named: "sample3.jpg")!, UIImage(named: "sample4.jpg")!, UIImage(named: "sample5.jpg")!, UIImage(named: "sample6.jpg")!, UIImage(named: "sample7.jpg")! ] }
31.728814
87
0.667735
22f6d7469b4582d246766fb84e0d102464da2f99
2,544
// // StructureDTO.swift // Fyre // // Created by Augusto Cesar do Nascimento dos Reis on 11/05/20. // Copyright © 2020 Augusto Reis. All rights reserved. // import Foundation struct StructureDTO: Codable { var id: Int? var name: String? var description: String? var expansion: String? var age: String? var cost: CostDTO? var buildTime: Float? var hitPoints: Int? var lineOfSight: Int? var armor: String? var range: String? var reloadTime: Float? var attack: Int? var special: [String]? enum CodingKeys: String, CodingKey { case id = "id" case name = "name" case description = "description" case expansion = "expansion" case age = "age" case cost = "cost" case buildTime = "build_time" case hitPoints = "hit_points" case lineOfSight = "line_of_sight" case armor = "armor" case range = "range" case reloadTime = "reload_time" case attack = "attack" case special = "special" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.id = try container.decodeIfPresent(Int.self, forKey: .id) self.name = try container.decodeIfPresent(String.self, forKey: .name) self.description = try container.decodeIfPresent(String.self, forKey: .description) self.expansion = try container.decodeIfPresent(String.self, forKey: .expansion) self.age = try container.decodeIfPresent(String.self, forKey: .age) self.cost = try container.decodeIfPresent(CostDTO.self, forKey: .cost) self.buildTime = try container.decodeIfPresent(Float.self, forKey: .buildTime) self.reloadTime = try container.decodeIfPresent(Float.self, forKey: .reloadTime) self.lineOfSight = try container.decodeIfPresent(Int.self, forKey: .lineOfSight) self.hitPoints = try container.decodeIfPresent(Int.self, forKey: .hitPoints) if let value = try? container.decodeIfPresent(Int.self, forKey: .range) { self.range = String(value) } if let value = try? container.decodeIfPresent(String.self, forKey: .range) { self.range = value } self.attack = try container.decodeIfPresent(Int.self, forKey: .attack) self.armor = try container.decodeIfPresent(String.self, forKey: .armor) self.special = try container.decodeIfPresent([String].self, forKey: .special) } }
35.830986
91
0.646226
f7df0c0499f554f3f0e6a330985956aed432aacc
292
// // SearchViewModelState.swift // iOSEngineerCodeCheck // // Created by Yoshihisa Masaki on 2021/03/30. // Copyright © 2021 YUMEMI Inc. All rights reserved. // import Foundation enum SearchViewModelState { case none case loading case loaded case repositoriesUpdated }
17.176471
53
0.719178
dd61c6b362e4ca2a5f14d0c14931cccd002b9f6e
1,225
// // TasksBuilder.swift // RIBsTodo // // Created by myung gi son on 2020/04/19. // Copyright © 2020 myunggison. All rights reserved. // import RIBs import RealmSwift protocol TasksDependency: Dependency { } final class TasksComponent: Component<TasksDependency> { var taskService: TaskServiceProtocol { self.container.resolve(TaskServiceProtocol.self)! } } // MARK: - Builder protocol TasksBuildable: Buildable { func build(withListener listener: TasksListener) -> TasksRouting } final class TasksBuilder: Builder<TasksDependency>, TasksBuildable { override init(dependency: TasksDependency) { super.init(dependency: dependency) } func build(withListener listener: TasksListener) -> TasksRouting { let component = TasksComponent(dependency: dependency) let viewController = TasksViewController() let interactor = TasksInteractor( presenter: viewController, taskService: component.taskService ) interactor.listener = listener let taskEditingBuilder = TaskEditingBuilder(dependency: component) return TasksRouter( interactor: interactor, viewController: viewController, taskEditingBuilder: taskEditingBuilder ) } }
24.019608
70
0.734694
e44818d04803886e2a6b211e831826275fc6c81b
3,372
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit class HorizontalStackScrollView: UIScrollView { private var arrangedViews: [UIView] = [] private var arrangedViewContraints: [NSLayoutConstraint] = [] var interItemSpacing: CGFloat = 0.0 { didSet { self.setNeedsUpdateConstraints() } } func addArrangedViews(views: [UIView]) { for view in views { view.translatesAutoresizingMaskIntoConstraints = false self.addSubview(view) } self.arrangedViews.appendContentsOf(views) self.setNeedsUpdateConstraints() } override func updateConstraints() { super.updateConstraints() self.removeConstraintsForArrangedViews() self.addConstraintsForArrengedViews() } private func removeConstraintsForArrangedViews() { for constraint in arrangedViewContraints { self.removeConstraint(constraint) } self.arrangedViewContraints.removeAll() } private func addConstraintsForArrengedViews() { for (index, view) in arrangedViews.enumerate() { switch index { case 0: let constraint = NSLayoutConstraint(item: view, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0) addConstraint(constraint) arrangedViewContraints.append(constraint) case arrangedViews.count-1: let constraint = NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 0) addConstraint(constraint) arrangedViewContraints.append(constraint) fallthrough default: let constraint = NSLayoutConstraint(item: view, attribute: .Leading, relatedBy: .Equal, toItem: arrangedViews[index-1], attribute: .Trailing, multiplier: 1, constant: self.interItemSpacing) addConstraint(constraint) arrangedViewContraints.append(constraint) } addConstraint(NSLayoutConstraint(item: view, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0)) } } }
42.15
205
0.693654
79ebcafcda3c25534366be8ba8872fac53774c3c
5,797
// // SentimentClassifier.swift // // This file was automatically generated and should not be edited. // import CoreML /// Model Prediction Input Type @available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 5.0, *) class SentimentClassifierInput : MLFeatureProvider { /// Input text as string value var text: String var featureNames: Set<String> { get { return ["text"] } } func featureValue(for featureName: String) -> MLFeatureValue? { if (featureName == "text") { return MLFeatureValue(string: text) } return nil } init(text: String) { self.text = text } } /// Model Prediction Output Type @available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 5.0, *) class SentimentClassifierOutput : MLFeatureProvider { /// Source provided by CoreML private let provider : MLFeatureProvider /// Text label as string value lazy var label: String = { [unowned self] in return self.provider.featureValue(for: "label")!.stringValue }() var featureNames: Set<String> { return self.provider.featureNames } func featureValue(for featureName: String) -> MLFeatureValue? { return self.provider.featureValue(for: featureName) } init(label: String) { self.provider = try! MLDictionaryFeatureProvider(dictionary: ["label" : MLFeatureValue(string: label)]) } init(features: MLFeatureProvider) { self.provider = features } } /// Class for model loading and prediction @available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 5.0, *) class SentimentClassifier { var model: MLModel /// URL of model assuming it was installed in the same bundle as this class class var urlOfModelInThisBundle : URL { let bundle = Bundle(for: SentimentClassifier.self) return bundle.url(forResource: "SentimentClassifier", withExtension: "mlmodelc")! } /** Construct a model with explicit path to mlmodelc file - parameters: - url: the file url of the model - throws: an NSError object that describes the problem */ init(contentsOf url: URL) throws { self.model = try MLModel(contentsOf: url) } /// Construct a model that automatically loads the model from the app's bundle convenience init() { try! self.init(contentsOf: type(of:self).urlOfModelInThisBundle) } /** Construct a model with configuration - parameters: - configuration: the desired model configuration - throws: an NSError object that describes the problem */ convenience init(configuration: MLModelConfiguration) throws { try self.init(contentsOf: type(of:self).urlOfModelInThisBundle, configuration: configuration) } /** Construct a model with explicit path to mlmodelc file and configuration - parameters: - url: the file url of the model - configuration: the desired model configuration - throws: an NSError object that describes the problem */ init(contentsOf url: URL, configuration: MLModelConfiguration) throws { self.model = try MLModel(contentsOf: url, configuration: configuration) } /** Make a prediction using the structured interface - parameters: - input: the input to the prediction as SentimentClassifierInput - throws: an NSError object that describes the problem - returns: the result of the prediction as SentimentClassifierOutput */ func prediction(input: SentimentClassifierInput) throws -> SentimentClassifierOutput { return try self.prediction(input: input, options: MLPredictionOptions()) } /** Make a prediction using the structured interface - parameters: - input: the input to the prediction as SentimentClassifierInput - options: prediction options - throws: an NSError object that describes the problem - returns: the result of the prediction as SentimentClassifierOutput */ func prediction(input: SentimentClassifierInput, options: MLPredictionOptions) throws -> SentimentClassifierOutput { let outFeatures = try model.prediction(from: input, options:options) return SentimentClassifierOutput(features: outFeatures) } /** Make a prediction using the convenience interface - parameters: - text: Input text as string value - throws: an NSError object that describes the problem - returns: the result of the prediction as SentimentClassifierOutput */ func prediction(text: String) throws -> SentimentClassifierOutput { let input_ = SentimentClassifierInput(text: text) return try self.prediction(input: input_) } /** Make a batch prediction using the structured interface - parameters: - inputs: the inputs to the prediction as [SentimentClassifierInput] - options: prediction options - throws: an NSError object that describes the problem - returns: the result of the prediction as [SentimentClassifierOutput] */ func predictions(inputs: [SentimentClassifierInput], options: MLPredictionOptions = MLPredictionOptions()) throws -> [SentimentClassifierOutput] { let batchIn = MLArrayBatchProvider(array: inputs) let batchOut = try model.predictions(from: batchIn, options: options) var results : [SentimentClassifierOutput] = [] results.reserveCapacity(inputs.count) for i in 0..<batchOut.count { let outProvider = batchOut.features(at: i) let result = SentimentClassifierOutput(features: outProvider) results.append(result) } return results } }
33.900585
150
0.671899
f4b9c9f09b28e53acba7d59f29e46a8d0708f04e
8,801
import Foundation import RequestKit import XCTest #if canImport(FoundationNetworking) import FoundationNetworking #endif class RouterTests: XCTestCase { lazy var router: TestRouter = { let config = TestConfiguration("1234", url: "https://example.com/api/v1/") let router = TestRouter.testRoute(config) return router }() func testRequest() { let subject = router.request() XCTAssertEqual(subject?.url?.absoluteString, "https://example.com/api/v1/some_route?access_token=1234&key1=value1%3A456&key2=value2") XCTAssertEqual(subject?.httpMethod, "GET") } func testRequestWithAuthorizationHeader() { let config = TestAuthorizationHeaderConfiguration("1234", url: "https://example.com/api/v1/") let router = TestRouter.testRoute(config) let subject = router.request() XCTAssertEqual(subject?.url?.absoluteString, "https://example.com/api/v1/some_route?key1=value1%3A456&key2=value2") XCTAssertEqual(subject?.httpMethod, "GET") XCTAssertEqual(subject?.value(forHTTPHeaderField: "Authorization"), "BEARER 1234") } func testRequestWithCustomHeaders() { let config = TestCustomConfiguration("1234", url: "https://github.com", customHeader: HTTPHeader(headerField: "x-custom-header", value: "custom_value")) let router = TestRouter.testRoute(config) let subject = router.request() XCTAssertEqual(subject?.value(forHTTPHeaderField: "x-custom-header"), "custom_value") } func testWasSuccessful() { let url = URL(string: "https://example.com/api/v1")! let response200 = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:])! XCTAssertTrue(response200.wasSuccessful) let response201 = HTTPURLResponse(url: url, statusCode: 201, httpVersion: "HTTP/1.1", headerFields: [:])! XCTAssertTrue(response201.wasSuccessful) let response400 = HTTPURLResponse(url: url, statusCode: 400, httpVersion: "HTTP/1.1", headerFields: [:])! XCTAssertFalse(response400.wasSuccessful) let response300 = HTTPURLResponse(url: url, statusCode: 300, httpVersion: "HTTP/1.1", headerFields: [:])! XCTAssertFalse(response300.wasSuccessful) let response301 = HTTPURLResponse(url: url, statusCode: 301, httpVersion: "HTTP/1.1", headerFields: [:])! XCTAssertFalse(response301.wasSuccessful) } func testURLComponents() { let test1: [String: Any] = ["key1": "value1", "key2": "value2"] XCTAssertEqual(router.urlQuery(test1)!, [URLQueryItem(name: "key1", value: "value1"), URLQueryItem(name: "key2", value: "value2")]) let test2: [String: Any] = ["key1": ["value1", "value2"]] XCTAssertEqual(router.urlQuery(test2)!, [URLQueryItem(name: "key1[0]", value: "value1"), URLQueryItem(name: "key1[1]", value: "value2")]) let test3: [String: Any] = ["key1": ["key2": "value1", "key3": "value2"]] XCTAssertEqual(router.urlQuery(test3)!, [URLQueryItem(name: "key1[key2]", value: "value1"), URLQueryItem(name: "key1[key3]", value: "value2")]) } func testFormEncodedRouteRequest() { let config = TestConfiguration("1234", url: "https://example.com/api/v1/") let router = TestRouter.formEncodedRoute(config) let subject = router.request() XCTAssertEqual(subject?.url?.absoluteString, "https://example.com/api/v1/route") XCTAssertEqual(String(data: subject?.httpBody ?? Data(), encoding: .utf8), "access_token=1234&key1=value1%3A456&key2=value2") XCTAssertEqual(subject?.httpMethod, "POST") } func testErrorWithJSON() { let jsonDict = ["message": "Bad credentials", "documentation_url": "https://developer.github.com/v3"] let jsonString = String(data: try! JSONSerialization.data(withJSONObject: jsonDict, options: JSONSerialization.WritingOptions()), encoding: String.Encoding.utf8) let session = RequestKitURLTestSession(expectedURL: "https://example.com/some_route", expectedHTTPMethod: "GET", response: jsonString, statusCode: 401) let task = TestInterface().getJSON(session) { response in switch response { case .success: XCTAssert(false, "should not retrieve a succesful response") case let .failure(error): XCTAssertEqual(Helper.getNSError(from: error)?.code, 401) XCTAssertEqual(Helper.getNSError(from: error)?.domain, "com.nerdishbynature.RequestKitTests") XCTAssertEqual((Helper.getNSError(from: error)?.userInfo[RequestKitErrorKey] as? [String: String]) ?? [:], jsonDict) } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if !canImport(FoundationNetworking) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testErrorWithJSONAsync() async throws { let jsonDict = ["message": "Bad credentials", "documentation_url": "https://developer.github.com/v3"] let jsonString = String(data: try! JSONSerialization.data(withJSONObject: jsonDict, options: JSONSerialization.WritingOptions()), encoding: String.Encoding.utf8) let session = RequestKitURLTestSession(expectedURL: "https://example.com/some_route", expectedHTTPMethod: "GET", response: jsonString, statusCode: 401) do { _ = try await TestInterface().getJSON(session) XCTFail("should not retrieve a succesful response") } catch { XCTAssertEqual(Helper.getNSError(from: error)?.code, 401) XCTAssertEqual(Helper.getNSError(from: error)?.domain, "com.nerdishbynature.RequestKitTests") XCTAssertEqual((Helper.getNSError(from: error)?.userInfo[RequestKitErrorKey] as? [String: String]) ?? [:], jsonDict) XCTAssertTrue(session.wasCalled) } } #endif func testLoadAndIgnoreResponseBody() { let session = RequestKitURLTestSession(expectedURL: "https://example.com/some_route", expectedHTTPMethod: "POST", response: nil, statusCode: 204) var receivedSuccessResponse = false let task = TestInterface().loadAndIgnoreResponseBody(session) { response in switch response { case .success: receivedSuccessResponse = true case .failure: XCTAssert(false, "should not retrieve a failure response") } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) XCTAssertTrue(receivedSuccessResponse) } func testErrorWithLoadAndIgnoreResponseBody() { let jsonDict = ["message": "Bad credentials", "documentation_url": "https://developer.github.com/v3"] let jsonString = String(data: try! JSONSerialization.data(withJSONObject: jsonDict, options: JSONSerialization.WritingOptions()), encoding: String.Encoding.utf8) let session = RequestKitURLTestSession(expectedURL: "https://example.com/some_route", expectedHTTPMethod: "POST", response: jsonString, statusCode: 401) var receivedFailureResponse = false let task = TestInterface().loadAndIgnoreResponseBody(session) { response in switch response { case .success: XCTAssert(false, "should not retrieve a successful response") case let .failure(error): receivedFailureResponse = true XCTAssertEqual(Helper.getNSError(from: error)?.code, 401) XCTAssertEqual(Helper.getNSError(from: error)?.domain, "com.nerdishbynature.RequestKitTests") XCTAssertEqual((Helper.getNSError(from: error)?.userInfo[RequestKitErrorKey] as? [String: String]) ?? [:], jsonDict) } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) XCTAssertTrue(receivedFailureResponse) } } enum TestRouter: Router { case testRoute(Configuration) case formEncodedRoute(Configuration) var configuration: Configuration { switch self { case let .testRoute(config): return config case let .formEncodedRoute(config): return config } } var method: HTTPMethod { switch self { case .testRoute: return .GET case .formEncodedRoute: return .POST } } var encoding: HTTPEncoding { switch self { case .testRoute: return .url case .formEncodedRoute: return .form } } var path: String { switch self { case .testRoute: return "some_route" case .formEncodedRoute: return "route" } } var params: [String: Any] { return ["key1": "value1:456", "key2": "value2"] } }
46.321053
169
0.657425
2f830acff417e32fcac93baa0a3e7320b4893e0a
227
// // CVRange.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 17/03/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit enum CVRange { case Started case Changed case Ended }
15.133333
52
0.665198
64358ee6a1306e2574745512bb5d1d88c000df09
94,965
// // ViewController.swift // WordGame // // Created by Aaron Halvorsen on 4/21/17. // Copyright © 2017 Aaron Halvorsen. All rights reserved. // import UIKit import SwiftyStoreKit class GameViewController: UIViewController, UIGestureRecognizerDelegate, UIScrollViewDelegate { var tilesInPlay = [Tile]() var boostTimer = Timer() var myTimer = Timer() let progressHUD = ProgressHUD(text: "Loading") var isFirstPlayFunc = true let myColor = CustomColor() let myBoard = Board.sharedInstance var pan = UIPanGestureRecognizer() var pan2 = UIPanGestureRecognizer() var tap = UITapGestureRecognizer() var doubleTap = UITapGestureRecognizer() var allTiles = [Tile]() var movingTile: Tile? var onDeckTiles = [Tile]() var wordTiles = [Tile]() var wordTilesPerpendicular = [Tile]() let pile = Tile() var pileOfTiles = 30 { didSet { pileOfTilesString = String(pileOfTiles); pile.text.text = pileOfTilesString} } var pileOfTilesString = "x15" var isNotSameTile = false let onDeckAlpha: CGFloat = 0.1 var playButton = UIButton() var amountOfBoosts = Int() { didSet { LoadSaveCoreData.sharedInstance.saveBoost(amount: amountOfBoosts); if amountOfBoosts > 9 { boostIndicator.text = String(amountOfBoosts) } else { boostIndicator.text = "0" + String(amountOfBoosts) } }} var refillMode = false {didSet{ if refillMode { view.removeGestureRecognizer(pan) view.addGestureRecognizer(pan2) for tile in allTiles { if tile.myWhereInPlay == .pile { tile.topOfBlock.backgroundColor = self.myColor.teal tile.text.textColor = .black tile.alpha = 1.0 } if tile.myWhereInPlay == .onDeck { tile.topOfBlock.backgroundColor = self.myColor.purple tile.text.textColor = .black tile.alpha = 1.0 } if tile.myWhereInPlay == .atBat { tile.topOfBlock.backgroundColor = .white } } pile.alpha = 1.0 } else { view.addGestureRecognizer(pan) view.removeGestureRecognizer(pan2) pile.alpha = onDeckAlpha for tile in allTiles { delay(bySeconds: 0.5) { if tile.myWhereInPlay == .pile { tile.topOfBlock.backgroundColor = self.myColor.teal tile.text.textColor = .black tile.alpha = self.onDeckAlpha } if tile.myWhereInPlay == .onDeck { tile.topOfBlock.backgroundColor = self.myColor.purple tile.text.textColor = .black tile.alpha = self.onDeckAlpha } if tile.myWhereInPlay == .atBat { tile.topOfBlock.backgroundColor = self.myColor.purple } } } }}} var trash = UIImageView() var onTheBoard: Int = 0 var duplicateLetterAmount2: Int = 0 var duplicateLetter2 = "A" var duplicateLetterAmount: Int = 0 var duplicateLetter = "A" var lengthOfWord: Int = 0 var banner = UIImageView() var boostIndicator = UILabel() var isFirstLoading = false var startingNewGame = false var isWin = false var newGame = false override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() isFirstLoading = !UserDefaults.standard.bool(forKey: "launchedWordGameBefore") myLoad() } private func myLoad() { let launchedBefore = UserDefaults.standard.bool(forKey: "launchedWordGameBefore") let menuButton = UIButton() menuButton.frame = CGRect(x: 0, y: 0, width: 64*sw/375, height: 64*sw/375) menuButton.setImage(#imageLiteral(resourceName: "menu"), for: .normal) menuButton.addTarget(self, action: #selector(GameViewController.menuFunc(_:)), for: .touchUpInside) view.addSubview(menuButton) trash.frame = CGRect(x: 309*sw/375, y: 567*sh/667, width: 66*sw/375, height: 100*sh/667) trash.image = #imageLiteral(resourceName: "trash") view.addSubview(trash) view.backgroundColor = myColor.white245 view.addSubview(myBoard) pan = UIPanGestureRecognizer(target: self, action: #selector(GameViewController.moveTile(_:))) view.addGestureRecognizer(pan) pan2 = UIPanGestureRecognizer(target: self, action: #selector(GameViewController.moveTile2(_:))) tap = UITapGestureRecognizer(target: self, action: #selector(GameViewController.tapTile(_:))) view.addGestureRecognizer(tap) pile.text.font = UIFont(name: "HelveticaNeue-Bold", size: 14*fontSizeMultiplier) pile.frame = CGRect(x: 13*sw/375, y: 616*sh/667, width: 34*sw/375, height: 34*sw/375) pile.myWhereInPlay = .pile view.addSubview(pile) pile.text.text = pileOfTilesString allTiles.append(pile) pile.alpha = onDeckAlpha if launchedBefore { LoadSaveCoreData.sharedInstance.loadState() } addTilesToBoard() startGameWithTilesOnBoard(difficulty: .hard) playButton.frame = CGRect(x: sw/4, y: 45*sh/667, width: sw/2, height: 69*sh/667) playButton.setImage(#imageLiteral(resourceName: "play"),for: .normal) playButton.backgroundColor = myColor.white245 playButton.addTarget(self, action: #selector(GameViewController.playFunc(_:)), for: .touchUpInside) playButton.setTitleColor(myColor.purple, for: .normal) view.addSubview(playButton) myBoard.delegate = self self.myBoard.showsHorizontalScrollIndicator = false self.myBoard.showsVerticalScrollIndicator = false doubleTap.numberOfTapsRequired = 2 doubleTap = UITapGestureRecognizer(target: self, action: #selector(GameViewController.doubleTapFunc(_:))) view.addGestureRecognizer(doubleTap) tap.require(toFail: doubleTap) doubleTap.numberOfTapsRequired = 2 delay(bySeconds: 1.0){ // self.view.alpha = 0.2 if launchedBefore { print("Not first launch.") } else { self.performSegue(withIdentifier: "fromGameToTutorial", sender: self) UserDefaults.standard.set(true, forKey: "launchedWordGameBefore") } } banner.image = #imageLiteral(resourceName: "rocket") banner.frame = CGRect(x: 276*sw/375, y: 0, width: 99*sw/375, height: 70*sw/375) banner.alpha = 1.0 view.addSubview(banner) boostIndicator = UILabel(frame: CGRect(x: 290*sw/375, y: 25*sh/667, width: 30*sw/375, height: 25*sw/667)) if amountOfBoosts < 10 { boostIndicator.text = "0" + String(amountOfBoosts) } else { boostIndicator.text = String(amountOfBoosts) } boostIndicator.font = UIFont(name: "Helvetica-Bold", size: 19*fontSizeMultiplier) boostIndicator.textColor = myColor.teal boostIndicator.textAlignment = .left view.addSubview(boostIndicator) } var myMenu = MenuViewController() override func viewWillAppear(_ animated: Bool) { print(isWin) doubleTap.numberOfTapsRequired = 2 let a = LoadSaveCoreData.sharedInstance.loadBoost() if a != nil { amountOfBoosts = a! } else { amountOfBoosts = 3 } if newGame { isWin = false Set1.winState = false restart() storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } else if Set1.winState { isWin = true alreadyWinSequence() } LoadSaveCoreData.sharedInstance.saveState() print(isWin) if !UserDefaults.standard.bool(forKey: "launchedWordGameBefore") { let viewMask = UIView() viewMask.frame = view.bounds viewMask.backgroundColor = .white view.addSubview(viewMask) delay(bySeconds: 1.0) { UIView.animate(withDuration: 1.0) { viewMask.alpha = 0.0 } } } } private func bannerFunc() { if amountOfBoosts > 0 { boost() amountOfBoosts -= 1 } else { IAP() } } private func IAP() { let alert = UIAlertController(title: "Boost", message: "Buy 3 Boosts for $.99", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default) { (action: UIAlertAction!) in self.purchase(productId: "com.fooble.boosts") }) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } private func takeTilesOffBoardAndSave() { for tile in allTiles { if tile.myWhereInPlay == .board && !tile.isLockedInPlace { myBoard.slots[tile.slotsIndex!].isOccupied = false tile.myWhereInPlay = .atBat tile.removeFromSuperview() onTheBoard -= 1 tile.atBatTileOrder = 1 view.addSubview(tile) movingTile?.myWhereInPlay = .atBat reOrderAtBat() dropTileWhereItBelongs(tile: tile) } } self.storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } @objc private func menuFunc(_ button: UIButton) { takeTilesOffBoardAndSave() for tile in allTiles { tile.removeFromSuperview() } performSegue(withIdentifier: "fromGameToMenu", sender: self) } func leave() { dismiss(animated: true, completion: nil) } private func findTheString(callback: (_ word: String?, _ rowWord: Bool, _ mainWordTiles: [Tile]) -> Void) { var mainWordTiles = [Tile]() tilesInPlay.removeAll() for tile in allTiles { if tile.myWhereInPlay == .board && tile.isLockedInPlace == false { tilesInPlay.append(tile) mainWordTiles.append(tile) } } guard tilesInPlay.count > 0 else {return} let row = tilesInPlay[0].row! let column = tilesInPlay[0].column! var isSameRow = true var isSameColumn = true var smallestRow = 16 var smallestColumn = 16 var bool1 = false var bool2 = false var bool3 = false var word = String() for tile in tilesInPlay { if tile.row! < smallestRow { smallestRow = tile.row! } if tile.column! < smallestColumn { smallestColumn = tile.column! } if row != tile.row { isSameRow = false } if column != tile.column { isSameColumn = false } } for _ in 0...6 { for tile in allTiles { if tile.isStarterBlock || tile.isLockedInPlace { if isSameRow { if tile.row == smallestRow && tile.column == smallestColumn - 1 { smallestColumn -= 1 mainWordTiles.append(tile) } } else if isSameColumn { if tile.row == smallestRow - 1 && tile.column == smallestColumn { smallestRow -= 1 mainWordTiles.append(tile) } } } } } // if tilesInPlay.count == 1 { // // for tile in allTiles { // if tile.isLockedInPlace == true && tile.row == wordTiles[0].row! - 1 { // isSameRow = false // isSameColumn = true // } // if tile.isLockedInPlace == true && tile.column == wordTiles[0].column! - 1 { // isSameRow = true // isSameColumn = false // } // if tile.isLockedInPlace == true && tile.row == wordTiles[0].row! + 1 { // isSameRow = false // isSameColumn = true // } // if tile.isLockedInPlace == true && tile.column == wordTiles[0].column! + 1 { // isSameRow = true // isSameColumn = false // } // } // } if !isSameColumn && !isSameRow { callback(nil, true, tilesInPlay) } if isSameRow { (bool1,bool2,bool3) = checkIfThereIsPriorTileInSameRow(row: smallestRow, column: smallestColumn) if bool1 == true { smallestColumn -= 1 if bool2 == true { smallestColumn -= 1 if bool3 == true { smallestColumn -= 1 } } } var dontQuit = true while dontQuit { var count = 1 outerLoop: for tile in allTiles { if tile.row != nil && tile.myWhereInPlay == .board { if tile.row! == smallestRow && tile.column! == smallestColumn { word += tile.mySymbol.rawValue wordTiles.append(tile) smallestColumn += 1 break outerLoop } else if allTiles.count == count { dontQuit = false callback(word, true, mainWordTiles) } } else if allTiles.count == count { dontQuit = false callback(word, true, mainWordTiles) } count += 1 } } } else if isSameColumn { (bool1,bool2,bool3) = checkIfThereIsPriorTileInSameColumn(row: smallestRow, column: smallestColumn) if bool1 == true { smallestRow -= 1 if bool2 == true { smallestRow -= 1 if bool3 == true { smallestRow -= 1 } } } var dontQuit = true while dontQuit { var count = 1 outerLoop: for tile in allTiles { if tile.row != nil && tile.myWhereInPlay == .board { if tile.row! == smallestRow && tile.column! == smallestColumn { word += tile.mySymbol.rawValue wordTiles.append(tile) smallestRow += 1 break outerLoop } else if allTiles.count == count { dontQuit = false callback(word, false, mainWordTiles) } } else if allTiles.count == count { dontQuit = false callback(word, false, tilesInPlay) } count += 1 } } } } private func checkIfThereIsPriorTileInSameRow(row: Int, column: Int) -> (Bool,Bool,Bool) { var one = false var two = false var three = false for tile in allTiles { if tile.column != nil { if tile.column! + 1 == column && tile.row! == row { one = true } if tile.column! + 2 == column && tile.row! == row { two = true } if tile.column! + 3 == column && tile.row! == row { three = true } } } return (one,two,three) } private func checkIfThereIsPriorTileInSameColumn(row: Int, column: Int) -> (Bool,Bool,Bool) { var one = false var two = false var three = false for tile in allTiles { if tile.row != nil { if tile.row! + 1 == row && tile.column! == column { one = true } if tile.row! + 2 == row && tile.column! == column { two = true } if tile.row! + 3 == row && tile.column! == column { three = true } } } return (one,two,three) } var isMainWordReal = false @objc private func playFunc(_ button: UIButton) { isMainWordReal = false let bonusTiles = ["Q","X","J","Z","W"] guard isFirstPlayFunc == true else {isFirstPlayFunc = true;return} isFirstPlayFunc = false for tile in allTiles { if tile.myWhereInPlay == .board { } } findTheString() { (word,isRowWord,mainWordTiles) -> Void in if let w = word { lengthOfWord = wordTiles.count var lettersList = [String]() var repeat1 = 1 var repeat2 = 1 var repeat1Letter = String() var repeat2Letter = String() duplicateLetterAmount = 0 duplicateLetterAmount2 = 0 for tile in wordTiles { if lettersList.contains(tile.mySymbol.rawValue) { if repeat1 == 1 { repeat1 += 1 repeat1Letter = tile.mySymbol.rawValue } else if repeat2 == 1 { repeat2 += 1 repeat2Letter = tile.mySymbol.rawValue } else if tile.mySymbol.rawValue == repeat1Letter { repeat1 += 1 } else if tile.mySymbol.rawValue == repeat2Letter { repeat2 += 1 } } else { lettersList.append(tile.mySymbol.rawValue) } } if repeat1 > 1 { duplicateLetter = repeat1Letter duplicateLetterAmount = repeat1 } if repeat2 > 1 { duplicateLetter2 = repeat2Letter duplicateLetterAmount2 = repeat2 } let everythingChecksOutPerpendicular = perpendicularWords(isRowWord: isRowWord, mainWordTiles: mainWordTiles) myBoard.zoomOut() { () -> Void in for tile in allTiles { dropTileWhereItBelongs(tile: tile) } refreshSizes() } guard isReal(word: w.lowercased()) != nil else { wordTiles.removeAll();return} if isReal(word: w.lowercased())! && everythingChecksOutPerpendicular { var isDetachedLetter = false for tile in tilesInPlay { if !wordTiles.contains(tile) { isDetachedLetter = true } } guard isDetachedLetter == false else { wordTiles.removeAll() let alert = UIAlertController(title: "Retry", message: "Can only spell one word at a time", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) return } var notAlreadyWonThisGame = false for i in 0..<wordTiles.count { wordTiles[i].isBuildable = true delay(bySeconds: 0.2*Double(i)+0.6) { if self.wordTiles[i].isStarterBlock { self.wordTiles[i].isStarterBlock = false notAlreadyWonThisGame = true self.wordTiles[i].topOfBlock.backgroundColor = self.myColor.teal self.wordTiles[i].text.textColor = .white } if bonusTiles.contains(self.wordTiles[i].mySymbol.rawValue) && !self.wordTiles[i].isLockedInPlace { self.bonusPile(character: self.wordTiles[i].mySymbol.rawValue) } self.wordTiles[i].isLockedInPlace = true if i == self.wordTiles.count - 1 { if self.lengthOfWord > 4 { self.longWordBonus(length: self.lengthOfWord) } self.lengthOfWord = 0 self.isMainWordReal = true self.wordTiles.removeAll() self.tilesInPlay.removeAll() self.wordTilesPerpendicular.removeAll() self.onTheBoard = 0 self.isFirstPlayFunc = true self.lockTilesAndRefillRack() if self.duplicateLetterAmount > 1 { self.multipleLetterBonus(letter: self.duplicateLetter, amount: self.duplicateLetterAmount) } self.delay(bySeconds: 0.3) { if self.duplicateLetterAmount2 > 1 { self.multipleLetterBonus(letter: self.duplicateLetter2, amount: self.duplicateLetterAmount2) } } self.duplicateLetterAmount = 0 self.duplicateLetterAmount2 = 0 self.isWin = true for tile in self.allTiles { if tile.isStarterBlock { self.isWin = false } } if self.isWin && notAlreadyWonThisGame { self.winSequence() } self.storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } } } } else { wordTiles.removeAll() wordAlert(word: w) } } else { wordTiles.removeAll() isFirstPlayFunc = true let alert = UIAlertController(title: "Retry", message: "Can only spell one word at a time", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } isFirstPlayFunc = true } private func boost() { for i in 0...14 { delay(bySeconds: 0.2*Double(i)+0.4) { self.bonusPile() if i == 14 { var container = [Int]() for tile2 in self.allTiles { if let order = tile2.atBatTileOrder { if tile2.myWhereInPlay == .atBat { container.append(order) } } } if container.count < 7 {self.refillMode = true} self.storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } } } } private func winSequence() { Set1.wins += 1 Set1.winState = true isWin = true for i in 0...10 { delay(bySeconds: 1.0*Double(i)) { for tile in self.allTiles { tile.topOfBlock.backgroundColor = UIColor(colorLiteralRed: Float(drand48()), green: Float(drand48()), blue: Float(drand48()), alpha: 1.0) tile.text.textColor = .black // win.textColor = UIColor(colorLiteralRed: Float(drand48()), green: Float(drand48()), blue: Float(drand48()), alpha: 1.0) } } } view.removeGestureRecognizer(tap) view.removeGestureRecognizer(pan2) view.removeGestureRecognizer(pan) view.removeGestureRecognizer(doubleTap) } private func alreadyWinSequence() { for i in 0...2 { delay(bySeconds: 1.0*Double(i)) { for tile in self.allTiles { tile.topOfBlock.backgroundColor = UIColor(colorLiteralRed: Float(drand48()), green: Float(drand48()), blue: Float(drand48()), alpha: 1.0) tile.text.textColor = UIColor(colorLiteralRed: Float(drand48()), green: Float(drand48()), blue: Float(drand48()), alpha: 1.0) // win.textColor = UIColor(colorLiteralRed: Float(drand48()), green: Float(drand48()), blue: Float(drand48()), alpha: 1.0) } } } view.removeGestureRecognizer(tap) view.removeGestureRecognizer(pan) view.removeGestureRecognizer(pan2) view.removeGestureRecognizer(doubleTap) } private func bonusPile(character: String? = nil) { pileOfTiles += 1 let bonus = UILabel(frame: CGRect(x: 22*sw/375, y: 625*sh/667, width: 50*sw/375, height: 16*sw/375)) bonus.font = UIFont(name: "ArialRoundedMTBold", size: 14*fontSizeMultiplier) bonus.textAlignment = .left if character != nil { bonus.text = "+1" + character! } else { bonus.text = "+1" } view.addSubview(bonus) UIView.animate(withDuration: 2.5) { bonus.frame.origin = CGPoint(x: 22*self.sw/375, y: 550*self.sh/667) bonus.font.withSize(20*self.fontSizeMultiplier) bonus.alpha = 0.0 } delay(bySeconds: 2.5) { bonus.removeFromSuperview() } } private func bonusBoost(text: String) { let bonus = UILabel(frame: CGRect(x: 290*sw/375, y: 22*sh/667, width: 50*sw/375, height: 16*sw/375)) bonus.font = UIFont(name: "ArialRoundedMTBold", size: 14*fontSizeMultiplier) bonus.textAlignment = .left bonus.text = text view.addSubview(bonus) UIView.animate(withDuration: 2.5) { bonus.frame.origin = CGPoint(x: 290*self.sw/375, y: 5*self.sh/667) bonus.font.withSize(20*self.fontSizeMultiplier) bonus.alpha = 0.0 } delay(bySeconds: 2.5) { bonus.removeFromSuperview() } } private func bonusOnDeck(x: CGFloat, y: CGFloat, text: String = "+1") { let bonus = UILabel(frame: CGRect(x: x, y: y, width: 50*sw/375, height: 16*sw/375)) bonus.font = UIFont(name: "ArialRoundedMTBold", size: 14*fontSizeMultiplier) bonus.text = text view.addSubview(bonus) UIView.animate(withDuration: 2.5) { bonus.frame.origin = CGPoint(x: x, y: y - 75*self.sh/667) bonus.font.withSize(20*self.fontSizeMultiplier) bonus.alpha = 0.0 } delay(bySeconds: 2.5) { bonus.removeFromSuperview() } } private func multipleLetterBonus(letter: String, amount: Int) { switch amount { case 2: if self.onDeckTiles.count < 10 { let tile = Tile() self.onDeckTiles.append(tile) tile.mySymbol = self.pickRandomLetter() tile.onDeckTileOrder = self.onDeckTiles.count - 1 tile.myWhereInPlay = .onDeck tile.topOfBlock.backgroundColor = self.myColor.purple tile.text.textColor = .black self.view.addSubview(tile) self.allTiles.append(tile) for tile1 in self.onDeckTiles { self.dropTileWhereItBelongs(tile: tile1) if tile == tile1 { self.bonusOnDeck(x: tile.frame.origin.x, y: tile.frame.origin.y, text: String(amount) + " " + letter + "'s") } } } else { self.bonusPile() } case 3,4,5,6,7: for i in 0..<2 { delay(bySeconds: 0.2*Double(i)+0.4) { if self.onDeckTiles.count < 10 { let tile = Tile() self.onDeckTiles.append(tile) tile.mySymbol = self.pickRandomLetter() tile.onDeckTileOrder = self.onDeckTiles.count - 1 tile.myWhereInPlay = .onDeck tile.topOfBlock.backgroundColor = self.myColor.teal tile.text.textColor = .black self.view.addSubview(tile) self.allTiles.append(tile) for tile1 in self.onDeckTiles { self.dropTileWhereItBelongs(tile: tile1) if tile == tile1 { self.bonusOnDeck(x: tile.frame.origin.x, y: tile.frame.origin.y, text: String(amount) + " " + letter + "'s") } } } else { self.bonusPile() } } } default: break } } private func numberOfTilesInPlay() -> Int { var count = 0 for tile in allTiles { if tile.myWhereInPlay == .board && !tile.isLockedInPlace { count += 1 } } return count } private func longWordBonus(length: Int) { var pileBonus = 0 var flippedBonus = 0 switch length { case 5: pileBonus = 3 flippedBonus = 0 case 6: pileBonus = 4 flippedBonus = 1 case 7: pileBonus = 5 flippedBonus = 2 case 8: pileBonus = 5 flippedBonus = 2 amountOfBoosts += 1 bonusBoost(text: "+1") case 9: pileBonus = 5 flippedBonus = 2 amountOfBoosts += 1 bonusBoost(text: "+1") case 10,11,12,13,14,15: pileBonus = 6 flippedBonus = 2 amountOfBoosts += 1 bonusBoost(text: "+1") default: break } for i in 0..<pileBonus { delay(bySeconds: 0.2*Double(i)+0.4) { self.bonusPile() } } for i in 0..<flippedBonus { delay(bySeconds: 0.2*Double(i)+0.4) { if self.onDeckTiles.count < 10 { let tile = Tile() self.onDeckTiles.append(tile) tile.mySymbol = self.pickRandomLetter() tile.onDeckTileOrder = self.onDeckTiles.count - 1 tile.myWhereInPlay = .onDeck tile.topOfBlock.backgroundColor = self.myColor.purple tile.text.textColor = .black self.view.addSubview(tile) self.allTiles.append(tile) for tile1 in self.onDeckTiles { self.dropTileWhereItBelongs(tile: tile1) if tile == tile1 { self.bonusOnDeck(x: tile.frame.origin.x, y: tile.frame.origin.y) } } } else { self.bonusPile() } } } } private func wordAlert(word: String) { wordTiles.removeAll() wordTilesPerpendicular.removeAll() isFirstPlayFunc = true let alert = UIAlertController(title: word.uppercased(), message: "Not a word", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } var length = 1 private func perpendicularWords(isRowWord: Bool, mainWordTiles: [Tile]) -> Bool { var everythingChecksOut = true var indexesOfWords = [Int]() var smallestRow = 16 var smallestColumn = 16 switch isRowWord { case true: for tile in mainWordTiles { if tile.slotsIndex! - 1 > -1 { if myBoard.slots[tile.slotsIndex! - 1].isOccupied { indexesOfWords.append(tile.slotsIndex!) } } if tile.slotsIndex! + 1 < 225 { if myBoard.slots[tile.slotsIndex! + 1].isOccupied{ indexesOfWords.append(tile.slotsIndex!) } } } for index in indexesOfWords { smallestRow = myBoard.slots[index].row smallestColumn = myBoard.slots[index].column var isKeepGoing = true while isKeepGoing { isKeepGoing = false loop: for tile in allTiles { if tile.myWhereInPlay == .board && myBoard.slots[index].column == tile.column! && tile.row! + 1 == smallestRow { smallestRow = tile.row! isKeepGoing = true break loop } } } var word = String() var dontQuit = true var perpedicularWordHasNewLetter = false var isAtLeastOneNewTile = false while dontQuit { var count = 1 outerLoop: for tile in allTiles { if tile.column != nil && tile.myWhereInPlay == .board { if tile.column! == smallestColumn && tile.row! == smallestRow { if !tile.isBuildable { perpedicularWordHasNewLetter = true } if mainWordTiles.contains(tile) { isAtLeastOneNewTile = true } word += tile.mySymbol.rawValue wordTilesPerpendicular.append(tile) smallestRow += 1 break outerLoop } else if allTiles.count == count { dontQuit = false if !isReal2(word: word.lowercased()){ everythingChecksOut = false wordAlert(word: word) } else { length = word.characters.count if perpedicularWordHasNewLetter && word.characters.count > 4 && isAtLeastOneNewTile { self.myTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(GameViewController.rowPerpendicularLongWordBonus), userInfo: nil, repeats: false) } } } } else if allTiles.count == count { dontQuit = false if !isReal2(word: word.lowercased()) { everythingChecksOut = false wordAlert(word: word) } else { if perpedicularWordHasNewLetter && word.characters.count > 4 && isAtLeastOneNewTile { length = word.characters.count if perpedicularWordHasNewLetter && word.characters.count > 4 && isAtLeastOneNewTile { self.myTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(GameViewController.rowPerpendicularLongWordBonus), userInfo: nil, repeats: false) } } } } count += 1 } } } case false: for tile in mainWordTiles { if tile.slotsIndex! - 15 > -1 { if myBoard.slots[tile.slotsIndex! - 15].isOccupied { indexesOfWords.append(tile.slotsIndex!) } } if tile.slotsIndex! + 15 < 225 { if myBoard.slots[tile.slotsIndex! + 15].isOccupied { indexesOfWords.append(tile.slotsIndex!) } } } for index in indexesOfWords { smallestRow = myBoard.slots[index].row smallestColumn = myBoard.slots[index].column var isKeepGoing = true while isKeepGoing { isKeepGoing = false loop: for tile in allTiles { if tile.myWhereInPlay == .board && myBoard.slots[index].row == tile.row! && tile.column! + 1 == smallestColumn { smallestColumn = tile.column! isKeepGoing = true break loop } } } var dontQuit = true var word = String() var perpedicularWordHasNewLetter = false while dontQuit { var count = 1 outerLoop: for tile in allTiles { if tile.row != nil && tile.myWhereInPlay == .board { if tile.row! == smallestRow && tile.column! == smallestColumn { if !tile.isBuildable { perpedicularWordHasNewLetter = true } word += tile.mySymbol.rawValue wordTilesPerpendicular.append(tile) smallestColumn += 1 break outerLoop } else if allTiles.count == count { dontQuit = false if !isReal2(word: word.lowercased()) { everythingChecksOut = false wordAlert(word: word) } else { length = word.characters.count if perpedicularWordHasNewLetter && word.characters.count > 4 { self.myTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(GameViewController.columnPerpendicularLongWordBonus), userInfo: nil, repeats: false) } } } } else if allTiles.count == count { dontQuit = false if !isReal2(word: word.lowercased()) { everythingChecksOut = false wordAlert(word: word) } else { length = word.characters.count if perpedicularWordHasNewLetter && word.characters.count > 4 { self.myTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(GameViewController.columnPerpendicularLongWordBonus), userInfo: nil, repeats: false) } } } count += 1 } } } } return everythingChecksOut } @objc private func rowPerpendicularLongWordBonus() { if self.isMainWordReal || self.numberOfTilesInPlay() == 1 { self.longWordBonus(length: length) } } @objc private func columnPerpendicularLongWordBonus() { if self.isMainWordReal { self.longWordBonus(length: length) } } private func rearrangeAtBat() { var container = [Int]() var taken = [Int]() for tile in allTiles { if tile.myWhereInPlay == .atBat { container.append(tile.atBatTileOrder!) } } for tile in allTiles { if tile.myWhereInPlay == .atBat { if taken.contains(tile.atBatTileOrder!) { for i in 0...6 { if !container.contains(i) { tile.atBatTileOrder = i container.append(tile.atBatTileOrder!) dropTileWhereItBelongs(tile: tile) } } } taken.append(tile.atBatTileOrder!) } } } private func lockTilesAndRefillRack() { if !(pileOfTiles == 0 && onDeckTiles.count == 0) { refillMode = true } } func isReal(word: String) -> Bool? { var isWordBuildable = false for tile in allTiles { if tile.isBuildable { for tile2 in tilesInPlay { let test1: Bool = tile2.row! - 1 == tile.row! && tile2.column! == tile.column! let test2: Bool = tile2.row! + 1 == tile.row! && tile2.column! == tile.column! let test3: Bool = tile2.column! - 1 == tile.column! && tile2.row! == tile.row! let test4: Bool = tile2.column! + 1 == tile.column! && tile2.row! == tile.row! if test1 || test2 || test3 || test4 { isWordBuildable = true } } } } guard isWordBuildable == true else { isFirstPlayFunc = true let alert = UIAlertController(title: word.uppercased(), message: "Must build off teal tiles", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) return nil } let checker = UITextChecker() let range = NSMakeRange(0, word.characters.count) let wordRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en") if word == "fe" || word == "ki" || word == "oi" || word == "qi" || word == "za" || word == "qis" || word == "zas" || word == "fes" || word == "kis" { return true } if wordRange.location == NSNotFound { for tile in wordTilesPerpendicular { if !wordTiles.contains(tile) { wordTiles.append(tile) } } } return wordRange.location == NSNotFound } func isReal2(word: String) -> Bool { let checker = UITextChecker() let range = NSRange(location: 0, length: word.utf16.count) let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en") if word == "fe" || word == "ki" || word == "oi" || word == "qi" || word == "za" || word == "qis" || word == "zas" || word == "fes" || word == "kis" { return true } return misspelledRange.location == NSNotFound } private func reOrderAtBat() { var here = [Int]() for tile in allTiles { if tile.myWhereInPlay == .atBat && tile != movingTile { if here.contains(tile.atBatTileOrder!) { tile.atBatTileOrder! += 1 if tile.atBatTileOrder == 7 { tile.atBatTileOrder = 0 } } here.append(tile.atBatTileOrder!) dropTileWhereItBelongs(tile: tile) } } } func addTilesToBoard() { if isFirstLoading || startingNewGame { for i in 0...4 { let tile = Tile() tile.mySymbol = pickRandomLetter() tile.onDeckTileOrder = i tile.myWhereInPlay = .onDeck tile.alpha = onDeckAlpha view.addSubview(tile) allTiles.append(tile) onDeckTiles.append(tile) } for tile in onDeckTiles { dropTileWhereItBelongs(tile: tile) } for i in 0...6 { let tile = Tile() tile.mySymbol = pickRandomLetter() tile.atBatTileOrder = i tile.myWhereInPlay = .atBat view.addSubview(tile) allTiles.append(tile) dropTileWhereItBelongs(tile: tile) } } else { for i in 0..<Set1.onDeckRawValue.count { let tile = Tile() tile.mySymbol = whatsMySymbol(character: Set1.onDeckRawValue[i]) tile.onDeckTileOrder = i tile.myWhereInPlay = .onDeck tile.alpha = onDeckAlpha view.addSubview(tile) allTiles.append(tile) onDeckTiles.append(tile) } for tile in onDeckTiles { dropTileWhereItBelongs(tile: tile) } for i in 0..<Set1.atBatRawValue.count { let tile = Tile() tile.mySymbol = whatsMySymbol(character: Set1.atBatRawValue[i]) tile.myWhereInPlay = .atBat tile.atBatTileOrder = i view.addSubview(tile) allTiles.append(tile) dropTileWhereItBelongs(tile: tile) } if Set1.atBatRawValue.count < 7 { if !(pileOfTiles == 0 && onDeckTiles.count == 0) { refillMode = true } } } } enum Difficulty { case easy,medium,hard } func whileFunction(rowLow: Int, rowHigh: Int, randomStartSlotIndex: Int, randomEndSlotIndex: Int, callback: (Int) -> Void) { var oneIndex = 500 var oneIndexRow = -1 while oneIndexRow < rowLow || oneIndexRow > rowHigh || oneIndex == randomStartSlotIndex || oneIndex == randomEndSlotIndex || oneIndex == randomStartSlotIndex + 1 || oneIndex == randomStartSlotIndex - 1 || oneIndex == randomStartSlotIndex + 15 || oneIndex == randomEndSlotIndex - 1 || oneIndex == randomEndSlotIndex + 1 || oneIndex == randomEndSlotIndex - 15 { oneIndex = Int(arc4random_uniform(224)) oneIndexRow = myBoard.slots[oneIndex].row } callback(oneIndex) // call the callback function } private func startGameWithTilesOnBoard(difficulty: Difficulty) { if isFirstLoading || startingNewGame { let randomStartSlotIndex = Int(arc4random_uniform(14)) let randomEndSlotIndex = Int(arc4random_uniform(14) + 210) for i in 0...1 { let tile = Tile() tile.mySymbol = pickRandomLetter() tile.myWhereInPlay = .board if i == 1 { tile.isStarterBlock = true } else { tile.isBuildable = true } if i == 0 { let slot = myBoard.slots[randomStartSlotIndex] tile.slotsIndex = randomStartSlotIndex slot.isOccupied = true slot.isPermanentlyOccupied = true slot.isOccupiedFromStart = true tile.row = slot.row tile.column = slot.column } else { let slot = myBoard.slots[randomEndSlotIndex] tile.slotsIndex = randomEndSlotIndex slot.isOccupied = true slot.isPermanentlyOccupied = true slot.isOccupiedFromStart = true tile.row = slot.row tile.column = slot.column } tile.isLockedInPlace = true view.addSubview(tile) allTiles.append(tile) dropTileWhereItBelongs(tile: tile) } switch difficulty { case .easy: break case .medium: let rowStart = myBoard.slots[randomStartSlotIndex].row let rowEnd = myBoard.slots[randomEndSlotIndex].row var rowLow = Int() var rowHigh = Int() // var oneIndexRow = 20 // var oneIndex = -1 if rowEnd > rowStart { rowHigh = rowEnd; rowLow = rowStart } else { rowHigh = rowStart; rowLow = rowEnd } whileFunction(rowLow: rowLow, rowHigh: rowHigh, randomStartSlotIndex: randomStartSlotIndex, randomEndSlotIndex: randomEndSlotIndex) { (oneIndex) -> Void in let tile = Tile() tile.isStarterBlock = true tile.mySymbol = pickRandomLetter() tile.myWhereInPlay = .board tile.isLockedInPlace = true let slot = myBoard.slots[oneIndex] tile.slotsIndex = oneIndex slot.isOccupied = true slot.isPermanentlyOccupied = true slot.isOccupiedFromStart = true tile.row = slot.row tile.column = slot.column view.addSubview(tile) allTiles.append(tile) dropTileWhereItBelongs(tile: tile) } case .hard: for _ in 0...4 { whileFunction(rowLow: 2, rowHigh: 13, randomStartSlotIndex: randomStartSlotIndex, randomEndSlotIndex: randomEndSlotIndex) { (oneIndex) -> Void in var _oneIndex = oneIndex if oneIndex - 15 < 0 {_oneIndex += 15} if oneIndex + 15 > 224 {_oneIndex -= 15} if !myBoard.slots[_oneIndex - 1].isOccupied && !myBoard.slots[_oneIndex + 1].isOccupied && !myBoard.slots[_oneIndex - 15].isOccupied && !myBoard.slots[_oneIndex + 15].isOccupied && !myBoard.slots[_oneIndex].isOccupied { let tile = Tile() tile.isStarterBlock = true tile.mySymbol = pickRandomLetter() tile.myWhereInPlay = .board tile.isLockedInPlace = true let slot = myBoard.slots[_oneIndex] tile.slotsIndex = _oneIndex slot.isOccupied = true slot.isPermanentlyOccupied = true slot.isOccupiedFromStart = true tile.row = slot.row tile.column = slot.column view.addSubview(tile) dropTileWhereItBelongs(tile: tile) allTiles.append(tile) } } } } } else { for i in 0..<Set1.indexBuildable.count { let tile = Tile() tile.mySymbol = whatsMySymbol(character: Set1.buildableRawValue[i]) tile.myWhereInPlay = .board tile.isLockedInPlace = true tile.isBuildable = true let slot = myBoard.slots[Set1.indexBuildable[i]] tile.slotsIndex = Set1.indexBuildable[i] slot.isOccupied = true slot.isPermanentlyOccupied = true tile.row = slot.row tile.column = slot.column view.addSubview(tile) dropTileWhereItBelongs(tile: tile) allTiles.append(tile) } for i in 0..<Set1.indexStart.count { let tile = Tile() tile.isStarterBlock = true tile.mySymbol = whatsMySymbol(character: Set1.startRawValue[i]) tile.myWhereInPlay = .board let slot = myBoard.slots[Set1.indexStart[i]] tile.slotsIndex = Set1.indexStart[i] tile.isLockedInPlace = true tile.topOfBlock.backgroundColor = myColor.purple tile.text.textColor = .black slot.isOccupied = true slot.isPermanentlyOccupied = true tile.row = slot.row tile.column = slot.column view.addSubview(tile) dropTileWhereItBelongs(tile: tile) allTiles.append(tile) } pileOfTiles = Set1.pileAmount var container = [Int]() for tile2 in allTiles { if let order = tile2.atBatTileOrder { if tile2.myWhereInPlay == .atBat { container.append(order) } } } if container.count < 7 && (onDeckTiles.count != 0 || pileOfTiles != 0) {refillMode = true} } storeWholeState() } var once = true @objc private func tapTile(_ gesture: UITapGestureRecognizer) { once = true switch refillMode { case false: for tile in allTiles { if !myBoard.frame.contains(gesture.location(in: view)) && once { once = false if tile.frame.contains(gesture.location(in: view)) && !tile.isLockedInPlace && tile.myWhereInPlay == .atBat { movingTile = tile } } else { if tile.frame.contains(gesture.location(in: myBoard)) && !tile.isLockedInPlace && tile.myWhereInPlay == .board && once { once = false tile.removeFromSuperview() tile.alpha = 0.0 onTheBoard -= 1 tile.atBatTileOrder = 1 view.addSubview(tile) tile.myWhereInPlay = .atBat dropTileWhereItBelongs(tile: tile) rearrangeAtBat() delay(bySeconds: 0.3) { tile.alpha = 1.0 } } } } case true: for tile in allTiles { if !myBoard.frame.contains(gesture.location(in: view)){ if tile.frame.contains(gesture.location(in: view)) && tile == pile && once { guard pileOfTiles > 0 else {return} once = false pileOfTiles -= 1 let newTile = Tile() newTile.mySymbol = pickRandomLetter() allTiles.append(newTile) newTile.myWhereInPlay = .atBat newTile.mySize = .large newTile.atBatTileOrder = seatWarmerFunc() view.addSubview(newTile) dropTileWhereItBelongs(tile: newTile) storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } else if tile.frame.contains(gesture.location(in: view)) && tile.myWhereInPlay == .onDeck && once { once = false tile.atBatTileOrder = seatWarmerFunc() tile.myWhereInPlay = .atBat tile.mySize = .large tile.topOfBlock.backgroundColor = myColor.purple tile.text.textColor = .black dropTileWhereItBelongs(tile: tile) // Set1.atBatRawValue.append(tile.mySymbol.rawValue) onDeckTiles.removeAll() for tile in allTiles { if tile.myWhereInPlay == .onDeck { onDeckTiles.append(tile) } } rearrangeOnDeck(gone: tile.onDeckTileOrder!) } else { delay(bySeconds: 0.1) { self.once = true } } //maybe fixes the color problem??? var tileCount = 0 for tile in allTiles { if tile.myWhereInPlay == .onDeck { tile.topOfBlock.backgroundColor = myColor.purple tile.text.textColor = .black tileCount += 1 if tileCount == allTiles.count { once = true } } } } } storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } if banner.frame.contains(gesture.location(in: view)) { bannerFunc() } } private func seatWarmerFunc() -> Int { var container = [Int]() var seatWarmer = Int() for tile2 in allTiles { if let order = tile2.atBatTileOrder { if tile2.myWhereInPlay == .atBat { container.append(order) } } } if self.pileOfTiles == 0 && self.onDeckTiles.count == 0 {refillMode = false} if container.count + onTheBoard >= 6 {refillMode = false} o: for i in 0...6 { if !container.contains(i) { seatWarmer = i break o } } return seatWarmer } private func rearrangeOnDeck(gone: Int) { for tile in allTiles { if tile.myWhereInPlay == .onDeck { if tile.onDeckTileOrder! > gone { tile.onDeckTileOrder? -= 1 } dropTileWhereItBelongs(tile: tile) } } } @objc private func doubleTapFunc(_ gesture: UITapGestureRecognizer) { if Set1.isZoomed == false && myBoard.frame.contains(gesture.location(in: view)) { myBoard.zoomIn() { () -> Void in myBoard.contentOffset.x = gesture.location(in: myBoard).x*(myBoard.scale) - myBoard.frame.width/2 if myBoard.contentOffset.x < 0 { myBoard.contentOffset.x = 0 } if myBoard.contentOffset.x > myBoard.frame.width*(myBoard.scale - 1) { myBoard.contentOffset.x = myBoard.frame.width*(myBoard.scale - 1) } myBoard.contentOffset.y = gesture.location(in: myBoard).y*(myBoard.scale) - myBoard.frame.height/2 if myBoard.contentOffset.y < 0 { myBoard.contentOffset.y = 0 } if myBoard.contentOffset.y > myBoard.frame.height*(myBoard.scale - 1) { myBoard.contentOffset.y = myBoard.frame.height*(myBoard.scale - 1) } } } else if myBoard.frame.contains(gesture.location(in: view)) { myBoard.zoomOut(){() -> Void in} } for tile in allTiles { dropTileWhereItBelongs(tile: tile) } refreshSizes() } var iWantToScrollMyBoard = true @objc private func moveTile2(_ gesture: UIPanGestureRecognizer) { switch gesture.state { case .began: once = true for tile in allTiles { if tile.frame.contains(gesture.location(in: view)) && (tile.myWhereInPlay == .atBat) { let alert = UIAlertController(title: "", message: "Your rack of letters is no longer full. Fill it with the tiles on the bottom", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } if tile.frame.contains(gesture.location(in: view)) && (tile.myWhereInPlay == .onDeck || tile == pile) { if tile.frame.contains(gesture.location(in: view)) && tile == pile && once { guard pileOfTiles > 0 else {return} once = false pileOfTiles -= 1 let newTile = Tile() newTile.mySymbol = pickRandomLetter() allTiles.append(newTile) newTile.myWhereInPlay = .atBat newTile.mySize = .large newTile.atBatTileOrder = seatWarmerFunc() view.addSubview(newTile) dropTileWhereItBelongs(tile: newTile) storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } else if tile.frame.contains(gesture.location(in: view)) && tile.myWhereInPlay == .onDeck && once { once = false tile.atBatTileOrder = seatWarmerFunc() tile.myWhereInPlay = .atBat tile.mySize = .large tile.topOfBlock.backgroundColor = myColor.purple tile.text.textColor = .black dropTileWhereItBelongs(tile: tile) // Set1.atBatRawValue.append(tile.mySymbol.rawValue) onDeckTiles.removeAll() for tile in allTiles { if tile.myWhereInPlay == .onDeck { onDeckTiles.append(tile) } } rearrangeOnDeck(gone: tile.onDeckTileOrder!) } else { delay(bySeconds: 0.1) { self.once = true } } //maybe fixes the color problem??? var tileCount = 0 for tile in allTiles { if tile.myWhereInPlay == .onDeck { tile.topOfBlock.backgroundColor = myColor.purple tile.text.textColor = .black tileCount += 1 if tileCount == allTiles.count { once = true } } } } } default: break } } @objc private func moveTile(_ gesture: UIPanGestureRecognizer) { switch gesture.state { case .began: outer: for tile in allTiles { if !myBoard.frame.contains(gesture.location(in: view)) { iWantToScrollMyBoard = false if tile.frame.contains(gesture.location(in: view)) && !tile.isLockedInPlace && tile.myWhereInPlay == .atBat { movingTile = tile movingTile?.layer.zPosition = 10 movingTile?.mySize = .large //isNotSameTile = true if movingTile?.slotsIndex != nil { myBoard.slots[(movingTile?.slotsIndex!)!].isOccupied = false } } //break outer } else { if tile.frame.contains(gesture.location(in: myBoard)) && tile.isLockedInPlace { guard tile.topOfBlock.backgroundColor == myColor.purple else {return} let alert = UIAlertController(title: "", message: "This tile does not move, use tiles below to build a word off a teal tile.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } if tile.frame.contains(gesture.location(in: myBoard)) && !tile.isLockedInPlace && tile.myWhereInPlay == .board { iWantToScrollMyBoard = false movingTile = tile movingTile?.mySize = .large //isNotSameTile = true if movingTile?.slotsIndex != nil { myBoard.slots[(movingTile?.slotsIndex!)!].isOccupied = false } // break outer } } } case .changed: if iWantToScrollMyBoard && Set1.isZoomed { let translation = gesture.translation(in: view) if myBoard.contentOffset.x - translation.x > 0 && myBoard.contentOffset.x - translation.x < myBoard.frame.width*(myBoard.scale - 1) { myBoard.contentOffset.x -= translation.x } if myBoard.contentOffset.y - translation.y > 0 && myBoard.contentOffset.y - translation.y < myBoard.frame.width*(myBoard.scale - 1) { myBoard.contentOffset.y -= translation.y } gesture.setTranslation(CGPoint(x:0,y:0), in: self.view) if myBoard.contentOffset.x < 0 { myBoard.contentOffset.x = 0 } if myBoard.contentOffset.y < 0 { myBoard.contentOffset.y = 0 } } if movingTile != nil { let translation = gesture.translation(in: view) movingTile?.center = CGPoint(x: (movingTile?.center.x)! + translation.x, y: (movingTile?.center.y)! + translation.y) gesture.setTranslation(CGPoint(x:0,y:0), in: self.view) // moving in and out of board frame if myBoard.frame.contains(CGPoint(x: movingTile!.frame.origin.x + movingTile!.frame.width/2, y: movingTile!.frame.maxY)) && !movingTile!.isDescendant(of: myBoard) { movingTile!.removeFromSuperview() onTheBoard += 1 movingTile!.frame.origin.y -= myBoard.frame.origin.y - myBoard.contentOffset.y movingTile!.frame.origin.x += myBoard.contentOffset.x - myBoard.frame.origin.x myBoard.addSubview(movingTile!) } else if !myBoard.bounds.contains(CGPoint(x: movingTile!.frame.origin.x + movingTile!.frame.width/2, y: movingTile!.frame.maxY)) && movingTile!.isDescendant(of: myBoard) { movingTile!.removeFromSuperview() onTheBoard -= 1 movingTile!.frame.origin.y += myBoard.frame.origin.y - myBoard.contentOffset.y movingTile!.frame.origin.x -= myBoard.contentOffset.x - myBoard.frame.origin.x movingTile?.atBatTileOrder = nil view.addSubview(movingTile!) movingTile?.myWhereInPlay = .atBat } // enable swapping of atBat tiles if !movingTile!.isDescendant(of: myBoard) { for tile in allTiles { if tile.myWhereInPlay == .atBat && tile != movingTile { guard movingTile?.atBatTileOrder != nil else {movingTile?.atBatTileOrder = seatWarmerFunc(); reOrderAtBat(); return} if tile.center.x > (movingTile?.center.x)! && (movingTile?.atBatTileOrder!)! > tile.atBatTileOrder! { movingTile!.atBatTileOrder = tile.atBatTileOrder tile.atBatTileOrder! += 1 } else if tile.center.x < (movingTile?.center.x)! && (movingTile?.atBatTileOrder!)! < tile.atBatTileOrder! { movingTile!.atBatTileOrder = tile.atBatTileOrder tile.atBatTileOrder! -= 1 } let order = tile.atBatTileOrder! let x = 13*self.sw/375 + CGFloat(order)*50*self.sw/375 let y = 13*self.sh/667 + myBoard.frame.maxY UIView.animate(withDuration: 0.3) { tile.frame.origin = CGPoint(x: x, y: y) } } } } reOrderAtBat() } case .ended: iWantToScrollMyBoard = true if trash.frame.contains(gesture.location(in: view)) && movingTile != nil { if playButton.isDescendant(of: view) { } UIView.animate(withDuration: 0.1) { self.movingTile?.frame.origin = CGPoint(x: 345*self.sw/375, y: 620*self.sh/667) self.movingTile?.topOfBlock.frame.size = CGSize(width: 0, height: 0) self.movingTile?.shadowOfBlock.frame.size = CGSize(width: 0, height: 0) self.movingTile?.text.frame.size = CGSize(width: 0, height: 0) } delay(bySeconds: 0.3) { self.movingTile?.removeFromSuperview() self.movingTile?.myWhereInPlay = .trash self.movingTile?.atBatTileOrder = nil if !(self.pileOfTiles == 0 && self.onDeckTiles.count == 0) { self.refillMode = true } self.movingTile = nil self.movingTile?.layer.zPosition = 0 self.rearrangeAtBat() } } else if movingTile != nil { var ct = 0 outer: for slotView in myBoard.slots { var largerFrame = CGRect() if !Set1.isZoomed { largerFrame = CGRect(x: slotView.frame.origin.x - 1, y: slotView.frame.origin.y - 1, width: slotView.frame.width + 1, height: slotView.frame.height + 1) } else { largerFrame = CGRect(x: slotView.frame.origin.x - 2.5, y: slotView.frame.origin.y - 2.5, width: slotView.frame.width + 2.5, height: slotView.frame.height + 2.5) } if largerFrame.contains(gesture.location(in: myBoard)) && !slotView.isOccupied && myBoard.frame.contains(gesture.location(in: view)) { guard slotView.isOccupied == false else {movingTile?.myWhereInPlay = .atBat; movingTile?.atBatTileOrder = seatWarmerFunc(); onTheBoard -= 1;movingTile?.removeFromSuperview(); view.addSubview(movingTile!); dropTileWhereItBelongs(tile: movingTile!); return} slotView.isOccupied = true movingTile?.slotsIndex = ct movingTile?.myWhereInPlay = .board movingTile?.atBatTileOrder = nil // moveButton() movingTile?.row = slotView.row movingTile?.column = slotView.column if Set1.isZoomed == false { myBoard.zoomIn() { () -> Void in // moveButton() myBoard.contentOffset.x = slotView.frame.origin.x - myBoard.bounds.width/2 + slotView.frame.width/2 if myBoard.contentOffset.x < 0 { myBoard.contentOffset.x = 0 } myBoard.contentOffset.y = slotView.frame.origin.y - myBoard.bounds.height/2 + slotView.frame.width/2 if myBoard.contentOffset.y < 0 { myBoard.contentOffset.y = 0 } if myBoard.contentOffset.x > myBoard.frame.width*(myBoard.scale - 1) { myBoard.contentOffset.x = myBoard.frame.width*(myBoard.scale - 1) } if myBoard.contentOffset.y > myBoard.frame.height*(myBoard.scale - 1) { myBoard.contentOffset.y = myBoard.frame.height*(myBoard.scale - 1) } } } if (movingTile?.isDescendant(of: myBoard))! { movingTile?.atBatTileOrder = seatWarmerFunc() } for tile in allTiles { dropTileWhereItBelongs(tile: tile) } refreshSizes() movingTile?.layer.zPosition = 0 movingTile = nil break outer } ct += 1 if ct == 225 { //make it belong back in atBat movingTile?.removeFromSuperview(); view.addSubview(movingTile!); dropTileWhereItBelongs(tile: movingTile!)} } movingTile?.layer.zPosition = 0 movingTile = nil rearrangeAtBat() } default: break } } func dropTileWhereItBelongs(tile: Tile) { switch tile.myWhereInPlay { case .board: tile.removeFromSuperview() myBoard.addSubview(tile) let row = tile.row! let column = tile.column! var x = 0.5*sw/375 + CGFloat(column)*23*sw/375 var y = 0.5*sw/375 + CGFloat(row)*23*sw/375 if Set1.isZoomed { let scale = myBoard.scale x = scale*(0.5*sw/375 + CGFloat(column)*23*sw/375) y = scale*(0.5*sw/375 + CGFloat(row)*23*sw/375) } tile.frame.origin = CGPoint(x: x, y: y) tile.shadowOfBlock.alpha = 0.0 tile.topOfBlock.layer.borderColor = UIColor.clear.cgColor case .atBat: guard let order = tile.atBatTileOrder else {tile.atBatTileOrder = 1; rearrangeAtBat(); return} let x = 15*self.sw/375 + CGFloat(order)*49.7*self.sw/375 let y = 29*self.sh/667 + myBoard.frame.maxY UIView.animate(withDuration: 0.3) { tile.frame.origin = CGPoint(x: x, y: y) } tile.shadowOfBlock.alpha = 0.0 tile.topOfBlock.layer.borderColor = UIColor.black.cgColor case .pile: tile.shadowOfBlock.alpha = 1.0 tile.topOfBlock.layer.borderColor = UIColor.black.cgColor case .trash: break case .onDeck: let amount = onDeckTiles.count let order = tile.onDeckTileOrder! var x: CGFloat = 0 var y: CGFloat = 0 switch amount { case 1: y = 616 x = 170.5 case 2: y = 616 switch order { case 0: x = 150 case 1: x = 191 default: break } case 3: y = 616 switch order { case 0: x = 129.5 case 1: x = 170.5 case 2: x = 211.5 default: break } case 4: y = 616 switch order { case 0: x = 109 case 1: x = 150 case 2: x = 191 case 3: x = 232 default: break } case 5: y = 616 switch order { case 0: x = 88.5 case 1: x = 129.5 case 2: x = 170.5 case 3: x = 211.5 case 4: x = 252.5 default: break } case 6...14: y = 616 switch order { case 0: x = 88.5 case 1: x = 129.5 case 2: x = 170.5 case 3: x = 211.5 case 4: x = 252.5 default: break } default: break } switch amount { case 6: switch order { case 5: y = 575 x = 170.5 default: break } case 7: switch order { case 5: y = 575 x = 150 case 6: y = 575 x = 191 default: break } case 8: switch order { case 5: y = 575 x = 129.5 case 6: y = 575 x = 170.5 case 7: y = 575 x = 211.5 default: break } case 9: switch order { case 5: y = 575 x = 109 case 6: y = 575 x = 150 case 7: y = 575 x = 191 case 8: y = 575 x = 232 default: break } case 10...14: switch order { case 5: y = 575 x = 88.5 case 6: y = 575 x = 129.5 case 7: y = 575 x = 170.5 case 8: y = 575 x = 211.5 case 9: y = 575 x = 252.5 default: break } default: break } switch amount { case 11: switch order { case 10: y = 534 x = 170.5 default: break } case 12: switch order { case 10: y = 534 x = 150 case 11: y = 534 x = 191 default: break } case 13: switch order { case 10: y = 534 x = 129.5 case 11: y = 534 x = 170.5 case 12: y = 534 x = 211.5 default: break } case 14: switch order { case 10: y = 534 x = 109 case 11: y = 534 x = 150 case 12: y = 534 x = 191 case 13: y = 534 x = 232 default: break } case 15: switch order { case 10: y = 534 x = 88.5 case 11: y = 534 x = 129.5 case 12: y = 534 x = 170.5 case 13: y = 534 x = 211.5 case 14: y = 534 x = 252.5 default: break } tile.shadowOfBlock.alpha = 1.0 tile.topOfBlock.layer.borderColor = UIColor.black.cgColor default: break } tile.frame.origin = CGPoint(x: x*self.sw/375, y: y*self.sh/667) } } private func pickRandomLetter() -> Tile.symbol { let random = arc4random_uniform(98) let myTile = Tile() switch random { case 0...11: myTile.mySymbol = .e case 12...20: myTile.mySymbol = .a case 21...29: myTile.mySymbol = .i case 30...37: myTile.mySymbol = .o case 38...43: myTile.mySymbol = .n case 44...49: myTile.mySymbol = .r case 50...55: myTile.mySymbol = .t case 56...59: myTile.mySymbol = .l case 60...63: myTile.mySymbol = .s case 64...67: myTile.mySymbol = .u case 68...71: myTile.mySymbol = .d case 72...74: myTile.mySymbol = .g case 75,76: myTile.mySymbol = .b; case 77,78: myTile.mySymbol = .c; case 79,80: myTile.mySymbol = .f; case 81,82: myTile.mySymbol = .h; case 83: myTile.mySymbol = .j; case 84: myTile.mySymbol = .k; case 85,86: myTile.mySymbol = .m; case 87,88: myTile.mySymbol = .p; case 89: myTile.mySymbol = .q; case 90,91: myTile.mySymbol = .v; case 92,93: myTile.mySymbol = .w; case 94: myTile.mySymbol = .x; case 95,96: myTile.mySymbol = .y; case 97: myTile.mySymbol = .z default: break } return myTile.mySymbol } func refreshSizes() { for tile in allTiles { switch tile.myWhereInPlay { case .trash: break case .atBat: tile.mySize = .large tile.topOfBlock.layer.borderColor = UIColor.black.cgColor case .pile: tile.topOfBlock.layer.borderColor = UIColor.black.cgColor case .onDeck: tile.mySize = .medium tile.topOfBlock.layer.borderColor = UIColor.black.cgColor case .board: tile.mySize = .small tile.topOfBlock.layer.borderColor = UIColor.clear.cgColor if Set1.isZoomed { tile.mySize = .large tile.topOfBlock.layer.borderColor = UIColor.clear.cgColor } } } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if (gestureRecognizer is UIPanGestureRecognizer || gestureRecognizer is UITapGestureRecognizer) && !refillMode { return true } else { return false } } private func restart() { startingNewGame = true view.subviews.forEach({ $0.removeFromSuperview() }) for case let view as Tile in myBoard.subviews { view.removeFromSuperview() } isFirstPlayFunc = true allTiles.removeAll() onDeckTiles.removeAll() wordTiles.removeAll() tilesInPlay.removeAll() wordTilesPerpendicular.removeAll() for slot in myBoard.slots { slot.isOccupied = false slot.isPermanentlyOccupied = false slot.isOccupiedFromStart = false } pileOfTiles = 30 myBoard.zoomOut(){} myLoad() for tile in allTiles { if tile.isStarterBlock { tile.topOfBlock.backgroundColor = myColor.purple tile.text.textColor = .black } } pile.topOfBlock.backgroundColor = myColor.teal pile.text.textColor = .black startingNewGame = false storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } func storeWholeState() { var atBatRawValue = [String]() var onDeckRawValue = [String]() var buildableRawValue = [String]() var startRawValue = [String]() var indexBuildable = [Int]() var indexStart = [Int]() for tile in allTiles { if tile.isBuildable { indexBuildable.append(tile.slotsIndex!) buildableRawValue.append(tile.mySymbol.rawValue) } if tile.isStarterBlock { indexStart.append(tile.slotsIndex!) startRawValue.append(tile.mySymbol.rawValue) } if tile.myWhereInPlay == .atBat { atBatRawValue.append(tile.mySymbol.rawValue) } if tile.myWhereInPlay == .onDeck { onDeckRawValue.append(tile.mySymbol.rawValue) } } Set1.pileAmount = pileOfTiles Set1.winState = isWin Set1.atBatRawValue = atBatRawValue Set1.onDeckRawValue = onDeckRawValue Set1.buildableRawValue = buildableRawValue Set1.indexBuildable = indexBuildable Set1.startRawValue = startRawValue Set1.indexStart = indexStart } private func whatsMySymbol(character: String) -> Tile.symbol { switch character { case "A": return .a; case "B": return .b; case "C": return .c; case "D": return .d; case "E": return .e; case "F": return .f; case "G": return .g; case "H": return .h; case "I": return .i; case "J": return .j; case "K": return .k; case "L": return .l; case "M": return .m; case "N": return .n; case "O": return .o; case "P": return .p; case "Q": return .q; case "R": return .r; case "S": return .s; case "T": return .t; case "U": return .u; case "V": return .v; case "W": return .w; case "X": return .x; case "Y": return .y; case "Z": return .z; default: return .a } } func purchase(productId: String) { view.addSubview(progressHUD) SwiftyStoreKit.purchaseProduct(productId) { result in switch result { case .success( _): if productId == "com.fooble.boosts" { self.amountOfBoosts += 3 self.bonusBoost(text: "+3") self.storeWholeState() LoadSaveCoreData.sharedInstance.saveState() } self.progressHUD.removeFromSuperview() case .error(let error): print("error: \(error)") print("Purchase Failed: \(error)") self.progressHUD.removeFromSuperview() let alert = UIAlertController(title: "Purchase", message: "Purchase Failed", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } }
39.985263
553
0.444164
e0fdf8e982c23806023925da405570eaa469f42c
2,477
// AOC12.swift // AdventOfCode // // Created by Dash on 12/11/20. // import Foundation fileprivate extension Point { func move(direction: Direction, amount: Int, vector: Point? = nil) -> Point { switch direction { case .forward: return self + (amount * vector!) case .right: return rotate(turns: amount) case .left: return rotate(turns: -amount) case .east: return self + Point(amount, 0) case .west: return self + Point(-amount, 0) case .north: return self + Point(0, amount) case .south: return self + Point(0, -amount) } } } fileprivate enum Direction: Character { case forward = "F" case right = "R" case left = "L" case east = "E" case west = "W" case north = "N" case south = "S" var isRotation: Bool { switch self { case .right, .left: return true default: return false } } } class AOC12: Puzzle { fileprivate func scanMove(line: String) -> (direction: Direction, amount: Int) { let scanner = Scanner(string: line) let direction = Direction(rawValue: scanner.scanCharacter()!)! let amount = scanner.scanInt()! if direction.isRotation { return (direction, amount / 90) } else { return (direction, amount) } } func solve1(input: String) -> Int { var ship = Point(0, 0) var vector = Point(1, 0) for line in input.lines { let move = scanMove(line: line) if move.direction.isRotation { vector = vector.move(direction: move.direction, amount: move.amount) } else { ship = ship.move(direction: move.direction, amount: move.amount, vector: vector) } } return ship.manhattanDistance } func solve2(input: String) -> Int { var ship = Point(0, 0) var waypoint = Point(10, 1) for line in input.lines { let move = scanMove(line: line) if move.direction == .forward { ship = ship.move(direction: move.direction, amount: move.amount, vector: waypoint) } else { waypoint = waypoint.move(direction: move.direction, amount: move.amount) } } return ship.manhattanDistance } }
27.831461
98
0.535729
bfe548b401af6c413a5cc5254eb7557f06833a15
3,369
// // NextViewController.swift // SlideShowDemo // // Created by Kaushal Elsewhere on 03/09/16. // Copyright © 2016 Kaushal Elsewhere. All rights reserved. // import UIKit import KIImagePager import SDWebImage extension NextViewController: KIImagePagerDataSource, KIImagePagerImageSource{ func arrayWithImages(pager: KIImagePager!) -> [AnyObject]! { return images } func contentModeForImage(image: UInt, inPager pager: KIImagePager!) -> UIViewContentMode { return .ScaleAspectFill } func imageWithUrl(url: NSURL!, completion: KIImagePagerImageRequestBlock!) { let manager = SDWebImageManager.sharedManager() manager.downloadImageWithURL(url, options: .CacheMemoryOnly, progress: { (ob, on) in // }) { (image, error, cacheType, success, url) in completion(image, nil) } } } extension NextViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .lightGrayColor() setupPagerwithtableView() setupconstraints() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) pager.pageControl.currentPage = 0 } func setupPagerwithtableView() { pager.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.width) kTableHeaderHieght = self.view.bounds.width tableView.addSubview(pager) tableView.contentInset = UIEdgeInsets(top: kTableHeaderHieght , left: 0, bottom: 0, right: 0) tableView.contentOffset = CGPoint(x: 0, y: -kTableHeaderHieght) view.addSubview(tableView) updateHeaderView() } func setupconstraints() { let superView = self.view tableView.snp_makeConstraints { (make) in make.edges.equalTo(superView) } } } extension NextViewController: UITableViewDelegate, UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { updateHeaderView() } func updateHeaderView() { var headerRect = CGRect(x: 0, y: -kTableHeaderHieght, width: tableView.bounds.width, height: kTableHeaderHieght) if tableView.contentOffset.y < -kTableHeaderHieght { headerRect.origin.y = tableView.contentOffset.y headerRect.size.height = -tableView.contentOffset.y } lastPageIndex = pager.currentPage pager.frame = headerRect tableView.layoutIfNeeded() pager.setCurrentPage(lastPageIndex, animated: false) } } class NextViewController: UIViewController { lazy var tableView: UITableView = { let tableView = UITableView() tableView.backgroundColor = .clearColor() tableView.delegate = self return tableView }() lazy var pager: KIImagePager = { let pager = KIImagePager() pager.contentMode = .ScaleAspectFill pager.dataSource = self pager.imageSource = self pager.backgroundColor = UIColor.blackColor() pager.currentPage = 0 return pager }() var kTableHeaderHieght: CGFloat = 300 var lastPageIndex: UInt = 0 }
28.075
120
0.626892
0adc79ded523aa02b5dd16a03947f50ba8569933
6,272
// // CommentAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation import RxSwift #if canImport(AnyCodable) import AnyCodable #endif open class CommentAPI { /** Get private comments for a restaurant - parameter id: (path) - parameter restaurantId: (path) - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<[Comment]> */ open class func getRestaurantComment(id: Int, restaurantId: Int, apiResponseQueue: DispatchQueue = OpenAPIClient.apiResponseQueue) -> Observable<[Comment]> { return Observable.create { observer -> Disposable in getRestaurantCommentWithRequestBuilder(id: id, restaurantId: restaurantId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): observer.onNext(response.body!) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Get private comments for a restaurant - GET /community/{id}/restaurants/{restaurant_id}/comments - API Key: - type: apiKey Authorization - name: token - parameter id: (path) - parameter restaurantId: (path) - returns: RequestBuilder<[Comment]> */ open class func getRestaurantCommentWithRequestBuilder(id: Int, restaurantId: Int) -> RequestBuilder<[Comment]> { var localVariablePath = "/community/{id}/restaurants/{restaurant_id}/comments" let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) let restaurantIdPreEscape = "\(APIHelper.mapValueToPathItem(restaurantId))" let restaurantIdPostEscape = restaurantIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{restaurant_id}", with: restaurantIdPostEscape, options: .literal, range: nil) let localVariableURLString = OpenAPIClient.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<[Comment]>.Type = OpenAPIClient.requestBuilderFactory.getBuilder() return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Update comment of the restaurant - parameter id: (path) - parameter restaurantId: (path) - parameter updateCommentRequest: (body) - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<Comment> */ open class func updateRestaurantComment(id: Int, restaurantId: Int, updateCommentRequest: UpdateCommentRequest, apiResponseQueue: DispatchQueue = OpenAPIClient.apiResponseQueue) -> Observable<Comment> { return Observable.create { observer -> Disposable in updateRestaurantCommentWithRequestBuilder(id: id, restaurantId: restaurantId, updateCommentRequest: updateCommentRequest).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): observer.onNext(response.body!) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Update comment of the restaurant - PUT /community/{id}/restaurants/{restaurant_id}/comments - API Key: - type: apiKey Authorization - name: token - parameter id: (path) - parameter restaurantId: (path) - parameter updateCommentRequest: (body) - returns: RequestBuilder<Comment> */ open class func updateRestaurantCommentWithRequestBuilder(id: Int, restaurantId: Int, updateCommentRequest: UpdateCommentRequest) -> RequestBuilder<Comment> { var localVariablePath = "/community/{id}/restaurants/{restaurant_id}/comments" let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) let restaurantIdPreEscape = "\(APIHelper.mapValueToPathItem(restaurantId))" let restaurantIdPostEscape = restaurantIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{restaurant_id}", with: restaurantIdPostEscape, options: .literal, range: nil) let localVariableURLString = OpenAPIClient.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: updateCommentRequest) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Comment>.Type = OpenAPIClient.requestBuilderFactory.getBuilder() return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } }
47.515152
214
0.698023
f8935614c769194e6845ff3f4df73e17d8ec0bd7
1,722
// // ViewController.swift // demo // // Created by Denis Martin on 28/06/2015. // Copyright (c) 2015 iRLMobile. All rights reserved. // import UIKit class ViewController : UIViewController, IRLScannerViewControllerDelegate { @IBOutlet weak var scanButton: UIButton! @IBOutlet weak var imageView: UIImageView! // MARK: User Actions @IBAction func scan(sender: AnyObject) { let scanner = IRLScannerViewController.standardCameraViewWithDelegate(self) scanner.showControls = true scanner.showAutoFocusWhiteRectangle = true presentViewController(scanner, animated: true, completion: nil) } // MARK: IRLScannerViewControllerDelegate func pageSnapped(page_image: UIImage!, from controller: IRLScannerViewController!) { controller.dismissViewControllerAnimated(true) { () -> Void in self.imageView.image = page_image } } func cameraViewWillUpdateTitleLabel(cameraView: IRLScannerViewController!) -> String! { var text = "" switch cameraView.cameraViewType { case .Normal: text = text + "NORMAL" case .BlackAndWhite: text = text + "B/W-FILTER" case .UltraContrast: text = text + "CONTRAST" } switch cameraView.detectorType { case .Accuracy: text = text + " | Accuracy" case .Performance: text = text + " | Performance" } return text } func didCancelIRLScannerViewController(controller: IRLScannerViewController){ controller.dismissViewControllerAnimated(true){ ()-> Void in NSLog("Cancel pressed"); } } }
30.75
91
0.632404
117082749ef6173b203160990e9536e2c3e05f01
633
// // PreviewLivePhotoViewCell.swift // HXPHPicker // // Created by Slience on 2021/3/12. // import UIKit class PreviewLivePhotoViewCell: PhotoPreviewViewCell { var livePhotoPlayType: PhotoPreviewViewController.PlayType = .once { didSet { scrollContentView.livePhotoPlayType = livePhotoPlayType } } override init(frame: CGRect) { super.init(frame: frame) scrollContentView = PhotoPreviewContentView.init(type: .livePhoto) initView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
21.827586
74
0.647709
d6a111c93377627118fb3ec5aad361dc931ff86b
1,105
// // SetupScreen.swift // Biologer // // Created by Nikola Popovic on 27.6.21.. // import SwiftUI struct SetupScreen: View { @ObservedObject var viewModel: SetupScreenViewModel var body: some View { ScrollView { VStack { ForEach(viewModel.sections.indices, id: \.self) { sectionIndex in let section = viewModel.sections[sectionIndex] SetupSectionView(viewModel: section, onItemTapped: { itemIndex in viewModel.itemTapped(sectionIndex: sectionIndex, itemIndex: itemIndex) }) } } .padding(.horizontal, 30) } } } struct SetupScreen_Previews: PreviewProvider { static var previews: some View { SetupScreen(viewModel: SetupScreenViewModel(sections: SetupDataMapper.getSetupData(), onItemTapped: { item in })) } }
29.864865
93
0.495928
61597e695c8db4db5bc986b028ff992843ef69b9
2,546
@testable import DangerDependenciesResolver import SnapshotTesting import XCTest final class PackageGeneratorTests: XCTestCase { override func setUp() { super.setUp() record = false } func testGeneratedPackageWhenThereAreNoDependencies() throws { let packageListMaker = StubbedPackageListMaker(packages: []) let spyFileCreator = SpyFileCreator() let generator = PackageGenerator(folder: "folder", generatedFolder: "generatedFolder", packageListMaker: packageListMaker, fileCreator: spyFileCreator) try generator.generateMasterPackageDescription(forSwiftToolsVersion: .init(5, 0, 0)) assertSnapshot(matching: String(data: spyFileCreator.receivedContents!, encoding: .utf8)!, as: .lines) } func testGeneratedPackageWhenThereAreDependencies() throws { let packageListMaker = StubbedPackageListMaker(packages: [ Package(name: "Dependency1", url: URL(string: "https://github.com/danger/dependency1")!, majorVersion: 1), Package(name: "Dependency2", url: URL(string: "https://github.com/danger/dependency2")!, majorVersion: 2), Package(name: "Dependency3", url: URL(string: "https://github.com/danger/dependency3")!, majorVersion: 3), ]) let spyFileCreator = SpyFileCreator() let generator = PackageGenerator(folder: "folder", generatedFolder: "generatedFolder", packageListMaker: packageListMaker, fileCreator: spyFileCreator) try generator.generateMasterPackageDescription(forSwiftToolsVersion: .init(5, 0, 0)) assertSnapshot(matching: String(data: spyFileCreator.receivedContents!, encoding: .utf8)!, as: .lines) } func testGeneratedDescriptionHeader() throws { let packageListMaker = StubbedPackageListMaker(packages: []) let spyFileCreator = SpyFileCreator() let generator = PackageGenerator(folder: "folder", generatedFolder: "generatedFolder", packageListMaker: packageListMaker, fileCreator: spyFileCreator) assertSnapshot(matching: generator.makePackageDescriptionHeader(forSwiftToolsVersion: .init(4, 2, 0)), as: .lines) } } private struct StubbedPackageListMaker: PackageListMaking { let packages: [Package] func makePackageList() -> [Package] { packages } } private final class SpyFileCreator: FileCreating { var receivedPath: String? var receivedContents: Data? func createFile(atPath path: String, contents: Data) { receivedPath = path receivedContents = contents } }
41.064516
159
0.719167
d6ed5e84a0fc43a05cea7be5fc08c41a0be4fa6c
580
// // Asset.swift // HeatBall // // Created by Atilla Özder on 25.09.2020. // Copyright © 2020 Atilla Özder. All rights reserved. // import UIKit // MARK: - Asset enum Asset: String { case music = "music" case podium = "podium" case star = "star" case heart = "heart" case pause = "pause" case fuel = "fuel" case menu = "menu" case playVideo = "play-video" case splash = "splash" case settings = "settings" case play = "play" func imageRepresentation() -> UIImage? { return UIImage(named: self.rawValue) } }
19.333333
55
0.6
56d9197415ee87c607e60bfc660c5c891ea89cbd
1,753
// // GetStyles.swift // EdmundsAPI // // Created by Graham Pancio on 2016-04-27. // Copyright © 2016 Graham Pancio. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper public protocol GetStylesDelegate: class { func retrievedStyleSet(styleSet: VehicleStyleSet) func getStyleSetFailed() } /** Retrieves vehicle styles using the Edmunds Vehicle API. A vehicle style identifies a vehicle more precisely than year, make and model. An example of a style name is: "LE Plus 4dr Sedan (1.8L 4cyl CVT)". Thus the vehicle style gives more information on the vehicle such as: - Number of doors - Category (submodel) of vehicle (eg. "Sedan") - The set of colors the vehicle of that style is available in. - And more. */ public class GetStyles { public weak var delegate: GetStylesDelegate? var apiKey: String public init(apiKey: String) { self.apiKey = apiKey } public func makeRequest(year: String, make: String, model: String) { Alamofire.request(Method.GET, formatUrl(year, make: make, model: model)).validate().responseObject { (response: Response<VehicleStyleSet, NSError>) in let vss = response.result.value if vss != nil && vss?.styles != nil && vss?.styles?.count > 0 { self.delegate?.retrievedStyleSet(vss!) } else { self.delegate?.getStyleSetFailed() } } } private func formatUrl(year: String, make: String, model: String) -> String { let urlString = String(format: "https://api.edmunds.com/api/vehicle/v2/%@/%@/%@/styles?view=full&fmt=json&api_key=%@", make, model, year, apiKey) return urlString } }
31.303571
158
0.656018
ac3987176de5453d96770d675d65c6acf50dae9d
6,877
// // ViewController.swift // OnboardExample // import UIKit import OnboardKit class ViewController: UIViewController { lazy var onboardingPages: [OnboardPage] = { let pageOne = OnboardPage(title: "Welcome to Habitat", imageName: "Onboarding1", description: "Habitat is an easy to use productivity app designed to keep you motivated.") let pageTwo = OnboardPage(title: "Habit Entries", imageName: "Onboarding2", description: "For each of your habits an entry is created for every day you need to complete it.") let pageThree = OnboardPage(title: "Marking and Tracking", imageName: "Onboarding3", description: "By marking entries as Done you can track your progress on the path to success.") let pageFour = OnboardPage(title: "Notifications", imageName: "Onboarding4", description: "Turn on notifications to get reminders and keep up with your goals.", advanceButtonTitle: "Decide Later", actionButtonTitle: "Enable Notifications", action: { [weak self] completion in self?.showAlert(completion) }) let pageFive = OnboardPage(title: "All Ready", imageName: "Onboarding5", description: "You are all set up and ready to use Habitat. Begin by adding your first habit.", advanceButtonTitle: "Done") return [pageOne, pageTwo, pageThree, pageFour, pageFive] }() lazy var onboardingPagesAlternative: [OnboardPage] = { let pageOne = OnboardPage(title: "Welcome to Habitat", imageName: "Onboarding1_alt", description: "Habitat is an easy to use productivity app designed to keep you motivated.") let pageTwo = OnboardPage(title: "Habit Entries", imageName: "Onboarding2", description: "An entry is created for every day you need to complete each habit.") let pageThree = OnboardPage(title: "Marking and Tracking", imageName: "Onboarding3", description: "By marking entries as Done you can track your progress.") let pageFour = OnboardPage(title: "Notifications", imageName: "Onboarding4", description: "Turn on notifications to get reminders and keep up with your goals.", advanceButtonTitle: "Decide Later", actionButtonTitle: "Enable Notifications", action: { [weak self] completion in self?.showAlert(completion) }) let pageFive = OnboardPage(title: "All Ready", imageName: "Onboarding5", description: "You are all set up and ready to use Habitat. Adding your first habit.", advanceButtonTitle: "Done") return [pageOne, pageTwo, pageThree, pageFour, pageFive] }() @IBAction func showOnboardingDefaultTapped(_ sender: Any) { let onboardingVC = OnboardViewController(pageItems: onboardingPages) onboardingVC.modalPresentationStyle = .formSheet onboardingVC.presentFrom(self, animated: true) } @IBAction func showOnboardingCustomTapped(_ sender: Any) { let tintColor = UIColor(red: 1.00, green: 0.52, blue: 0.40, alpha: 1.00) let titleColor = UIColor(red: 1.00, green: 0.35, blue: 0.43, alpha: 1.00) let boldTitleFont = UIFont.systemFont(ofSize: 32.0, weight: .bold) let mediumTextFont = UIFont.systemFont(ofSize: 17.0, weight: .semibold) let appearanceConfiguration = OnboardViewController.AppearanceConfiguration(tintColor: tintColor, titleColor: titleColor, textColor: .white, backgroundColor: .black, titleFont: boldTitleFont, textFont: mediumTextFont) let onboardingVC = OnboardViewController(pageItems: onboardingPagesAlternative, appearanceConfiguration: appearanceConfiguration) onboardingVC.modalPresentationStyle = .formSheet onboardingVC.presentFrom(self, animated: true) } @IBAction func showOnboardingStyledButtonsTapped(_ sender: Any) { let advanceButtonStyling: OnboardViewController.ButtonStyling = { button in button.setTitleColor(UIColor.lightGray, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 16.0, weight: .semibold) } let actionButtonStyling: OnboardViewController.ButtonStyling = { button in button.setTitleColor(.black, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 22.0, weight: .semibold) button.backgroundColor = UIColor(white: 0.95, alpha: 1.0) button.layer.cornerRadius = button.bounds.height / 2.0 button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) button.layer.shadowColor = UIColor.black.cgColor button.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) button.layer.shadowRadius = 2.0 button.layer.shadowOpacity = 0.2 } let appearance = OnboardViewController.AppearanceConfiguration(advanceButtonStyling: advanceButtonStyling, actionButtonStyling: actionButtonStyling) let onboardingVC = OnboardViewController(pageItems: onboardingPages, appearanceConfiguration: appearance) onboardingVC.modalPresentationStyle = .formSheet onboardingVC.presentFrom(self, animated: true) } /// Only for the purpouses of the example. /// Not really asking for notifications permissions. private func showAlert(_ completion: @escaping (_ success: Bool, _ error: Error?) -> Void) { let alert = UIAlertController(title: "Allow Notifications?", message: "Habitat wants to send you notifications", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completion(true, nil) }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completion(false, nil) }) presentedViewController?.present(alert, animated: true) } }
51.706767
120
0.589065
eb12fbf56f274610a0a759d6f4b529bd0a6727e0
8,426
// Copyright SIX DAY LLC. All rights reserved. import UIKit import RealmSwift import AWSSNS import AWSCore import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? private var appCoordinator: AppCoordinator! private let SNSPlatformApplicationArn = "arn:aws:sns:us-west-2:400248756644:app/APNS/AlphaWallet-iOS" private let SNSPlatformApplicationArnSANDBOX = "arn:aws:sns:us-west-2:400248756644:app/APNS_SANDBOX/AlphaWallet-testing" private let identityPoolId = "us-west-2:42f7f376-9a3f-412e-8c15-703b5d50b4e2" private let SNSSecurityTopicEndpoint = "arn:aws:sns:us-west-2:400248756644:security" //This is separate coordinator for the protection of the sensitive information. private lazy var protectionCoordinator: ProtectionCoordinator = { return ProtectionCoordinator() }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) //Necessary to make UIAlertController have the correct tint colors, despite already doing: `UIWindow.appearance().tintColor = Colors.appTint` window?.tintColor = Colors.appTint do { //NOTE: we move AnalyticsService creation from AppCoordinator.init method to allow easily replace let analyticsService = AnalyticsService() let keystore = try EtherKeystore(analyticsCoordinator: analyticsService) let navigationController = UINavigationController() navigationController.view.backgroundColor = Colors.appWhite appCoordinator = try AppCoordinator(window: window!, analyticsService: analyticsService, keystore: keystore, navigationController: navigationController) appCoordinator.start() if let shortcutItem = launchOptions?[UIApplication.LaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem, shortcutItem.type == Constants.launchShortcutKey { //Delay needed to work because app is launching.. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.appCoordinator.launchUniversalScanner() } } } catch { } protectionCoordinator.didFinishLaunchingWithOptions() return true } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { if shortcutItem.type == Constants.launchShortcutKey { appCoordinator.launchUniversalScanner() } completionHandler(true) } private func cognitoRegistration() { // Override point for customization after application launch. /// Setup AWS Cognito credentials // Initialize the Amazon Cognito credentials provider let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USWest2, identityPoolId: identityPoolId) let configuration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = configuration let defaultServiceConfiguration = AWSServiceConfiguration( region: AWSRegionType.USWest2, credentialsProvider: credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = defaultServiceConfiguration } func applicationWillResignActive(_ application: UIApplication) { protectionCoordinator.applicationWillResignActive() } func applicationDidBecomeActive(_ application: UIApplication) { //Lokalise.shared.checkForUpdates { _, _ in } protectionCoordinator.applicationDidBecomeActive() appCoordinator.handleUniversalLinkInPasteboard() } func applicationDidEnterBackground(_ application: UIApplication) { protectionCoordinator.applicationDidEnterBackground() } func applicationWillEnterForeground(_ application: UIApplication) { protectionCoordinator.applicationWillEnterForeground() } func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplication.ExtensionPointIdentifier) -> Bool { if extensionPointIdentifier == .keyboard { return false } return true } // URI scheme links and AirDrop func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { return appCoordinator.handleOpen(url: url) } // Respond to Universal Links func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { var handled = false if let url = userActivity.webpageURL { handled = handleUniversalLink(url: url) } //TODO: if we handle other types of URLs, check if handled==false, then we pass the url to another handlers return handled } // Respond to amazon SNS registration func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { /// Attach the device token to the user defaults var token = "" for i in 0..<deviceToken.count { let tokenInfo = String(format: "%02.2hhx", arguments: [deviceToken[i]]) token.append(tokenInfo) } UserDefaults.standard.set(token, forKey: "deviceTokenForSNS") /// Create a platform endpoint. In this case, the endpoint is a /// device endpoint ARN cognitoRegistration() let sns = AWSSNS.default() let request = AWSSNSCreatePlatformEndpointInput() request?.token = token #if DEBUG request?.platformApplicationArn = SNSPlatformApplicationArnSANDBOX #else request?.platformApplicationArn = SNSPlatformApplicationArn #endif sns.createPlatformEndpoint(request!).continueWith(executor: AWSExecutor.mainThread(), block: { (task: AWSTask!) -> AnyObject? in if task.error == nil { let createEndpointResponse = task.result! as AWSSNSCreateEndpointResponse if let endpointArnForSNS = createEndpointResponse.endpointArn { UserDefaults.standard.set(endpointArnForSNS, forKey: "endpointArnForSNS") //every user should subscribe to the security topic self.subscribeToTopicSNS(token: token, topicEndpoint: self.SNSSecurityTopicEndpoint) // if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { // //TODO subscribe to version topic when created // } } } return nil }) } func subscribeToTopicSNS(token: String, topicEndpoint: String) { let sns = AWSSNS.default() guard let endpointRequest = AWSSNSCreatePlatformEndpointInput() else { return } #if DEBUG endpointRequest.platformApplicationArn = SNSPlatformApplicationArnSANDBOX #else endpointRequest.platformApplicationArn = SNSPlatformApplicationArn #endif endpointRequest.token = token sns.createPlatformEndpoint(endpointRequest).continueWith { task in guard let response: AWSSNSCreateEndpointResponse = task.result else { return nil } guard let subscribeRequest = AWSSNSSubscribeInput() else { return nil } subscribeRequest.endpoint = response.endpointArn subscribeRequest.protocols = "application" subscribeRequest.topicArn = topicEndpoint return sns.subscribe(subscribeRequest) } } //TODO Handle SNS errors func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { //no op } @discardableResult private func handleUniversalLink(url: URL) -> Bool { let handled = appCoordinator.handleUniversalLink(url: url) return handled } }
45.793478
175
0.688346
26825f44dc0b73d1151e94ec417e1a0d8f39bd48
5,138
// // feedViewController.swift // Instagram // // Created by Elan Halpern on 6/27/17. // Copyright © 2017 Elan Halpern. All rights reserved. // import UIKit import Parse import ParseUI class feedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var profilePictureButton: UIButton! var imagePickerController: UIImagePickerController = UIImagePickerController() var feedPosts: [PFObject] = [] @IBOutlet weak var feedTableView: UITableView! var refreshControl: UIRefreshControl! var choosenImage: UIImage! var username: String! var captionText: String! var datePosted: Date! override func viewDidLoad() { super.viewDidLoad() feedTableView.dataSource = self feedTableView.delegate = self refresh() refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_refreshControl:)), for: UIControlEvents.valueChanged) feedTableView.insertSubview(refreshControl, at: 0) imagePickerController.delegate = self imagePickerController.allowsEditing = true } override func viewWillAppear(_ animated: Bool) { refresh() } func refresh() { let query = PFQuery(className: "Post") //query.limit = 20 query.order(byDescending: "_created_at") query.includeKey("account") query.findObjectsInBackground { (posts: [PFObject]?, error: Error?) in if let posts = posts { // do something with the array of object returned by the call self.feedPosts.removeAll() for post in posts { self.feedPosts.append(post) } self.feedTableView.reloadData() self.refreshControl.endRefreshing() } else { print(error?.localizedDescription) } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return feedPosts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell let post = feedPosts[indexPath.row] //ppfobject let caption = post["caption"] as! String //string let image = post["image"] as! PFFile let account = post["account"] as! PFUser if let profilePicture = account["profilePicture"] as? PFFile { cell.profilePictureView.file = profilePicture cell.profilePictureView.loadInBackground() } else { print("can't get profile picture") } username = account.username captionText = caption datePosted = post.createdAt cell.userNameLabel.text = account.username cell.captionLabel.text = caption cell.postImage.file = image cell.postImage.loadInBackground() return cell } @IBAction func onLogout(_ sender: Any) { self.dismiss(animated: true, completion: nil) let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.loggedOut() } @IBAction func onCamera(_ sender: Any) { if UIImagePickerController.isSourceTypeAvailable(.camera) { print("Camera is avaliable 📸") imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage choosenImage = originalImage dismiss(animated: true, completion: nil) performSegue(withIdentifier: "cameraSegue", sender: nil) } func refreshControlAction(_refreshControl: UIRefreshControl) { refresh() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if(segue.identifier == "cameraSegue") { let photoMapViewController = segue.destination as! PhotoMapViewController photoMapViewController.chosenImage = choosenImage photoMapViewController.isFromCamera = true } else if (segue.identifier == "detailsSegue") { let detailsViewController = segue.destination as! DetailsViewController let cell = sender as! UITableViewCell if let indexPath = feedTableView.indexPath(for: cell) { let post = feedPosts[indexPath.row] detailsViewController.post = post detailsViewController.timestamp = datePosted } } } }
33.363636
153
0.622616
9c48fddf35ef4be8958bb6a65cc6aef750e71645
2,693
// // SplitViewController.swift // IBDecodable // // Created by phimage on 04/04/2018. // import SWXMLHash public struct SplitViewController: IBDecodable, ViewControllerProtocol { public let elementClass: String = "UISplitViewController" public let id: String public let customClass: String? public let customModule: String? public let customModuleProvider: String? public let userLabel: String? public let colorLabel: String? public var storyboardIdentifier: String? public var sceneMemberID: String? public let layoutGuides: [ViewControllerLayoutGuide]? public let userDefinedRuntimeAttributes: [UserDefinedRuntimeAttribute]? public let connections: [AnyConnection]? public let keyCommands: [KeyCommand]? public let tabBarItem: TabBar.TabBarItem? public let view: View? public var rootView: ViewProtocol? { return view } public let size: [Size]? enum LayoutGuidesCodingKeys: CodingKey { case viewControllerLayoutGuide } static func decode(_ xml: XMLIndexerType) throws -> SplitViewController { let container = xml.container(keys: CodingKeys.self) let layoutGuidesContainer = container.nestedContainerIfPresent(of: .layoutGuides, keys: LayoutGuidesCodingKeys.self) return SplitViewController( id: try container.attribute(of: .id), customClass: container.attributeIfPresent(of: .customClass), customModule: container.attributeIfPresent(of: .customModule), customModuleProvider: container.attributeIfPresent(of: .customModuleProvider), userLabel: container.attributeIfPresent(of: .userLabel), colorLabel: container.attributeIfPresent(of: .colorLabel), storyboardIdentifier: container.attributeIfPresent(of: .storyboardIdentifier), sceneMemberID: container.attributeIfPresent(of: .sceneMemberID), layoutGuides: layoutGuidesContainer?.elementsIfPresent(of: .viewControllerLayoutGuide), userDefinedRuntimeAttributes: container.childrenIfPresent(of: .userDefinedRuntimeAttributes), connections: container.childrenIfPresent(of: .connections), keyCommands: container.childrenIfPresent(of: .keyCommands), tabBarItem: container.elementIfPresent(of: .tabBarItem), view: container.elementIfPresent(of: .view), size: container.elementsIfPresent(of: .size) ) } }
49.87037
124
0.659488
9c0be6a23cbe4f3b3c5643d13fd66326e9f51d1a
6,035
// // NetworkCall.swift // Pods // // Created by Elliot Schrock on 9/11/17. // // import UIKit import ReactiveSwift import Result import Prelude open class NetworkCall { public let configuration: ServerConfigurationProtocol public let endpoint: String public let httpMethod: String public let postData: Data? public let httpHeaders: [String: String]? open var requestFromEndpoint: (String) -> NSMutableURLRequest? open var configuredRequest: (NSMutableURLRequest?) -> NSMutableURLRequest? = { r in r } open var url: (String) -> URL? open var urlString: (String) -> String public let dataTaskSignal: Signal<URLSessionDataTask, NoError> public let responseSignal: Signal<URLResponse, NoError> public let httpResponseSignal: Signal<HTTPURLResponse, NoError> public let dataSignal: Signal<Data?, NoError> public let errorSignal: Signal<NSError, NoError> public let serverErrorSignal: Signal<NSError, NoError> public let errorDataSignal: Signal<Data, NoError> let dataTaskProperty = MutableProperty<URLSessionDataTask?>(nil) let responseProperty = MutableProperty<URLResponse?>(nil) let dataProperty = MutableProperty<Data?>(nil) let errorProperty = MutableProperty<NSError?>(nil) let serverErrorProperty = MutableProperty<NSError?>(nil) let errorResponseProperty = MutableProperty<URLResponse?>(nil) let errorDataProperty = MutableProperty<Data?>(nil) let fireProperty = MutableProperty(()) public init(configuration: ServerConfigurationProtocol, httpMethod: String = "GET", httpHeaders: Dictionary<String, String>? = [:], endpoint: String, postData: Data?, networkErrorHandler: NetworkErrorHandler? = nil) { self.configuration = configuration self.httpMethod = httpMethod self.httpHeaders = httpHeaders self.endpoint = endpoint self.postData = postData self.urlString = { endpoint in return (configuration |> NetworkCall.configurationToBaseUrlString) + endpoint } self.url = URL.init(string:) <<< urlString dataTaskSignal = dataTaskProperty.signal.skipNil() responseSignal = responseProperty.signal.skipNil() httpResponseSignal = responseSignal.map({ $0 as? HTTPURLResponse }).skipNil() dataSignal = dataProperty.signal errorDataSignal = errorDataProperty.signal.skipNil() if let handler = networkErrorHandler { errorSignal = errorProperty.signal.skipNil().filter { !handler.handleError($0) } serverErrorSignal = httpResponseSignal.filter({ $0.statusCode > 300 }).map({ NSError(domain: "Server", code: $0.statusCode, userInfo: ["url" : $0.url?.absoluteString as Any]) }).filter { !handler.handleError($0) } } else { errorSignal = errorProperty.signal.skipNil() serverErrorSignal = httpResponseSignal.filter({ $0.statusCode > 300 }).map({ NSError(domain: "Server", code: $0.statusCode, userInfo: ["url" : $0.url?.absoluteString as Any]) }) } self.requestFromEndpoint = (self.url <^> NSMutableURLRequest.init(url:)) self.configuredRequest = applyHeaders >>> applyHttpMethod >>> applyBody dataTaskSignal.observeValues { task in task.resume() } } open func fire() { let session = URLSession(configuration: configuration.urlConfiguration, delegate: nil, delegateQueue: OperationQueue.main) if let request = self.mutableRequest() { dataTaskProperty.value = session.dataTask(with: request as URLRequest) { (data, response, error) in self.errorProperty.value = error as NSError? self.responseProperty.value = response if let _ = error { self.errorDataProperty.value = data } else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode > 299 { self.errorDataProperty.value = data } else { self.dataProperty.value = data } session.finishTasksAndInvalidate() } } } open func mutableRequest() -> NSMutableURLRequest? { return endpoint |> (requestFromEndpoint >>> configuredRequest) } public static func configurationToBaseUrlString(_ configuration: ServerConfigurationProtocol) -> String { let baseUrlString = "\(configuration.scheme)://\(configuration.host)" if let apiRoute = configuration.apiBaseRoute { return "\(baseUrlString)/\(apiRoute)/" } else { return "\(baseUrlString)/" } } open func applyHeaders(_ request: NSURLRequest?) -> NSMutableURLRequest? { if let mutableRequest = request?.mutableCopy() as? NSMutableURLRequest { if let headers = httpHeaders { for key in headers.keys { mutableRequest.addValue(headers[key]!, forHTTPHeaderField: key) } } return mutableRequest } return nil } open func applyHttpMethod(_ request: NSURLRequest?) -> NSMutableURLRequest? { if let mutableRequest = request?.mutableCopy() as? NSMutableURLRequest { mutableRequest.httpMethod = httpMethod return mutableRequest } return nil } open func applyBody(_ request: NSURLRequest?) -> NSMutableURLRequest? { if let mutableRequest = request?.mutableCopy() as? NSMutableURLRequest { mutableRequest.httpBody = postData return mutableRequest } return nil } } precedencegroup ForwardApplication { associativity: left } infix operator <^>: ForwardApplication func <^><A, B, C>(f: @escaping (A) -> B?, g: @escaping (B) -> C) -> (A) -> C? { return { a in if let b = f(a) { return g(b) } else { return nil } } }
39.188312
225
0.640762
ccd3a1d4e06522a22fab70e4ff627710deb3a372
21,853
// RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency // REQUIRES: concurrency // some utilities func thrower() throws {} func asyncer() async {} func rethrower(_ f : @autoclosure () throws -> Any) rethrows -> Any { return try f() } func asAutoclosure(_ f : @autoclosure () -> Any) -> Any { return f() } // not a concurrency-safe type class Box { // expected-note 4{{class 'Box' does not conform to the 'Sendable' protocol}} var counter : Int = 0 } actor BankAccount { private var curBalance : Int private var accountHolder : String = "unknown" // expected-note@+1 {{mutation of this property is only permitted within the actor}} var owner : String { get { accountHolder } set { accountHolder = newValue } } init(initialDeposit : Int) { curBalance = initialDeposit } func balance() -> Int { return curBalance } // expected-note@+1 {{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}} func deposit(_ amount : Int) -> Int { guard amount >= 0 else { return 0 } curBalance = curBalance + amount return curBalance } func canWithdraw(_ amount : Int) -> Bool { // call 'balance' from sync through self return self.balance() >= amount } func testSelfBalance() async { _ = await balance() // expected-warning {{no 'async' operations occur within 'await' expression}} } // returns the amount actually withdrawn func withdraw(_ amount : Int) -> Int { guard canWithdraw(amount) else { return 0 } curBalance = curBalance - amount return amount } // returns the balance of this account following the transfer func transferAll(from : BankAccount) async -> Int { // call sync methods on another actor let amountTaken = await from.withdraw(from.balance()) return deposit(amountTaken) } func greaterThan(other : BankAccount) async -> Bool { return await balance() > other.balance() } func testTransactions() { _ = deposit(withdraw(deposit(withdraw(balance())))) } func testThrowing() throws {} var effPropA : Box { get async { await asyncer() return Box() } } var effPropT : Box { get throws { try thrower() return Box() } } var effPropAT : Int { get async throws { await asyncer() try thrower() return 0 } } // expected-note@+1 2 {{add 'async' to function 'effPropertiesFromInsideActorInstance()' to make it asynchronous}} func effPropertiesFromInsideActorInstance() throws { // expected-error@+1{{'async' property access in a function that does not support concurrency}} _ = effPropA // expected-note@+4{{did you mean to handle error as optional value?}} // expected-note@+3{{did you mean to use 'try'?}} // expected-note@+2{{did you mean to disable error propagation?}} // expected-error@+1{{property access can throw but is not marked with 'try'}} _ = effPropT _ = try effPropT // expected-note@+6 {{did you mean to handle error as optional value?}} // expected-note@+5 {{did you mean to use 'try'?}} // expected-note@+4 {{did you mean to disable error propagation?}} // expected-error@+3 {{property access can throw but is not marked with 'try'}} // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(effPropT) // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(try effPropT) _ = try rethrower(effPropT) _ = try rethrower(thrower()) _ = try rethrower(try effPropT) _ = try rethrower(try thrower()) _ = rethrower(effPropA) // expected-error{{'async' property access in an autoclosure that does not support concurrency}} _ = asAutoclosure(effPropT) // expected-error{{property access can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}} // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{property access can throw but is not marked with 'try'}} // expected-error@+1{{'async' property access in a function that does not support concurrency}} _ = effPropAT } } // end actor func someAsyncFunc() async { let deposit1 = 120, deposit2 = 45 let a = BankAccount(initialDeposit: 0) let b = BankAccount(initialDeposit: deposit2) let _ = await a.deposit(deposit1) let afterXfer = await a.transferAll(from: b) let reportedBal = await a.balance() // check on account A guard afterXfer == (deposit1 + deposit2) && afterXfer == reportedBal else { print("BUG 1!") return } // check on account B guard await b.balance() == 0 else { print("BUG 2!") return } _ = await a.deposit(b.withdraw(a.deposit(b.withdraw(b.balance())))) // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{3-3=await }} expected-note@+1 {{call is 'async'}} a.testSelfBalance() await a.testThrowing() // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}} //////////// // effectful properties from outside the actor instance // expected-warning@+2 {{cannot use property 'effPropA' with a non-sendable type 'Box' across actors}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}} _ = a.effPropA // expected-warning@+3 {{cannot use property 'effPropT' with a non-sendable type 'Box' across actors}} // expected-error@+2{{property access can throw, but it is not marked with 'try' and the error is not handled}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}} _ = a.effPropT // expected-error@+2{{property access can throw, but it is not marked with 'try' and the error is not handled}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}} _ = a.effPropAT // (mostly) corrected ones _ = await a.effPropA // expected-warning {{cannot use property 'effPropA' with a non-sendable type 'Box' across actors}} _ = try! await a.effPropT // expected-warning {{cannot use property 'effPropT' with a non-sendable type 'Box' across actors}} _ = try? await a.effPropAT print("ok!") } ////////////////// // check for appropriate error messages ////////////////// extension BankAccount { func totalBalance(including other: BankAccount) async -> Int { //expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{12-12=await }} return balance() + other.balance() // expected-note{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}} } func breakAccounts(other: BankAccount) async { // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} _ = other.deposit( // expected-note{{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}} other.withdraw( // expected-note{{calls to instance method 'withdraw' from outside of its actor context are implicitly asynchronous}} self.deposit( other.withdraw( // expected-note{{calls to instance method 'withdraw' from outside of its actor context are implicitly asynchronous}} other.balance())))) // expected-note{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}} } } func anotherAsyncFunc() async { let a = BankAccount(initialDeposit: 34) let b = BankAccount(initialDeposit: 35) // expected-error@+2{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} // expected-note@+1{{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}} _ = a.deposit(1) // expected-error@+2{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} // expected-note@+1{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}} _ = b.balance() _ = b.balance // expected-error {{actor-isolated instance method 'balance()' can not be partially applied}} a.owner = "cat" // expected-error{{actor-isolated property 'owner' can not be mutated from a non-isolated context}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}} _ = b.owner _ = await b.owner == "cat" } func regularFunc() { let a = BankAccount(initialDeposit: 34) _ = a.deposit //expected-error{{actor-isolated instance method 'deposit' can not be partially applied}} _ = a.deposit(1) // expected-error{{actor-isolated instance method 'deposit' can not be referenced from a non-isolated context}} } actor TestActor {} @globalActor struct BananaActor { static var shared: TestActor { TestActor() } } @globalActor struct OrangeActor { static var shared: TestActor { TestActor() } } func blender(_ peeler : () -> Void) { peeler() } // expected-note@+2 {{var declared here}} // expected-note@+1 2 {{mutation of this var is only permitted within the actor}} @BananaActor var dollarsInBananaStand : Int = 250000 @BananaActor func wisk(_ something : Any) { } @BananaActor func peelBanana() { } @BananaActor func takeInout(_ x : inout Int) {} @OrangeActor func makeSmoothie() async { var money = await dollarsInBananaStand money -= 1200 dollarsInBananaStand = money // expected-error{{var 'dollarsInBananaStand' isolated to global actor 'BananaActor' can not be mutated from different global actor 'OrangeActor'}} // FIXME: these two errors seem a bit redundant. // expected-error@+2 {{actor-isolated var 'dollarsInBananaStand' cannot be passed 'inout' to implicitly 'async' function call}} // expected-error@+1 {{var 'dollarsInBananaStand' isolated to global actor 'BananaActor' can not be used 'inout' from different global actor 'OrangeActor'}} await takeInout(&dollarsInBananaStand) _ = wisk await wisk({}) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} await wisk(1) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} await (peelBanana)() await (((((peelBanana)))))() await (((wisk)))((wisk)((wisk)(1))) // expected-warning@-1 3{{cannot pass argument of non-sendable type 'Any' across actors}} blender((peelBanana)) // expected-error@-1{{converting function value of type '@BananaActor () -> ()' to '() -> Void' loses global actor 'BananaActor'}} await wisk(peelBanana) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} await wisk(wisk) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} await (((wisk)))(((wisk))) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} // expected-warning@+1 {{cannot pass argument of non-sendable type 'Any' across actors}} await {wisk}()(1) // expected-warning@+1 {{cannot pass argument of non-sendable type 'Any' across actors}} await (true ? wisk : {n in return})(1) } actor Chain { var next : Chain? } func walkChain(chain : Chain) async { // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 4 {{property access is 'async'}} _ = chain.next?.next?.next?.next // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 3 {{property access is 'async'}} _ = (await chain.next)?.next?.next?.next // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 2 {{property access is 'async'}} _ = (await chain.next?.next)?.next?.next } // want to make sure there is no note about implicitly async on this func. @BananaActor func rice() async {} @OrangeActor func quinoa() async { // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }} expected-note@+1 {{call is 'async'}} rice() } /////////// // check various curried applications to ensure we mark the right expression. actor Calculator { func addCurried(_ x : Int) -> ((Int) -> Int) { return { (_ y : Int) in x + y } } func add(_ x : Int, _ y : Int) -> Int { return x + y } } @BananaActor func bananaAdd(_ x : Int) -> ((Int) -> Int) { return { (_ y : Int) in x + y } } @OrangeActor func doSomething() async { let _ = (await bananaAdd(1))(2) // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let _ = await (await bananaAdd(1))(2) // expected-warning{{no 'async' operations occur within 'await' expression}} // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let calc = Calculator() let _ = (await calc.addCurried(1))(2) // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let _ = await (await calc.addCurried(1))(2) // expected-warning{{no 'async' operations occur within 'await' expression}} // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let plusOne = await calc.addCurried(await calc.add(0, 1)) // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let _ = plusOne(2) } /////// // Effectful properties isolated to a global actor @BananaActor var effPropA : Int { get async { await asyncer() try thrower() // expected-error{{errors thrown from here are not handled}} return 0 } } @BananaActor var effPropT : Int { // expected-note{{var declared here}} get throws { await asyncer() // expected-error{{'async' call in a function that does not support concurrency}} try thrower() return 0 } } @BananaActor var effPropAT : Int { get async throws { await asyncer() try thrower() return 0 } } // expected-note@+1 2 {{add 'async' to function 'tryEffPropsFromBanana()' to make it asynchronous}} @BananaActor func tryEffPropsFromBanana() throws { // expected-error@+1{{'async' property access in a function that does not support concurrency}} _ = effPropA // expected-note@+4{{did you mean to handle error as optional value?}} // expected-note@+3{{did you mean to use 'try'?}} // expected-note@+2{{did you mean to disable error propagation?}} // expected-error@+1{{property access can throw but is not marked with 'try'}} _ = effPropT _ = try effPropT // expected-note@+6 {{did you mean to handle error as optional value?}} // expected-note@+5 {{did you mean to use 'try'?}} // expected-note@+4 {{did you mean to disable error propagation?}} // expected-error@+3 {{property access can throw but is not marked with 'try'}} // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(effPropT) // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(try effPropT) _ = try rethrower(effPropT) _ = try rethrower(thrower()) _ = try rethrower(try effPropT) _ = try rethrower(try thrower()) _ = rethrower(effPropA) // expected-error{{'async' property access in an autoclosure that does not support concurrency}} _ = asAutoclosure(effPropT) // expected-error{{property access can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}} // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{property access can throw but is not marked with 'try'}} // expected-error@+1{{'async' property access in a function that does not support concurrency}} _ = effPropAT } // expected-note@+2 {{add '@BananaActor' to make global function 'tryEffPropsFromSync()' part of global actor 'BananaActor'}} // expected-note@+1 2 {{add 'async' to function 'tryEffPropsFromSync()' to make it asynchronous}} func tryEffPropsFromSync() { _ = effPropA // expected-error{{'async' property access in a function that does not support concurrency}} // expected-error@+1 {{property access can throw, but it is not marked with 'try' and the error is not handled}} _ = effPropT // expected-error{{var 'effPropT' isolated to global actor 'BananaActor' can not be referenced from this synchronous context}} // NOTE: that we don't complain about async access on `effPropT` because it's not declared async, and we're not in an async context! // expected-error@+1 {{property access can throw, but it is not marked with 'try' and the error is not handled}} _ = effPropAT // expected-error{{'async' property access in a function that does not support concurrency}} } @OrangeActor func tryEffPropertiesFromGlobalActor() async throws { // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}} _ = effPropA // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{property access can throw but is not marked with 'try'}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}} _ = effPropT // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{property access can throw but is not marked with 'try'}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}} _ = effPropAT _ = await effPropA _ = try? await effPropT _ = try! await effPropAT } ///////////// // check subscripts in actors actor SubscriptA { subscript(_ i : Int) -> Int { get async { try thrower() // expected-error{{errors thrown from here are not handled}} await asyncer() return 0 } } func f() async { // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{9-9=await }} expected-note@+1{{subscript access is 'async'}} _ = self[0] } } actor SubscriptT { subscript(_ i : Int) -> Int { get throws { try thrower() await asyncer() // expected-error{{'async' call in a function that does not support concurrency}} return 0 } } func f() throws { _ = try self[0] // expected-note@+6 {{did you mean to handle error as optional value?}} // expected-note@+5 {{did you mean to use 'try'?}} // expected-note@+4 {{did you mean to disable error propagation?}} // expected-error@+3 {{subscript access can throw but is not marked with 'try'}} // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(self[1]) // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(try self[1]) _ = try rethrower(self[1]) _ = try rethrower(try self[1]) } } actor SubscriptAT { subscript(_ i : Int) -> Int { get async throws { try thrower() await asyncer() return 0 } } func f() async throws { _ = try await self[0] } } func tryTheActorSubscripts(a : SubscriptA, t : SubscriptT, at : SubscriptAT) async throws { // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}} _ = a[0] _ = await a[0] // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{subscript access can throw but is not marked with 'try'}} // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}} _ = t[0] _ = try await t[0] _ = try! await t[0] _ = try? await t[0] // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{subscript access can throw but is not marked with 'try'}} // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}} _ = at[0] _ = try await at[0] }
37.677586
178
0.675239
671518d97cf870cc3820acaebfa240156e8f27a0
13,851
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 public final class WCDBTokenizerInfo: TokenizerInfoBase { public required init(withArgc argc: Int32, andArgv argv: UnsafePointer<UnsafePointer<Int8>?>?) {} } public final class WCDBCursorInfo: CursorInfoBase { private enum TokenType: UInt { case basicMultilingualPlaneLetter = 0x00000001 case basicMultilingualPlaneDigit = 0x00000002 case basicMultilingualPlaneSymbol = 0x00000003 case basicMultilingualPlaneOther = 0x0000FFFF case auxiliaryPlaneOther = 0xFFFFFFFF } private let input: UnsafePointer<Int8>! private let inputLength: Int32 private var position: Int32 = 0 private var startOffset: Int32 = 0 private var endOffset: Int32 = 0 private var cursor: Int32 = 0 private var cursorTokenType: TokenType? private var cursorTokenLength: Int32 = 0 private lazy var symbolCharacterSet: CFCharacterSet? = { var characterSet = CFCharacterSetCreateMutable(kCFAllocatorDefault) CFCharacterSetUnion(characterSet, CFCharacterSetGetPredefined(CFCharacterSetPredefinedSet.control)) CFCharacterSetUnion(characterSet, CFCharacterSetGetPredefined(CFCharacterSetPredefinedSet.whitespaceAndNewline)) CFCharacterSetUnion(characterSet, CFCharacterSetGetPredefined(CFCharacterSetPredefinedSet.nonBase)) CFCharacterSetUnion(characterSet, CFCharacterSetGetPredefined(CFCharacterSetPredefinedSet.punctuation)) CFCharacterSetUnion(characterSet, CFCharacterSetGetPredefined(CFCharacterSetPredefinedSet.symbol)) CFCharacterSetUnion(characterSet, CFCharacterSetGetPredefined(CFCharacterSetPredefinedSet.illegal)) return characterSet }() private var lemmaBuffer: [UInt8] = [] private var lemmaBufferLength: Int32 = 0 //>0 lemma is not empty private var subTokensLengthArray: [UInt8] = [] private var subTokensCursor: Int32 = 0 private var subTokensDoubleChar: Bool = false private var buffer: [UInt8] = [] private var bufferLength: Int32 = 0 public required init(withInput pInput: UnsafePointer<Int8>?, count: Int32, tokenizerInfo: TokenizerInfoBase) { input = pInput inputLength = count } func cursorStep() -> Int32 { guard cursor + cursorTokenLength < inputLength else { cursor = inputLength cursorTokenType = nil cursorTokenLength = 0 return SQLITE_OK } cursor += cursorTokenLength return cursorSetup() } func cursorSetup() -> Int32 { var rc = SQLITE_OK let first = UInt8(bitPattern: input.advanced(by: Int(cursor)).pointee) switch first { case ..<0xC0: cursorTokenLength = 1 switch first { case 0x30...0x39: cursorTokenType = .basicMultilingualPlaneDigit case 0x41...0x5a, 0x61...0x7a: cursorTokenType = .basicMultilingualPlaneLetter default: var result = false rc = isSymbol(unicodeChar: UInt16(first), result: &result) guard rc == SQLITE_OK else { return rc } cursorTokenType = result ? .basicMultilingualPlaneSymbol : .basicMultilingualPlaneOther } case ..<0xF0: var unicode: UInt16 = 0 switch first { case ..<0xE0: cursorTokenLength = 2 unicode = UInt16(first & 0x1F) default: cursorTokenLength = 3 unicode = UInt16(first & 0x0F) } for i in cursor+1..<cursor+cursorTokenLength { guard i < inputLength else { cursorTokenType = nil cursorTokenLength = inputLength - i return SQLITE_OK } unicode = (unicode << 6) | UInt16(UInt8(bitPattern: input.advanced(by: Int(i)).pointee) & 0x3F) } var result = false rc = isSymbol(unicodeChar: unicode, result: &result) guard rc == SQLITE_OK else { return rc } cursorTokenType = result ? .basicMultilingualPlaneSymbol : .basicMultilingualPlaneOther default: cursorTokenType = .auxiliaryPlaneOther switch first { case ..<0xF8: cursorTokenLength = 4 case ..<0xFC: cursorTokenLength = 5 default: cursorTokenLength = 6 } } return SQLITE_OK } func isSymbol(unicodeChar: UInt16, result: inout Bool) -> Int32 { guard let symbolCharacterSet = self.symbolCharacterSet else { return SQLITE_NOMEM } result = CFCharacterSetIsCharacterMember(symbolCharacterSet, unicodeChar) return SQLITE_OK } static let orthography = NSOrthography(dominantScript: "Latin", languageMap: [ "Latn": ["en"]]) func lemmatization(input: UnsafePointer<Int8>, inputLength: Int32) -> Int32 { if inputLength > buffer.count { buffer.expand(toNewSize: Int(inputLength)) } for i in 0..<Int(inputLength) { buffer[i] = UInt8(tolower(Int32(input.advanced(by: i).pointee))) } let optionalString = buffer.withUnsafeBytes { (bytes) -> String? in return String(bytes: bytes.baseAddress!.assumingMemoryBound(to: Int8.self), count: Int(inputLength), encoding: .ascii) } guard let string = optionalString else { return SQLITE_OK } var optionalLemma: String? = nil optionalLemma = string // string.enumerateLinguisticTags(in: string.startIndex..<string.endIndex, // scheme: NSLinguisticTagScheme.lemma.rawValue, // options: NSLinguisticTagger.Options.omitWhitespace, // orthography: WCDBCursorInfo.orthography, // invoking: { (tag, _, _, stop) in // optionalLemma = tag.lowercased() // stop = true // }) guard let lemma = optionalLemma, lemma.count > 0, lemma.caseInsensitiveCompare(string) != ComparisonResult.orderedSame else { return SQLITE_OK } lemmaBufferLength = Int32(lemma.count) if lemmaBufferLength > lemmaBuffer.capacity { lemmaBuffer.expand(toNewSize: Int(lemmaBufferLength)) } memcpy(&lemmaBuffer, lemma.cString, Int(lemmaBufferLength)) return SQLITE_OK } func subTokensStep() { self.startOffset = self.subTokensCursor self.bufferLength = Int32(self.subTokensLengthArray[0]) if self.subTokensDoubleChar { if self.subTokensLengthArray.count > 1 { self.bufferLength += Int32(self.subTokensLengthArray[1]) self.subTokensDoubleChar = false } else { self.subTokensLengthArray.removeAll() } } else { self.subTokensCursor += Int32(subTokensLengthArray[0]) self.subTokensLengthArray.removeFirst() self.subTokensDoubleChar = true } self.endOffset = self.startOffset + self.bufferLength } public func step(pToken: inout UnsafePointer<Int8>?, count: inout Int32, startOffset: inout Int32, endOffset: inout Int32, position: inout Int32) -> Int32 { var rc = SQLITE_OK if self.position == 0 { rc = cursorSetup() guard rc == SQLITE_OK else { return rc } } if self.lemmaBufferLength == 0 { if self.subTokensLengthArray.isEmpty { guard self.cursorTokenType != nil else { return SQLITE_DONE } //Skip symbol while self.cursorTokenType == .basicMultilingualPlaneSymbol { rc = cursorStep() guard rc == SQLITE_OK else { return rc } } guard let tokenType = self.cursorTokenType else { return SQLITE_DONE } switch tokenType { case .basicMultilingualPlaneLetter: fallthrough case .basicMultilingualPlaneDigit: self.startOffset = self.cursor repeat { rc = cursorStep() }while(rc == SQLITE_OK && self.cursorTokenType == tokenType) guard rc == SQLITE_OK else { return rc } self.endOffset = self.cursor self.bufferLength = self.endOffset - self.startOffset case .basicMultilingualPlaneOther: fallthrough case .auxiliaryPlaneOther: self.subTokensLengthArray.append(UInt8(self.cursorTokenLength)) self.subTokensCursor = self.cursor self.subTokensDoubleChar = true rc = cursorStep() while rc == SQLITE_OK && self.cursorTokenType == tokenType { self.subTokensLengthArray.append(UInt8(cursorTokenLength)) rc = cursorStep() } guard rc == SQLITE_OK else { return rc } subTokensStep() default: break } if tokenType == .basicMultilingualPlaneLetter { rc = lemmatization(input: self.input.advanced(by: Int(self.startOffset)), inputLength: self.bufferLength) guard rc == SQLITE_OK else { return rc } } else { if self.bufferLength > self.buffer.count { self.buffer.expand(toNewSize: Int(self.bufferLength)) } memcpy(&self.buffer, input.advanced(by: Int(self.startOffset)), Int(self.bufferLength)) } } else { subTokensStep() if self.bufferLength > self.buffer.capacity { self.buffer.expand(toNewSize: Int(self.bufferLength)) } memcpy(&self.buffer, input.advanced(by: Int(self.startOffset)), Int(self.bufferLength)) } pToken = self.buffer.withUnsafeBytes { (bytes) -> UnsafePointer<Int8> in return bytes.baseAddress!.assumingMemoryBound(to: Int8.self) } count = self.bufferLength } else { pToken = self.lemmaBuffer.withUnsafeBytes { (bytes) -> UnsafePointer<Int8> in return bytes.baseAddress!.assumingMemoryBound(to: Int8.self) } count = self.lemmaBufferLength self.lemmaBufferLength = 0 } startOffset = self.startOffset endOffset = self.endOffset self.position += 1 position = self.position return SQLITE_OK } } public final class WCDBModule: Module { public typealias TokenizerInfo = WCDBTokenizerInfo public typealias CursorInfo = WCDBCursorInfo public static let name = "WCDB" public private(set) static var module = sqlite3_tokenizer_module( iVersion: 0, xCreate: { (argc, argv, ppTokenizer) -> Int32 in return WCDBModule.create(argc: argc, argv: argv, ppTokenizer: ppTokenizer) }, xDestroy: { (pTokenizer) -> Int32 in return WCDBModule.destroy(pTokenizer: pTokenizer) }, xOpen: { (pTokenizer, pInput, nBytes, ppCursor) -> Int32 in return WCDBModule.open(pTokenizer: pTokenizer, pInput: pInput, nBytes: nBytes, ppCursor: ppCursor) }, xClose: { (pCursor) -> Int32 in return WCDBModule.close(pCursor: pCursor) }, xNext: { (pCursor, ppToken, pnBytes, piStartOffset, piEndOffset, piPosition) -> Int32 in return WCDBModule.next(pCursor: pCursor, ppToken: ppToken, pnBytes: pnBytes, piStartOffset: piStartOffset, piEndOffset: piEndOffset, piPosition: piPosition) }, xLanguageid: nil) public static let address = { () -> Data in var pointer = UnsafeMutableRawPointer(&module) return Data(bytes: &pointer, count: MemoryLayout.size(ofValue: pointer)) }() } extension Tokenize { public static let WCDB = Tokenize(module: WCDBModule.self) }
40.031792
120
0.572594
fe045dc3c58e9005ef3e570ab0e2818a7f8bf51a
248
import UIKit // Overriding methods class Dog { func makeNoise() { print("Woof!") } } class Poodle: Dog { override func makeNoise() { print("Yip!") } } let poppy = Poodle() poppy.makeNoise() // Result: "Yip!"
10.333333
31
0.556452
ac82345f2d04d573cedde567eca788cc258b74c0
7,579
// // ContainerController.swift // LNPopupControllerExample // // Created by Patrick BODET on 25/09/2018. // Copyright © 2018 Leo Natan. All rights reserved. // import UIKit public extension UIViewController{ public var containerController: ContainerController? { var current: UIViewController? = parent repeat { if current is ContainerController { return current as? ContainerController } current = current?.parent } while current != nil return nil } } public class ContainerController: UIViewController { let useConstraintsForBottomBar: Bool = true let useSafeAreaLayoutGuideForChild: Bool = true @IBOutlet weak var containerView: UIView! @IBOutlet weak var bottomBar: UIView! @IBOutlet weak var buttonsStackView: UIStackView! var viewControllers: [UIViewController?]! { didSet { for controller in viewControllers { if controller != nil { addChildViewController(controller!) } } } } var selectedIndex: Int = 0 var currentChildVC: UIViewController! override public func viewDidLoad() { super.viewDidLoad() self.viewControllers = [UIViewController]() buttonsStackView.alignment = .fill buttonsStackView.distribution = .fillEqually buttonsStackView.spacing = 0 for button in (self.buttonsStackView?.arrangedSubviews)! { (button as! UIButton).addTarget(self, action: #selector(self.tabButtonAction(button:)), for: .touchUpInside) } let childVC1 = self.storyboard?.instantiateViewController(withIdentifier: "ChildViewController") as? ChildViewController childVC1?.view.backgroundColor = LNRandomLightColor() let childVC2 = self.storyboard?.instantiateViewController(withIdentifier: "ChildViewController") as? ChildViewController childVC2?.view.backgroundColor = LNRandomLightColor() childVC2?.title = "ChildVC2" let nc = UINavigationController(rootViewController: childVC2!) nc.view.backgroundColor = childVC2?.view.backgroundColor let childVC3 = self.storyboard?.instantiateViewController(withIdentifier: "ChildViewController") as? ChildViewController childVC3?.view.backgroundColor = LNRandomLightColor() self.viewControllers = [childVC1, nc, childVC3] self.selectedIndex = 0 self.presentChild() print("childs: \(childViewControllers)") } func tabButtonAction(button: UIButton) { print("button: \(String(describing: button.currentTitle))") if let index = self.buttonsStackView.arrangedSubviews.index(of: button) { if index != self.selectedIndex { self.selectedIndex = index self.presentChild() } } } func presentChild() { if let childVC = self.viewControllers[selectedIndex] { self.containerView.addSubview(childVC.view) childVC.didMove(toParentViewController: self) self.currentChildVC?.willMove(toParentViewController: nil) self.currentChildVC?.view.removeFromSuperview() self.currentChildVC = childVC self.view.backgroundColor = currentChildVC.view.backgroundColor self.setupConstraintsForChildController() } } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if useConstraintsForBottomBar == true { self.setupConstraintsForBottomBar() } else { self.setupFrameForBottomBar() } self.setupConstraintsForButtonsStackView() self.setupConstraintsForContainerView() } func setupConstraintsForContainerView() { self.containerView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.containerView.topAnchor.constraint(equalTo:(self.view.topAnchor)), self.containerView.leftAnchor.constraint(equalTo: (self.view.leftAnchor)), self.containerView.rightAnchor.constraint(equalTo: (self.view.rightAnchor)), self.containerView.bottomAnchor.constraint(equalTo: (bottomBar.topAnchor)) ]) } func setupConstraintsForBottomBar() { var height: CGFloat = 50 if #available(iOS 11.0, *) { height += self.view.superview?.safeAreaInsets.bottom ?? 0.0 } NSLayoutConstraint.deactivate(self.bottomBar.constraints) self.bottomBar.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.bottomBar.leadingAnchor.constraint(equalTo: (self.view.leadingAnchor)), self.bottomBar.trailingAnchor.constraint(equalTo: (self.view.trailingAnchor)), self.bottomBar.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), self.bottomBar.heightAnchor.constraint(equalToConstant: height) ]) } func setupConstraintsForButtonsStackView() { self.buttonsStackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.buttonsStackView.topAnchor.constraint(equalTo: self.bottomBar.topAnchor), self.buttonsStackView.leadingAnchor.constraint(equalTo: self.bottomBar.leadingAnchor, constant: 0), self.buttonsStackView.trailingAnchor.constraint(equalTo: self.bottomBar.trailingAnchor, constant: 0), self.buttonsStackView.heightAnchor.constraint(equalToConstant: 50) ]) } func setupConstraintsForChildController() { currentChildVC.view.translatesAutoresizingMaskIntoConstraints = false if #available(iOS 11.0, *) { self.currentChildVC.view.leadingAnchor.constraint(equalTo: self.containerView.leadingAnchor).isActive = true self.currentChildVC.view.trailingAnchor.constraint(equalTo: self.containerView.trailingAnchor).isActive = true self.currentChildVC.view.topAnchor.constraint(equalTo: self.containerView.topAnchor).isActive = true if useSafeAreaLayoutGuideForChild == true { let guide = self.view.safeAreaLayoutGuide self.currentChildVC.view.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -50).isActive = true } else { self.currentChildVC.view.bottomAnchor.constraint(equalTo: self.containerView.bottomAnchor).isActive = true } } else { // Fallback on earlier versions self.currentChildVC.view.leadingAnchor.constraint(equalTo: self.containerView.leadingAnchor).isActive = true self.currentChildVC.view.trailingAnchor.constraint(equalTo: self.containerView.trailingAnchor).isActive = true self.currentChildVC.view.topAnchor.constraint(equalTo: self.containerView.topAnchor).isActive = true self.currentChildVC.view.bottomAnchor.constraint(equalTo: self.containerView.bottomAnchor).isActive = true } } func setupFrameForBottomBar() { var height: CGFloat = 50 if #available(iOS 11.0, *) { height += self.view.superview?.safeAreaInsets.bottom ?? 0.0 } self.bottomBar.frame = CGRect(x: 0, y: self.view.bounds.height - height, width: self.view.bounds.width, height: height) } }
41.642857
128
0.666843
75674a3a1b9dd7bb3d57d3e4743ff388a0cf816f
3,443
// // TableViewController.swift // TableViewSample // // Created by Carlos on 31/05/2017. // Copyright © 2017 Woowrale. All rights reserved. // import UIKit class TableViewController: UITableViewController { let fruits = ["Apple", "Orange", "Peper", "Strawverry"] let titleSection = ["Tamaños", "Cantidad"] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return fruits.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellTamanio = tableView.dequeueReusableCell(withIdentifier: "LabelCellTamanio", for: indexPath) cellTamanio.textLabel?.text = fruits[indexPath.row] return cellTamanio } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return titleSection[section] } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
34.089109
136
0.674412
abf29a9d631e5b5a1ff5fdaff479ba4a7981442c
10,949
// // ReceiveViewController.swift // breadwallet // // Created by Adrian Corscadden on 2016-11-30. // Copyright © 2016 breadwallet LLC. All rights reserved. // import UIKit private let qrSize: CGFloat = 186.0 private let smallButtonHeight: CGFloat = 32.0 private let buttonPadding: CGFloat = 20.0 private let smallSharePadding: CGFloat = 12.0 private let largeSharePadding: CGFloat = 20.0 typealias PresentShare = (String, UIImage) -> Void class ReceiveViewController : UIViewController, Subscriber { //MARK - Public var presentEmail: PresentShare? var presentText: PresentShare? init(wallet: BRWallet, store: Store, isRequestAmountVisible: Bool) { self.wallet = wallet self.isRequestAmountVisible = isRequestAmountVisible self.store = store super.init(nibName: nil, bundle: nil) } //MARK - Private private let qrCode = UIImageView() private let address = UILabel(font: .customBody(size: 14.0)) private let addressPopout = InViewAlert(type: .primary) private let share = ShadowButton(title: S.Receive.share, type: .tertiary, image: #imageLiteral(resourceName: "Share")) private let sharePopout = InViewAlert(type: .secondary) private let border = UIView() private let request = ShadowButton(title: S.Receive.request, type: .secondary) private let addressButton = UIButton(type: .system) private var topSharePopoutConstraint: NSLayoutConstraint? private let wallet: BRWallet private let store: Store private var balance: UInt64? = nil { didSet { if let newValue = balance, let oldValue = oldValue { if newValue > oldValue { setReceiveAddress() } } } } fileprivate let isRequestAmountVisible: Bool override func viewDidLoad() { addSubviews() addConstraints() setStyle() addActions() setupCopiedMessage() setupShareButtons() store.subscribe(self, selector: { $0.walletState.balance != $1.walletState.balance }, callback: { self.balance = $0.walletState.balance }) } private func addSubviews() { view.addSubview(qrCode) view.addSubview(address) view.addSubview(addressPopout) view.addSubview(share) view.addSubview(sharePopout) view.addSubview(border) view.addSubview(request) view.addSubview(addressButton) } private func addConstraints() { qrCode.constrain([ qrCode.constraint(.width, constant: qrSize), qrCode.constraint(.height, constant: qrSize), qrCode.constraint(.top, toView: view, constant: C.padding[4]), qrCode.constraint(.centerX, toView: view) ]) address.constrain([ address.constraint(toBottom: qrCode, constant: C.padding[1]), address.constraint(.centerX, toView: view) ]) addressPopout.heightConstraint = addressPopout.constraint(.height, constant: 0.0) addressPopout.constrain([ addressPopout.constraint(toBottom: address, constant: 0.0), addressPopout.constraint(.centerX, toView: view), addressPopout.constraint(.width, toView: view), addressPopout.heightConstraint ]) share.constrain([ share.constraint(toBottom: addressPopout, constant: C.padding[2]), share.constraint(.centerX, toView: view), share.constraint(.width, constant: qrSize), share.constraint(.height, constant: smallButtonHeight) ]) sharePopout.heightConstraint = sharePopout.constraint(.height, constant: 0.0) topSharePopoutConstraint = sharePopout.constraint(toBottom: share, constant: largeSharePadding) sharePopout.constrain([ topSharePopoutConstraint, sharePopout.constraint(.centerX, toView: view), sharePopout.constraint(.width, toView: view), sharePopout.heightConstraint ]) border.constrain([ border.constraint(.width, toView: view), border.constraint(toBottom: sharePopout, constant: 0.0), border.constraint(.centerX, toView: view), border.constraint(.height, constant: 1.0) ]) request.constrain([ request.constraint(toBottom: border, constant: C.padding[3]), request.constraint(.leading, toView: view, constant: C.padding[2]), request.constraint(.trailing, toView: view, constant: -C.padding[2]), request.constraint(.height, constant: C.Sizes.buttonHeight), request.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -C.padding[2]) ]) addressButton.constrain([ addressButton.leadingAnchor.constraint(equalTo: address.leadingAnchor, constant: -C.padding[1]), addressButton.topAnchor.constraint(equalTo: qrCode.topAnchor), addressButton.trailingAnchor.constraint(equalTo: address.trailingAnchor, constant: C.padding[1]), addressButton.bottomAnchor.constraint(equalTo: address.bottomAnchor, constant: C.padding[1]) ]) } private func setStyle() { view.backgroundColor = .white address.textColor = .grayTextTint border.backgroundColor = .secondaryBorder share.isToggleable = true if !isRequestAmountVisible { border.isHidden = true request.isHidden = true } sharePopout.clipsToBounds = true addressButton.setBackgroundImage(UIImage.imageForColor(.secondaryShadow), for: .highlighted) addressButton.layer.cornerRadius = 4.0 addressButton.layer.masksToBounds = true setReceiveAddress() } private func setReceiveAddress() { address.text = wallet.receiveAddress qrCode.image = UIImage.qrCode(data: "\(address.text!)".data(using: .utf8)!, color: CIColor(color: .black))? .resize(CGSize(width: qrSize, height: qrSize))! } private func addActions() { addressButton.tap = { [weak self] in self?.addressTapped() } request.tap = { [weak self] in guard let modalTransitionDelegate = self?.parent?.transitioningDelegate as? ModalTransitionDelegate else { return } modalTransitionDelegate.reset() self?.dismiss(animated: true, completion: { self?.store.perform(action: RootModalActions.Present(modal: .requestAmount)) }) } share.addTarget(self, action: #selector(ReceiveViewController.shareTapped), for: .touchUpInside) } private func setupCopiedMessage() { let copiedMessage = UILabel(font: .customMedium(size: 14.0)) copiedMessage.textColor = .white copiedMessage.text = S.Receive.copied copiedMessage.textAlignment = .center addressPopout.contentView = copiedMessage } private func setupShareButtons() { let container = UIView() container.translatesAutoresizingMaskIntoConstraints = false let email = ShadowButton(title: S.Receive.emailButton, type: .tertiary) let text = ShadowButton(title: S.Receive.textButton, type: .tertiary) container.addSubview(email) container.addSubview(text) email.constrain([ email.constraint(.leading, toView: container, constant: C.padding[2]), email.constraint(.top, toView: container, constant: buttonPadding), email.constraint(.bottom, toView: container, constant: -buttonPadding), email.trailingAnchor.constraint(equalTo: container.centerXAnchor, constant: -C.padding[1]) ]) text.constrain([ text.constraint(.trailing, toView: container, constant: -C.padding[2]), text.constraint(.top, toView: container, constant: buttonPadding), text.constraint(.bottom, toView: container, constant: -buttonPadding), text.leadingAnchor.constraint(equalTo: container.centerXAnchor, constant: C.padding[1]) ]) sharePopout.contentView = container email.addTarget(self, action: #selector(ReceiveViewController.emailTapped), for: .touchUpInside) text.addTarget(self, action: #selector(ReceiveViewController.textTapped), for: .touchUpInside) } @objc private func shareTapped() { toggle(alertView: sharePopout, shouldAdjustPadding: true) if addressPopout.isExpanded { toggle(alertView: addressPopout, shouldAdjustPadding: false) } } @objc private func addressTapped() { guard let text = address.text else { return } UIPasteboard.general.string = text toggle(alertView: addressPopout, shouldAdjustPadding: false, shouldShrinkAfter: true) if sharePopout.isExpanded { toggle(alertView: sharePopout, shouldAdjustPadding: true) } } @objc private func emailTapped() { presentEmail?(address.text!, qrCode.image!) } @objc private func textTapped() { presentText?(address.text!, qrCode.image!) } private func toggle(alertView: InViewAlert, shouldAdjustPadding: Bool, shouldShrinkAfter: Bool = false) { share.isEnabled = false address.isUserInteractionEnabled = false var deltaY = alertView.isExpanded ? -alertView.height : alertView.height if shouldAdjustPadding { if deltaY > 0 { deltaY -= (largeSharePadding - smallSharePadding) } else { deltaY += (largeSharePadding - smallSharePadding) } } if alertView.isExpanded { alertView.contentView?.isHidden = true } UIView.spring(C.animationDuration, animations: { if shouldAdjustPadding { let newPadding = self.sharePopout.isExpanded ? largeSharePadding : smallSharePadding self.topSharePopoutConstraint?.constant = newPadding } alertView.toggle() self.parent?.view.layoutIfNeeded() }, completion: { _ in alertView.isExpanded = !alertView.isExpanded self.share.isEnabled = true self.address.isUserInteractionEnabled = true alertView.contentView?.isHidden = false if shouldShrinkAfter { DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: { if alertView.isExpanded { self.toggle(alertView: alertView, shouldAdjustPadding: shouldAdjustPadding) } }) } }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ReceiveViewController : ModalDisplayable { var faqArticleId: String? { return ArticleIds.receiveBitcoin } var modalTitle: String { return S.Receive.title } }
41.161654
127
0.64773
16ffe64f16552501c0b502550d1e07091f108f2d
934
// // PHAssetCollection+Extension.swift // Pellicola // // Created by Andrea Antonioni on 16/01/2018. // import Foundation import Photos extension PHAssetCollection { class func fetch(withType albumType: AlbumType) -> [PHAssetCollection] { var allAlbums: [PHAssetCollection] = [] //PHAssetCollection doesn't currently allow fetching for multiple subtypes at once, thus we should perform multiple fetches and merge results. //This is also the main reason for returning [PHAssetCollection] instead of PHFetchResult (which should have better performances). albumType.subtypes.forEach { subtype in let fetchResult = PHAssetCollection.fetchAssetCollections(with: albumType.type, subtype: subtype, options: nil) let albums = fetchResult.objects(at: IndexSet(0..<fetchResult.count)) allAlbums += albums } return allAlbums } }
35.923077
150
0.695931
e4ac78c0d0983dab5f9e1fd4eb07de09959344fc
971
// // Corona-Warn-App // // SAP SE and all other contributors // copyright owners license this file to you under the Apache // License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // import UIKit protocol WarnOthersRemindable { var hasPositiveTestResult: Bool { get set } var notificationOneTimeInterval: TimeInterval { get set } var notificationTwoTimeInterval: TimeInterval { get set } func evaluateNotificationState(testResult: TestResult) func reset() func cancelNotifications() }
29.424242
62
0.755922
e904c1ec14643f3d146225396e1fdb715d7333b4
6,301
/* * Copyright (c) 2016 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. * * 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 enum RingIndex : Int { case inner = 0 case middle = 1 case outer = 2 } public let RingCompletedNotification = "RingCompletedNotification" public let AllRingsCompletedNotification = "AllRingsCompletedNotification" @IBDesignable public class ThreeRingView : UIView { fileprivate let rings : [RingIndex : RingLayer] = [.inner : RingLayer(), .middle : RingLayer(), .outer : RingLayer()] fileprivate let ringColors = [UIColor.hrPinkColor, UIColor.hrGreenColor, UIColor.hrBlueColor] override init(frame: CGRect) { super.init(frame: frame) sharedInitialization() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInitialization() } override public func layoutSubviews() { super.layoutSubviews() drawLayers() } fileprivate func sharedInitialization() { backgroundColor = UIColor.black for (_, ring) in rings { layer.addSublayer(ring) ring.backgroundColor = UIColor.clear.cgColor ring.ringBackgroundColor = ringBackgroundColor.cgColor ring.ringWidth = ringWidth } // Set the default values for (index, ring) in rings { setColorForRing(index, color: ringColors[index.rawValue]) ring.value = 0.0 } } fileprivate func drawLayers() { let size = min(bounds.width, bounds.height) let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) for (index, ring) in rings { // Sort sizes let curSize = size - CGFloat(index.rawValue) * ( ringWidth + ringPadding ) * 2.0 ring.bounds = CGRect(x: 0, y: 0, width: curSize, height: curSize) ring.position = center } } //: API Properties @IBInspectable public var ringWidth : CGFloat = 20.0 { didSet { drawLayers() for (_, ring) in rings { ring.ringWidth = ringWidth } } } @IBInspectable public var ringPadding : CGFloat = 1.0 { didSet { drawLayers() } } @IBInspectable public var ringBackgroundColor : UIColor = UIColor.darkGray { didSet { for (_, ring) in rings { ring.ringBackgroundColor = ringBackgroundColor.cgColor } } } var animationDuration : TimeInterval = 1.5 } //: Values extension ThreeRingView { @IBInspectable public var innerRingValue : CGFloat { get { return rings[.inner]?.value ?? 0 } set(newValue) { maybePostNotification(innerRingValue, new: newValue, current: .inner) setValueOnRing(.inner, value: newValue, animated: false) } } @IBInspectable public var middleRingValue : CGFloat { get { return rings[.middle]?.value ?? 0 } set(newValue) { maybePostNotification(middleRingValue, new: newValue, current: .middle) setValueOnRing(.middle, value: newValue, animated: false) } } @IBInspectable public var outerRingValue : CGFloat { get { return rings[.outer]?.value ?? 0 } set(newValue) { maybePostNotification(outerRingValue, new: newValue, current: .outer) setValueOnRing(.outer, value: newValue, animated: false) } } func setValueOnRing(_ ringIndex: RingIndex, value: CGFloat, animated: Bool = false) { CATransaction.begin() CATransaction.setAnimationDuration(animationDuration) rings[ringIndex]?.setValue(value, animated: animated) CATransaction.commit() } fileprivate func maybePostNotification(_ old: CGFloat, new: CGFloat, current: RingIndex) { if old < 1 && new >= 1 { //threshold crossed let allDone: Bool switch(current) { case .inner: allDone = outerRingValue >= 1 && middleRingValue >= 1 case .middle: allDone = innerRingValue >= 1 && outerRingValue >= 1 case .outer: allDone = innerRingValue >= 1 && middleRingValue >= 1 } if allDone { postAllRingsCompletedNotification() } else { postRingCompletedNotification() } } } fileprivate func postAllRingsCompletedNotification() { NotificationCenter.default.post(name: Notification.Name(rawValue: AllRingsCompletedNotification), object: self) } fileprivate func postRingCompletedNotification() { NotificationCenter.default.post(name: Notification.Name(rawValue: RingCompletedNotification), object: self) } } //: Colors extension ThreeRingView { @IBInspectable public var innerRingColor : UIColor { get { return colorForRing(.inner) } set(newColor) { setColorForRing(.inner, color: newColor) } } @IBInspectable public var middleRingColor : UIColor { get { return UIColor.clear } set(newColor) { setColorForRing(.middle, color: newColor) } } @IBInspectable public var outerRingColor : UIColor { get { return UIColor.clear } set(newColor) { setColorForRing(.outer, color: newColor) } } fileprivate func colorForRing(_ index: RingIndex) -> UIColor { return UIColor(cgColor: rings[index]!.ringColors.0) } fileprivate func setColorForRing(_ index: RingIndex, color: UIColor) { rings[index]?.ringColors = (color.cgColor, color.darkerColor.cgColor) } }
29.171296
119
0.679257
4ad8c405849499d75a31b1f844b7e173018326b9
518
// // ListPresenter.swift // VIPtest // // Created by Eduard Panasiuk on 8/12/16. // Copyright © 2016 somedev. All rights reserved. // import Foundation protocol ListPresenterInput:class { func update(_ data:Array<Employee>?) } class ListPresenter: ListPresenterInput { weak var view:ListViewInput? func update(_ data:Array<Employee>?) { guard let data = data else { view?.showError("error") return } view?.updateWithData(data) } }
19.185185
50
0.619691
d74b5503019e1bf3f3f65f929c9505257517caf8
375
import XCTest @testable import ImagePickerView final class ImagePickerViewTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. } static var allTests = [ ("testExample", testExample), ] }
23.4375
87
0.648
09f92277c8f75f2c88af786b699323d762268a1f
1,046
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "NetworkManager", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "NetworkManager", targets: ["NetworkManager"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "NetworkManager", dependencies: []), .testTarget( name: "NetworkManagerTests", dependencies: ["NetworkManager"]), ] )
36.068966
117
0.630019
ebac072056f2ef168011dc6bed8ef15d9b2d6652
2,149
// // AppDelegate.swift // xSchedule-ios // // Created by Clinton Buie on 1/10/16. // Copyright © 2016 Clinton Buie. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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.723404
285
0.753839
79e015949660356634a1d5210e93e287836611d3
4,751
// // ViewController.swift // NotToDoListV3 // // Created by arturo ho on 8/6/17. // Copyright © 2017 Micajuine App Team. All rights reserved. // import UIKit //UIViewController is parent of UIcollectionViewController, Datasource handles what goes in the cells and delegate handles when cells are touched class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{ let toDoListCellid = "toDoListCellid" let notToDoListCellid = "notToDoListCellid" //Add pageCtonroller let pageController: UIPageControl = { let pc = UIPageControl() pc.pageIndicatorTintColor = UIColor.lightGray pc.currentPageIndicatorTintColor = UIColor.darkGray pc.numberOfPages = 2 return pc }() //Add in a collection view lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.backgroundColor = UIColor.purple cv.delegate = self cv.dataSource = self cv.isPagingEnabled = true return cv }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.red navigationController?.navigationBar.barTintColor = UIColor.white registerCells() setupViews() //Perhaps this should be frame = navagationframe something like that collectionView.frame = view.frame } fileprivate func registerCells() { collectionView.register(ToDoListCell.self, forCellWithReuseIdentifier: toDoListCellid) collectionView.register(NotToDoListCell.self, forCellWithReuseIdentifier: notToDoListCellid) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if (indexPath.item == 0) { let toDoCell = collectionView.dequeueReusableCell(withReuseIdentifier: toDoListCellid, for: indexPath) return toDoCell } else { let notToDoCell = collectionView.dequeueReusableCell(withReuseIdentifier: notToDoListCellid, for: indexPath) return notToDoCell } } //Size of the Cells (we want it to fit the entire screen) func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: view.frame.height-64) } //Control the current page for the page contorller, as well as the navagation bar title. func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let pageNumber = Int(targetContentOffset.pointee.x / view.frame.width) pageController.currentPage = pageNumber if (pageNumber == 0) { navigationItem.title = "To Do List" } else { navigationItem.title = "Not To Do List" } } func setupViews() { view.addSubview(collectionView) view.addSubview(pageController) pageController.translatesAutoresizingMaskIntoConstraints = false collectionView.translatesAutoresizingMaskIntoConstraints = false //ios9 constraints x,y,w,h collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true collectionView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true collectionView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true pageController.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true pageController.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true pageController.widthAnchor.constraint(equalToConstant: 40).isActive = true pageController.heightAnchor.constraint(equalToConstant: 20).isActive = true navigationItem.title = "To Do List" } // override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { // // print ("hello") // collectionView.performBatchUpdates(nil, completion: nil) // } }
35.721805
160
0.684277
f76f773afae6bb4154213dc48f1f5903a9d094f2
1,686
// // CountryCell.swift // ScubaCalendar // // Created by Mahipalsinh on 10/29/17. // Copyright © 2017 CodzGarage. All rights reserved. // import UIKit import Kingfisher class CountryCell: UICollectionViewCell { @IBOutlet weak var imgCountry: UIImageView! @IBOutlet weak var lblCountryName: UILabel! override func awakeFromNib() { super.awakeFromNib() imgCountry.alpha = 0.5 lblCountryName.font = CommonMethods.SetFont.RalewaySemiBold?.withSize(CGFloat(CommonMethods.SetFontSize.S12)) lblCountryName.textColor = CommonMethods.SetColor.darkGrayColor } func updateUI(countryData: CountryModel) { lblCountryName.text = countryData.getCountryName imgCountry.kf.indicatorType = .activity let urlAnimal = URL(string: APIList.strBaseUrl+countryData.getCountryMap)! imgCountry.kf.setImage(with: urlAnimal, placeholder: #imageLiteral(resourceName: "logo")) selectedCEllUI(isSelected: countryData.getIsSelected) } func selectedCEllUI(isSelected: Bool) { if isSelected == true { imgCountry.alpha = 1.0 lblCountryName.font = CommonMethods.SetFont.RalewaySemiBold?.withSize(CGFloat(CommonMethods.SetFontSize.S17)) lblCountryName.textColor = CommonMethods.SetColor.whiteColor } else { imgCountry.alpha = 0.5 lblCountryName.font = CommonMethods.SetFont.RalewaySemiBold?.withSize(CGFloat(CommonMethods.SetFontSize.S12)) lblCountryName.textColor = CommonMethods.SetColor.darkGrayColor } } }
31.222222
121
0.66548
9b39357d9c3222b9c7ce9ced6c4b2c083288b2f6
3,524
// // SongListViewController.swift // CocoaSwiftPlayer // // Created by Harry Ng on 5/2/2016. // Copyright © 2016 STAY REAL. All rights reserved. // import Cocoa import RealmSwift class SongListViewController: NSViewController { dynamic var songs: [Song] = [] @IBOutlet weak var tableView: NSTableView! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. print("SongListViewController viewDidLoad") let defaults = NSUserDefaults.standardUserDefaults() if !defaults.boolForKey("APP_LAUNCHED") { let songManager = SongManager() try! songManager.importSongs() defaults.setBool(true, forKey: "APP_LAUNCHED") } let realm = try! Realm() let result = realm.objects(Song) songs = result.map { song in return song } tableView.doubleAction = "doubleClick:" tableView.setDataSource(self) let menu = NSMenu() menu.addItem(NSMenuItem(title: "Delete", action: "deleteSongs:", keyEquivalent: "")) tableView.menu = menu NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeSong:", name: Constants.Notifications.ChangeSong, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchPlaylist:", name: Constants.Notifications.SwitchPlaylist, object: nil) } func doubleClick(sender: NSTableView) { let manager = PlayerManager.sharedManager if tableView.selectedRow != -1 { manager.currentPlayList = songs manager.currentSong = songs[tableView.selectedRow] } manager.play() } func deleteSongs(sender: AnyObject) { let songsMutableArray = NSMutableArray(array: songs) let toBeDeletedSongs = songsMutableArray.objectsAtIndexes(tableView.selectedRowIndexes) as? [Song] songsMutableArray.removeObjectsAtIndexes(tableView.selectedRowIndexes) if let mutableArray = songsMutableArray as AnyObject as? [Song] { songs = mutableArray tableView.reloadData() } if let songs = toBeDeletedSongs { for song in songs { song.delete() } } } // MARK: - Notification func changeSong(notification: NSNotification) { guard let song = notification.userInfo?[Constants.NotificationUserInfos.Song] as? Song else { return } let index = songs.indexOf { s in return s.location == song.location } if let index = index { tableView.selectRowIndexes(NSIndexSet(index: index), byExtendingSelection: false) tableView.scrollRowToVisible(index) } } func switchPlaylist(notification: NSNotification) { guard let playlist = notification.userInfo?[Constants.NotificationUserInfos.Playlist] as? Playlist else { return } songs = playlist.songs.map { song in return song } tableView.reloadData() } } extension SongListViewController: NSTableViewDataSource { func tableView(tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { let song = songs[row] let pbItem = NSPasteboardItem() pbItem.setString(song.location, forType: NSPasteboardTypeString) return pbItem } }
32.036364
150
0.626844
612de8c5075787951aedfe7a1f1a25eab9fc7b4d
3,888
// // NetworkAPITokenAuthenticator.swift // Network // // Copyright © 2020 E-SOFT, OOO. All rights reserved. // import Foundation import RxCocoa import RxSwift public class NetworkAPITokenAuthenticator: NetworkAPIAuthenticator { private var isRenewingToken = false private let currentToken = BehaviorRelay<String?>(value: nil) private let tokenHeaderName: String private let getCurrentToken: () -> String? private let renewToken: () -> Single<String> private let shouldRenewToken: (URLRequest, HTTPURLResponse, Data?) -> Bool private let logger: NetworkAPITokenAuthenticatorLogger? public init(tokenHeaderName: String, getCurrentToken: @escaping () -> String?, renewToken: @escaping () -> Single<String>, shouldRenewToken: @escaping(URLRequest, HTTPURLResponse, Data?) -> Bool = { _, _, _ in true }, logger: NetworkAPITokenAuthenticatorLogger? = nil) { self.tokenHeaderName = tokenHeaderName self.getCurrentToken = getCurrentToken self.renewToken = renewToken self.shouldRenewToken = shouldRenewToken self.logger = logger } func requestWithNewToken(session: Reactive<URLSession>, request: URLRequest, newToken: String) -> Single<Data> { logger?.log(state: .retryingRequestWithNewToken) var newRequest = request newRequest.setValue(newToken, forHTTPHeaderField: tokenHeaderName) return session.fetch(newRequest) .map { $0.data } .asSingle() } public func authenticate(session: Reactive<URLSession>, request: URLRequest, response: HTTPURLResponse, data: Data?) -> Single<Data>? { logger?.log(state: .invoked) guard response.statusCode == 401, getCurrentToken() != nil else { response.statusCode == 401 ? logger?.log(state: .skippedHandlingBecauseOfMissingToken) : logger?.log(state: .skippedHandlingBecauseOfWrongErrorCode(response.statusCode)) return nil } if !shouldRenewToken(request, response, data) { logger?.log(state: .skippedHandlingBecauseOfBusinessLogic) return nil } if isRenewingToken { logger?.log(state: .waitingForTokenRenewWhichIsInProgress) return currentToken .filter { $0 != nil } .map { $0! } .take(1) .asSingle() .flatMap { [weak self] token in guard let self = self else { return Single.error(NetworkAPIError.unknown) } self.logger?.log(state: .finishedWaitingForTokenRenew) return self.requestWithNewToken(session: session, request: request, newToken: token) } } logger?.log(state: .startedTokenRefresh) setNewToken(token: nil, isRenewing: true) return renewToken() .catchError { [weak self] error in guard let self = self else { return Single.error(NetworkAPIError.unknown) } self.logger?.log(state: .tokenRenewError(error)) self.setNewToken(token: nil, isRenewing: false) let httpError = NetworkAPIError.httpError(request: request, response: response, data: data ?? Data()) return Single.error(httpError) }.flatMap { [weak self] newToken in guard let self = self else { return Single.error(NetworkAPIError.unknown) } self.setNewToken(token: newToken, isRenewing: false) self.logger?.log(state: .tokenRenewSucceeded) return self.requestWithNewToken(session: session, request: request, newToken: newToken) } } func setNewToken(token: String?, isRenewing: Bool) { if currentToken.value == nil && token != nil || currentToken.value != nil && token != nil { isRenewingToken = false } else { isRenewingToken = isRenewing } currentToken.accept(token) } }
34.105263
137
0.654321
e43d1e9082677ee5da27436a23d052873d8613fa
410
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "CouchbaseLiteSwift", platforms: [ .iOS(.v9), .macOS(.v10_11) ], products: [ .library( name: "CouchbaseLiteSwift", targets: ["CouchbaseLiteSwift"]) ], targets: [ .target( name: "CouchbaseLiteSwift", path: "Swift" ) ] )
19.52381
44
0.519512
20235c3a50091bf0243cf4611c3359c1bcca307f
1,019
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 UIKit public struct PageIndicatorUIViewModel { public let numberOfPages: Int public let currentPage: Int } public protocol PageIndicatorUIView: AnyObject { var outputReceiver: PageIndicatorOutput? { get set } var model: PageIndicatorUIViewModel? { get set } } public protocol PageIndicatorOutput: AnyObject { func swipeToPage(at index: Int) }
30.878788
75
0.750736
03e9a688f6dc6cdc0a76e27189a466126938c39f
232
// // Monoid.swift // Pods // // Created by José Manuel Sánchez Peñarroja on 3/6/16. // // import Foundation public protocol Monoid { static var unit: Self { get } static func combine(_ left: Self, _ right: Self) -> Self }
14.5
57
0.655172
e52923adb18ec4f6c8decb9f93ba7bcef3bde231
973
// // DiceAppTests.swift // DiceAppTests // // Created by Aaron Caines on 03/07/2017. // Copyright © 2017 Aaron Caines. All rights reserved. // import XCTest @testable import DiceApp class DiceAppTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.297297
111
0.633094
de625a15cafac5c281d10c4cf7ffc329207fb670
24,973
// // UIView+Layout.swift // ResearchUI // // Copyright © 2017 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit extension CGFloat { /// Occasionally we do want UI elements to be a little bigger or wider on bigger screens, /// such as with label widths. This can be used to increase values based on screen size. It /// uses the small screen (320 wide) as a baseline. This is a much simpler alternative to /// defining a matrix with screen sizes and constants and achieves much the same result /// - parameter max: A maximum size to apply to the returned value. public func rsd_proportionalToScreenWidth(max: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGFloat { let baseline = CGFloat(320.0) let ret = ceil((UIScreen.main.bounds.size.width / baseline) * self) return ret < max ? ret : max } /// Occasionally we want padding to be a little bigger or longer on bigger screens. /// This can be used to increase values based on screen size. It uses the small screen /// (568 high) as a baseline. This is a much simpler alternative to defining a matrix /// with screen sizes and constants and achieves much the same result. /// - parameter max: A maximum size to apply to the returned value. public func rsd_proportionalToScreenHeight(max: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGFloat { let baseline = CGFloat(568.0) let ret = ceil((UIScreen.main.bounds.size.height / baseline) * self) return ret < max ? ret : max } /// Occasionally we want padding to be a little bigger or longer on bigger screens. /// This method will apply the `multiplier` if and only if this is an iPad. /// - note: This does not check the size class of the view. /// - parameter multiplier: The value to multiply by if this is an iPad. public func rsd_iPadMultiplier(_ multiplier: CGFloat) -> CGFloat { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { return self * multiplier } else { return self } } } extension UIView { /// A convenience method to align all edges of the view to the edges of another view. Note: this method /// does not use the 'margin' attributes, such as .topMargin, but uses the 'edge' attributes, such as .top /// /// - parameters: /// - relation: The 'NSLayoutRelation' to apply to all constraints. /// - view: The 'UIView' to which the view will be aligned. /// - padding: The padding (or inset) to be applied to each constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignAll(_ relation: NSLayoutConstraint.Relation, to view: UIView!, padding: CGFloat) -> [NSLayoutConstraint] { let attributes: [NSLayoutConstraint.Attribute] = [.leading, .top, .trailing, .bottom] return rsd_align(attributes, relation, to: view, attributes, padding: padding) } /// A convenience method to align all edges of the view to the edges of another view. Note: this method /// uses the 'margin' attributes, such as .topMargin, and not the 'edge' attributes, such as .top /// /// - parameters: /// - relation: The 'NSLayoutRelation' to apply to all constraints. /// - view: The 'UIView' to which the view will be aligned. /// - padding: The padding (or inset) to be applied to each constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignAllMargins(_ relation: NSLayoutConstraint.Relation, to view: UIView!, padding: CGFloat) -> [NSLayoutConstraint] { let attributes: [NSLayoutConstraint.Attribute] = [.leadingMargin, .topMargin, .trailingMargin, .bottomMargin] return rsd_align(attributes, relation, to: view, attributes, padding: padding) } /// A convenience method to align an array of attributes of the view to the same attributes of it's superview. /// /// - parameters: /// - attribute: The 'NSLayoutAttribute' to align to the view's superview. /// - padding: The padding (or inset) to be applied to the constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignToSuperview(_ attributes: [NSLayoutConstraint.Attribute], padding: CGFloat, priority: UILayoutPriority = UILayoutPriority(1000.0)) -> [NSLayoutConstraint] { return rsd_align(attributes, .equal, to: self.superview, attributes, padding: padding, priority: priority) } /// A convenience method to align all edges of the view to the edges of its superview. Note: this method /// does not use the 'margin' attributes, such as .topMargin, but uses the 'edge' attributes, such as .top /// /// - parameter padding: The padding (or inset) to be applied to each constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignAllToSuperview(padding: CGFloat) -> [NSLayoutConstraint] { return rsd_alignAll(.equal, to: self.superview, padding: padding) } /// A convenience method to align all edges of the view to the edges of its superview. Note: this method /// does not use the 'margin' attributes, such as .topMargin, but uses the 'edge' attributes, such as .top /// /// - parameter padding: The padding (or inset) to be applied to each constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignAllMarginsToSuperview(padding: CGFloat) -> [NSLayoutConstraint] { return rsd_alignAllMargins(.equal, to: self.superview, padding: padding) } /// A convenience method to position the view below another view. /// /// - parameters: /// - view: The 'UIView' to which the view will be aligned. /// - padding: The padding (or inset) to be applied to the constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignBelow(view: UIView, padding: CGFloat, priority: UILayoutPriority = UILayoutPriority(1000.0)) -> [NSLayoutConstraint] { return rsd_align([.top], .equal, to: view, [.bottom], padding: padding, priority: priority) } /// A convenience method to position the view above another view. /// /// - parameters: /// - view: The 'UIView' to which the view will be aligned. /// - padding: The padding (or inset) to be applied to the constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignAbove(view: UIView, padding: CGFloat, priority: UILayoutPriority = UILayoutPriority(1000.0)) -> [NSLayoutConstraint] { return rsd_align([.bottom], .equal, to: view, [.top], padding: padding, priority: priority) } /// A convenience method to position the view to the left of another view. /// /// - parameters: /// - view: The 'UIView' to which the view will be aligned. /// - padding: The padding (or inset) to be applied to the constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignLeftOf(view: UIView, padding: CGFloat, priority: UILayoutPriority = UILayoutPriority(1000.0)) -> [NSLayoutConstraint] { return rsd_align([.trailing], .equal, to: view, [.leading], padding: padding, priority: priority) } ///A convenience method to position the view to the right of another view. /// /// - parameters: /// - view: The 'UIView' to which the view will be aligned. /// - padding: The padding (or inset) to be applied to the constraint. /// - priority: The layout priority of the constraint. By default, this is `1000`. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignRightOf(view: UIView, padding: CGFloat, priority: UILayoutPriority = UILayoutPriority(1000.0)) -> [NSLayoutConstraint] { return rsd_align([.leading], .equal, to: view, [.trailing], padding: padding, priority: priority) } /// A convenience method to create a NSLayoutConstraint for the purpose of aligning views within /// their 'superview'. As such, the view must have a 'superview'. /// /// - parameters: /// - attributes: An array of 'NSLayoutAttribute' to be applied to the 'firstItem' (self) in the constraints. /// - relation: The 'NSLayoutRelation' used for the constraint. /// - view: The 'UIView' that the view is being constrained to. /// - toAttributes: An array of 'NSLayoutAttribute' to be applied to the 'secondItem' (to View) in the constraints. /// - padding: The padding (or inset) to be applied to the constraints. /// - priority: The layout priority of the constraint. By default, this is `1000`. /// - returns: The layout constraints that were added. @discardableResult public func rsd_align(_ attributes: [NSLayoutConstraint.Attribute]!, _ relation: NSLayoutConstraint.Relation, to view:UIView!, _ toAttributes: [NSLayoutConstraint.Attribute]!, padding: CGFloat, priority: UILayoutPriority = UILayoutPriority(1000.0)) -> [NSLayoutConstraint] { guard let superview = self.superview else { assertionFailure("Trying to set constraints without first setting superview") return [] } guard attributes.count > 0 else { assertionFailure("'attributes' must contain at least one 'NSLayoutAttribute'") return [] } guard attributes.count == toAttributes.count else { assertionFailure("The number of 'attributes' must match the number of 'toAttributes'") return [] } var constraints: [NSLayoutConstraint] = [] attributes.forEach({ let toAttribute = toAttributes[attributes.firstIndex(of: $0)!] let _padding = $0 == .trailing || $0 == .bottom ? -1 * padding : padding let constraint = NSLayoutConstraint(item: self, attribute: $0, relatedBy: relation, toItem: view, attribute: toAttribute, multiplier: 1.0, constant: _padding) constraint.priority = priority constraints.append(constraint) superview.addConstraint(constraint) }) return constraints } /// A convenience method to center the view vertically within its 'superview'. The view must have /// a 'superview'. /// - parameter padding: The padding (or offset from center) to be applied to the constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignCenterVertical(padding: CGFloat) -> [NSLayoutConstraint] { guard let superview = self.superview else { assertionFailure("Trying to set constraints without first setting superview") return [] } let constraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: superview, attribute: .centerY, multiplier: 1.0, constant: padding) superview.addConstraint(constraint) return [constraint] } /// A convenience method to center the view horizontally within it's 'superview'. The view must have /// a 'superview'. /// - parameter padding: The padding (or offset from center) to be applied to the constraint. /// - returns: The layout constraints that were added. @discardableResult public func rsd_alignCenterHorizontal(padding: CGFloat) -> [NSLayoutConstraint] { guard let superview = self.superview else { assertionFailure("Trying to set constraints without first setting superview") return [] } let constraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: superview, attribute: .centerX, multiplier: 1.0, constant: padding) superview.addConstraint(constraint) return [constraint] } /// A convenience method to constrain the view's width. /// /// - parameters: /// - relation: The 'NSLayoutRelation' used in the constraint. /// - width: A 'CGFloat' constant for the width. /// - priority: The layout priority of the constraint. By default, this is `1000`. /// - returns: The layout constraints that were added. @discardableResult public func rsd_makeWidth(_ relation: NSLayoutConstraint.Relation, _ width : CGFloat, priority: UILayoutPriority = UILayoutPriority(1000.0)) -> [NSLayoutConstraint] { let constraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: width) self.addConstraint(constraint) return [constraint] } /// A convenience method to constrain the view's height. /// /// - parameters: /// - relation: The 'NSLayoutRelation' used in the constraint. /// - height: A 'CGFloat' constant for the height. /// - priority: The layout priority of the constraint. By default, this is `1000`. /// - returns: The layout constraints that were added. @discardableResult public func rsd_makeHeight(_ relation: NSLayoutConstraint.Relation, _ height : CGFloat, priority: UILayoutPriority = UILayoutPriority(1000.0)) -> [NSLayoutConstraint] { let constraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: height) self.addConstraint(constraint) return [constraint] } /// A convenience method to constraint the view's width relative to its superview. /// - parameter multiplier: A `CGFloat` constant for the constraint multiplier. /// - returns: The layout constraints that were added. @discardableResult public func rsd_makeWidthEqualToSuperview(multiplier: CGFloat) -> [NSLayoutConstraint] { guard let superview = self.superview else { assertionFailure("Trying to set constraints without first setting superview") return [] } let constraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: superview, attribute: .width, multiplier: multiplier, constant: 0.0) superview.addConstraint(constraint) return [constraint] } /// A convenience method to constrain the view's height relative to its superview. /// - parameter multiplier: A `CGFloat` constant for the constraint multiplier. /// - returns: The layout constraints that were added. @discardableResult public func rsd_makeHeightEqualToSuperview(multiplier: CGFloat) -> [NSLayoutConstraint] { guard let superview = self.superview else { assertionFailure("Trying to set constraints without first setting superview") return [] } let constraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: superview, attribute: .height, multiplier: multiplier, constant: 0.0) superview.addConstraint(constraint) return [constraint] } /// A convenience method to constraint the view's width relative to its superview. /// - parameter multiplier: A `CGFloat` constant for the constraint multiplier. /// - returns: The layout constraints that were added. @discardableResult public func rsd_makeWidthEqualToView(_ view: UIView) -> [NSLayoutConstraint] { guard let superview = self.superview else { assertionFailure("Trying to set constraints without first setting superview") return [] } let constraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0.0) superview.addConstraint(constraint) return [constraint] } /// A convenience method to remove all the view's constraints that exist between it and its superview /// or its superview's other child views. It does NOT remove constraints between the view and its child views. public func rsd_removeSiblingAndAncestorConstraints() { for constraint in self.constraints { // iOS automatically creates special types of constraints, like for intrinsicContentSize, // and we don't want these. So test here for that and skip. if type(of: constraint) != NSLayoutConstraint.self { continue } if constraint.firstItem as? UIView == self && !isChildView(item: constraint.secondItem) { self.removeConstraint(constraint) } } if let superview = superview { for constraint in superview.constraints { // iOS automatically creates special types of constraints, like for intrinsicContentSize, // and we don't want to remove these. So test here for that and skip. if type(of: constraint) != NSLayoutConstraint.self { continue } if constraint.firstItem as? UIView == self || constraint.secondItem as? UIView == self { superview.removeConstraint(constraint) } } } } /// A convenience method to remove all the view's constraints that exist between it and its superview. It does /// NOT remove constraints between the view and its child views or constraints on itself (such as width and height). public func rsd_removeSuperviewConstraints() { guard let superview = superview else { return } for constraint in superview.constraints { // iOS automatically creates special types of constraints, like for intrinsicContentSize, // and we don't want these. So test here for that and skip. if type(of: constraint) != NSLayoutConstraint.self { continue } if constraint.firstItem as? UIView == self || constraint.secondItem as? UIView == self { superview.removeConstraint(constraint) } } } fileprivate func isChildView(item : AnyObject?) -> Bool { var isChild = false if let item = item { if item is UIView { for subView in self.subviews { if subView == item as! NSObject { isChild = true break } } } } return isChild } /// A convenience method to return a constraint on the view that matches the supplied constraint properties. /// If multiple constraints matching those properties are found, it returns the constraint with the highest priority. /// /// - parameters: /// - attribute: The 'NSLayoutAttribute' of the constaint to be returned. /// - relation: The 'NSLayoutRelation' of the constraint to be returned. /// - returns: The 'NSLayoutConstraint' matching the supplied constraint properties, if any. public func rsd_constraint(for attribute: NSLayoutConstraint.Attribute, relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint? { var theConstraints = Array<NSLayoutConstraint>() // Iterate the view constraints and superview constraints. In most cases, we should have only one that has the 'firstItem', // 'firstAttribute' and 'relation' values that we're looking for. It's possible there could be more than one with // different priorities. So, we collect all of them and return the one with highest priority. [self, self.superview ?? nil].forEach({ if let constraints = $0?.constraints { for constraint in constraints { // iOS automatically creates special types of constraints, like for intrinsicContentSize, // and we don't want these. So we make sure we have a 'NSLayoutConstraint' base class. if type(of: constraint) != NSLayoutConstraint.self { continue } if RSDObjectEquality(constraint.firstItem, self) && constraint.firstAttribute == attribute && constraint.relation == relation { theConstraints.append(constraint) } } } }) return theConstraints.max { $0.priority.rawValue < $1.priority.rawValue } ?? nil } }
51.703934
278
0.597045
91fb8429a05589897e0e54fc405e8f1afd1d05d7
884
// // AsyncImage.swift // FarGoTraders // // Created by Artem Labazin on 13.01.2021. // import SwiftUI struct AsyncImage<Placeholder: View>: View { @ObservedObject private var loader: ImageLoader private let placeholder: Placeholder? private let configuration: (Image) -> Image init (url: URL, cache: ImageCache? = nil, placeholder: Placeholder? = nil, configuration: @escaping (Image) -> Image = { $0 } ) { loader = ImageLoader(url: url, cache: cache) self.placeholder = placeholder self.configuration = configuration } var body: some View { image .onAppear(perform: loader.load) .onDisappear(perform: loader.cancel) } private var image: some View { Group { if loader.image != nil { configuration(Image(uiImage: loader.image!)) } else { placeholder } } } }
20.090909
58
0.628959
2f806cf1e3e48fd1f44852342d0c6fcb0e549b44
5,026
// // SwttingsUserDefaults.swift // ReceiptsSorted // // Created by Maksim on 04/08/2020. // Copyright © 2020 Maksim. All rights reserved. // import Foundation enum IndicatorPeriod: Int { case Week = 0 case Month = 1 } class SettingsUserDefaults { static let shared = SettingsUserDefaults() private let currencySymbolKey = "currencySymbolKey" private let currencyNameKey = "currencyNameKey" private let currencyMulticastDelegate = MulticastDelegate<CurrencyChangedProtocol>() private let periodKey = "period" private let dateMulticastDelegate = MulticastDelegate<DateSettingChangedProtocol>() private let removalNumberKey = "receiptRemovalKey" // MARK: - Initialisation init() { if getCurrency().name == nil { setDefaultCurrency(to: "£", currencyName: "British Pound Sterling") } setReceiptRemoval(after: 6) } // MARK: - Currency func setDefaultCurrency(to currencySymbol: String, currencyName: String) { UserDefaults.standard.set(currencySymbol, forKey: currencySymbolKey) UserDefaults.standard.set(currencyName, forKey: currencyNameKey) invokeCurrencyDelegates(with: currencySymbol, name: currencyName) } func getCurrency() -> (symbol: String?, name: String?) { let currencySymbol = UserDefaults.standard.string(forKey: currencySymbolKey) let currencyName = UserDefaults.standard.string(forKey: currencyNameKey) return (symbol: currencySymbol, name: currencyName) } // MARK: - Date indicator /** Set write to UserDefaults the date indicator period. - Parameter period: Enum that represents what period should be set. */ func setIndicatorPeriod(to period: IndicatorPeriod) { let value = period.rawValue UserDefaults.standard.set(value, forKey: periodKey) invokePeriodDelegates(with: period) } /** Gets date indicator period - Returns: Either a week or a month depending on what was saved in UserDefaults */ func getDateIndicatorPeriod() -> IndicatorPeriod { let value = UserDefaults.standard.integer(forKey: periodKey) return (value == IndicatorPeriod.Week.rawValue) ? .Week : .Month } // MARK: - Date indicator /** Sets period after which receipts will be removed in months (-1 indicates to do not remove) - Parameter value: Value in months (which will be saved to userdefaults) after which receipts should be removed */ func setReceiptRemoval(after value: Int) { UserDefaults.standard.set(value, forKey: removalNumberKey) } /** Gets period after which receipts will be removed in months (-1 indicates to do not remove) - Returns: Value in months (which will be saved to userdefaults) after which receipts should be removed */ func getReceiptRemovalPeriod() -> Int { let value = UserDefaults.standard.integer(forKey: removalNumberKey) return value } } // MARK: - Currency Multicast extension extension SettingsUserDefaults { /** Adds a delegate which will listen to changes for the date period - Parameter object: Object that will listen to changes */ func addCurrencyChangedListener(_ object: CurrencyChangedProtocol) { currencyMulticastDelegate.addDelegate(object) } /** Removes listener from date changed delegates - Parameter object: Object to be removed */ func removeCurrencyListener(_ object: CurrencyChangedProtocol) { currencyMulticastDelegate.removeDelegate(object) } /** Invokes all the delegates with changes - Parameter period: New period that is being saved to UserDefaults */ private func invokeCurrencyDelegates(with currencySymbol: String, name currencyName: String) { currencyMulticastDelegate.invokeDelegates { $0.currencySettingChanged(to: currencySymbol, name: currencyName) } } } // MARK: - Date Indicator Multicast extension extension SettingsUserDefaults { /** Adds a delegate which will listen to changes for the date period - Parameter object: Object that will listen to changes */ func addDateChangedListener(_ object: DateSettingChangedProtocol) { dateMulticastDelegate.addDelegate(object) } /** Removes listener from date changed delegates - Parameter object: Object to be removed */ func removeDateListener(_ object: DateSettingChangedProtocol) { dateMulticastDelegate.removeDelegate(object) } /** Invokes all the delegates with changes - Parameter period: New period that is being saved to UserDefaults */ private func invokePeriodDelegates(with period: IndicatorPeriod) { dateMulticastDelegate.invokeDelegates { $0.dateIndicatorSettingChanged(to: period) } } }
30.277108
116
0.680064
48992fc48c95c822d781334dc15426c25ff2ca14
1,907
// // TestWrapped.swift // Bitcoin_Tests // // Created by Wolf McNally on 11/6/18. // // Copyright © 2018 Blockchain Commons. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import Bitcoin import WolfCore class TestWrapped: XCTestCase { func testWrapEncode() { let f = { tagBase16 >>> toData >>> wrapEncode(version: $0) >>> toBase16 } XCTAssert(try! "031bab84e687e36514eeaf5a017c30d32c1f59dd4ea6629da7970ca374513dd006" |> f(0) == "00031bab84e687e36514eeaf5a017c30d32c1f59dd4ea6629da7970ca374513dd0065b09d03c") XCTAssert(try! "031bab84e687e36514eeaf5a017c30d32c1f59dd4ea6629da7970ca374513dd006" |> f(42) == "2a031bab84e687e36514eeaf5a017c30d32c1f59dd4ea6629da7970ca374513dd006298eebe4") } func testWrapDecode() { let f = tagBase16 >>> toData >>> wrapDecode >>> toJSONString(outputFormatting: .sortedKeys) XCTAssert(try! "00031bab84e687e36514eeaf5a017c30d32c1f59dd4ea6629da7970ca374513dd0065b09d03c" |> f == """ {"checksum":1020266843,"payload":"031bab84e687e36514eeaf5a017c30d32c1f59dd4ea6629da7970ca374513dd006","prefix":0} """) XCTAssert(try! "2a031bab84e687e36514eeaf5a017c30d32c1f59dd4ea6629da7970ca374513dd006298eebe4" |> f == """ {"checksum":3840642601,"payload":"031bab84e687e36514eeaf5a017c30d32c1f59dd4ea6629da7970ca374513dd006","prefix":42} """) } }
45.404762
183
0.735711
18574bc9c2c3e9a6ac14c5766347c9ac6ea7bb47
3,004
// // ChineseConverter.swift // OpenCC // // Created by ddddxxx on 2017/3/9. // import Foundation import copencc /// The `ChineseConverter` class is used to represent and apply conversion /// between Traditional Chinese and Simplified Chinese to Unicode strings. /// An instance of this class is an immutable representation of a compiled /// conversion pattern. /// /// The `ChineseConverter` supporting character-level conversion, phrase-level /// conversion, variant conversion and regional idioms among Mainland China, /// Taiwan and HongKong /// /// `ChineseConverter` is designed to be immutable and threadsafe, so that /// a single instance can be used in conversion on multiple threads at once. /// However, the string on which it is operating should not be mutated /// during the course of a conversion. public class ChineseConverter { /// These constants define the ChineseConverter options. public struct Options: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// Convert to Traditional Chinese. (default) public static let traditionalize = Options(rawValue: 1 << 0) /// Convert to Simplified Chinese. public static let simplify = Options(rawValue: 1 << 1) /// Use Taiwan standard. public static let twStandard = Options(rawValue: 1 << 5) /// Use HongKong standard. public static let hkStandard = Options(rawValue: 1 << 6) /// Taiwanese idiom conversion. public static let twIdiom = Options(rawValue: 1 << 10) } private let seg: ConversionDictionary private let chain: [ConversionDictionary] private let converter: CCConverterRef private init(loader: DictionaryLoader, options: Options) throws { seg = try loader.segmentation(options: options) chain = try loader.conversionChain(options: options) var rawChain = chain.map { $0.dict } converter = CCConverterCreate("SwiftyOpenCC", seg.dict, &rawChain, rawChain.count) } /// Returns an initialized `ChineseConverter` instance with the specified /// conversion options. /// /// - Parameter options: The convert’s options. /// - Throws: Throws `ConversionError` if failed. public convenience init(options: Options) throws { let loader = DictionaryLoader(bundle: .module) try self.init(loader: loader, options: options) } /// Return a converted string using the convert’s current option. /// /// - Parameter text: The string to convert. /// - Returns: A converted string using the convert’s current option. public func convert(_ text: String) -> String { let stlStr = CCConverterCreateConvertedStringFromString(converter, text)! defer { STLStringDestroy(stlStr) } return String(utf8String: STLStringGetUTF8String(stlStr))! } }
35.761905
90
0.667443
7aa7b3f2b7726be36b8df0de0aa6a901113a2336
140
import Foundation struct Photo: Equatable { let URL: URL let title: String? let author: String? let aspectRatio: Float? }
14
27
0.664286
5de38368aaedf04876a03245e5af99e1f1e4fa1e
1,193
/* ----------------------------------------------------------------------------- This source file is part of MedKitDomain. Copyright 2016-2018 Jon Griffeth Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- */ import Foundation import MedKitCore /** Patient Directory Delegate */ public protocol PatientDirectoryObserver: class { func patientDirectoryDidUpdateReachability(_ directory: PatientDirectory) } /** Patient Directory Delegate Defaults */ public extension PatientDirectoryObserver { func patientDirectoryDidUpdateReachability(_ directory: PatientDirectory) {} } // End of File
25.934783
80
0.663034
268a3f720259479922e2a99edc92b9c6b226b579
10,745
import Foundation import TSCBasic import TuistSupport public enum TargetError: FatalError, Equatable { case invalidSourcesGlob(targetName: String, invalidGlobs: [InvalidGlob]) public var type: ErrorType { .abort } public var description: String { switch self { case let .invalidSourcesGlob(targetName: targetName, invalidGlobs: invalidGlobs): return "The target \(targetName) has the following invalid source files globs:\n" + invalidGlobs.invalidGlobsDescription } } } public struct Target: Equatable, Hashable, Comparable { // MARK: - Static public static let validSourceExtensions: [String] = ["m", "swift", "mm", "cpp", "c", "d", "intentdefinition", "xcmappingmodel", "metal"] public static let validFolderExtensions: [String] = ["framework", "bundle", "app", "xcassets", "appiconset", "scnassets"] // MARK: - Attributes public var name: String public var platform: Platform public var product: Product public var bundleId: String public var productName: String public var deploymentTarget: DeploymentTarget? // An info.plist file is needed for (dynamic) frameworks, applications and executables // however is not needed for other products such as static libraries. public var infoPlist: InfoPlist? public var entitlements: AbsolutePath? public var settings: Settings? public var dependencies: [Dependency] public var sources: [SourceFile] public var resources: [FileElement] public var headers: Headers? public var coreDataModels: [CoreDataModel] public var actions: [TargetAction] public var environment: [String: String] public var launchArguments: [String: Bool] public var filesGroup: ProjectGroup public var scripts: [TargetScript] // MARK: - Init public init(name: String, platform: Platform, product: Product, productName: String?, bundleId: String, deploymentTarget: DeploymentTarget? = nil, infoPlist: InfoPlist? = nil, entitlements: AbsolutePath? = nil, settings: Settings? = nil, sources: [SourceFile] = [], resources: [FileElement] = [], headers: Headers? = nil, coreDataModels: [CoreDataModel] = [], actions: [TargetAction] = [], environment: [String: String] = [:], launchArguments: [String: Bool] = [:], filesGroup: ProjectGroup, dependencies: [Dependency] = [], scripts: [TargetScript] = []) { self.name = name self.product = product self.platform = platform self.bundleId = bundleId self.productName = productName ?? name.replacingOccurrences(of: "-", with: "_") self.deploymentTarget = deploymentTarget self.infoPlist = infoPlist self.entitlements = entitlements self.settings = settings self.sources = sources self.resources = resources self.headers = headers self.coreDataModels = coreDataModels self.actions = actions self.environment = environment self.launchArguments = launchArguments self.filesGroup = filesGroup self.dependencies = dependencies self.scripts = scripts } /// Target can be included in the link phase of other targets public func isLinkable() -> Bool { [.dynamicLibrary, .staticLibrary, .framework, .staticFramework].contains(product) } /// Returns target's pre actions. public var preActions: [TargetAction] { actions.filter { $0.order == .pre } } /// Returns target's post actions. public var postActions: [TargetAction] { actions.filter { $0.order == .post } } /// Target can link static products (e.g. an app can link a staticLibrary) public func canLinkStaticProducts() -> Bool { [ .framework, .app, .unitTests, .uiTests, .appExtension, .watch2Extension, ].contains(product) } /// It returns the name of the variable that should be used to create an empty file /// in the $BUILT_PRODUCTS_DIR directory that is used after builds to reliably locate the /// directories where the products have been exported into. public var targetLocatorBuildPhaseVariable: String { let upperCasedSnakeCasedProductName = productName .camelCaseToSnakeCase() .components(separatedBy: .whitespaces).joined(separator: "_") .uppercased() return "\(upperCasedSnakeCasedProductName)_LOCATE_HASH" } /// Returns the product name including the extension. public var productNameWithExtension: String { switch product { case .staticLibrary, .dynamicLibrary: return "lib\(productName).\(product.xcodeValue.fileExtension!)" case _: return "\(productName).\(product.xcodeValue.fileExtension!)" } } /// Returns true if the target supports having a headers build phase.. public var shouldIncludeHeadersBuildPhase: Bool { switch product { case .framework, .staticFramework, .staticLibrary, .dynamicLibrary: return true default: return false } } /// Returns true if the target supports having sources. public var supportsSources: Bool { switch (platform, product) { case (.iOS, .bundle), (.iOS, .stickerPackExtension), (.watchOS, .watch2App): return false default: return true } } /// Returns true if the target supports hosting resources public var supportsResources: Bool { switch product { case .dynamicLibrary, .staticLibrary, .staticFramework: return false default: return true } } /// Returns true if the target is an AppClip public var isAppClip: Bool { if case .appClip = product { return true } return false } /// Returns true if the file at the given path is a resource. /// - Parameter path: Path to the file to be checked. public static func isResource(path: AbsolutePath) -> Bool { if !FileHandler.shared.isFolder(path) { return true // We filter out folders that are not Xcode supported bundles such as .app or .framework. } else if let `extension` = path.extension, Target.validFolderExtensions.contains(`extension`) { return true } else { return false } } /// This method unfolds the source file globs subtracting the paths that are excluded and ignoring /// the files that don't have a supported source extension. /// - Parameter sources: List of source file glob to be unfolded. public static func sources(targetName: String, sources: [SourceFileGlob]) throws -> [TuistCore.SourceFile] { var sourceFiles: [AbsolutePath: TuistCore.SourceFile] = [:] var invalidGlobs: [InvalidGlob] = [] try sources.forEach { source in let sourcePath = AbsolutePath(source.glob) let base = AbsolutePath(sourcePath.dirname) // Paths that should be excluded from sources var excluded: [AbsolutePath] = [] source.excluding.forEach { path in let absolute = AbsolutePath(path) let globs = AbsolutePath(absolute.dirname).glob(absolute.basename) excluded.append(contentsOf: globs) } let paths: [AbsolutePath] do { paths = try base.throwingGlob(sourcePath.basename) } catch let GlobError.nonExistentDirectory(invalidGlob) { paths = [] invalidGlobs.append(invalidGlob) } Set(paths) .subtracting(excluded) .filter { path in if let `extension` = path.extension, Target.validSourceExtensions.contains(`extension`) { return true } return false }.forEach { sourceFiles[$0] = SourceFile(path: $0, compilerFlags: source.compilerFlags) } } if !invalidGlobs.isEmpty { throw TargetError.invalidSourcesGlob(targetName: targetName, invalidGlobs: invalidGlobs) } return Array(sourceFiles.values) } // MARK: - Equatable public static func == (lhs: Target, rhs: Target) -> Bool { lhs.name == rhs.name && lhs.platform == rhs.platform && lhs.product == rhs.product && lhs.bundleId == rhs.bundleId && lhs.productName == rhs.productName && lhs.infoPlist == rhs.infoPlist && lhs.entitlements == rhs.entitlements && lhs.settings == rhs.settings && lhs.sources == rhs.sources && lhs.resources == rhs.resources && lhs.headers == rhs.headers && lhs.coreDataModels == rhs.coreDataModels && lhs.actions == rhs.actions && lhs.dependencies == rhs.dependencies && lhs.environment == rhs.environment } public func hash(into hasher: inout Hasher) { hasher.combine(name) hasher.combine(platform) hasher.combine(product) hasher.combine(bundleId) hasher.combine(productName) hasher.combine(entitlements) hasher.combine(environment) } /// Returns a new copy of the target with the given InfoPlist set. /// - Parameter infoPlist: InfoPlist to be set to the copied instance. public func with(infoPlist: InfoPlist) -> Target { var copy = self copy.infoPlist = infoPlist return copy } /// Returns a new copy of the target with the given actions. /// - Parameter actions: Actions to be set to the copied instance. public func with(actions: [TargetAction]) -> Target { var copy = self copy.actions = actions return copy } // MARK: - Comparable public static func < (lhs: Target, rhs: Target) -> Bool { lhs.name < rhs.name } } extension Sequence where Element == Target { /// Filters and returns only the targets that are test bundles. var testBundles: [Target] { filter { $0.product.testsBundle } } /// Filters and returns only the targets that are apps and app clips. var apps: [Target] { filter { $0.product == .app || $0.product == .appClip } } }
35.816667
140
0.609121
d51217a4739a84834089cd808e947dbb257dd312
1,486
import Foundation // https://leetcode.com/problems/knight-dialer/ class Solution { private let mode = 1e9 + 7 // 1000000007 private let moves = [[4,6],[6,8],[7,9],[4,8],[3,9,0],[],[1,7,0],[2,6],[1,3],[2,4]] func knightDialer(_ n: Int) -> Int { var res = 0 let arr = Array(repeating: -1, count: 10) var visit = Array(repeating: arr, count: n+1) for i in 0..<10 { res = (res + helper(n, i, &visit, [Int]())) % Int(mode) } return res } private func helper(_ n: Int, _ i: Int, _ visit: inout [[Int]], _ sub: [Int]) -> Int { if n == 1 { return 1 } if visit[n][i] != -1 { return visit[n][i] } // 34452 times var sum = 0 // 28228 times moves[i].forEach({ sum = (sum + helper(n-1, $0, &visit, [i, $0])) % Int(mode) // 62720 times }) visit[n][i] = sum // 28228 times return sum } } import XCTest // Executed 5 tests, with 0 failures (0 unexpected) in 2.065 (2.066) seconds class Tests: XCTestCase { private let s = Solution() func test1() { XCTAssertEqual(s.knightDialer(1), 10) } func test2() { XCTAssertEqual(s.knightDialer(2), 20) } func test3() { XCTAssertEqual(s.knightDialer(3), 46) } func test4() { XCTAssertEqual(s.knightDialer(4), 104) } func test5() { XCTAssertEqual(s.knightDialer(3131), 136006598) } } Tests.defaultTestSuite.run()
27.518519
90
0.534993
fedacc9a2435d4c371e428d429759527750064e8
591
import Cocoa public class ListNode { public var val: Int public var next: ListNode? public init() { self.val = 0; self.next = nil; } public init(_ val: Int) { self.val = val; self.next = nil; } public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } } class Solution { func reverseList(_ head: ListNode?) -> ListNode? { var pre: ListNode? var cur = head while cur != nil { let next = cur!.next cur!.next = pre pre = cur cur = next } return pre } }
24.625
84
0.532995
286fedab11ef374631cf8e78f7829d83489e2f5e
5,930
// // PopoverViewController.swift // Boop // // Created by Ivan on 1/27/19. // Copyright © 2019 OKatBest. All rights reserved. // import Cocoa import SavannaKit class PopoverViewController: NSViewController { @IBOutlet weak var overlayView: OverlayView! @IBOutlet weak var popoverView: PopoverContainerView! @IBOutlet weak var searchField: SearchField! @IBOutlet weak var editorView: SyntaxTextView! @IBOutlet weak var statusView: StatusView! @IBOutlet weak var scriptManager: ScriptManager! @IBOutlet weak var tableView: ScriptTableView! @IBOutlet weak var tableHeightConstraint: NSLayoutConstraint! @IBOutlet weak var tableViewController: ScriptsTableViewController! @IBOutlet weak var appDelegate: AppDelegate! var enabled = false // Closed by default override func viewDidLoad() { super.viewDidLoad() // Double-click script selection tableView.doubleAction = #selector(runSelectedScript) // Dismiss popover on background view click overlayView.onMouseDown = { [weak self] in self?.hide() } setupKeyHandlers() } func setupKeyHandlers() { var keyHandler: (_: NSEvent) -> NSEvent? keyHandler = { (_ theEvent: NSEvent) -> NSEvent? in var didSomething = false // Key codes: let kVKTab = 0x30 // 125 is down arrow // 126 is up // 53 is escape // 36 is enter if theEvent.keyCode == 53 && self.enabled { // ESCAPE // Let's dismiss the popover self.hide() didSomething = true } if theEvent.keyCode == 36 && self.enabled { // ENTER guard self.tableViewController.selectedScript != nil else { return theEvent } self.runSelectedScript() didSomething = true } let window = self.view.window if theEvent.keyCode == kVKTab && self.enabled { if window?.firstResponder is NSTextView && (window?.firstResponder as! NSTextView).delegate is SearchField { let offset = theEvent.modifierFlags.contains(.shift) ? -1 : 1 let newSel = IndexSet([self.tableView.selectedRow + offset]) self.tableView.selectRowIndexes(newSel, byExtendingSelection: false) self.tableView.scrollRowToVisible(self.tableView.selectedRow) } didSomething = true // prevent tabbing back into text document } if window?.firstResponder is NSTextView && (window?.firstResponder as! NSTextView).delegate is SearchField && theEvent.keyCode == 125 { // DOWN // Why -1? I don't know, and I don't even care. let indexSet = IndexSet(integer: -1) self.tableView.selectRowIndexes(indexSet, byExtendingSelection: false) window?.makeFirstResponder(self.tableView) } // Oh hey look now somehow it's 0. if window?.firstResponder is NSTableView && self.tableView.selectedRow == 0 && theEvent.keyCode == 126 { // UP window?.makeFirstResponder(self.searchField) // This doesn't work for some reason. //self.searchField.moveToEndOfLine(nil) } guard didSomething else { return theEvent } // Return an empty event to avoid the funk sound return nil } // Creates an object we do not own, but must keep track // of it so that it can be "removed" when we're done NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: keyHandler) } func show() { overlayView.show() popoverView.show() // FIXME: Use localized strings statusView.setStatus(.help("Select your action")) self.searchField.stringValue = "" self.tableHeightConstraint.constant = 0 self.view.window?.makeFirstResponder(self.searchField) self.enabled = true appDelegate.setPopover(isOpen: true) } func hide() { overlayView.hide() popoverView.hide() statusView.setStatus(.normal) self.view.window?.makeFirstResponder(self.editorView.contentTextView) self.enabled = false self.tableHeightConstraint.animator().constant = 0 tableViewController.results = [] appDelegate.setPopover(isOpen: false) } func runScriptAgain() { self.scriptManager.runScriptAgain(editor: self.editorView) } @objc private func runSelectedScript() { guard let script = tableViewController.selectedScript else { return } // Let's dismiss the popover hide() // Run the script afterwards in case we need to show a status scriptManager.runScript(script, into: editorView) } } extension PopoverViewController: NSTextFieldDelegate { func controlTextDidChange(_ obj: Notification) { guard (obj.object as? SearchField) == searchField else { return } let results = scriptManager.search(searchField.stringValue) tableViewController.results = results self.tableHeightConstraint.constant = CGFloat(45 * min(5, results.count) + ((results.count != 0) ? 20 : 0)) } }
31.88172
115
0.563744
728dfebbeec22e7f59c281a336cfc34a4d28e1af
1,457
//---------------------------------------------------- // // Generated by www.easywsdl.com // Version: 5.7.0.0 // // Created by Quasar Development // //--------------------------------------------------- import Foundation /** * specDomain: S14535 (C-0-T19651-A14411-A14412-A14484-S14534-S14535-cpt) */ public enum EPA_FdV_AUTHZ_TopicalPowder:Int,CustomStringConvertible { case TOPPWD case RECPWD case VAGPWD static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_TopicalPowder? { return createWithString(value: node.stringValue!) } static func createWithString(value:String) -> EPA_FdV_AUTHZ_TopicalPowder? { var i = 0 while let item = EPA_FdV_AUTHZ_TopicalPowder(rawValue: i) { if String(describing: item) == value { return item } i += 1 } return nil } public var stringValue : String { return description } public var description : String { switch self { case .TOPPWD: return "TOPPWD" case .RECPWD: return "RECPWD" case .VAGPWD: return "VAGPWD" } } public func getValue() -> Int { return rawValue } func serialize(__parent:DDXMLNode) { __parent.stringValue = stringValue } }
20.814286
79
0.50652
dec03db4207f225b0a229f628db4f990ae49e1ff
1,662
/* 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. */ /* IMPORTANT: This file contains supplemental code used to populate the examples with dummy data and/or instructions. It is not necessary to import this file to use Material Components for iOS. */ import Foundation import MaterialComponents extension NavigationBarTypicalUseSwiftExample { // (CatalogByConvention) @objc class func catalogBreadcrumbs() -> [String] { return [ "Navigation Bar", "Navigation Bar (Swift)" ] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } func catalogShouldHideNavigation() -> Bool { return true } @objc class func catalogIsPresentable() -> Bool { return false } override open func setupExampleViews() { /// Both self.viewDidLoad() and super.viewDidLoad() will add NavigationBars to the hierarchy. /// We only want to keep one. for subview in view.subviews { if let navBarSubview = subview as? MDCNavigationBar, navBarSubview != self.navBar { navBarSubview.removeFromSuperview() } } super.setupExampleViews() } }
28.655172
97
0.740674
ddd96da45a71e2aa68df8214bbda346deaa33111
1,276
// // Message.swift // SwiftJNChatApp // // Created by Yuki Takei on 2017/02/20. // // import Foundation import SwiftProtobuf extension Message: Entity { public init(row: Row) throws { guard let id = row["id"] as? Int, let text = row["text"] as? String, let createdAt = row["created_at"] as? Date, let uid = row["u_id"] as? Int, let uname = row["u_name"] as? String, let ulogin = row["u_login"] as? String, let uavaterURL = row["u_avatar_url"] as? String else { throw ValidationError.required("messages.*") } var user = User() user.id = Int32(uid) user.login = ulogin user.name = uname user.avaterURL = uavaterURL self.init() self.id = Int32(id) self.user = user self.text = text self.createdAt = Google_Protobuf_Timestamp(seconds: Int64(createdAt.timeIntervalSince1970)) } } extension Message: Serializable { public func serialize() throws -> [String: Any] { let now = Date().dateTimeString() return [ "text": text, "user_id": user.id, "created_at": now, "updated_at": now ] } }
25.52
99
0.54232
6737a30856363ca8edbf55d4e5a50a7ba7a245dd
2,185
// // User.swift // Odysee // // Created by Akinwale Ariwodola on 10/11/2020. // import Foundation struct User: Decodable { var createdAt: String? var familyName: String? var givenName: String? var groups: [String]? var hasVerifiedEmail: Bool? var id: Int64? var inviteRewardClaimed: Bool? var invitedAt: String? var invitedById: Int64? var invitesRemaining: Int? var isEmailEnabled: Bool? var isIdentityVerified: Bool? var isRewardApproved: Bool? var language: String? var manualApprovalUserId: Int64? var primaryEmail: String? var rewardStatusChangeTrigger: String? var youtubeChannels: [YoutubeChannel]? var deviceTypes: [String]? private enum CodingKeys: String, CodingKey { case createdAt = "created_at", familyName = "family_name", givenName = "given_name", groups, hasVerifiedEmail = "has_verified_email", id, inviteRewardClaimed = "invite_reward_claimed", invitedAt = "invited_at", invitedById = "invited_by_id", invitesRemaining = "invites_remaining", isEmailEnabled = "is_email_enabled", isIdentityVerified = "is_identity_verified", isRewardApproved = "is_reward_approved", language = "language", manualApprovalUserId = "manual_approval_user_id", primaryEmail = "primary_email", rewardStatusChangeTrigger = "reward_status_change_trigger", youtubeChannels = "youtube_channels", deviceTypes = "device_types" } struct YoutubeChannel: Decodable { var ytChannelName: String? var lbryChannelName: String? var channelClaimId: String? var syncStatus: String? var statusToken: String? var transferable: Bool? var transferState: String? var publishToAddress: [String]? var publicKey: String? private enum CodingKeys: String, CodingKey { case ytChannelName = "yt_channel_name", lbryChannelName = "lbry_channel_name", channelClaimId = "channel_claim_id", syncStatus = "sync_status", statusToken = "status_token", transferable = "transferable", transferState = "transfer_state", publishToAddress = "publish_to_address", publicKey = "public_key" } } }
42.019231
517
0.706636
8a4c57c7185a9fd755c552fe9ac634b631f984ef
2,350
// // SceneDelegate.swift // Pitch Changer // // Created by Dhiraj Jain on 5/23/20. // Copyright © 2020 Dhiraj Jain. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.518519
147
0.713191
e812d8d00eff326cd876f2eca65362fcb1d0d92a
2,326
// // GameViewController.swift // NimbleNinja // // Created by Jinchun Xia on 15/4/14. // Copyright (c) 2015 TEAM. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true skView.multipleTouchEnabled = false /* Congfit the scene equls view size */ scene.size = skView.bounds.size /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
31.863014
104
0.61006
163e88458aa45f6d3c56be0803681df986ee0c10
18,719
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 private struct HashableItem: Hashable { private let uid: String private let type: String init(chatItem: ChatItemProtocol) { self.uid = chatItem.uid self.type = chatItem.type } } extension BaseChatViewController { public func enqueueModelUpdate(updateType: UpdateType, completion: (() -> Void)? = nil) { let newItems = self.chatDataSource?.chatItems ?? [] if self.updatesConfig.coalesceUpdates { self.updateQueue.flushQueue() } self.updateQueue.addTask({ [weak self] (runNextTask) -> Void in guard let sSelf = self else { return } let oldItems = sSelf.chatItemCompanionCollection sSelf.updateModels(newItems: newItems, oldItems: oldItems, updateType: updateType, completion: { guard let sSelf = self else { return } if sSelf.updateQueue.isEmpty { sSelf.enqueueMessageCountReductionIfNeeded() } completion?() DispatchQueue.main.async(execute: { () -> Void in // Reduces inconsistencies before next update: https://github.com/diegosanchezr/UICollectionViewStressing runNextTask() }) }) }) } public func enqueueMessageCountReductionIfNeeded() { guard let preferredMaxMessageCount = self.constants.preferredMaxMessageCount, (self.chatDataSource?.chatItems.count ?? 0) > preferredMaxMessageCount else { return } self.updateQueue.addTask { [weak self] (completion) -> Void in guard let sSelf = self else { return } sSelf.chatDataSource?.adjustNumberOfMessages(preferredMaxCount: sSelf.constants.preferredMaxMessageCountAdjustment, focusPosition: sSelf.focusPosition, completion: { (didAdjust) -> Void in guard didAdjust, let sSelf = self else { completion() return } let newItems = sSelf.chatDataSource?.chatItems ?? [] let oldItems = sSelf.chatItemCompanionCollection sSelf.updateModels(newItems: newItems, oldItems: oldItems, updateType: .messageCountReduction, completion: completion ) }) } } // Returns scrolling position in interval [0, 1], 0 top, 1 bottom public var focusPosition: Double { guard let collectionView = self.collectionView else { return 0 } if self.isCloseToBottom() { return 1 } else if self.isCloseToTop() { return 0 } let contentHeight = collectionView.contentSize.height guard contentHeight > 0 else { return 0.5 } // Rough estimation let collectionViewContentYOffset = collectionView.contentOffset.y let midContentOffset = collectionViewContentYOffset + self.visibleRect().height / 2 return min(max(0, Double(midContentOffset / contentHeight)), 1.0) } func updateVisibleCells(_ changes: CollectionChanges) { // Datasource should be already updated! assert(self.visibleCellsAreValid(changes: changes), "Invalid visible cells. Don't call me") let cellsToUpdate = updated(collection: self.visibleCellsFromCollectionViewApi(), withChanges: changes) self.visibleCells = cellsToUpdate cellsToUpdate.forEach { (indexPath, cell) in let presenter = self.presenterForIndexPath(indexPath) presenter.configureCell(cell, decorationAttributes: self.decorationAttributesForIndexPath(indexPath)) presenter.cellWillBeShown(cell) // `createModelUpdates` may have created a new presenter instance for existing visible cell so we need to tell it that its cell is visible } } private func visibleCellsFromCollectionViewApi() -> [IndexPath: UICollectionViewCell] { var visibleCells: [IndexPath: UICollectionViewCell] = [:] guard let collectionView = self.collectionView else { return visibleCells } collectionView.indexPathsForVisibleItems.forEach({ (indexPath) in if let cell = collectionView.cellForItem(at: indexPath) { visibleCells[indexPath] = cell } }) return visibleCells } private func visibleCellsAreValid(changes: CollectionChanges) -> Bool { // Afer performBatchUpdates, indexPathForCell may return a cell refering to the state before the update // if self.updatesConfig.fastUpdates is enabled, very fast updates could result in `updateVisibleCells` updating wrong cells. // See more: https://github.com/diegosanchezr/UICollectionViewStressing if self.updatesConfig.fastUpdates { return updated(collection: self.visibleCells, withChanges: changes) == updated(collection: self.visibleCellsFromCollectionViewApi(), withChanges: changes) } else { return true // never seen inconsistency without fastUpdates } } private enum ScrollAction { case scrollToBottom case preservePosition(rectForReferenceIndexPathBeforeUpdate: CGRect?, referenceIndexPathAfterUpdate: IndexPath?) } func performBatchUpdates(updateModelClosure: @escaping () -> Void, changes: CollectionChanges, updateType: UpdateType, completion: @escaping () -> Void) { guard let collectionView = self.collectionView else { completion() return } let usesBatchUpdates: Bool do { // Recover from too fast updates... let visibleCellsAreValid = self.visibleCellsAreValid(changes: changes) let wantsReloadData = updateType != .normal let hasUnfinishedBatchUpdates = self.unfinishedBatchUpdatesCount > 0 // This can only happen when enabling self.updatesConfig.fastUpdates // a) It's unsafe to perform reloadData while there's a performBatchUpdates animating: https://github.com/diegosanchezr/UICollectionViewStressing/tree/master/GhostCells // Note: using reloadSections instead reloadData is safe and might not need a delay. However, using always reloadSections causes flickering on pagination and a crash on the first layout that needs a workaround. Let's stick to reloaData for now // b) If it's a performBatchUpdates but visible cells are invalid let's wait until all finish (otherwise we would give wrong cells to presenters in updateVisibleCells) let mustDelayUpdate = hasUnfinishedBatchUpdates && (wantsReloadData || !visibleCellsAreValid) guard !mustDelayUpdate else { // For reference, it is possible to force the current performBatchUpdates to finish in the next run loop, by cancelling animations: // self.collectionView.subviews.forEach { $0.layer.removeAllAnimations() } self.onAllBatchUpdatesFinished = { [weak self] in self?.onAllBatchUpdatesFinished = nil self?.performBatchUpdates(updateModelClosure: updateModelClosure, changes: changes, updateType: updateType, completion: completion) } return } // ... if they are still invalid the only thing we can do is a reloadData let mustDoReloadData = !visibleCellsAreValid // Only way to recover from this inconsistent state usesBatchUpdates = !wantsReloadData && !mustDoReloadData } let scrollAction: ScrollAction = .scrollToBottom // do { // Scroll action // if updateType != .pagination && self.isScrolledAtBottom() { // scrollAction = .scrollToBottom // } else { // let (oldReferenceIndexPath, newReferenceIndexPath) = self.referenceIndexPathsToRestoreScrollPositionOnUpdate(itemsBeforeUpdate: self.chatItemCompanionCollection, changes: changes) // let oldRect = self.rectAtIndexPath(oldReferenceIndexPath) // scrollAction = .preservePosition(rectForReferenceIndexPathBeforeUpdate: oldRect, referenceIndexPathAfterUpdate: newReferenceIndexPath) // } // } let myCompletion: () -> Void do { // Completion var myCompletionExecuted = false myCompletion = { if myCompletionExecuted { return } myCompletionExecuted = true completion() } } if usesBatchUpdates { UIView.animate(withDuration: self.constants.updatesAnimationDuration, animations: { () -> Void in self.unfinishedBatchUpdatesCount += 1 collectionView.performBatchUpdates({ () -> Void in updateModelClosure() self.updateVisibleCells(changes) // For instance, to support removal of tails collectionView.deleteItems(at: Array(changes.deletedIndexPaths)) collectionView.insertItems(at: Array(changes.insertedIndexPaths)) for move in changes.movedIndexPaths { collectionView.moveItem(at: move.indexPathOld, to: move.indexPathNew) } }, completion: { [weak self] (_) -> Void in defer { myCompletion() } guard let sSelf = self else { return } sSelf.unfinishedBatchUpdatesCount -= 1 if sSelf.unfinishedBatchUpdatesCount == 0, let onAllBatchUpdatesFinished = self?.onAllBatchUpdatesFinished { DispatchQueue.main.async(execute: onAllBatchUpdatesFinished) } }) if self.placeMessagesFromBottom { self.adjustCollectionViewInsets(shouldUpdateContentOffset: false) } }) } else { self.visibleCells = [:] updateModelClosure() collectionView.reloadData() collectionView.collectionViewLayout.prepare() if self.placeMessagesFromBottom { self.adjustCollectionViewInsets(shouldUpdateContentOffset: false) } } switch scrollAction { case .scrollToBottom: self.scrollToBottom(animated: updateType == .normal) case .preservePosition(rectForReferenceIndexPathBeforeUpdate: let oldRect, referenceIndexPathAfterUpdate: let indexPath): let newRect = self.rectAtIndexPath(indexPath) self.scrollToPreservePosition(oldRefRect: oldRect, newRefRect: newRect) } if !usesBatchUpdates || self.updatesConfig.fastUpdates { myCompletion() } } private func updateModels(newItems: [ChatItemProtocol], oldItems: ChatItemCompanionCollection, updateType: UpdateType, completion: @escaping () -> Void) { guard let collectionView = self.collectionView else { completion() return } let collectionViewWidth = collectionView.bounds.width let updateType = self.isFirstLayout ? .firstLoad : updateType let performInBackground = updateType != .firstLoad self.autoLoadingEnabled = false let perfomBatchUpdates: (_ changes: CollectionChanges, _ updateModelClosure: @escaping () -> Void) -> Void = { [weak self] (changes, updateModelClosure) in self?.performBatchUpdates( updateModelClosure: updateModelClosure, changes: changes, updateType: updateType, completion: { () -> Void in self?.autoLoadingEnabled = true completion() }) } let createModelUpdate = { return self.createModelUpdates( newItems: newItems, oldItems: oldItems, collectionViewWidth: collectionViewWidth) } if performInBackground { DispatchQueue.global(qos: .userInitiated).async { () -> Void in let modelUpdate = createModelUpdate() DispatchQueue.main.async(execute: { () -> Void in perfomBatchUpdates(modelUpdate.changes, modelUpdate.updateModelClosure) }) } } else { let modelUpdate = createModelUpdate() perfomBatchUpdates(modelUpdate.changes, modelUpdate.updateModelClosure) } } private func createModelUpdates(newItems: [ChatItemProtocol], oldItems: ChatItemCompanionCollection, collectionViewWidth: CGFloat) -> (changes: CollectionChanges, updateModelClosure: () -> Void) { let newDecoratedItems = self.chatItemsDecorator?.decorateItems(newItems) ?? newItems.map { DecoratedChatItem(chatItem: $0, decorationAttributes: nil) } let changes = Chatto.generateChanges(oldCollection: oldItems.map { HashableItem(chatItem: $0.chatItem) }, newCollection: newDecoratedItems.map { HashableItem(chatItem: $0.chatItem) }) let itemCompanionCollection = self.createCompanionCollection(fromChatItems: newDecoratedItems, previousCompanionCollection: oldItems) let layoutModel = self.createLayoutModel(itemCompanionCollection, collectionViewWidth: collectionViewWidth) let updateModelClosure : () -> Void = { [weak self] in self?.layoutModel = layoutModel self?.chatItemCompanionCollection = itemCompanionCollection } return (changes, updateModelClosure) } private func createCompanionCollection(fromChatItems newItems: [DecoratedChatItem], previousCompanionCollection oldItems: ChatItemCompanionCollection) -> ChatItemCompanionCollection { return ChatItemCompanionCollection(items: newItems.map { (decoratedChatItem) -> ChatItemCompanion in let chatItem = decoratedChatItem.chatItem var presenter: ChatItemPresenterProtocol! // We assume that a same messageId can't mutate from one cell class to a different one. // If we ever need to support that then generation of changes needs to suppport reloading items. // Oherwise updateVisibleCells may try to update existing cell with a new presenter which is working with a different type of cell // Optimization: reuse presenter if it's the same instance. if let oldChatItemCompanion = oldItems[decoratedChatItem.uid], oldChatItemCompanion.chatItem === chatItem { presenter = oldChatItemCompanion.presenter } else { presenter = self.createPresenterForChatItem(decoratedChatItem.chatItem) } return ChatItemCompanion(uid: decoratedChatItem.uid, chatItem: decoratedChatItem.chatItem, presenter: presenter, decorationAttributes: decoratedChatItem.decorationAttributes) }) } private func createLayoutModel(_ items: ChatItemCompanionCollection, collectionViewWidth: CGFloat) -> ChatCollectionViewLayoutModel { typealias IntermediateItemLayoutData = (height: CGFloat?, bottomMargin: CGFloat) typealias ItemLayoutData = (height: CGFloat, bottomMargin: CGFloat) func createLayoutModel(intermediateLayoutData: [IntermediateItemLayoutData]) -> ChatCollectionViewLayoutModel { let layoutData = intermediateLayoutData.map { (intermediateLayoutData: IntermediateItemLayoutData) -> ItemLayoutData in return (height: intermediateLayoutData.height!, bottomMargin: intermediateLayoutData.bottomMargin) } return ChatCollectionViewLayoutModel.createModel(collectionViewWidth, itemsLayoutData: layoutData) } let isInbackground = !Thread.isMainThread var intermediateLayoutData = [IntermediateItemLayoutData]() var itemsForMainThread = [(index: Int, itemCompanion: ChatItemCompanion)]() for (index, itemCompanion) in items.enumerated() { var height: CGFloat? let bottomMargin: CGFloat = itemCompanion.decorationAttributes?.bottomMargin ?? 0 if !isInbackground || itemCompanion.presenter.canCalculateHeightInBackground { height = itemCompanion.presenter.heightForCell(maximumWidth: collectionViewWidth, decorationAttributes: itemCompanion.decorationAttributes) } else { itemsForMainThread.append((index: index, itemCompanion: itemCompanion)) } intermediateLayoutData.append((height: height, bottomMargin: bottomMargin)) } if itemsForMainThread.count > 0 { DispatchQueue.main.sync(execute: { () -> Void in for (index, itemCompanion) in itemsForMainThread { let height = itemCompanion.presenter.heightForCell(maximumWidth: collectionViewWidth, decorationAttributes: itemCompanion.decorationAttributes) intermediateLayoutData[index].height = height } }) } return createLayoutModel(intermediateLayoutData: intermediateLayoutData) } public func chatCollectionViewLayoutModel() -> ChatCollectionViewLayoutModel { guard let collectionView = self.collectionView else { return self.layoutModel } if self.layoutModel.calculatedForWidth != collectionView.bounds.width { self.layoutModel = self.createLayoutModel(self.chatItemCompanionCollection, collectionViewWidth: collectionView.bounds.width) } return self.layoutModel } }
51.997222
255
0.664726
2288d8a6047ad8034c606423c85bb85e2a9107b5
3,681
/* See LICENSE folder for this sample’s licensing information. Abstract: A visualization of a detected object, using either a loaded 3D asset or a simple bounding box. 已检测到物体的可视化,用在加载出的3D素材时或简单边界盒时. */ import Foundation import ARKit import SceneKit class DetectedObject: SCNNode { var displayDuration: TimeInterval = 1.0 // How long this visualization is displayed in seconds after an update 更新后展示的时长 private var detectedObjectVisualizationTimer: Timer? private let pointCloudVisualization: DetectedPointCloud private var boundingBox: DetectedBoundingBox? private var originVis: SCNNode private var customModel: SCNNode? private let referenceObject: ARReferenceObject func set3DModel(_ url: URL?) { if let url = url, let model = load3DModel(from: url) { customModel?.removeFromParentNode() customModel = nil originVis.removeFromParentNode() ViewController.instance?.sceneView.prepare([model], completionHandler: { _ in self.addChildNode(model) }) customModel = model pointCloudVisualization.isHidden = true boundingBox?.isHidden = true } else { customModel?.removeFromParentNode() customModel = nil addChildNode(originVis) pointCloudVisualization.isHidden = false boundingBox?.isHidden = false } } init(referenceObject: ARReferenceObject) { self.referenceObject = referenceObject pointCloudVisualization = DetectedPointCloud(referenceObjectPointCloud: referenceObject.rawFeaturePoints, center: referenceObject.center, extent: referenceObject.extent) if let scene = SCNScene(named: "axes.scn", inDirectory: "art.scnassets") { originVis = SCNNode() for child in scene.rootNode.childNodes { originVis.addChildNode(child) } } else { originVis = SCNNode() print("Error: Coordinate system visualization missing.") } super.init() addChildNode(pointCloudVisualization) isHidden = true set3DModel(ViewController.instance?.modelURL) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateVisualization(newTransform: float4x4, currentPointCloud: ARPointCloud) { // Update the transform // 更新变换 self.simdTransform = newTransform // Update the point cloud visualization // 更新点云的可视化 updatePointCloud(currentPointCloud) if boundingBox == nil { let scale = CGFloat(referenceObject.scale.x) let boundingBox = DetectedBoundingBox(points: referenceObject.rawFeaturePoints.points, scale: scale) boundingBox.isHidden = customModel != nil addChildNode(boundingBox) self.boundingBox = boundingBox } // This visualization should only displayed for displayDuration seconds on every update. // 每次更新时,该可视化展示时长应为displayDuration. self.detectedObjectVisualizationTimer?.invalidate() self.isHidden = false self.detectedObjectVisualizationTimer = Timer.scheduledTimer(withTimeInterval: displayDuration, repeats: false) { _ in self.isHidden = true } } func updatePointCloud(_ currentPointCloud: ARPointCloud) { pointCloudVisualization.updateVisualization(for: currentPointCloud) } }
35.394231
126
0.645205
fb5454d9a017d1da30c39611644551d148e3e21a
235
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { deinit { { let a { { { } class r { init { case { { class case ,
12.368421
87
0.697872
034ea03cc4f227761ec142283586cae3457cd23c
4,173
// // RecurrenceRule.swift // RRuleSwift // // Created by Xin Hong on 16/3/28. // Copyright © 2016年 Teambition. All rights reserved. // import Foundation import EventKit public struct RecurrenceRule { /// The calendar of recurrence rule. public var calendar = Calendar.current /// The frequency of the recurrence rule. public var frequency: RecurrenceFrequency /// Specifies how often the recurrence rule repeats over the component of time indicated by its frequency. For example, a recurrence rule with a frequency type of RecurrenceFrequency.weekly and an interval of 2 repeats every two weeks. /// /// The default value of this property is 1. public var interval = 1 /// Indicates which day of the week the recurrence rule treats as the first day of the week. /// /// The default value of this property is EKWeekday.monday. public var firstDayOfWeek: EKWeekday = .monday /// The start date of recurrence rule. /// /// The default value of this property is current date. public var startDate = Date() /// The timezone in which the rules must be based on public var timeZone: TimeZone? /// Indicates when the recurrence rule ends. This can be represented by an end date or a number of occurrences. public var recurrenceEnd: EKRecurrenceEnd? /// An array of ordinal integers that filters which recurrences to include in the recurrence rule’s frequency. Values can be from 1 to 366 and from -1 to -366. /// /// For example, if a bysetpos of -1 is combined with a RecurrenceFrequency.monthly frequency, and a byweekday of (EKWeekday.monday, EKWeekday.tuesday, EKWeekday.wednesday, EKWeekday.thursday, EKWeekday.friday), will result in the last work day of every month. /// /// Negative values indicate counting backwards from the end of the recurrence rule’s frequency. public var bysetpos = [Int]() /// The days of the year associated with the recurrence rule, as an array of integers. Values can be from 1 to 366 and from -1 to -366. /// /// Negative values indicate counting backwards from the end of the year. public var byyearday = [Int]() /// The months of the year associated with the recurrence rule, as an array of integers. Values can be from 1 to 12. public var bymonth = [Int]() /// The weeks of the year associated with the recurrence rule, as an array of integers. Values can be from 1 to 53 and from -1 to -53. According to ISO8601, the first week of the year is that containing at least four days of the new year. /// /// Negative values indicate counting backwards from the end of the year. public var byweekno = [Int]() /// The days of the month associated with the recurrence rule, as an array of integers. Values can be from 1 to 31 and from -1 to -31. /// /// Negative values indicate counting backwards from the end of the month. public var bymonthday = [Int]() /// The days of the week associated with the recurrence rule, as an array of EKWeekday objects. public var byweekday = [(Int?, EKWeekday)]() /// The hours of the day associated with the recurrence rule, as an array of integers. public var byhour = [Int]() /// The minutes of the hour associated with the recurrence rule, as an array of integers. public var byminute = [Int]() /// The seconds of the minute associated with the recurrence rule, as an array of integers. public var bysecond = [Int]() /// The inclusive dates of the recurrence rule. public var rdate: InclusionDate? /// The exclusion dates of the recurrence rule. The dates of this property will not be generated, even if some inclusive rdate matches the recurrence rule. public var exdate: ExclusionDate? public init(frequency: RecurrenceFrequency) { self.frequency = frequency } public init?(rruleString: String) { if let recurrenceRule = RRule.ruleFromString(rruleString) { self = recurrenceRule } else { return nil } } public func toRRuleString() -> String { return RRule.stringFromRule(self) } }
42.151515
264
0.698538
46a7433c3daa06d572cd40ce273a0cba8542834c
365
// // UICollectionViewCellExtension.swift // // // Created by NohEunTae on 2021/07/01. // #if os(iOS) import UIKit extension UICollectionViewCell { var currentIndexPath: IndexPath? { guard let superCollectionView = superview as? UICollectionView else { return nil } return superCollectionView.indexPath(for: self) } } #endif
18.25
90
0.684932
fedf64407e05e01140aa4561104f765ba2c2f55b
712
// // Timer+VGPlayer.swift // VGPlayer // // Created by Vein on 2017/6/12. // Copyright © 2017年 Vein. All rights reserved. // https://gist.github.com/onevcat/2d1ceff1c657591eebde // Timer break retain cycle import Foundation extension Timer { class func vgPlayer_scheduledTimerWithTimeInterval(_ timeInterval: TimeInterval, block: @escaping()->(), repeats: Bool) -> Timer { return self.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(self.vgPlayer_blcokInvoke(_:)), userInfo: block, repeats: repeats) } @objc class func vgPlayer_blcokInvoke(_ timer: Timer) { let block: ()->() = timer.userInfo as! ()->() block() } }
29.666667
134
0.672753
9c2c3f8a3278c6ea632f2ff1fdb9bb2f045947ee
4,133
import Foundation import Eureka import Shared import PromiseKit class AccountCell: Cell<HomeAssistantAccountRowInfo>, CellType { private var accountRow: HomeAssistantAccountRow? { return row as? HomeAssistantAccountRow } override func setup() { super.setup() imageView?.layer.masksToBounds = true textLabel?.font = UIFont.preferredFont(forTextStyle: .body) detailTextLabel?.font = UIFont.preferredFont(forTextStyle: .body) selectionStyle = .default accessoryType = .disclosureIndicator } override func update() { super.update() let userName = accountRow?.value?.user?.Name let locationName = accountRow?.value?.locationName let height = min(64, UIFont.preferredFont(forTextStyle: .body).lineHeight * 2.0) let size = CGSize(width: height, height: height) if let imageView = imageView { if let image = accountRow?.cachedImage { UIView.transition( with: imageView, duration: imageView.image != nil ? 0.25 : 0, options: [.transitionCrossDissolve] ) { // scaled down because the cell sizes to fit too much imageView.image = image.scaledToSize(size) } completion: { _ in } } else { imageView.image = AccountInitialsImage .image( for: userName, size: CGSize(width: height, height: height) ) } imageView.layer.cornerRadius = ceil(height / 2.0) } textLabel?.text = locationName detailTextLabel?.text = userName if #available(iOS 13, *) { detailTextLabel?.textColor = .secondaryLabel } else { detailTextLabel?.textColor = .darkGray } } } struct HomeAssistantAccountRowInfo: Equatable { var user: AuthenticatedUser? var locationName: String? static func == (lhs: HomeAssistantAccountRowInfo, rhs: HomeAssistantAccountRowInfo) -> Bool { return lhs.user?.ID == rhs.user?.ID && lhs.locationName == rhs.locationName } } final class HomeAssistantAccountRow: Row<AccountCell>, RowType { var presentationMode: PresentationMode<UIViewController>? override func customDidSelect() { super.customDidSelect() if !isDisabled { if let presentationMode = presentationMode { if let controller = presentationMode.makeController() { presentationMode.present(controller, row: self, presentingController: cell.formViewController()!) } else { presentationMode.present(nil, row: self, presentingController: cell.formViewController()!) } } } } required init(tag: String?) { super.init(tag: tag) self.cellStyle = .subtitle } fileprivate var cachedImage: UIImage? override var value: Cell.Value? { didSet { if value != oldValue { fetchAvatar() } } } private func fetchAvatar() { guard let user = value?.user else { cachedImage = nil return } firstly { HomeAssistantAPI.authenticatedAPIPromise }.then { $0.GetStates() }.firstValue { $0.Attributes["user_id"] as? String == user.ID }.compactMap { $0.Attributes["entity_picture"] as? String }.compactMap { Current.settingsStore.connectionInfo?.activeURL.appendingPathComponent($0) }.then { URLSession.shared.dataTask(.promise, with: $0) }.compactMap { UIImage(data: $0.data) }.done { [self] image in Current.Log.verbose("got image \(image.size)") cachedImage = image updateCell() }.catch { error in Current.Log.error("failed to grab thumbnail: \(error)") } } }
30.843284
117
0.568836
39c811a7279b9ad49ea58f4186a17a6905c1d2fb
2,087
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -enable-library-evolution -disable-availability-checking -emit-module -emit-module-path %t/opaque_result_type_debug_other.swiftmodule -module-name opaque_result_type_debug_other -enable-anonymous-context-mangled-names %s -DLIBRARY // RUN: %target-swift-frontend -disable-availability-checking -g -emit-ir -enable-anonymous-context-mangled-names %s -DCLIENT -I %t | %FileCheck %s #if LIBRARY public protocol P {} extension Int: P {} public func foo() -> some P { return 0 } public var prop: some P { return 0 } public struct Foo { public init() {} public subscript() -> some P { return 0 } } #else import opaque_result_type_debug_other @_silgen_name("use") public func use<T: P>(_: T) @inlinable public func bar<T: P>(genericValue: T) { use(genericValue) let intValue = 0 use(intValue) let opaqueValue = foo() use(opaqueValue) let opaquePropValue = prop use(opaquePropValue) let opaqueSubValue = Foo()[] use(opaqueSubValue) } #endif // CHECK-DAG: ![[OPAQUE_TYPE:[0-9]+]] = !DICompositeType({{.*}} name: "$s30opaque_result_type_debug_other3fooQryFQOyQo_D" // CHECK-DAG: ![[LET_OPAQUE_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[OPAQUE_TYPE]]) // CHECK-DAG: ![[OPAQUE_PROP_TYPE:[0-9]+]] = !DICompositeType({{.*}} name: "$s30opaque_result_type_debug_other4propQrvpQOyQo_D" // CHECK-DAG: ![[LET_OPAQUE_PROP_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[OPAQUE_PROP_TYPE]]) // CHECK-DAG: ![[OPAQUE_SUB_TYPE:[0-9]+]] = !DICompositeType({{.*}} name: "$s30opaque_result_type_debug_other3FooVQrycipQOy_Qo_D" // CHECK-DAG: ![[LET_OPAQUE_SUB_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[OPAQUE_SUB_TYPE]]) // CHECK-DAG: {{![0-9]+}} = !DILocalVariable(name: "opaqueValue",{{.*}} type: ![[LET_OPAQUE_TYPE]]) // CHECK-DAG: {{![0-9]+}} = !DILocalVariable(name: "opaquePropValue",{{.*}} type: ![[LET_OPAQUE_PROP_TYPE]]) // CHECK-DAG: {{![0-9]+}} = !DILocalVariable(name: "opaqueSubValue",{{.*}} type: ![[LET_OPAQUE_SUB_TYPE]])
35.372881
261
0.702923
75ff3c3f569547f350e853cfe60e28ff12155720
1,430
// // AppDelegate.swift // SwipeTest // // Created by Александр Цветков on 02.06.2020. // Copyright © 2020 Александр Цветков. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.631579
179
0.74965
090c95f84375fc2405b84132e0edb6984944f105
483
// // Line.swift // Scryfall // // Created by Alexander on 30.08.2021. // import SwiftUI struct Line: Shape { func path(in rect: CGRect) -> Path { var path = Path() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: rect.width, y: 0)) return path } } struct DashedLine: View { var body: some View { Line() .stroke(style: StrokeStyle(lineWidth: 0.5, dash: [5])) .frame(height: 0.5) } }
18.576923
66
0.540373
71274a3930c04c136129890cb8270cdb1d8b22cd
3,120
// // Object.swift // Fizmo // // Created by Chris Sessions on 3/19/22. // import Foundation public typealias Function = () -> Bool /// Objects are things in the world with which the player can interact. /// public struct Object { public let action: Function? public let adjectives: [String] public let attributes: [Attribute] public let capacity: Int? public let description: String? public let descriptionFunction: String? public let firstDescription: String? public let globals: [Object] public let longDescription: String? public let name: String? public var parent: Room? public let pseudos: [String: Function] public let size: Int? public let strength: Int? public let synonyms: [String] public let takeValue: Int? public let text: String? public let value: Int? public let vType: Attribute? public init( name: String, action: Function? = nil, adjectives: [String] = [], attributes: [Attribute] = [], capacity: Int? = nil, description: String? = nil, descriptionFunction: String? = nil, firstDescription: String? = nil, globals: [Object] = [], longDescription: String? = nil, parent: Room? = nil, pseudos: [String: Function] = [:], size: Int? = nil, strength: Int? = nil, synonyms: [String] = [], takeValue: Int? = nil, text: String? = nil, value: Int? = nil, vType: Attribute? = nil ) { self.action = action self.adjectives = adjectives self.attributes = attributes self.capacity = capacity self.description = description self.descriptionFunction = descriptionFunction self.firstDescription = firstDescription self.globals = globals self.longDescription = longDescription self.name = name self.parent = parent self.pseudos = pseudos self.size = size self.strength = strength self.synonyms = synonyms self.takeValue = takeValue self.text = text self.value = value self.vType = vType } /// Evaluates whether `self` is located directly inside the specified ``Object``. /// /// - Parameter object: The object in which to look for `self`. /// /// - Returns: Whether `self` is in the specified object. func isIn(_ object: Object) -> Bool { return true } /// Evaluates whether `self` is located directly inside the specified ``Room``. /// /// - Parameter room: The room in which to look for `self`. /// /// - Returns: Whether `self` is in the specified room. func isIn(_ room: Room) -> Bool { return true } /// Change the location of `self` to the specified ``Object``. /// /// - Parameter to: The object to which `self` is moved. func move(to: Object) { } /// Change the location of `self` to the specified ``Room``. /// /// - Parameter to: The room to which `self` is moved. func move(to: Room) { } }
28.623853
85
0.598397
f86d1f209e451f4223035b3fd117b65915030521
2,545
// // DirectoryTests.swift // DirectoryTests // // Created by Charles Wang on 3/4/20. // Copyright © 2020 Charles Wang. All rights reserved. // // import XCTest @testable import Directory class DirectoryTests: XCTestCase { var employees = [Employee]() var malformedEmployees = [Employee]() var emptyEmployees = [Employee]() override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. let aEmployee = Employee(uuid: "1", fullName: "A", email: "A", team: "Z", employeeType: "FULL_TIME") let bEmployee = Employee(uuid: "2", fullName: "B", email: "B", team: "Y", employeeType: "PART_TIME") let cEmployee = Employee(uuid: "3", fullName: "C", email: "C", team: "X", employeeType: "CONTRACTOR") employees = [aEmployee, bEmployee, cEmployee] } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testSort() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let contactsDD = ContactsDD(nil) let teamOrder = contactsDD.sort(employees, .team) XCTAssert(teamOrder[0].team! == "X") XCTAssert(teamOrder[1].team! == "Y") XCTAssert(teamOrder[2].team! == "Z") let nameOrder = contactsDD.sort(employees, .name) XCTAssert(nameOrder[0].full_name! == "A") XCTAssert(nameOrder[1].full_name! == "B") XCTAssert(nameOrder[2].full_name! == "C") } func testEmployeeTypeParse() { let dEmployee = Employee(uuid: "4", fullName: "D", email: "D", team: "D", employeeType: "D") employees.append(dEmployee) for employee in employees { switch employee.uuid { case "1": XCTAssert(employee.getEmployeeType() == "Employment: Full Time") case "2": XCTAssert(employee.getEmployeeType() == "Employment: Part Time") case "3": XCTAssert(employee.getEmployeeType() == "Employment: Contractor") default: XCTAssert(employee.getEmployeeType() == "Employment: ---") } } } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
35.84507
111
0.600786
89a830290c0ed83ed06d57792301a9fe05ad823e
2,189
// // JSBackgroundView.swift // JSHUD // // Created by Max on 2018/11/19. // Copyright © 2018 Max. All rights reserved. // import UIKit public class JSBackgroundView: UIView { // MARK: 属性 public var backgroundStyle: JSHUDBackgroundStyle = .blur { didSet { if self.backgroundStyle != oldValue { self.resetBackgroundStyle() } } } public var blurStyle: UIBlurEffect.Style = .light { didSet { if self.blurStyle != oldValue { self.resetBackgroundStyle() } } } public var color: UIColor = UIColor(white: 0.8, alpha: 0.6) { didSet { if self.color != oldValue { self.resetBackgroundColor() } } } private var effectView: UIVisualEffectView? // MARK: 初始化 public override init(frame: CGRect) { super.init(frame: frame) self.setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: 设置方法 private func setupView() { self.clipsToBounds = true self.resetBackgroundStyle() } // MARK: 重写父类方法 public override var intrinsicContentSize: CGSize { return .zero } // MARK: 私有方法 private func resetBackgroundStyle() { self.effectView?.removeFromSuperview() self.effectView = nil if self.backgroundStyle == .blur { let effect = UIBlurEffect(style: self.blurStyle) let effectView = UIVisualEffectView(effect: effect) effectView.frame = self.bounds effectView.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.insertSubview(effectView, at: 0) self.backgroundColor = self.color self.layer.allowsGroupOpacity = false self.effectView = effectView } else { self.backgroundColor = self.color } } private func resetBackgroundColor() { self.backgroundColor = self.color } }
24.595506
75
0.555048