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
|
---|---|---|---|---|---|
e2c455e85f959f05d382d2c85b79a1f0094d7b43 | 1,054 | //
// ClaimMultiplier.swift
// Cosmostation
//
// Created by 정용주 on 2021/03/04.
// Copyright © 2021 wannabit. All rights reserved.
//
import Foundation
public struct ClaimMultiplier {
var denom: String?
var multipliers: Array<Multiplier> = Array<Multiplier>()
init(_ dictionary: NSDictionary?) {
self.denom = dictionary?["denom"] as? String
if let rawMultipliers = dictionary?["multipliers"] as? Array<NSDictionary> {
for rawMultiplier in rawMultipliers {
self.multipliers.append(Multiplier(rawMultiplier))
}
}
}
}
public struct Multiplier {
var name: String?
var months_lockup: String?
var factor: NSDecimalNumber = NSDecimalNumber.zero
init(_ dictionary: NSDictionary?) {
self.name = dictionary?["name"] as? String
self.months_lockup = dictionary?["months_lockup"] as? String
if let rawFactor = dictionary?["factor"] as? String {
self.factor = NSDecimalNumber.init(string: rawFactor)
}
}
}
| 27.736842 | 85 | 0.639469 |
feda25935ce82c8561aa062cb6ee30a03e37889c | 2,038 | //
// MusicProvidersViewController.swift
// iOS Demo App
//
// Created by Stefan Renne on 10/04/2018.
// Copyright © 2018 Uberweb. All rights reserved.
//
import UIKit
import RxSonosLib
import RxSwift
import RxCocoa
class MusicProvidersViewController: UIViewController {
internal var router: MusicProvidersRouter!
@IBOutlet var navigationBar: UINavigationBar!
@IBOutlet var navigationItemDone: UIBarButtonItem!
@IBOutlet var table: UITableView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.topItem?.title = "MusicProviders"
setupNavigationBar()
setupTableViewItems()
setupCellTapHandling()
setupCloseButton()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
func setupTableViewItems() {
table.register(UINib(nibName: String(describing: MusicProvidersTableViewCell.self), bundle: Bundle.main), forCellReuseIdentifier: MusicProvidersTableViewCell.identifier)
SonosInteractor
.getAllMusicProviders()
.asObservable()
.bind(to: table.rx.items(cellIdentifier: MusicProvidersTableViewCell.identifier, cellType: MusicProvidersTableViewCell.self)) { (_, service, cell) in
cell.model = MusicProviderViewModel(service: service)
}
.disposed(by: disposeBag)
}
func setupCellTapHandling() {
table
.rx
.modelSelected(MusicProvider.self)
.subscribe(onNext: { [weak self] (service) in
self?.router.didSelect(service: service)
})
.disposed(by: disposeBag)
}
func setupNavigationBar() {
navigationBar.styleWhite()
}
func setupCloseButton() {
navigationItemDone.rx.tap.subscribe(onNext: { [weak self] (_) in
self?.router.didClose()
}).disposed(by: disposeBag)
}
}
| 29.536232 | 177 | 0.647203 |
f5d806e472233483be75da187af3f39a8e5faec0 | 14,176 | //
// TableViewController.swift
// AXPhotoViewerExample
//
// Created by Alex Hill on 6/4/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
import UIKit
import AXPhotoViewer
import FLAnimatedImage
// This class contains some hacked together sample project code that I couldn't be arsed to make less ugly. ¯\_(ツ)_/¯
class TableViewController: UITableViewController, AXPhotosViewControllerDelegate, UIViewControllerPreviewingDelegate {
let ReuseIdentifier = "AXReuseIdentifier"
var previewingContext: UIViewControllerPreviewing?
var urlSession = URLSession(configuration: .default)
var content = [Int: Any]()
weak var photosViewController: AXPhotosViewController?
weak var customView: UILabel?
let photos = [
AXPhoto(attributedTitle: NSAttributedString(string: "Niagara Falls"),
image: UIImage(named: "niagara-falls")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash Poster"),
attributedDescription: NSAttributedString(string: "Season 3"),
attributedCredit: NSAttributedString(string: "Vignette"),
url: URL(string: "https://goo.gl/T4oZdY")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash and Savitar"),
attributedDescription: NSAttributedString(string: "Season 3"),
attributedCredit: NSAttributedString(string: "Screen Rant"),
url: URL(string: "https://goo.gl/pYeJ4H")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash: Rebirth"),
attributedDescription: NSAttributedString(string: "Comic Book"),
attributedCredit: NSAttributedString(string: "DC Comics"),
url: URL(string: "https://goo.gl/9wgyAo")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash has a cute smile"),
attributedDescription: nil,
attributedCredit: NSAttributedString(string: "Giphy"),
url: URL(string: "https://media.giphy.com/media/IOEcl8A8iLIUo/giphy.gif")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash slinging a rocket"),
attributedDescription: nil,
attributedCredit: NSAttributedString(string: "Giphy"),
url: URL(string: "https://media.giphy.com/media/lXiRDbPcRYfUgxOak/giphy.gif"))
]
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return [.portrait, .landscapeLeft]
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 9.0, *) {
if self.traitCollection.forceTouchCapability == .available {
if self.previewingContext == nil {
self.previewingContext = self.registerForPreviewing(with: self, sourceView: self.tableView)
}
} else if let previewingContext = self.previewingContext {
self.unregisterForPreviewing(withContext: previewingContext)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorStyle = .none
self.tableView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 30, right: 0)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: ReuseIdentifier)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tableView.scrollIndicatorInsets = UIEdgeInsets(top: UIApplication.shared.statusBarFrame.size.height,
left: 0,
bottom: 0,
right: 0)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.photos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifier) else {
return UITableViewCell()
}
// sample project worst practices top kek
if cell.contentView.viewWithTag(666) == nil {
let imageView = FLAnimatedImageView()
imageView.tag = 666
imageView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
imageView.layer.cornerRadius = 20
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFit
cell.contentView.addSubview(imageView)
}
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let imageView = cell.contentView.viewWithTag(666) as? FLAnimatedImageView else {
return
}
imageView.image = nil
imageView.animatedImage = nil
let emptyHeight: CGFloat = 200
let emptyWidth: CGFloat = 150
imageView.frame = CGRect(x: floor((cell.frame.size.width - emptyWidth)) / 2, y: 0, width: emptyWidth, height: emptyHeight)
let maxSize = cell.frame.size.height
self.loadContent(at: indexPath) { (image, data) in
func onMainQueue(_ block: @escaping () -> Void) {
if Thread.isMainThread {
block()
} else {
DispatchQueue.main.async {
block()
}
}
}
var imageViewSize: CGSize
if let data = data {
if let animatedImage = FLAnimatedImage(animatedGIFData: data) {
imageViewSize = (animatedImage.size.width > animatedImage.size.height) ?
CGSize(width: maxSize,height: (maxSize * animatedImage.size.height / animatedImage.size.width)) :
CGSize(width: maxSize * animatedImage.size.width / animatedImage.size.height, height: maxSize)
onMainQueue {
imageView.animatedImage = animatedImage
imageView.frame.size = imageViewSize
imageView.center = cell.contentView.center
}
} else if let image = UIImage(data: data) {
imageViewSize = (image.size.width > image.size.height) ?
CGSize(width: maxSize, height: (maxSize * image.size.height / image.size.width)) :
CGSize(width: maxSize * image.size.width / image.size.height, height: maxSize)
onMainQueue {
imageView.image = image
imageView.frame.size = imageViewSize
imageView.center = cell.contentView.center
}
}
} else if let image = image {
imageViewSize = (image.size.width > image.size.height) ?
CGSize(width: maxSize, height: (maxSize * image.size.height / image.size.width)) :
CGSize(width: maxSize * image.size.width / image.size.height, height: maxSize)
onMainQueue {
imageView.image = image
imageView.frame.size = imageViewSize
imageView.center = cell.contentView.center
}
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
let imageView = cell?.contentView.viewWithTag(666) as? FLAnimatedImageView
let transitionInfo = AXTransitionInfo(interactiveDismissalEnabled: true, startingView: imageView) { [weak self] (photo, index) -> UIImageView? in
guard let `self` = self else {
return nil
}
let indexPath = IndexPath(row: index, section: 0)
guard let cell = self.tableView.cellForRow(at: indexPath) else {
return nil
}
// adjusting the reference view attached to our transition info to allow for contextual animation
return cell.contentView.viewWithTag(666) as? FLAnimatedImageView
}
let container = UIViewController()
let dataSource = AXPhotosDataSource(photos: self.photos, initialPhotoIndex: indexPath.row)
let pagingConfig = AXPagingConfig(loadingViewClass: CustomLoadingView.self)
let photosViewController = AXPhotosViewController(dataSource: dataSource, pagingConfig: pagingConfig, transitionInfo: transitionInfo)
// photosViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
photosViewController.delegate = self
let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let bottomView = UIToolbar(frame: CGRect(origin: .zero, size: CGSize(width: 320, height: 44)))
let customView = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 80, height: 20)))
customView.text = "\(photosViewController.currentPhotoIndex + 1)"
customView.textColor = .white
customView.sizeToFit()
bottomView.items = [
UIBarButtonItem(barButtonSystemItem: .add, target: nil, action: nil),
flex,
UIBarButtonItem(customView: customView),
flex,
UIBarButtonItem(barButtonSystemItem: .trash, target: nil, action: nil),
]
bottomView.backgroundColor = .clear
bottomView.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
photosViewController.overlayView.bottomStackContainer.insertSubview(bottomView, at: 0)
self.customView = customView
// container.addChildViewController(photosViewController)
// container.view.addSubview(photosViewController.view)
// photosViewController.didMove(toParentViewController: container)
self.present(photosViewController, animated: true)
self.photosViewController = photosViewController
}
// MARK: - AXPhotosViewControllerDelegate
func photosViewController(_ photosViewController: AXPhotosViewController,
willUpdate overlayView: AXOverlayView,
for photo: AXPhotoProtocol,
at index: Int,
totalNumberOfPhotos: Int) {
self.customView?.text = "\(index + 1)"
self.customView?.sizeToFit()
}
// MARK: - Loading
func loadContent(at indexPath: IndexPath, completion: ((_ image: UIImage?, _ data: Data?) -> Void)?) {
if let data = self.content[indexPath.row] as? Data {
completion?(nil, data)
return
} else if let image = self.content[indexPath.row] as? UIImage {
completion?(image, nil)
return
}
if let imageData = self.photos[indexPath.row].imageData {
self.content[indexPath.row] = imageData
completion?(nil, imageData)
} else if let image = self.photos[indexPath.row].image {
self.content[indexPath.row] = image
completion?(image, nil)
} else if let url = self.photos[indexPath.row].url {
self.urlSession.dataTask(with: url) { [weak self] (data, response, error) in
guard let `data` = data else {
return
}
self?.content[indexPath.row] = data
completion?(nil, data)
}.resume()
}
}
// MARK: - AXPhotosViewControllerDelegate
func photosViewController(_ photosViewController: AXPhotosViewController,
didNavigateTo photo: AXPhotoProtocol,
at index: Int) {
let indexPath = IndexPath(row: index, section: 0)
// ideally, _your_ URL cache will be large enough to the point where this isn't necessary
// (or, you're using a predefined integration that has a shared cache with your codebase)
self.loadContent(at: indexPath, completion: nil)
}
// MARK: - UIViewControllerPreviewingDelegate
@available(iOS 9.0, *)
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = self.tableView.indexPathForRow(at: location),
let cell = self.tableView.cellForRow(at: indexPath),
let imageView = cell.contentView.viewWithTag(666) as? FLAnimatedImageView else {
return nil
}
previewingContext.sourceRect = self.tableView.convert(imageView.frame, from: imageView.superview)
let dataSource = AXPhotosDataSource(photos: self.photos, initialPhotoIndex: indexPath.row)
let previewingPhotosViewController = AXPreviewingPhotosViewController(dataSource: dataSource)
return previewingPhotosViewController
}
@available(iOS 9.0, *)
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if let previewingPhotosViewController = viewControllerToCommit as? AXPreviewingPhotosViewController {
self.present(AXPhotosViewController(from: previewingPhotosViewController), animated: false)
}
}
}
| 46.326797 | 153 | 0.613502 |
622394a8ffa1f8d706e3aa043dac318c1aa9532e | 2,193 | //
// AppDelegate.swift
// WeatherStationApp
//
// Created by programming-xcode on 10/12/17.
// Copyright © 2017 programming-xcode. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.659574 | 285 | 0.75741 |
ff42b0edbf70c9175e20ed1da07be6f0fc24d77a | 617 | //
// NotificationViewController.swift
// PushTemplates
//
// Created by Chengappa C D on 23/02/21.
// Copyright © 2021 The Chromium Authors. All rights reserved.
//
import UIKit
import UserNotifications
import UserNotificationsUI
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet var label: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
// Do any required interface initialization here.
}
func didReceive(_ notification: UNNotification) {
self.label?.text = notification.request.content.body
}
}
| 22.851852 | 84 | 0.71637 |
e50cd13ac41d788f0ca96656b443d082c11f538a | 2,150 | //
// AppDelegate.swift
// Forecast
//
// Created by Richard Neitzke on 11/9/15.
// Copyright © 2015 Richard Neitzke. 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.744681 | 285 | 0.754419 |
090d3170f67dc85ea4e06dd13ffa9dfcd246e4ac | 1,071 | //
// AssetSectionView.swift
// MyAsset
//
// Created by 윤병일 on 2022/01/25.
//
import SwiftUI
struct AssetSectionView: View {
@ObservedObject var assetSection : Asset
var body: some View {
VStack(spacing : 20) {
AssetSectionHeaderView(title: assetSection.type.title)
ForEach(assetSection.data) { asset in
HStack {
Text(asset.title)
.font(.title)
.foregroundColor(.secondary)
Spacer()
Text(asset.amount)
.font(.title2)
.foregroundColor(.primary)
}
Divider()
}
}
.padding()
}
}
struct AssetSectionView_Previews: PreviewProvider {
static var previews: some View {
let asset = Asset(id: 0, type: .bankAccount, data: [
AssetData(id: 0, title: "신한은행", amount: "5,3000000원"),
AssetData(id: 1, title: "국민은행", amount: "5,3000000원"),
AssetData(id: 2, title: "카카오뱅크", amount: "5,3000000원"),
])
AssetSectionView(assetSection: asset)
}
}
| 24.340909 | 63 | 0.55929 |
efb769a4e0eee1045f39c0bb6896ab8e737e218a | 8,486 | //
// AddWalletViewController.swift
// DiveLane
//
// Created by Anton Grigorev on 08/09/2018.
// Copyright © 2018 Matter Inc. All rights reserved.
//
import UIKit
class AddWalletViewController: BasicViewController {
// MARK: - Outlets
@IBOutlet weak var settingUp: UILabel!
@IBOutlet weak var iv: UIImageView!
@IBOutlet weak var prodName: UILabel!
@IBOutlet weak var subtitle: UILabel!
@IBOutlet weak var importWallet: BasicWhiteButton!
@IBOutlet weak var createWallet: BasicGreenButton!
@IBOutlet weak var animationImageView: UIImageView!
// MARK: - Internal lets
internal let navigationItems = NavigationItems()
internal let walletCreating = WalletCreating()
internal let appController = AppController()
internal let alerts = Alerts()
internal var walletCreated = false
// MARK: - Weak vars
weak var animationTimer: Timer?
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
createView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setNavigation(hidden: false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//additionalSetup()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
setNavigation(hidden: true)
}
// MARK: - Main setup
func setNavigation(hidden: Bool) {
navigationController?.setNavigationBarHidden(hidden, animated: true)
navigationController?.makeClearNavigationController()
let home = navigationItems.homeItem(target: self, action: #selector(goToApp))
navigationItem.setRightBarButton(home, animated: false)
}
// func additionalSetup() {
// self.topViewForModalAnimation.blurView()
// self.topViewForModalAnimation.alpha = 0
// self.topViewForModalAnimation.tag = Constants.ModalView.ShadowView.tag
// self.topViewForModalAnimation.isUserInteractionEnabled = false
// self.view.addSubview(topViewForModalAnimation)
// }
func createView() {
animationImageView.setGifImage(UIImage(gifName: "loading.gif"))
animationImageView.loopCount = -1
self.parent?.view.backgroundColor = .white
prodName.text = Constants.prodName
prodName.textAlignment = .center
prodName.textColor = Colors.textDarkGray
prodName.font = UIFont(name: Constants.Fonts.franklinSemibold, size: 55) ?? UIFont.boldSystemFont(ofSize: 55)
subtitle.textAlignment = .center
subtitle.text = Constants.slogan
subtitle.textColor = Colors.textDarkGray
subtitle.font = UIFont(name: Constants.Fonts.franklinMedium, size: 22) ?? UIFont.systemFont(ofSize: 22)
settingUp.textAlignment = .center
settingUp.text = "Setting up your wallet"
settingUp.textColor = Colors.textDarkGray
settingUp.font = UIFont(name: Constants.Fonts.regular, size: 24) ?? UIFont.systemFont(ofSize: 24)
animationImageView.frame = CGRect(x: 0, y: 0, width: 0.8*UIScreen.main.bounds.width, height: 257)
animationImageView.contentMode = .center
animationImageView.alpha = 0
animationImageView.isUserInteractionEnabled = false
iv.contentMode = .scaleAspectFit
iv.image = UIImage(named: "franklin")!
settingUp.alpha = 0
importWallet.addTarget(self,
action: #selector(importAction(sender:)),
for: .touchUpInside)
importWallet.setTitle("Import Wallet", for: .normal)
importWallet.alpha = 1
createWallet.addTarget(self,
action: #selector(createAction(sender:)),
for: .touchUpInside)
createWallet.setTitle("Create Wallet", for: .normal)
createWallet.alpha = 1
// link.addTarget(self, action: #selector(readTerms(sender:)), for: .touchUpInside)
}
// MARK: - Actions
func creatingWallet() {
DispatchQueue.global().async { [unowned self] in
do {
let wallet = try self.walletCreating.createWallet()
self.finishSavingWallet(wallet)
} catch let error {
self.alerts.showErrorAlert(for: self, error: error, completion: nil)
}
}
}
func finishSavingWallet(_ wallet: Wallet) {
do {
try walletCreating.prepareWallet(wallet)
walletCreated = true
if animationTimer == nil {
goToApp()
}
} catch let error {
deleteWallet(wallet: wallet, withError: error)
}
}
func deleteWallet(wallet: Wallet, withError error: Error) {
do {
try wallet.delete()
alerts.showErrorAlert(for: self, error: error, completion: nil)
} catch let deleteErr {
alerts.showErrorAlert(for: self, error: deleteErr, completion: nil)
}
}
@objc func goToApp() {
DispatchQueue.main.async { [unowned self] in
UIView.animate(withDuration: Constants.Main.animationDuration) { [unowned self] in
self.view.hideSubviews()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [unowned self] in
self.setNavigation(hidden: true)
self.navigationController?.popToRootViewController(animated: true)
// let tabViewController = self.appController.goToApp()
// tabViewController.view.backgroundColor = Colors.background
// let transition = CATransition()
// transition.duration = Constants.Main.animationDuration
// transition.type = CATransitionType.push
// transition.subtype = CATransitionSubtype.fromRight
// transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
// self.view.window!.layer.add(transition, forKey: kCATransition)
// self.present(tabViewController, animated: false, completion: nil)
})
}
}
}
// MARK: - Buttons actions
@objc func createAction(sender: UIButton) {
createWallet.isUserInteractionEnabled = false
importWallet.isUserInteractionEnabled = false
animation()
creatingWallet()
}
@objc func importAction(sender: UIButton) {
let vc = WalletImportingViewController()
// vc.delegate = self
// vc.modalPresentationStyle = .overCurrentContext
// vc.view.layer.speed = Constants.ModalView.animationSpeed
// self.present(vc, animated: true, completion: nil)
navigationController?.pushViewController(vc, animated: true)
}
// MARK: - Animations
func animation() {
navigationController?.navigationBar.isHidden = true
animationTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: false)
animateIndicator()
}
@objc func fireTimer() {
animationTimer?.invalidate()
if walletCreated {
goToApp()
}
}
func animateIndicator() {
UIView.animate(withDuration: Constants.Main.animationDuration) { [unowned self] in
self.createWallet.alpha = 0
self.importWallet.alpha = 0
self.animationImageView.alpha = 1
self.settingUp.alpha = 1
}
}
// func modalViewBeenDismissed(updateNeeded: Bool) {
// DispatchQueue.main.async { [unowned self] in
// UIView.animate(withDuration: Constants.ModalView.animationDuration, animations: {
// self.topViewForModalAnimation.alpha = 0
// })
// }
// }
//
// func modalViewAppeared() {
// DispatchQueue.main.async { [unowned self] in
// UIView.animate(withDuration: Constants.ModalView.animationDuration, animations: {
// self.topViewForModalAnimation.alpha = Constants.ModalView.ShadowView.alpha
// })
// }
// }
}
| 35.957627 | 139 | 0.613599 |
e26f578a48064f9fdd375f6d60054bf531d0680b | 872 | //
// UICodeTableViewCell.swift
// Presentation
//
// Created by Jezreel Barbosa on 09/01/21.
//
import UIKit
open class UICodeTableViewCell: UITableViewCell {
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
initSubViews()
initLayout()
initStyle()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
initSubViews()
initLayout()
initStyle()
}
open func initSubViews() {}
open func initLayout() {}
open func initStyle() {}
open func didSet(isFirstCell: Bool, isLastCell: Bool) {}
}
public extension UICodeTableViewCell {
final func setFirstLastCellFor(row: Int, count: Int) {
didSet(isFirstCell: row == 0, isLastCell: count == row + 1)
}
}
| 21.268293 | 86 | 0.645642 |
d7f74a53c65b45e6dedd550d34bd75766867c412 | 754 | //
// SetEndpointRequest.swift
// ScryfallKit
//
// Created by Jacob Hearst on 8/22/21.
//
import Foundation
struct GetSets: EndpointRequest {
var path: String? = "sets"
var queryParams: [URLQueryItem] = []
var requestMethod: RequestMethod = .GET
var body: Data? = nil
}
struct GetSet: EndpointRequest {
var identifier: Set.Identifier
var path: String? {
switch self.identifier {
case .code(let code):
return "sets/\(code)"
case .scryfallID(let id):
return "sets/\(id)"
case .tcgPlayerID(let id):
return "sets/tcglayer/\(id)"
}
}
var queryParams: [URLQueryItem] = []
var requestMethod: RequestMethod = .GET
var body: Data? = nil
}
| 22.176471 | 43 | 0.599469 |
5b998c35b43e8a402fe589453c6cc1d921eb0f1e | 3,355 | //
// WLPasswordTextFiled.swift
// WLCompoentViewDemo
//
// Created by three stone 王 on 2019/4/16.
// Copyright © 2019 three stone 王. All rights reserved.
//
import Foundation
import UIKit
@objc (AWMPasswordImageTextFiled)
public final class AWMPasswordImageTextFiled: AWMLeftImageTextField {
@objc (passwordItem)
public final let passwordItem: UIButton = UIButton(type: .custom)
@objc (normalIcon)
public var normalIcon: String = "" {
willSet {
guard !newValue.isEmpty else { return }
passwordItem.setImage(UIImage(named: newValue), for: .normal)
passwordItem.setImage(UIImage(named: newValue), for: .highlighted)
rightView = passwordItem
}
}
@objc (selectedIcon)
public var selectedIcon: String = "" {
willSet {
guard !newValue.isEmpty else { return }
passwordItem.setImage(UIImage(named: newValue), for: .selected)
}
}
public override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.rightViewRect(forBounds: bounds)
return CGRect(x: rect.minX - 30, y: rect.minY, width: rect.width , height: rect.height)
}
public override func editingRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.editingRect(forBounds: bounds)
return CGRect(x: rect.minX, y: rect.minY, width: rect.width - 30, height: rect.height)
}
@objc (commitInit)
public override func commitInit() {
super.commitInit()
awm_rightViewMode(.always)
awm_editType(.secret)
awm_maxLength(18)
awm_secureTextEntry(true)
}
}
@objc (AWMPasswordTitleTextFiled)
public final class AWMPasswordTitleTextFiled: AWMLeftTitleTextField {
@objc (passwordItem)
public final let passwordItem: UIButton = UIButton(type: .custom)
@objc (normalIcon)
public var normalIcon: String = "" {
willSet {
guard !newValue.isEmpty else { return }
passwordItem.setImage(UIImage(named: newValue), for: .normal)
passwordItem.setImage(UIImage(named: newValue), for: .highlighted)
}
}
@objc (selectedIcon)
public var selectedIcon: String = "" {
willSet {
guard !newValue.isEmpty else { return }
passwordItem.setImage(UIImage(named: newValue), for: .selected)
}
}
public override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.rightViewRect(forBounds: bounds)
return CGRect(x: rect.minX - 30, y: rect.minY, width: rect.width , height: rect.height)
}
public override func editingRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.editingRect(forBounds: bounds)
return CGRect(x: rect.minX, y: rect.minY, width: rect.width - 30, height: rect.height)
}
@objc (commitInit)
public override func commitInit() {
super.commitInit()
awm_rightViewMode(.always)
awm_rightView(passwordItem)
awm_editType(.secret)
awm_maxLength(18)
awm_secureTextEntry(true)
}
}
| 28.675214 | 95 | 0.604173 |
75bf850834490c107842b277d22832bdec525471 | 1,560 | import Foundation
import Combine
protocol JSONPlaceholderFetchable {
func fetchPosts() -> AnyPublisher<[PostResponse], JSONPlaceholderError>
}
class JSONPlaceholderFetcher {
private let session: URLSession
init(session: URLSession = .shared) {
self.session = session
}
}
extension JSONPlaceholderFetcher: JSONPlaceholderFetchable {
func fetchPosts() -> AnyPublisher<[PostResponse], JSONPlaceholderError> {
let components = makePostsComponents()
guard let url = components.url else {
let error = JSONPlaceholderError.network(description: "Couldn't create URL")
return Fail(error: error)
.eraseToAnyPublisher()
}
return URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: [PostResponse].self, decoder: JSONDecoder())
.mapError({ error in
.network(description: error.localizedDescription)
})
.eraseToAnyPublisher()
}
}
private extension JSONPlaceholderFetcher {
struct JSONPlaceholderAPI {
static let scheme = "https"
static let host = "jsonplaceholder.typicode.com"
static let path = "/posts"
}
func makePostsComponents() -> URLComponents {
var components = URLComponents()
components.scheme = JSONPlaceholderAPI.scheme
components.host = JSONPlaceholderAPI.host
components.path = JSONPlaceholderAPI.path
return components
}
}
| 29.433962 | 88 | 0.637179 |
e87c8cb80455091bc1032368179dad3ad83eeef2 | 5,659 | //
// LoginUserInfo.swift
// TrainingProgram
//
// Created by MAC User on 6/10/2018.
// Copyright © 2018 Zhao Ruohan. All rights reserved.
//
import Foundation
// This delegate method is called every time the face recognition has detected something (including change)
public func faceIsTracked(_ faceRect: CGRect, withOffsetWidth offsetWidth: Float, andOffsetHeight offsetHeight: Float, andDistance distance: Float, textView: UITextView) {
CATransaction.begin()
CATransaction.setAnimationDuration(0.1)
let layer: CALayer? = textView.layer
layer?.masksToBounds = false
//layer?.shadowOffset = CGSize(width: CGFloat(offsetWidth / 5.0), height: CGFloat(offsetHeight / 10.0))
layer?.shadowRadius = 0 //5
layer?.shadowOpacity = 0//0.1
CATransaction.commit()
}
// When the fluidUpdateInterval method is called, then this delegate method will be called on a regular interval
public func fluentUpdateDistance(_ distance: Float, textView: UITextView) {
// Animate to the zoom level.
let effectiveScale: Float = distance / 60.0 //origin : 60
CATransaction.begin()
CATransaction.setAnimationDuration(1.5)//origin: 0.1
textView.layer.setAffineTransform(CGAffineTransform(scaleX: CGFloat(effectiveScale), y: CGFloat(effectiveScale)))
CATransaction.commit()
}
//detect accuracy, whether continue()
//any one words match -> pass
//return number of error words and its contents
public func findAccuracy(inputResults : String, testResults : String) -> (Int,String) {
//error words
var filterWords = ""
//testResults = selectedChart[myNumber]
//var correctChar = Int()
var re1Arr = Array<String>()//input words
var re2Arr = Array<String>()//test words
//user say nothing -> equal to before
if(inputResults == ""){
return (12,testResults)
}
for i in inputResults.characters{
re1Arr.append(String(i))
}
for i in testResults.characters{
re2Arr.append(String(i))
}
let commonWords = re1Arr.filter(re2Arr.contains)
for a in re2Arr{
if(!commonWords.contains(a)){
filterWords += a
}
}
return (filterWords.count , filterWords)
}
//show training contents(start from num1)
public func contents(str : String, num : Int, textView: UITextView, recordButton : UIButton){
textView.isHidden = false
recordButton.isHidden = false
let fontSize = ModelData.shared.fontSize
textView.font = .systemFont(ofSize: CGFloat(fontSize[num - 1] * 1.4))
//fixed 3 lines
var number = 0
var fixStr = [Character]()
for everyChar in str.characters{
if(number == 4 || number == 8 || number == 12){
fixStr.append("\n")
fixStr.append(everyChar)
}
else{
fixStr.append(everyChar)
}
number += 1
}
let str = String(fixStr)
textView.textContainer.maximumNumberOfLines = 4
textView.text = str
}
public func hideContents(textView : UITextView, recordButton : UIButton){
textView.isHidden = true
recordButton.isHidden = false
}
public func showContents(leftContents: [String], times : Int, textView: UITextView, recordButton: UIButton) -> String{
let numCount = leftContents.count
let arrayKey = Int(arc4random_uniform(UInt32(numCount))) //random cases
let chooseContent = leftContents[arrayKey]
contents(str: chooseContent, num: times, textView: textView, recordButton: recordButton)
return chooseContent
}
//------------------------------------------------------------------------------------------------least square
func average(_ input: [Double]) -> Double {
return input.reduce(0, +) / Double(input.count)
}
func multiply(_ a: [Double], _ b: [Double]) -> [Double] {
return zip(a,b).map(*)
}
func linearRegression(_ xs: [Double], _ ys: [Double], midIndex : Int, theta :Double) -> Double {
let lsx = Array(xs.prefix(xs.count - midIndex))
let lsy = Array(ys.prefix(ys.count - midIndex))
let sum1 = average(multiply(lsx, lsy)) - average(lsx) * average(lsy)
let sum2 = average(multiply(lsx, lsx)) - pow(average(lsx), 2)
let slope = sum1 / sum2
let intercept = average(lsy) - slope * average(lsx)
let x = (theta - intercept) / slope
return x
}
//two stright lines intersection, find optimal(theshold 0.4) not reversed yet
//get thate and optimal index point
func findTheta(_ xs : [Double]) -> (Double , Int){
if(xs.count > 2){
for i in 0...xs.count - 3{
if(xs[i] - xs[i + 1] > 0.4 && xs[i + 1] > xs[i + 2]){
let resultArray : [Double] = Array(xs.prefix(i))
return (average(resultArray) , i)
}
}
}
return (0.0 , 0)
}
//------------------------------------------------------------------------------------------------
// d//m/yyyy <-> yyyy/m/d 便于排序
func change_Date(date: String, change: Bool) -> String{
if change{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d/m/yyyy"// yyyy-MM-dd"
let new_dateFormatter = DateFormatter()
new_dateFormatter.dateFormat = "yyyy/m/d"// yyyy-MM-dd"
let date_1 = dateFormatter.date(from: date)//只需显示日期
let new_date = new_dateFormatter.string(from: date_1!)
return new_date}
else{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/m/d"
let new_dateFormatter = DateFormatter()
new_dateFormatter.dateFormat = "d/m/yyyy"
let date_1 = dateFormatter.date(from: date)
let new_date = new_dateFormatter.string(from: date_1!)
return new_date
}
}
| 32.337143 | 171 | 0.634741 |
89c0a8618aac361e144d2436ce76250ac67b45dc | 12,988 | //
// GLCoreProfileView.swift
// FindRabbit
//
// Created by chenjie on 2019/12/30.
// Copyright © 2019 chenjie. All rights reserved.
//
import GLKit
import Accelerate
private struct MapProgramUniformsLocation {
var vpMatrix: GLint = 0
var floorTexture: GLint = 0
}
private struct RabbitProgramUniformsLocation {
var viewMatrix: GLint = 0
var perspectiveMatrix: GLint = 0
}
class GLCoreProfileView: NSOpenGLView {
//MARK:- Public properties
// 除去暂停后实际渲染的时间
var renderDuration: TimeInterval = 0
// 当前观察点在世界坐标系xz平面的位置,其每个分量的取值范围都是[-64, 64]
var location = CGPoint(x: 0, y: 0)
// 当前视线的观察方向,取值范围为[0, 360)
var course: Float = 0
// 当前视线的俯仰角,取值范围为[0, 90]
var verticalViewAngle: Float = 0
// 相机观察方向,单位向量
var viewDirection = simd_float3(x: 0, y: 0, z: -1)
//MARK:- Private Properties
private var mapProgram: GLuint = 0
private var mapProgramVAO: GLuint = 0
private var mapProgramFloorTexture: GLuint = 0
private var mapProgramUniformsLocation = MapProgramUniformsLocation()
private var rabbitProgram: GLuint = 0
private var rabbitUniformBlockBuffer: GLuint = 0
private var rabbitProgramUnifromsLocation = RabbitProgramUniformsLocation()
// 每个兔子模型映射到世界坐标系时的平移矩阵
private var rabbitTranslationMatrixs = [GLKMatrix4]()
//MARK:- Life Cycles
override init?(frame frameRect: NSRect, pixelFormat format: NSOpenGLPixelFormat?) {
super.init(frame: frameRect, pixelFormat: format)
// 禁用Retina屏幕显示
self.wantsBestResolutionOpenGLSurface = false
self.prepareOpenGLContex()
// 准备渲染所必须的数据
for _ in 0..<64 {
let translationMatrix = GLKMatrix4MakeTranslation(Float.random(in: -64...64), Float.random(in: 0...5), Float.random(in: -64...64))
self.rabbitTranslationMatrixs.append(translationMatrix)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
glDeleteProgram(self.mapProgram)
glDeleteVertexArrays(1, &self.mapProgramVAO)
glDeleteTextures(1, &self.mapProgramFloorTexture)
glDeleteProgram(self.rabbitProgram)
glDeleteBuffers(1, &self.rabbitUniformBlockBuffer)
}
//MARK:- Private Methods: General
override func reshape() {
super.reshape()
glViewport(0, 0, GLsizei(NSWidth(self.frame)), GLsizei(NSHeight(self.frame)))
}
//MARK:- Private Methods: Render
private func prepareOpenGLContex() {
let pixelFormatAttributes = [UInt32(NSOpenGLPFAColorSize), 32,
UInt32(NSOpenGLPFADepthSize), 24,
UInt32(NSOpenGLPFAStencilSize), 8,
UInt32(NSOpenGLPFAAccelerated),
UInt32(NSOpenGLPFAOpenGLProfile), UInt32(NSOpenGLProfileVersion4_1Core),
0]
guard let pixelFormat = NSOpenGLPixelFormat(attributes: pixelFormatAttributes) else { return }
let currentOpenGLContext = NSOpenGLContext(format: pixelFormat, share: nil)
self.openGLContext = currentOpenGLContext
self.openGLContext?.makeCurrentContext()
// 设置缓存交换频率和屏幕刷新同步
var swapInterval = GLint(1)
CGLSetParameter(CGLGetCurrentContext()!, kCGLCPSwapInterval, &swapInterval)
}
override func prepareOpenGL() {
super.prepareOpenGL()
print("Version: \(String(cString: glGetString(uint32(GL_VERSION))))")
print("Renderer: \(String(cString: glGetString(uint32(GL_RENDERER))))")
print("Vendor: \(String(cString: glGetString(GLenum(GL_VENDOR))))")
print("GLSL Version: \(String(cString: glGetString(GLenum(GL_SHADING_LANGUAGE_VERSION))))")
// 1. 准备所有的OpenGL程序
if !self.prepareOpenGLProgram() {
return
}
// 2. 加载地图程序所需要的纹理
let textureLoaded = TextureManager.shareManager.loadObject(fileName: "floor.ktx", toTexture: &self.mapProgramFloorTexture, atIndex: GL_TEXTURE0)
if !textureLoaded {
print("Load texture failed")
return
}
// 3. 创建地图程序所需要使用到的VAO对象
glGenVertexArrays(1, &self.mapProgramVAO)
// 4. 加载兔子程序所需要使用到的模型
let modelLoaded = ModelManager.shareManager.loadObject(fileName: "bunny_1k.sbm")
if !modelLoaded {
print("Load model failed")
}
// 5. 准备地图程序所需要使用到的统一闭包缓存
glGenBuffers(1, &self.rabbitUniformBlockBuffer)
glBindBufferBase(GLenum(GL_UNIFORM_BUFFER), 0, self.rabbitUniformBlockBuffer)
glBufferData(GLenum(GL_UNIFORM_BUFFER), MemoryLayout<GLKMatrix4>.stride * 64, nil, GLenum(GL_DYNAMIC_DRAW))
}
private func prepareOpenGLProgram() -> Bool {
// 1. 准备地图OpenGL程序
let mapShaders = ["MapVertexShader" : GLenum(GL_VERTEX_SHADER),
"MapFragmentShader" : GLenum(GL_FRAGMENT_SHADER)]
let mapProgramSuccessed = self.prepareGLProgram(&self.mapProgram, shaders: mapShaders)
if !mapProgramSuccessed {
return false
}
self.mapProgramUniformsLocation.vpMatrix = glGetUniformLocation(self.mapProgram, "vpMatrix")
self.mapProgramUniformsLocation.floorTexture = glGetUniformLocation(self.mapProgram, "floorTexture")
// 2. 准备兔子OpenGL程序
let rabbitShaders = ["RabbitVertexShader" : GLenum(GL_VERTEX_SHADER),
"RabbitFragmentShader" : GLenum(GL_FRAGMENT_SHADER)]
let rabbitProgramSuccessed = self.prepareGLProgram(&self.rabbitProgram, shaders: rabbitShaders)
if !rabbitProgramSuccessed {
return false
}
self.rabbitProgramUnifromsLocation.viewMatrix = glGetUniformLocation(self.rabbitProgram, "viewMatrix")
self.rabbitProgramUnifromsLocation.perspectiveMatrix = glGetUniformLocation(self.rabbitProgram, "perspectiveMatrix")
let uniformBlockIndex = glGetUniformBlockIndex(self.rabbitProgram, "ModelMatrixs")
glUniformBlockBinding(self.rabbitProgram, uniformBlockIndex, 0)
return true
}
private func prepareGLProgram(_ glProgram: inout GLuint, shaders: [String : GLenum]) -> Bool {
if shaders.count == 0 {
print("No available shader.")
return false
}
// 1. 创建GL程序
glProgram = glCreateProgram()
for (_, shaderInfo) in shaders.enumerated() {
// 2. 获取着色器的源码
guard let shaderPath = Bundle.main.path(forResource: shaderInfo.key, ofType: "glsl") else {
print("Can not find shader file at " + shaderInfo.key)
return false
}
// 3. 创建着色器
let shader = glCreateShader(shaderInfo.value)
// 4. 编译着色器
if !self.compileShader(shader, filePath: shaderPath) {
glDeleteShader(shader)
return false
}
// 5. 将着色器附着至OpenGL程序
glAttachShader(glProgram, shader)
glDeleteShader(shader)
}
// 6. 编译GL程序
if !self.linkProgram(program: glProgram) {
print("Failed to link program")
glDeleteProgram(glProgram)
glProgram = 0
return false
}
return true
}
private func compileShader(_ shader: GLuint, filePath: String) -> Bool {
// 1. 为着色器填充源码
var shaderSource: UnsafePointer<GLchar>?
do {
shaderSource = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue).utf8String
} catch {
print("Error when compile shader")
}
glShaderSource(shader, 1, &shaderSource, nil)
// 2. 编译着色器
glCompileShader(shader)
// 3. 查询着色器编译错误日志
var status: GLint = 0
glGetShaderiv(shader, GLenum(GL_COMPILE_STATUS), &status)
if status == 0 {
var logLength: GLint = 0
glGetShaderiv(shader, GLenum(GL_INFO_LOG_LENGTH), &logLength)
var infoLogChars = [GLchar](repeating: 0, count: Int(logLength))
glGetShaderInfoLog(shader, logLength, nil, &infoLogChars)
let infoLogString = String(utf8String: infoLogChars) ?? ""
print("Compile Shader Failed at \n" + filePath + "\nWith Log\n" + infoLogString)
return false
}
return true
}
func linkProgram(program: GLuint) -> Bool {
glLinkProgram(program)
var status: GLint = 0
glGetProgramiv(program, GLenum(GL_LINK_STATUS), &status)
if status == 0 {
var logLength: GLint = 0
glGetProgramiv(program, GLenum(GL_INFO_LOG_LENGTH), &logLength)
var logChars = [GLchar](repeating: 0, count: Int(logLength))
glGetProgramInfoLog(program, GLsizei(logLength), nil, &logChars)
let logString = String(utf8String: logChars) ?? ""
print("Compile program failed with log \n" + logString)
return false
}
return true
}
override func draw(_ dirtyRect: NSRect) {
// 1. 绘制地板
// 1.1 禁用面剔除和深度测试
glDisable(GLenum(GL_CULL_FACE))
glDisable(GLenum(GL_DEPTH_TEST))
// 1.2 清空颜色缓存
var blackColor: [GLfloat] = [0.1, 0.1, 0.1, 1]
glClearBufferfv(GLenum(GL_COLOR), 0, &blackColor)
// 1.3 设置OpenGL程序
glUseProgram(self.mapProgram)
// 1.4 为统一变量赋值
// 为观察投影矩阵赋值
let eyePosition = simd_float3(x: Float(self.location.x), y: 1, z: Float(self.location.y))
let poi = eyePosition + self.viewDirection
var viewMatrix = GLKMatrix4MakeLookAt(eyePosition.x, eyePosition.y, eyePosition.z,
poi.x, poi.y, poi.z,
0, 1, 0)
var perspectiveMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(50),
Float(NSWidth(self.frame)/NSHeight(self.frame)),
0.1, 1000)
var vpMatrix = GLKMatrix4Multiply(perspectiveMatrix, viewMatrix)
withUnsafePointer(to: &vpMatrix.m) {
$0.withMemoryRebound(to: GLfloat.self, capacity: 16) {
glUniformMatrix4fv(self.mapProgramUniformsLocation.vpMatrix, 1, GLboolean(GL_FALSE), $0)
}
}
// 为地板纹理赋值
glActiveTexture(GLenum(GL_TEXTURE0))
glBindTexture(GLenum(GL_TEXTURE_2D), self.mapProgramFloorTexture)
glUniform1i(self.mapProgramUniformsLocation.floorTexture, 0)
// 1.5 设置地图OpenGL程序需要使用的VAO对象
glBindVertexArray(self.mapProgramVAO)
// 1.6 绘制128*128个地砖
glDrawArraysInstanced(GLenum(GL_TRIANGLE_STRIP), 0, 4, 128 * 128)
// 2. 绘制64个兔子模型
// 2.1 开启面剔除和深度测试
glEnable(GLenum(GL_CULL_FACE))
glEnable(GLenum(GL_DEPTH_TEST))
glDepthFunc(GLenum(GL_LEQUAL))
// 2.2 设置深度缓存默认值
var defaultDepth: GLfloat = 1
glClearBufferfv(GLenum(GL_DEPTH), 0, &defaultDepth)
// 2.3 设置OpenGL程序
glUseProgram(self.rabbitProgram)
// 2.4 为统一变量赋值
// 填充模型矩阵的统一闭包数据
var matrixData = [GLKMatrix4]()
for index in 0..<64 {
let rotationMatrix = GLKMatrix4MakeYRotation(Float(self.renderDuration))
let modelMatrix = GLKMatrix4Multiply(self.rabbitTranslationMatrixs[index], rotationMatrix)
matrixData.append(modelMatrix)
}
glBindBufferBase(GLenum(GL_UNIFORM_BUFFER), 0, self.rabbitUniformBlockBuffer)
guard let dataAdress = glMapBufferRange(GLenum(GL_UNIFORM_BUFFER), 0, MemoryLayout<GLKMatrix4>.stride * 64, GLbitfield(GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT)) else {
return
}
dataAdress.initializeMemory(as: GLKMatrix4.self, from: &matrixData, count: 64)
glUnmapBuffer(GLenum(GL_UNIFORM_BUFFER))
// 设置观察矩阵
withUnsafePointer(to: &viewMatrix.m) {
$0.withMemoryRebound(to: GLfloat.self, capacity: 16) {
glUniformMatrix4fv(self.rabbitProgramUnifromsLocation.viewMatrix, 1, GLboolean(GL_FALSE), $0)
}
}
// 设置投影矩阵
withUnsafePointer(to: &perspectiveMatrix.m) {
$0.withMemoryRebound(to: GLfloat.self, capacity: 16) {
glUniformMatrix4fv(self.rabbitProgramUnifromsLocation.perspectiveMatrix, 1, GLboolean(GL_FALSE), $0)
}
}
// 2.5 绘制模型
ModelManager.shareManager.render(instanceCount: 64)
// 3. 清空OpenGL指令缓存,使渲染引擎尽快执行已经发布的渲染指令,同时发布窗口缓存的数据已经做好合并进入系统桌面缓存的准备
glFlush()
}
}
| 38.886228 | 183 | 0.614567 |
4bc482aa4a947536f2fca593f0825b562d04877a | 573 | //
// PostService.swift
// JPH
//
// Created by Ridoan Wibisono on 14/10/21.
//
import Foundation
import Combine
protocol PostProtocol{
func fecthPosts() -> AnyPublisher<[Post], Error>
func fetchPost(id: Int) -> AnyPublisher<Post, Error>
}
struct PostService : PostProtocol{
private var api: BaseService = BaseService()
func fecthPosts() -> AnyPublisher<[Post], Error>{
api.load(url: URL(string: endpoint.baseUrl+"/posts")!)
}
func fetchPost(id: Int) -> AnyPublisher<Post, Error> {
api.load(url: URL(string: endpoint.baseUrl+"/posts/\(id)")!)
}
}
| 19.1 | 62 | 0.682373 |
abfdabd8b025ab0207d3f6e569aa172418f70a63 | 3,785 | //
// PostViewController.swift
// InstantGram
//
// Created by Naveen Kashyap on 2/19/17.
// Copyright © 2017 Naveen Kashyap. All rights reserved.
//
import UIKit
import ASProgressHud
class PostViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageToPostView: UIImageView!
@IBOutlet weak var captionTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imageToPostView.image = #imageLiteral(resourceName: "NoPicture")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTakePicture(_ sender: Any) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
vc.sourceType = UIImagePickerControllerSourceType.camera
self.present(vc, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
// Get the image captured by the UIImagePickerController
let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage
//let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage
// Do something with the images (based on your use case)
imageToPostView.image = originalImage
// Dismiss UIImagePickerController to go back to your original view controller
dismiss(animated: true, completion: nil)
}
@IBAction func onPost(_ sender: Any) {
captionTextField.isEnabled = false
ASProgressHud.showHUDAddedTo(self.view, animated: true, type: .default)
let size = CGSize(width: imageToPostView.frame.size.width, height: imageToPostView.frame.size.height)
imageToPostView.image = resize(image: imageToPostView.image!, newSize: size)
Post.postUserImage(image: imageToPostView.image, withCaption: captionTextField.text) { (wasSuccessful: Bool, error: Error?) in
if wasSuccessful {
ASProgressHud.hideHUDForView(self.view, animated: true)
self.navigationController?.popViewController(animated: true)
} else {
print(error?.localizedDescription ?? "Could not post image. Idk.")
}
}
}
func resize(image: UIImage, newSize: CGSize) -> UIImage {
let resizeImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
resizeImageView.contentMode = UIViewContentMode.scaleAspectFill
resizeImageView.image = image
UIGraphicsBeginImageContext(resizeImageView.frame.size)
resizeImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
@IBAction func onChooseFromGallery(_ sender: Any) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
vc.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(vc, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 38.232323 | 134 | 0.676882 |
62af64fb5b40e100b80646313933872d3f526106 | 1,297 | /*
* Copyright 2019 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Internal API for working with a screen view controller when the specific screen type is unknown.
protocol UntypedScreenViewController {
var screenType: Screen.Type { get }
func update(untypedScreen: Screen)
}
extension ScreenViewController: UntypedScreenViewController {
// `var screenType: Screen.Type` is already present in ScreenViewController
func update(untypedScreen: Screen) {
guard let typedScreen = untypedScreen as? ScreenType else {
fatalError("Screen type mismatch: \(self) expected to receive a screen of type \(ScreenType.self), but instead received a screen of type \(type(of: screen))")
}
update(screen: typedScreen)
}
}
| 36.027778 | 170 | 0.727833 |
6a340d29d441a69edee4422d6abc9ddd9611ac77 | 2,155 | //
// AppDelegate.swift
// Pitch Perfect
//
// Created by Rodrigo Webler on 5/13/15.
// Copyright (c) 2015 Rodrigo Webler. 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.851064 | 285 | 0.75406 |
87737a93aa4af9fc85a6691670d245ab62eabcf2 | 10,940 | //
// HomeViewController.swift
// parsetagram
//
// Created by Angeline Rao on 6/20/16.
// Copyright © 2016 Angeline Rao. All rights reserved.
//
import UIKit
import Parse
import MBProgressHUD
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
@IBOutlet weak var feedView: UITableView!
var posts: [PFObject]? = []
var isMoreDataLoading = false
var loadingMoreView:InfiniteScrollActivityView?
var queryLimit: Int? = 20
var isLiked = false
override func viewDidLoad() {
super.viewDidLoad()
self.feedView.delegate = self
self.feedView.dataSource = self
// Do any additional setup after loading the view.
let frame = CGRectMake(0, feedView.contentSize.height, feedView.bounds.size.width, InfiniteScrollActivityView.defaultHeight)
loadingMoreView = InfiniteScrollActivityView(frame: frame)
loadingMoreView!.hidden = true
feedView.addSubview(loadingMoreView!)
var insets = feedView.contentInset;
insets.bottom += InfiniteScrollActivityView.defaultHeight;
feedView.contentInset = insets
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(loadFeed(_:firstLoad:)), forControlEvents: UIControlEvents.ValueChanged)
self.loadFeed(refreshControl, firstLoad: true)
feedView.insertSubview(refreshControl, atIndex: 0)
}
@IBAction func onComment(sender: AnyObject) {
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return posts?.count ?? 0
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 70.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = self.feedView.dequeueReusableCellWithIdentifier("HeaderCell") as! HeaderCell
let post = posts![section]
let user = post["author"] as! PFUser
headerCell.usernameLabel.text = user.username
if let time = post["creationString"] as? String {
headerCell.timeLabel.text = time
}
else {
headerCell.timeLabel.text = ""
}
if let caption = post["caption"] as? String {
headerCell.captionLabel.text = caption
}
else {
headerCell.captionLabel.text = ""
}
if let profpic = user["profilePic"] as? PFFile {
profpic.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) in
if imageData != nil {
let image = UIImage(data: imageData!)
headerCell.profPicView.layer.cornerRadius = headerCell.profPicView.frame.height/2
//headerCell.profPicView.layer.cornerRadius = 20
headerCell.profPicView.clipsToBounds = true
headerCell.profPicView.image = image
}
else {
print(error)
}
}
}
else {
headerCell.profPicView.image = UIImage()
}
headerCell.captionLabel.hidden = true
return headerCell
}
func loadFeed(refresh: UIRefreshControl, firstLoad: Bool) {
let query = PFQuery(className: "Post")
query.limit = queryLimit!
query.orderByDescending("createdAt")
query.includeKey("author")
if firstLoad {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
}
query.findObjectsInBackgroundWithBlock { (pics: [PFObject]?, error: NSError?) in
if error != nil {
print(error)
print("did not successfully get pics")
}
else {
self.posts = pics
self.isMoreDataLoading = false
self.feedView.reloadData()
MBProgressHUD.hideHUDForView(self.view, animated: true)
refresh.endRefreshing()
}
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if !isMoreDataLoading {
let scrollViewContentHeight = feedView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - feedView.bounds.size.height
if (scrollView.contentOffset.y > scrollOffsetThreshold && feedView.dragging) {
isMoreDataLoading = true
let frame = CGRectMake(0, feedView.contentSize.height, feedView.bounds.size.width, InfiniteScrollActivityView.defaultHeight)
loadingMoreView?.frame = frame
loadingMoreView!.startAnimating()
self.loadMoreData()
}
}
}
func loadMoreData() {
let query = PFQuery(className: "Post")
queryLimit = queryLimit! + 20
query.limit = queryLimit!
query.orderByDescending("createdAt")
query.includeKey("author")
query.findObjectsInBackgroundWithBlock { (pics: [PFObject]?, error: NSError?) in
if error != nil {
print(error)
print("did not successfully get pics")
}
else {
self.posts = pics
self.isMoreDataLoading = false
self.loadingMoreView!.stopAnimating()
self.feedView.reloadData()
}
}
}
@IBAction func onLike(sender: UIButton) {
// sender.enabled = false
// sender.userInteractionEnabled = false
// sender.alpha = 0.5
//get the point in the table view that corresponds to the button that was pressed
//in my case these were a bunch of cells each with their own like button
let hitPoint = sender.convertPoint(CGPointZero, toView: self.feedView)
let indexPath = self.feedView.indexPathForRowAtPoint(hitPoint)
let post = posts![(indexPath?.section)!]
//print(post["likesCount"])
let cell = self.feedView.cellForRowAtIndexPath((indexPath)!) as! PostCell
//let object = self.feedView.cellForRowAtIndexPath(hitIndex!)
//this is where I incremented the key for the object
// if you just liked the pic
if !isLiked {
let image = UIImage(named: "likedButton")
cell.likeButton.setImage(image, forState: UIControlState.Normal)
post.incrementKey("likesCount")
isLiked = true
}
else {
let image = UIImage(named: "likeButton")
cell.likeButton.setImage(image, forState: UIControlState.Normal)
post.incrementKey("likesCount", byAmount: -1)
isLiked = false
}
//print(post["likesCount"])
post.saveInBackgroundWithBlock { (success: Bool, error: NSError?) in
if success {
self.feedView.reloadData()
}
else {
print(error)
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.feedView.dequeueReusableCellWithIdentifier("PostCell", forIndexPath: indexPath) as! PostCell
let post = posts![indexPath.section]
let imageFile = post["media"] as! PFFile
imageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) in
if imageData != nil {
let image = UIImage(data: imageData!)
cell.pictureView.image = image
}
else {
print(error)
}
}
cell.captionLabel.text = post["caption"] as? String
let numLikes = post["likesCount"] as! Int
if numLikes == 0 {
cell.likeLabel.text = ""
}
else if numLikes == 1 {
cell.likeLabel.text = "1 like"
}
else {
cell.likeLabel.text = "\(numLikes) likes"
}
let user = post["author"] as! PFUser
if let username = user.username {
cell.usernameLabel.text = username
}
// if let profpic = user["profilePic"] as? PFFile {
// profpic.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) in
// if imageData != nil {
// let image = UIImage(data: imageData!)
// cell.profPicView.image = image
// }
// else {
// print(error)
// }
// }
// }
// else {
// cell.profPicView.image = UIImage()
// }
// if let date = post["creationString"] as? String {
// cell.timeLabel.text = date
// }
// else {
// cell.timeLabel.text = ""
// }
cell.usernameLabel.hidden = true
return cell
}
// func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return posts?.count ?? 0
// }
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier != "addComment" {
let detailViewController = segue.destinationViewController as! PostDetailViewController
let indexPath = feedView.indexPathForCell(sender as! UITableViewCell)
let post = posts![indexPath!.section]
detailViewController.post = post
detailViewController.isLiked = isLiked
}
else {
let commentViewController = segue.destinationViewController as! CommentViewController
let button = sender as! UIButton
let view = button.superview!
let cell = view.superview as! PostCell
let indexPath = feedView.indexPathForCell(cell)
let post = posts![indexPath!.section]
commentViewController.post = post
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 35.176849 | 140 | 0.577239 |
ef51c2207f9b24c2b8cfe2d5e32b191397f916ca | 332 | import RxSwift
class SessionService: Authentication {
func signIn() -> Single<SignInResponse> {
return Single<SignInResponse>.create { single in
// call to backend
single(.success(SignInResponse.success(token: "12345", userId: "5678")))
return Disposables.create()
}
}
}
| 27.666667 | 84 | 0.620482 |
22f542da752db5035fff438ef3f9766ccc06191f | 880 | import Foundation
import SwiftUI
import Stinsen
struct CreateTodoScreen: View {
@State private var text: String = ""
@EnvironmentObject private var todosRouter: TodosCoordinator.Router
@ObservedObject private var todosStore: TodosStore
var body: some View {
VStack {
RoundedTextField("Todo name", text: $text)
RoundedButton("Create") {
todosStore.all.append(Todo(name: text))
todosRouter.popToRoot()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
init(todosStore: TodosStore) {
self.todosStore = todosStore
}
}
struct CreateTodoScreen_Previews: PreviewProvider {
static var previews: some View {
CreateTodoScreen(todosStore: TodosStore(user: User(username: "[email protected]", accessToken: UUID().uuidString)))
}
}
| 28.387097 | 122 | 0.645455 |
ffc0171fdecfdeb259dee46eb7a07f5e5a765151 | 497 | //
// LocalStorage.swift
// UtilityKit
//
// Created by Vivek Kumar on 30/08/19.
//
import Foundation
public class LocalStorage{
public static let shared = LocalStorage()
public let userDefaults = UserDefaults.standard
public func store(value:Any,key:String){
userDefaults.setValue(value, forKey: key)
}
public func dictionary(forKey:String) -> [String:Any] {
let json = userDefaults.string(forKey: forKey) ?? "{}"
return json.toDictionary()
}
}
| 24.85 | 62 | 0.67002 |
4bfa24bb66d38ed5795d95c4d04f42ae92cffc30 | 6,900 | /**
* BulletinBoard
* Copyright (c) 2017 Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* A standard bulletin item with a title and optional additional informations. It can display a large
* action button and a smaller button for alternative options.
*
* - If you need to display custom elements with the standard buttons, subclass `PageBulletinItem` and
* implement the `makeArrangedSubviews` method to return the elements to display above the buttons.
*
* You can also override this class to customize button tap handling. Override the `actionButtonTapped(sender:)`
* and `alternativeButtonTapped(sender:)` methods to handle tap events. Make sure to call `super` in your
* implementations if you do.
*
* Use the `appearance` property to customize the appearance of the page. If you want to use a different interface
* builder type, change the `InterfaceBuilderType` property.
*/
@objc open class PageBulletinItem: ActionBulletinItem {
// MARK: Initialization
/**
* Creates a bulletin page with the specified title.
* - parameter title: The title of the page.
*/
@objc public init(title: String) {
self.title = title
}
@available(*, unavailable, message: "PageBulletinItem.init is unavailable. Use init(title:) instead.")
override init() {
fatalError("PageBulletinItem.init is unavailable. Use init(title:) instead.")
}
// MARK: - Page Contents
/// The title of the page.
@objc public let title: String
/**
* An image to display below the title.
*
* If you set this property to `nil`, no image will be displayed (this is the default).
*
* The image should have a size of 128x128 pixels (@1x).
*/
@objc public var image: UIImage?
/// An accessibility label which gets announced to VoiceOver users if the image gets focused.
@objc public var imageAccessibilityLabel: String?
/**
* An description text to display below the image.
*
* If you set this property to `nil`, no label will be displayed (this is the default).
*/
@objc public var descriptionText: String?
// MARK: - Customization
/**
* The views to display above the title.
*
* You can override this method to insert custom views before the title. The default implementation returns `nil` and
* does not append header elements.
*
* This method is called inside `makeArrangedSubviews` before the title is created.
*
* - parameter interfaceBuilder: The interface builder used to create the title.
* - returns: The header views for the item, or `nil` if no header views should be added.
*/
open func headerViews(_ interfaceBuilder: BulletinInterfaceBuilder) -> [UIView]? {
return nil
}
/**
* The views to display below the title.
*
* You can override this method to insert custom views after the title. The default implementation returns `nil` and
* does not append elements after the title.
*
* This method is called inside `makeArrangedSubviews` after the title is created.
*
* - parameter interfaceBuilder: The interface builder used to create the title.
* - returns: The views to display after the title, or `nil` if no views should be added.
*/
open func viewsUnderTitle(_ interfaceBuilder: BulletinInterfaceBuilder) -> [UIView]? {
return nil
}
/**
* The views to display below the image.
*
* You can override this method to insert custom views after the image. The default implementation returns `nil` and
* does not append elements after the image.
*
* This method is called inside `makeArrangedSubviews` after the image is created.
*
* - parameter interfaceBuilder: The interface builder used to create the image.
* - returns: The views to display after the image, or `nil` if no views should be added.
*/
open func viewsUnderImage(_ interfaceBuilder: BulletinInterfaceBuilder) -> [UIView]? {
return nil
}
/**
* The views to display below the description.
*
* You can override this method to insert custom views after the description. The default implementation
* returns `nil` and does not append elements after the description.
*
* This method is called inside `makeArrangedSubviews` after the description is created.
*
* - parameter interfaceBuilder: The interface builder used to create the description.
* - returns: The views to display after the description, or `nil` if no views should be added.
*/
open func viewsUnderDescription(_ interfaceBuilder: BulletinInterfaceBuilder) -> [UIView]? {
return nil
}
// MARK: - View Management
@objc public private(set) var titleLabel: UILabel!
@objc public private(set) var descriptionLabel: UILabel?
@objc public private(set) var imageView: UIImageView?
/**
* Creates the content views of the page.
*
* It creates the standard elements and appends the additional customized elements returned by the
* `viewsUnder` hooks.
*/
public final override func makeContentViews(interfaceBuilder: BulletinInterfaceBuilder) -> [UIView] {
var contentViews = [UIView]()
func insertComplementaryViews(_ builder: (BulletinInterfaceBuilder) -> [UIView]?) {
if let complementaryViews = builder(interfaceBuilder) {
contentViews.append(contentsOf: complementaryViews)
}
}
insertComplementaryViews(headerViews)
// Title Label
titleLabel = interfaceBuilder.makeTitleLabel()
titleLabel.text = title
contentViews.append(titleLabel)
insertComplementaryViews(viewsUnderTitle)
// Image View
if let image = self.image {
let imageView = UIImageView()
imageView.image = image
imageView.contentMode = .scaleAspectFit
imageView.tintColor = appearance.imageViewTintColor
imageView.heightAnchor.constraint(lessThanOrEqualToConstant: 128).isActive = true
if let imageAccessibilityLabel = imageAccessibilityLabel {
imageView.isAccessibilityElement = true
imageView.accessibilityLabel = imageAccessibilityLabel
}
self.imageView = imageView
contentViews.append(imageView)
}
insertComplementaryViews(viewsUnderImage)
// Description Label
if let descriptionText = self.descriptionText {
descriptionLabel = interfaceBuilder.makeDescriptionLabel()
descriptionLabel!.text = descriptionText
contentViews.append(descriptionLabel!)
}
insertComplementaryViews(viewsUnderDescription)
return contentViews
}
}
| 33.014354 | 121 | 0.675362 |
6aa7a67c4438cd4eebb1a0aa4a50f27a6dde3624 | 2,984 | //
// EVWorkaroundHelpers.swift
// EVReflection
//
// Created by Edwin Vermeer on 2/7/16.
// Copyright © 2016 evict. All rights reserved.
//
import Foundation
/**
Protocol for the workaround when using generics. See WorkaroundSwiftGenericsTests.swift
*/
public protocol EVGenericsKVC {
/**
Implement this protocol in a class with generic properties so that we can still use a standard mechanism for setting property values.
*/
func setValue(value: AnyObject!, forUndefinedKey key: String)
}
/**
Protocol for the workaround when using an enum with a rawValue of type Int
*/
public protocol EVRawInt {
/**
Protocol EVRawString can be added to an Enum that has Int as it's rawValue so that we can detect from a generic enum what it's rawValue is.
*/
var rawValue: Int { get }
}
/**
Protocol for the workaround when using an enum with a rawValue of type String
*/
public protocol EVRawString {
/**
Protocol EVRawString can be added to an Enum that has String as it's rawValue so that we can detect from a generic enum what it's rawValue is.
*/
var rawValue: String { get }
}
/**
Protocol for the workaround when using an enum with a rawValue of an undefined type
*/
public protocol EVRaw {
/**
For implementing a function that will return the rawValue for a non sepecific enum
*/
var anyRawValue: Any { get }
}
/**
Protocol for the workaround when using an array with nullable values
*/
public protocol EVArrayConvertable {
/**
For implementing a function for converting a generic array to a specific array.
*/
func convertArray(key: String, array: Any) -> NSArray
}
/**
Add a property to an enum to get the associated value
*/
public protocol EVAssociated {
}
/**
The implrementation of the protocol for getting the associated value
*/
public extension EVAssociated {
/**
Easy access to the associated value of an enum.
:returns: The label of the enum plus the associated value
*/
public var associated: (label: String, value: Any?) {
get {
let mirror = Mirror(reflecting: self)
if let associated = mirror.children.first {
return (associated.label!, associated.value)
}
print("WARNING: Enum option of \(self) does not have an associated value")
return ("\(self)", nil)
}
}
}
/**
Dictionary extension for creating a dictionary from an array of enum values
*/
public extension Dictionary {
/**
Create a dictionairy based on all associated values of an enum array
- parameter associated: array of dictionairy values which have an associated value
*/
init<T: EVAssociated>(associated: [T]?) {
self.init()
if associated != nil {
for myEnum in associated! {
self[(myEnum.associated.label as? Key)!] = myEnum.associated.value as? Value
}
}
}
}
| 27.127273 | 147 | 0.662534 |
f8b5a64f0a2b0135513fb1256b59e574e21610aa | 544 | //
// router.swift
// RestCombineApp
//
// Created by Trung on 13/03/2022.
//
import Foundation
import UIKit
enum RouteTarget {
case home
case detail(id: String)
case web(url: String, title: String?)
}
func makeViewController(target: RouteTarget) -> UIViewController {
switch(target) {
case .detail: return DetailViewController()
case .home: return createHomeVC()
case .web: return UIViewController()
}
}
private func createHomeVC() -> UIViewController {
container.resolve(HomeViewController.self)!
}
| 19.428571 | 66 | 0.696691 |
4a3cc2e048945d8679e1b882d49f1642db48d0c4 | 718 | //
// FirstViewController.swift
// SwiftProtocolOverExtension
//
// Created by Sanjeev Gautam on 22/11/20.
//
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.addRightBarButtonByExtenstion(title: "2nd Page")
self.title = "1st"
}
@objc override func rightBarButtonByExtenstionAction() {
print("rightBarButtonByExtenstionAction called on 1st VC")
if let secondVC = self.storyboard?.instantiateViewController(identifier: "SecondViewController") as? SecondViewController {
self.navigationController?.pushViewController(secondVC, animated: true)
}
}
}
| 25.642857 | 131 | 0.683844 |
fcedc314ccc189d1b88df7074644cce7ac66fe2d | 703 | import Foundation
// TODO: Remove this file when calls the API through KMM module is implemented
var dummyStaffs: [Staff] {
var staffs = [Staff]()
for _ in 0...10 {
let staff = Staff(
name: "dummy name",
detail: "dummy detail",
iconUrl: URL(string: "https://example.com")!
)
staffs.append(staff)
}
return staffs
}
var dummyContributors: [Contributor] {
var contributors = [Contributor]()
for _ in 0...10 {
let contributor = Contributor(
name: "dummy name",
iconUrl: URL(string: "https://example.com")!
)
contributors.append(contributor)
}
return contributors
}
| 25.107143 | 78 | 0.576102 |
de1fbb9731514b7d446e98a1d09304d23d0e7c58 | 1,253 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
struct Q<T where g: C {
var f : e
var f {
let a {
class a<T where H.h == D>(a<f : c<T where g
let v: c<I : a {
func b() -> <I : a {
if true {
}
func g: C {
}
protocol A : b() -> <f {
var d = b(a<I : P {
class d<T where g: () -> <T where H.e : a {
protocol b {
class a<Int>(a<T : b
protocol A {
var f : P {
func f: Int = b<T where H.e : P {
let a {
var f : d where g: a {
}
func b<T where T where g: a {
protocol A {
}
}
struct Q<Int>(a<T where g.e : C {
class a<T where g: C {
}
func g.e where g: C {
protocol A {
protocol A {
class A {
class a<Int>) {
var f {
var f {
protocol b {
func f: C {
}
}
if true {
protocol A {
struct Q<T>() {
for b {
}
for b in c: a {
class A {
if true {
}
func f: C {
func g: c<T : P {
if true {
class A {
var f : a {
protocol A {
if true {
}
let a {
}
class a<T>) {
}
}
let v: C {
class A {
class a<f {
for b {
for b in c<T where g: a {
func f: d = e, g: a {
class a<f : Int = B<I : P {
}
class c<f : e, g: a {
class a<I : P {
protocol b {
class B<T where T where H.h == b<T>) {
va d<T where T where g: e = f {
if true {
class a<Int>(a<T where
| 15.096386 | 87 | 0.565842 |
e635a72da525425a77e0bb919d9874eb324f5b50 | 2,174 | /*:
# Serial pipelines 4: asynchrony
> **This playground requires the CwlSignal.framework built by the CwlSignal_macOS scheme.** If you're seeing errors finding or building module 'CwlSignal', follow the Build Instructions on the [Contents](Contents) page.
## Using the `context` parameter.
Most functions in CwlSignal that accept a closure or other processing function will also take a `context` parameter immediately before the closure. This `context` specifies the execution context where the closure or function should run.
By default, this `context` is `.direct` (specifying that the closure should be directly invoked like a regular function) but you can specify an asynchronous context (like one of the Dispatch global concurrent queues or a private queue) to have the signal processed asychronously. In this way, reactive programming can snake across multiple contexts, multiple threads and multiple delays over time.
> `Signal` will ensure that values sent through the channel are delivered in-order, even if the context is concurrent.
---
*/
import CwlSignal
let semaphore = DispatchSemaphore(value: 0)
let completionContext = Exec.asyncQueue()
// Create an input/output pair
let (input, output) = Signal<Int>.channel()
.map(context: .global) { value in
// Perform the background work on the default global concurrent DispatchQueue
return sqrt(Double(value))
}
.subscribe(context: completionContext) { result in
// Deliver to a completion thread.
switch result {
case .success(let value): print(value)
case .failure: print("Done"); semaphore.signal()
}
}
// Send values to the input end
input.send(1, 2, 3, 4, 5, 6, 7, 8, 9)
input.close()
// In reactive programming, blocking is normally discouraged (you should subscribe to all
// dependencies and process when they're all done) but we need to block or the playground
// will finish before the background work.
semaphore.wait()
/*:
---
*This example writes to the "Debug Area". If it is not visible, show it from the menubar: "View" → "Debug Area" → "Show Debug Area".*
[Next page: Parallel composition - combine](@next)
[Previous page: Serial pipelines - channel](@previous)
*/
| 40.259259 | 397 | 0.75529 |
33db930b3d3aaaf6b80c0ad84d8847b49cde194f | 6,861 | //
// TrackersPreferences.swift
// HSTracker
//
// Created by Benjamin Michotte on 29/02/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import Preferences
class TrackersPreferences: NSViewController, PreferencePane {
var preferencePaneIdentifier = Preferences.PaneIdentifier.trackers
var preferencePaneTitle = NSLocalizedString("Trackers", comment: "")
var toolbarItemIcon = NSImage(named: "gear")!
@IBOutlet weak var highlightCardsInHand: NSButton!
@IBOutlet weak var highlightLastDrawn: NSButton!
@IBOutlet weak var removeCards: NSButton!
@IBOutlet weak var highlightDiscarded: NSButton!
@IBOutlet weak var opacity: NSSlider!
@IBOutlet weak var cardSize: NSComboBox!
@IBOutlet weak var showTimer: NSButton!
@IBOutlet weak var autoPositionTrackers: NSButton!
@IBOutlet weak var showSecretHelper: NSButton!
@IBOutlet weak var showRarityColors: NSButton!
@IBOutlet weak var showFloatingCard: NSButton!
@IBOutlet weak var showTopdeckChance: NSButton!
@IBOutlet weak var theme: NSComboBox!
@IBOutlet weak var allowFullscreen: NSButton!
@IBOutlet weak var hideAllWhenNotInGame: NSButton!
@IBOutlet weak var hideAllWhenGameInBackground: NSButton!
@IBOutlet weak var disableTrackingInSpectatorMode: NSButton!
@IBOutlet weak var floatingCardStyle: NSComboBox!
@IBOutlet weak var showExperienceCounter: NSButton!
let themes = ["classic", "frost", "dark", "minimal"]
override func viewDidLoad() {
super.viewDidLoad()
highlightCardsInHand.state = Settings.highlightCardsInHand ? .on : .off
highlightLastDrawn.state = Settings.highlightLastDrawn ? .on : .off
removeCards.state = Settings.removeCardsFromDeck ? .on : .off
highlightDiscarded.state = Settings.highlightDiscarded ? .on : .off
opacity.doubleValue = Settings.trackerOpacity
var index: Int
switch Settings.cardSize {
case .tiny: index = 0
case .small: index = 1
case .medium: index = 2
case .big: index = 3
case .huge: index = 4
}
cardSize.selectItem(at: index)
showTimer.state = Settings.showTimer ? .on : .off
autoPositionTrackers.state = Settings.autoPositionTrackers ? .on : .off
showSecretHelper.state = Settings.showSecretHelper ? .on : .off
showRarityColors.state = Settings.showRarityColors ? .on : .off
showFloatingCard.state = Settings.showFloatingCard ? .on : .off
showTopdeckChance.state = Settings.showTopdeckchance ? .on : .off
showExperienceCounter.state = Settings.showExperienceCounter ? .on : .off
floatingCardStyle.isEnabled = Settings.showFloatingCard
switch Settings.floatingCardStyle {
case .text: index = 0
case .image: index = 1
}
floatingCardStyle.selectItem(at: index)
theme.selectItem(at: themes.firstIndex(of: Settings.theme) ?? 0)
allowFullscreen.state = Settings.canJoinFullscreen ? .on : .off
hideAllWhenNotInGame.state = Settings.hideAllTrackersWhenNotInGame ? .on : .off
hideAllWhenGameInBackground.state = Settings.hideAllWhenGameInBackground
? .on : .off
disableTrackingInSpectatorMode.state = Settings.dontTrackWhileSpectating ? .on : .off
}
@IBAction func sliderChange(_ sender: AnyObject) {
Settings.trackerOpacity = opacity.doubleValue
}
@IBAction func comboboxChange(_ sender: NSComboBox) {
if sender == cardSize {
if let value = cardSize.objectValueOfSelectedItem as? String {
let size: CardSize
switch value {
case NSLocalizedString("Tiny", comment: ""): size = .tiny
case NSLocalizedString("Small", comment: ""): size = .small
case NSLocalizedString("Big", comment: ""): size = .big
case NSLocalizedString("Huge", comment: ""): size = .huge
default: size = .medium
}
Settings.cardSize = size
}
} else if sender == theme {
Settings.theme = themes[theme.indexOfSelectedItem]
}
}
@IBAction func checkboxClicked(_ sender: NSButton) {
if sender == highlightCardsInHand {
Settings.highlightCardsInHand = highlightCardsInHand.state == .on
} else if sender == highlightLastDrawn {
Settings.highlightLastDrawn = highlightLastDrawn.state == .on
} else if sender == removeCards {
Settings.removeCardsFromDeck = removeCards.state == .on
} else if sender == highlightDiscarded {
Settings.highlightDiscarded = highlightDiscarded.state == .on
} else if sender == autoPositionTrackers {
Settings.autoPositionTrackers = autoPositionTrackers.state == .on
if Settings.autoPositionTrackers {
Settings.windowsLocked = true
}
} else if sender == showSecretHelper {
Settings.showSecretHelper = showSecretHelper.state == .on
} else if sender == showRarityColors {
Settings.showRarityColors = showRarityColors.state == .on
} else if sender == showTimer {
Settings.showTimer = showTimer.state == .on
} else if sender == showFloatingCard {
Settings.showFloatingCard = showFloatingCard.state == .on
showTopdeckChance.isEnabled = Settings.showFloatingCard
} else if sender == showTopdeckChance {
Settings.showTopdeckchance = showTopdeckChance.state == .on
} else if sender == allowFullscreen {
Settings.canJoinFullscreen = allowFullscreen.state == .on
} else if sender == hideAllWhenNotInGame {
Settings.hideAllTrackersWhenNotInGame = hideAllWhenNotInGame.state == .on
} else if sender == hideAllWhenGameInBackground {
Settings.hideAllWhenGameInBackground = hideAllWhenGameInBackground.state == .on
} else if sender == disableTrackingInSpectatorMode {
Settings.dontTrackWhileSpectating = disableTrackingInSpectatorMode.state == .on
} else if sender == showExperienceCounter {
Settings.showExperienceCounter = showExperienceCounter.state == .on
let game = AppDelegate.instance().coreManager.game
if showExperienceCounter.state == .on {
if let mode = game.currentMode, mode == Mode.hub {
game.windowManager.experiencePanel.visible = true
}
} else {
game.windowManager.experiencePanel.visible = false
}
}
}
}
// MARK: - Preferences
extension Preferences.PaneIdentifier {
static let trackers = Self("trackers")
}
| 44.264516 | 93 | 0.655152 |
de84c9c8fdf968ac78050d621aee85386d577d41 | 4,270 | //
// Created by Krzysztof Zablocki on 16/01/2017.
// Copyright (c) 2017 Pixle. All rights reserved.
//
import Foundation
public enum TemplateAnnotationsParser {
public typealias AnnotatedRanges = [String: [(range: NSRange, indentation: String)]]
private static func regex(annotation: String) throws -> NSRegularExpression {
let commentPattern = NSRegularExpression.escapedPattern(for: "//")
let regex = try NSRegularExpression(
pattern: "(^(?:\\s*?\\n)?(\\s*)\(commentPattern)\\s*?sourcery:\(annotation):)(\\S*)\\s*?(^.*?)(^\\s*?\(commentPattern)\\s*?sourcery:end)",
options: [.allowCommentsAndWhitespace, .anchorsMatchLines, .dotMatchesLineSeparators]
)
return regex
}
public static func parseAnnotations(_ annotation: String, contents: String, aggregate: Bool = false, forceParse: [String]) -> (contents: String, annotatedRanges: AnnotatedRanges) {
let (annotatedRanges, rangesToReplace) = annotationRanges(annotation, contents: contents, aggregate: aggregate, forceParse: forceParse)
let strigView = StringView(contents)
var bridged = contents.bridge()
rangesToReplace
.sorted(by: { $0.location > $1.location })
.forEach {
bridged = bridged.replacingCharacters(in: $0, with: String(repeating: " ", count: strigView.NSRangeToByteRange($0)!.length.value)) as NSString
}
return (bridged as String, annotatedRanges)
}
public static func annotationRanges(_ annotation: String, contents: String, aggregate: Bool = false, forceParse: [String]) -> (annotatedRanges: AnnotatedRanges, rangesToReplace: Set<NSRange>) {
let bridged = contents.bridge()
let regex = try? self.regex(annotation: annotation)
var rangesToReplace = Set<NSRange>()
var annotatedRanges = AnnotatedRanges()
regex?.enumerateMatches(in: contents, options: [], range: bridged.entireRange) { result, _, _ in
guard let result = result, result.numberOfRanges == 6 else {
return
}
let indentationRange = result.range(at: 2)
let nameRange = result.range(at: 3)
let startLineRange = result.range(at: 4)
let endLineRange = result.range(at: 5)
let indentation = bridged.substring(with: indentationRange)
let name = bridged.substring(with: nameRange)
let range = NSRange(
location: startLineRange.location,
length: endLineRange.location - startLineRange.location
)
if aggregate {
var ranges = annotatedRanges[name] ?? []
ranges.append((range: range, indentation: indentation))
annotatedRanges[name] = ranges
} else {
annotatedRanges[name] = [(range: range, indentation: indentation)]
}
let rangeToBeRemoved = !forceParse.contains(where: { name.hasSuffix("." + $0) })
if rangeToBeRemoved {
rangesToReplace.insert(range)
}
}
return (annotatedRanges, rangesToReplace)
}
public static func removingEmptyAnnotations(from content: String) -> String {
var bridged = content.bridge()
let regex = try? self.regex(annotation: "\\S*")
var rangesToReplace = [NSRange]()
regex?.enumerateMatches(in: content, options: [], range: bridged.entireRange) { result, _, _ in
guard let result = result, result.numberOfRanges == 6 else {
return
}
let annotationStartRange = result.range(at: 1)
let startLineRange = result.range(at: 4)
let endLineRange = result.range(at: 5)
if startLineRange.length == 0 {
rangesToReplace.append(NSRange(
location: annotationStartRange.location,
length: NSMaxRange(endLineRange) - annotationStartRange.location
))
}
}
rangesToReplace
.reversed()
.forEach {
bridged = bridged.replacingCharacters(in: $0, with: "") as NSString
}
return bridged as String
}
}
| 41.057692 | 197 | 0.607026 |
1a001cfba41dc505f2c4b8b321c139049b1dc56a | 951 | //
// GetRemoteFile.swift
// tl2swift
//
// Created by Code Generator
//
import Foundation
/// Returns information about a file by its remote ID; this is an offline request. Can be used to register a URL as a file for further uploading, or sending as a message. Even the request succeeds, the file can be used only if it is still accessible to the user. For example, if the file is from a message, then the message must be not deleted and accessible to the user. If the file database is disabled, then the corresponding object with the file must be preloaded by the application
public struct GetRemoteFile: Codable {
/// File type; pass null if unknown
public let fileType: FileType?
/// Remote identifier of the file to get
public let remoteFileId: String?
public init(
fileType: FileType?,
remoteFileId: String?
) {
self.fileType = fileType
self.remoteFileId = remoteFileId
}
}
| 31.7 | 486 | 0.712934 |
11ec127c5c7ae2441041adfa8c5ffa649bdbf4bc | 9,777 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains the AddEditConfiguration class, which is responsible for controlling a view used to create or edit a VPN configuration.
*/
import UIKit
import NetworkExtension
import Security
import SimpleTunnelServices
/// A view controller object for a table view containing input fields used to specify configuration parameters for a VPN configuration.
class AddEditConfiguration: ConfigurationParametersViewController {
// MARK: Properties
/// A table view cell containing the text field where the name of the configuration is entered.
@IBOutlet weak var nameCell: TextFieldCell!
/// A table view cell containing the text field where the server address of the configuration is entered.
@IBOutlet weak var serverAddressCell: TextFieldCell!
/// A table view cell containing the text field where the username of the configuration is entered.
@IBOutlet weak var usernameCell: TextFieldCell!
/// A table view cell containing the text field where the password of the configuration is entered.
@IBOutlet weak var passwordCell: TextFieldCell!
/// A table view cell containing a switch used to enable and disable Connect On Demand for the configuration.
@IBOutlet weak var onDemandCell: SwitchCell!
/// A table view cell containing a switch used to enable and disable proxy settings for the configuration.
@IBOutlet weak var proxiesCell: SwitchCell!
/// A table view cell containing a switch used to enable and disable Disconnect On Sleep for the configuration.
@IBOutlet weak var disconnectOnSleepCell: SwitchCell!
/// A table view cell that when tapped transitions the app to a view where the Connect On Demand rules are managed.
@IBOutlet weak var onDemandRulesCell: UITableViewCell!
/// A table view cell that when tapped transitions the app to a view where the proxy settings are managed.
@IBOutlet weak var proxySettingsCell: UITableViewCell!
/// The NEVPNManager object corresponding to the configuration being added or edited.
var targetManager: NEVPNManager = NEVPNManager.shared()
// MARK: UIViewController
/// Handle the event of the view being loaded into memory.
override func viewDidLoad() {
super.viewDidLoad()
// Set up the table view cells
cells = [
nameCell,
serverAddressCell,
usernameCell,
passwordCell,
onDemandCell,
proxiesCell,
disconnectOnSleepCell
].compactMap { $0 }
// The switch in proxiesCell controls the display of proxySettingsCell
proxiesCell.dependentCells = [ proxySettingsCell ]
proxiesCell.getIndexPath = {
return self.getIndexPathOfCell(self.proxiesCell)
}
proxiesCell.valueChanged = {
self.updateCellsWithDependentsOfCell(self.proxiesCell)
}
// The switch in onDemandCell controls the display of onDemandRulesCell
onDemandCell.dependentCells = [ onDemandRulesCell ]
onDemandCell.getIndexPath = {
return self.getIndexPathOfCell(self.onDemandCell)
}
onDemandCell.valueChanged = {
self.updateCellsWithDependentsOfCell(self.onDemandCell)
self.targetManager.isOnDemandEnabled = self.onDemandCell.isOn
}
disconnectOnSleepCell.valueChanged = {
self.targetManager.protocolConfiguration?.disconnectOnSleep = self.disconnectOnSleepCell.isOn
}
nameCell.valueChanged = {
self.targetManager.localizedDescription = self.nameCell.textField.text
}
serverAddressCell.valueChanged = {
self.targetManager.protocolConfiguration?.serverAddress = self.serverAddressCell.textField.text
}
usernameCell.valueChanged = {
self.targetManager.protocolConfiguration?.username = self.usernameCell.textField.text
}
}
/// Handle the event of the view being displayed.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
// Set the text fields and switches per the settings in the configuration.
nameCell.textField.text = targetManager.localizedDescription
serverAddressCell.textField.text = targetManager.protocolConfiguration?.serverAddress
usernameCell.textField.text = targetManager.protocolConfiguration?.username
if let passRef = targetManager.protocolConfiguration?.passwordReference {
passwordCell.textField.text = getPasswordWithPersistentReference(passRef)
}
else {
passwordCell.textField.text = nil
}
disconnectOnSleepCell.isOn = targetManager.protocolConfiguration?.disconnectOnSleep ?? false
onDemandCell.isOn = targetManager.isOnDemandEnabled
onDemandRulesCell.detailTextLabel?.text = getDescriptionForListValue(targetManager.onDemandRules, itemDescription: "rule")
proxiesCell.isOn = targetManager.protocolConfiguration?.proxySettings != nil
}
/// Set up the destination view controller of a segue away from this view controller.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else { return }
switch identifier {
case "edit-proxy-settings":
// The user tapped on the proxy settings cell.
guard let controller = segue.destination as? ProxySettingsController else { break }
if targetManager.protocolConfiguration?.proxySettings == nil {
targetManager.protocolConfiguration?.proxySettings = NEProxySettings()
}
controller.targetConfiguration = targetManager.protocolConfiguration ?? NETunnelProviderProtocol()
case "edit-on-demand-rules":
// The user tapped on the Connect On Demand rules cell.
guard let controller = segue.destination as? OnDemandRuleListController else { break }
controller.targetManager = targetManager
default:
break
}
}
// MARK: Interface
/// Set the target configuration and the title to display in the view.
func setTargetManager(_ manager: NEVPNManager?, title: String?) {
if let newManager = manager {
// A manager was given, so an existing configuration is being edited.
targetManager = newManager
}
else {
// No manager was given, create a new configuration.
let newManager = NETunnelProviderManager()
newManager.protocolConfiguration = NETunnelProviderProtocol()
newManager.localizedDescription = "Demo VPN"
newManager.protocolConfiguration?.serverAddress = "TunnelServer"
targetManager = newManager
}
navigationItem.title = title
}
/// Save the configuration to the Network Extension preferences.
@IBAction func saveTargetManager(_ sender: AnyObject) {
if !proxiesCell.isOn {
targetManager.protocolConfiguration?.proxySettings = nil
}
targetManager.saveToPreferences { error in
if let saveError = error {
simpleTunnelLog("Failed to save the configuration: \(saveError)")
return
}
// Transition back to the configuration list view.
self.performSegue(withIdentifier: "save-configuration", sender: sender)
}
}
/// Save a password in the keychain.
func savePassword(_ password: String, inKeychainItem: Data?) -> Data? {
guard let passwordData = password.data(using: String.Encoding.utf8, allowLossyConversion: false) else { return nil }
var status = errSecSuccess
if let persistentReference = inKeychainItem {
// A persistent reference was given, update the corresponding keychain item.
let query: [NSObject: AnyObject] = [
kSecValuePersistentRef : persistentReference as AnyObject,
kSecReturnAttributes : kCFBooleanTrue
]
var result: AnyObject?
// Get the current attributes for the item.
status = SecItemCopyMatching(query as CFDictionary, &result)
if let attributes = result as? [NSObject: AnyObject] , status == errSecSuccess {
// Update the attributes with the new data.
var updateQuery = [NSObject: AnyObject]()
updateQuery[kSecClass] = kSecClassGenericPassword
updateQuery[kSecAttrService] = attributes[kSecAttrService]
var newAttributes = attributes
newAttributes[kSecValueData] = passwordData as AnyObject?
status = SecItemUpdate(updateQuery as CFDictionary, newAttributes as CFDictionary)
if status == errSecSuccess {
return persistentReference
}
}
}
if inKeychainItem == nil || status != errSecSuccess {
// No persistent reference was provided, or the update failed. Add a new keychain item.
let attributes: [NSObject: AnyObject] = [
kSecAttrService : UUID().uuidString as AnyObject,
kSecValueData : passwordData as AnyObject,
kSecAttrAccessible : kSecAttrAccessibleAlways,
kSecClass : kSecClassGenericPassword,
kSecReturnPersistentRef : kCFBooleanTrue
]
var result: AnyObject?
status = SecItemAdd(attributes as CFDictionary, &result)
if let newPersistentReference = result as? Data , status == errSecSuccess {
return newPersistentReference
}
}
return nil
}
/// Remove a password from the keychain.
func removePasswordWithPersistentReference(_ persistentReference: Data) {
let query: [NSObject: AnyObject] = [
kSecClass : kSecClassGenericPassword,
kSecValuePersistentRef : persistentReference as AnyObject
]
let status = SecItemDelete(query as CFDictionary)
if status != errSecSuccess {
simpleTunnelLog("Failed to delete a password: \(status)")
}
}
/// Get a password from the keychain.
func getPasswordWithPersistentReference(_ persistentReference: Data) -> String? {
var result: String?
let query: [NSObject: AnyObject] = [
kSecClass : kSecClassGenericPassword,
kSecReturnData : kCFBooleanTrue,
kSecValuePersistentRef : persistentReference as AnyObject
]
var returnValue: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &returnValue)
if let passwordData = returnValue as? Data , status == errSecSuccess {
result = NSString(data: passwordData, encoding: String.Encoding.utf8.rawValue) as String?
}
return result
}
}
| 35.813187 | 139 | 0.763731 |
23811c8618b2ba169050b9a7e35ee9fa190d1288 | 19,301 | //
// SettingsViewController.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 4/24/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
import Account
import CoreServices
import SafariServices
import SwiftUI
class SettingsViewController: UITableViewController {
private weak var opmlAccount: Account?
@IBOutlet weak var timelineSortOrderSwitch: UISwitch!
@IBOutlet weak var groupByFeedSwitch: UISwitch!
@IBOutlet weak var refreshClearsReadArticlesSwitch: UISwitch!
@IBOutlet weak var articleThemeDetailLabel: UILabel!
@IBOutlet weak var confirmMarkAllAsReadSwitch: UISwitch!
@IBOutlet weak var showFullscreenArticlesSwitch: UISwitch!
@IBOutlet weak var colorPaletteDetailLabel: UILabel!
@IBOutlet weak var openLinksInNetNewsWire: UISwitch!
var scrollToArticlesSection = false
weak var presentingParentController: UIViewController?
override func viewDidLoad() {
// This hack mostly works around a bug in static tables with dynamic type. See: https://spin.atomicobject.com/2018/10/15/dynamic-type-static-uitableview/
NotificationCenter.default.removeObserver(tableView!, name: UIContentSizeCategory.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange), name: .UserDidAddAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange), name: .UserDidDeleteAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange), name: .DisplayNameDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(activeExtensionPointsDidChange), name: .ActiveExtensionPointsDidChange, object: nil)
tableView.register(UINib(nibName: "SettingsComboTableViewCell", bundle: nil), forCellReuseIdentifier: "SettingsComboTableViewCell")
tableView.register(UINib(nibName: "SettingsTableViewCell", bundle: nil), forCellReuseIdentifier: "SettingsTableViewCell")
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if AppDefaults.shared.timelineSortDirection == .orderedAscending {
timelineSortOrderSwitch.isOn = true
} else {
timelineSortOrderSwitch.isOn = false
}
if AppDefaults.shared.timelineGroupByFeed {
groupByFeedSwitch.isOn = true
} else {
groupByFeedSwitch.isOn = false
}
if AppDefaults.shared.refreshClearsReadArticles {
refreshClearsReadArticlesSwitch.isOn = true
} else {
refreshClearsReadArticlesSwitch.isOn = false
}
articleThemeDetailLabel.text = ArticleThemesManager.shared.currentTheme.name
if AppDefaults.shared.confirmMarkAllAsRead {
confirmMarkAllAsReadSwitch.isOn = true
} else {
confirmMarkAllAsReadSwitch.isOn = false
}
if AppDefaults.shared.articleFullscreenAvailable {
showFullscreenArticlesSwitch.isOn = true
} else {
showFullscreenArticlesSwitch.isOn = false
}
colorPaletteDetailLabel.text = String(describing: AppDefaults.userInterfaceColorPalette)
openLinksInNetNewsWire.isOn = !AppDefaults.shared.useSystemBrowser
let buildLabel = NonIntrinsicLabel(frame: CGRect(x: 32.0, y: 0.0, width: 0.0, height: 0.0))
buildLabel.font = UIFont.systemFont(ofSize: 11.0)
buildLabel.textColor = UIColor.gray
buildLabel.text = "\(Bundle.main.appName) \(Bundle.main.versionNumber) (Build \(Bundle.main.buildNumber))"
buildLabel.sizeToFit()
buildLabel.translatesAutoresizingMaskIntoConstraints = false
let wrapperView = UIView(frame: CGRect(x: 0, y: 0, width: buildLabel.frame.width, height: buildLabel.frame.height + 10.0))
wrapperView.translatesAutoresizingMaskIntoConstraints = false
wrapperView.addSubview(buildLabel)
tableView.tableFooterView = wrapperView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
if scrollToArticlesSection {
tableView.scrollToRow(at: IndexPath(row: 0, section: 4), at: .top, animated: true)
scrollToArticlesSection = false
}
}
// MARK: UITableView
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 1:
return AccountManager.shared.accounts.count + 1
case 2:
return ExtensionPointManager.shared.activeExtensionPoints.count + 1
case 3:
let defaultNumberOfRows = super.tableView(tableView, numberOfRowsInSection: section)
if AccountManager.shared.activeAccounts.isEmpty || AccountManager.shared.anyAccountHasNetNewsWireNewsSubscription() {
return defaultNumberOfRows - 1
}
return defaultNumberOfRows
case 5:
return traitCollection.userInterfaceIdiom == .phone ? 4 : 3
default:
return super.tableView(tableView, numberOfRowsInSection: section)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
switch indexPath.section {
case 1:
let sortedAccounts = AccountManager.shared.sortedAccounts
if indexPath.row == sortedAccounts.count {
cell = tableView.dequeueReusableCell(withIdentifier: "SettingsTableViewCell", for: indexPath)
cell.textLabel?.text = NSLocalizedString("Add Account", comment: "Accounts")
} else {
let acctCell = tableView.dequeueReusableCell(withIdentifier: "SettingsComboTableViewCell", for: indexPath) as! SettingsComboTableViewCell
acctCell.applyThemeProperties()
let account = sortedAccounts[indexPath.row]
acctCell.comboImage?.image = AppAssets.image(for: account.type)
acctCell.comboNameLabel?.text = account.nameForDisplay
cell = acctCell
}
case 2:
let extensionPoints = Array(ExtensionPointManager.shared.activeExtensionPoints.values)
if indexPath.row == extensionPoints.count {
cell = tableView.dequeueReusableCell(withIdentifier: "SettingsTableViewCell", for: indexPath)
cell.textLabel?.text = NSLocalizedString("Add Extension", comment: "Extensions")
} else {
let acctCell = tableView.dequeueReusableCell(withIdentifier: "SettingsComboTableViewCell", for: indexPath) as! SettingsComboTableViewCell
acctCell.applyThemeProperties()
let extensionPoint = extensionPoints[indexPath.row]
acctCell.comboImage?.image = extensionPoint.image
acctCell.comboNameLabel?.text = extensionPoint.title
cell = acctCell
}
default:
cell = super.tableView(tableView, cellForRowAt: indexPath)
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
UIApplication.shared.open(URL(string: "\(UIApplication.openSettingsURLString)")!)
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 1:
let sortedAccounts = AccountManager.shared.sortedAccounts
if indexPath.row == sortedAccounts.count {
let controller = UIStoryboard.settings.instantiateController(ofType: AddAccountViewController.self)
self.navigationController?.pushViewController(controller, animated: true)
} else {
let controller = UIStoryboard.inspector.instantiateController(ofType: AccountInspectorViewController.self)
controller.account = sortedAccounts[indexPath.row]
self.navigationController?.pushViewController(controller, animated: true)
}
case 2:
let extensionPoints = Array(ExtensionPointManager.shared.activeExtensionPoints.values)
if indexPath.row == extensionPoints.count {
let controller = UIStoryboard.settings.instantiateController(ofType: AddExtensionPointViewController.self)
self.navigationController?.pushViewController(controller, animated: true)
} else {
let controller = UIStoryboard.inspector.instantiateController(ofType: ExtensionPointInspectorViewController.self)
controller.extensionPoint = extensionPoints[indexPath.row]
self.navigationController?.pushViewController(controller, animated: true)
}
case 3:
switch indexPath.row {
case 0:
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
if let sourceView = tableView.cellForRow(at: indexPath) {
let sourceRect = tableView.rectForRow(at: indexPath)
importOPML(sourceView: sourceView, sourceRect: sourceRect)
}
case 1:
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
if let sourceView = tableView.cellForRow(at: indexPath) {
let sourceRect = tableView.rectForRow(at: indexPath)
exportOPML(sourceView: sourceView, sourceRect: sourceRect)
}
case 2:
addFeed()
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
default:
break
}
case 4:
switch indexPath.row {
case 3:
let timeline = UIStoryboard.settings.instantiateController(ofType: TimelineCustomizerViewController.self)
self.navigationController?.pushViewController(timeline, animated: true)
default:
break
}
case 5:
switch indexPath.row {
case 0:
let articleThemes = UIStoryboard.settings.instantiateController(ofType: ArticleThemesTableViewController.self)
self.navigationController?.pushViewController(articleThemes, animated: true)
default:
break
}
case 6:
let colorPalette = UIStoryboard.settings.instantiateController(ofType: ColorPaletteTableViewController.self)
self.navigationController?.pushViewController(colorPalette, animated: true)
case 7:
switch indexPath.row {
case 0:
openURL("https://netnewswire.com/help/ios/6.0/en/")
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 1:
openURL("https://netnewswire.com/")
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 2:
openURL(URL.releaseNotes.absoluteString)
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 3:
openURL("https://github.com/brentsimmons/NetNewsWire/blob/main/Technotes/HowToSupportNetNewsWire.markdown")
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 4:
openURL("https://github.com/brentsimmons/NetNewsWire")
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 5:
openURL("https://github.com/brentsimmons/NetNewsWire/issues")
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 6:
openURL("https://github.com/brentsimmons/NetNewsWire/tree/main/Technotes")
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 7:
openURL("https://netnewswire.com/slack")
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
case 8:
let timeline = UIStoryboard.settings.instantiateController(ofType: AboutViewController.self)
self.navigationController?.pushViewController(timeline, animated: true)
default:
break
}
default:
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
return super.tableView(tableView, indentationLevelForRowAt: IndexPath(row: 0, section: 1))
}
// MARK: Actions
@IBAction func done(_ sender: Any) {
dismiss(animated: true)
}
@IBAction func switchTimelineOrder(_ sender: Any) {
if timelineSortOrderSwitch.isOn {
AppDefaults.shared.timelineSortDirection = .orderedAscending
} else {
AppDefaults.shared.timelineSortDirection = .orderedDescending
}
}
@IBAction func switchGroupByFeed(_ sender: Any) {
if groupByFeedSwitch.isOn {
AppDefaults.shared.timelineGroupByFeed = true
} else {
AppDefaults.shared.timelineGroupByFeed = false
}
}
@IBAction func switchClearsReadArticles(_ sender: Any) {
if refreshClearsReadArticlesSwitch.isOn {
AppDefaults.shared.refreshClearsReadArticles = true
} else {
AppDefaults.shared.refreshClearsReadArticles = false
}
}
@IBAction func switchConfirmMarkAllAsRead(_ sender: Any) {
if confirmMarkAllAsReadSwitch.isOn {
AppDefaults.shared.confirmMarkAllAsRead = true
} else {
AppDefaults.shared.confirmMarkAllAsRead = false
}
}
@IBAction func switchFullscreenArticles(_ sender: Any) {
if showFullscreenArticlesSwitch.isOn {
AppDefaults.shared.articleFullscreenAvailable = true
} else {
AppDefaults.shared.articleFullscreenAvailable = false
}
}
@IBAction func switchBrowserPreference(_ sender: Any) {
if openLinksInNetNewsWire.isOn {
AppDefaults.shared.useSystemBrowser = false
} else {
AppDefaults.shared.useSystemBrowser = true
}
}
// MARK: Notifications
@objc func contentSizeCategoryDidChange() {
tableView.reloadData()
}
@objc func accountsDidChange() {
tableView.reloadData()
}
@objc func displayNameDidChange() {
tableView.reloadData()
}
@objc func activeExtensionPointsDidChange() {
tableView.reloadData()
}
@objc func browserPreferenceDidChange() {
tableView.reloadData()
}
}
// MARK: OPML Document Picker
extension SettingsViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
for url in urls {
opmlAccount?.importOPML(url) { result in
switch result {
case .success:
break
case .failure:
let title = NSLocalizedString("Import Failed", comment: "Import Failed")
let message = NSLocalizedString("We were unable to process the selected file. Please ensure that it is a properly formatted OPML file.", comment: "Import Failed Message")
self.presentError(title: title, message: message)
}
}
}
}
}
// MARK: Private
private extension SettingsViewController {
func addFeed() {
self.dismiss(animated: true)
let addNavViewController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddWebFeedViewControllerNav") as! UINavigationController
let addViewController = addNavViewController.topViewController as! AddFeedViewController
addViewController.initialFeed = AccountManager.netNewsWireNewsURL
addViewController.initialFeedName = NSLocalizedString("NetNewsWire News", comment: "NetNewsWire News")
addNavViewController.modalPresentationStyle = .formSheet
addNavViewController.preferredContentSize = AddFeedViewController.preferredContentSizeForFormSheetDisplay
presentingParentController?.present(addNavViewController, animated: true)
}
func importOPML(sourceView: UIView, sourceRect: CGRect) {
switch AccountManager.shared.activeAccounts.count {
case 0:
presentError(title: "Error", message: NSLocalizedString("You must have at least one active account.", comment: "Missing active account"))
case 1:
opmlAccount = AccountManager.shared.activeAccounts.first
importOPMLDocumentPicker()
default:
importOPMLAccountPicker(sourceView: sourceView, sourceRect: sourceRect)
}
}
func importOPMLAccountPicker(sourceView: UIView, sourceRect: CGRect) {
let title = NSLocalizedString("Choose an account to receive the imported feeds and folders", comment: "Import Account")
let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = view
popoverController.sourceRect = sourceRect
}
for account in AccountManager.shared.sortedActiveAccounts {
let action = UIAlertAction(title: account.nameForDisplay, style: .default) { [weak self] action in
self?.opmlAccount = account
self?.importOPMLDocumentPicker()
}
alert.addAction(action)
}
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel))
self.present(alert, animated: true)
}
func importOPMLDocumentPicker() {
let utiArray = UTTypeCreateAllIdentifiersForTag(kUTTagClassFilenameExtension, "opml" as NSString, nil)?.takeRetainedValue() as? [String] ?? [String]()
var opmlUTIs = utiArray
.compactMap({ UTTypeCopyDeclaration($0 as NSString)?.takeUnretainedValue() as? [String: Any] })
.reduce([String]()) { (result, dict) in
return result + dict.values.compactMap({ $0 as? String })
}
opmlUTIs.append("public.xml")
let docPicker = UIDocumentPickerViewController(documentTypes: opmlUTIs, in: .import)
docPicker.delegate = self
docPicker.modalPresentationStyle = .formSheet
self.present(docPicker, animated: true)
}
func exportOPML(sourceView: UIView, sourceRect: CGRect) {
if AccountManager.shared.accounts.count == 1 {
opmlAccount = AccountManager.shared.accounts.first!
exportOPMLDocumentPicker()
} else {
exportOPMLAccountPicker(sourceView: sourceView, sourceRect: sourceRect)
}
}
func exportOPMLAccountPicker(sourceView: UIView, sourceRect: CGRect) {
let title = NSLocalizedString("Choose an account with the subscriptions to export", comment: "Export Account")
let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = view
popoverController.sourceRect = sourceRect
}
for account in AccountManager.shared.sortedAccounts {
let action = UIAlertAction(title: account.nameForDisplay, style: .default) { [weak self] action in
self?.opmlAccount = account
self?.exportOPMLDocumentPicker()
}
alert.addAction(action)
}
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel))
self.present(alert, animated: true)
}
func exportOPMLDocumentPicker() {
guard let account = opmlAccount else { return }
let accountName = account.nameForDisplay.replacingOccurrences(of: " ", with: "").trimmingCharacters(in: .whitespaces)
let filename = "Subscriptions-\(accountName).opml"
let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent(filename)
let opmlString = OPMLExporter.OPMLString(with: account, title: filename)
do {
try opmlString.write(to: tempFile, atomically: true, encoding: String.Encoding.utf8)
} catch {
self.presentError(title: "OPML Export Error", message: error.localizedDescription)
}
let docPicker = UIDocumentPickerViewController(url: tempFile, in: .exportToService)
docPicker.modalPresentationStyle = .formSheet
self.present(docPicker, animated: true)
}
func openURL(_ urlString: String) {
let vc = SFSafariViewController(url: URL(string: urlString)!)
vc.modalPresentationStyle = .pageSheet
present(vc, animated: true)
}
}
| 36.76381 | 176 | 0.764468 |
1d478f16e7294d34c40f1425556ef40b95632188 | 625 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
public struct AppSyncResponse {
let id: String?
let payload: [String: AppSyncJSONValue]?
let responseType: AppSyncResponseType
init(
id: String? = nil,
payload: [String: AppSyncJSONValue]? = nil,
type: AppSyncResponseType
) {
self.id = id
self.responseType = type
self.payload = payload
}
}
/// Response types
enum AppSyncResponseType {
case subscriptionAck
case unsubscriptionAck
case data
}
| 16.447368 | 51 | 0.6432 |
18e1a1498e172987571abde479750abf2cf9395a | 997 | //
// SignInRouter.swift
// Parylation
//
// Created by Vladislav Kondrashkov on 8/21/20.
// Copyright © 2020 Vladislav Kondrashkov. All rights reserved.
//
import UIKit
final class SignInRouterImpl {
private weak var view: UIViewController?
private let signUpBuilder: SignUpBuilder
private weak var signInListener: (SignInListener & SignUpListener)?
init(
view: UIViewController,
signUpBuilder: SignUpBuilder,
signInListener: (SignInListener & SignUpListener)?
) {
self.view = view
self.signUpBuilder = signUpBuilder
self.signInListener = signInListener
}
}
// MARK: - SignInRouter implementation
extension SignInRouterImpl: SignInRouter {
func showSignUp() {
let signUpView = signUpBuilder.build(listener: signInListener)
view?.navigationController?.setViewControllers([signUpView], animated: true)
}
func finishSignIn() {
signInListener?.onSignInFinish()
}
}
| 24.925 | 84 | 0.686058 |
72ce1c1e457a9ee7baba2c31b6ca39499573b46d | 483 | import UIKit
import Flutter
import Firebase
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure()
let db = Firestore.firestore()
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
| 28.411765 | 87 | 0.782609 |
e21cf6980652a118930ab6011eab8fd7f5a559f1 | 1,932 | // RUN: %target-typecheck-verify-swift
struct X { }
struct Y { }
struct Z { }
func f0(_ x1: X, x2: X) -> X {} // expected-note{{found this candidate}}
func f0(_ y1: Y, y2: Y) -> Y {} // expected-note{{found this candidate}}
var f0 : X // expected-note {{found this candidate}} expected-note {{'f0' previously declared here}}
func f0_init(_ x: X, y: Y) -> X {}
var f0 : (_ x : X, _ y : Y) -> X = f0_init // expected-error{{invalid redeclaration}}
func f1(_ x: X) -> X {}
func f2(_ g: (_ x: X) -> X) -> ((_ y: Y) -> Y) { }
func test_conv() {
var _ : (_ x1 : X, _ x2 : X) -> X = f0
var _ : (X, X) -> X = f0
var _ : (Y, X) -> X = f0 // expected-error{{ambiguous reference to member 'f0(_:x2:)'}}
var _ : (X) -> X = f1
var a7 : (X) -> (X) = f1
var a8 : (_ x2 : X) -> (X) = f1
var a9 : (_ x2 : X) -> ((X)) = f1
a7 = a8
a8 = a9
a9 = a7
var _ : ((X) -> X) -> ((Y) -> Y) = f2
var _ : ((_ x2 : X) -> (X)) -> (((_ y2 : Y) -> (Y))) = f2
typealias fp = ((X) -> X) -> ((Y) -> Y)
var _ = f2
}
var xy : X // expected-note {{previously declared here}}
var xy : Y // expected-error {{invalid redeclaration of 'xy'}}
func accept_X(_ x: inout X) { }
func accept_XY(_ x: inout X) -> X { }
func accept_XY(_ y: inout Y) -> Y { }
func accept_Z(_ z: inout Z) -> Z { }
func test_inout() {
var x : X
accept_X(&x);
accept_X(xy); // expected-error{{passing value of type 'X' to an inout parameter requires explicit '&'}} {{12-12=&}}
accept_X(&xy);
_ = accept_XY(&x);
x = accept_XY(&xy);
x = xy
x = &xy; // expected-error{{'&' used with non-inout argument of type 'X'}}
accept_Z(&xy); // expected-error{{cannot convert value of type 'X' to expected argument type 'Z'}}
}
func lvalue_or_rvalue(_ x: inout X) -> X { }
func lvalue_or_rvalue(_ x: X) -> Y { }
func test_lvalue_or_rvalue() {
var x : X
var y : Y
let x1 = lvalue_or_rvalue(&x)
x = x1
let y1 = lvalue_or_rvalue(x)
y = y1
_ = y
}
| 27.211268 | 118 | 0.551242 |
1d36105527717bbdfa7c432cac7f149b233d7cab | 2,792 | //
// ViewController.swift
// ToDo List
//
// Created by NWPU on 15/12/2017.
// Copyright © 2017 NWPU. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableViewToDO: UITableView!
var plans = [String]()
@IBAction func onAddTapped(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Add ToDo", message: nil, preferredStyle: .alert)
alert.addTextField { (planTF) in
planTF.placeholder = "Add Your Today's Plan"
}
let action = UIAlertAction(title: "Add", style: .default) { (_) in
guard let plan = alert.textFields?.first?.text else { return }
print(plan)
self.add(plan)
}
alert.addAction(action)
present(alert, animated: true)
}
func add(_ plantoDO: String) {
let index = 0
plans.insert(plantoDO, at: index)
let indexPath = IndexPath(row: index, section: 0)
tableViewToDO.insertRows(at: [indexPath], with: .left)
}
func update(_ plantoDO: String, indexNum: IndexPath) {
let index = 0
plans[indexNum.row] = plantoDO
tableViewToDO.reloadData()
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return plans.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let plan = plans[indexPath.row]
cell.textLabel?.text = plan
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else { return }
plans.remove(at: indexPath.row)
tableViewToDO.deleteRows(at: [indexPath], with: .automatic)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let alert = UIAlertController(title: "Edit It", message: nil, preferredStyle: .alert)
alert.addTextField { (planTF) in
planTF.placeholder = "Add Your Today's Plan"
planTF.text = self.plans[indexPath.row]
}
let action = UIAlertAction(title: "Done", style: .default) { (_) in
guard let plan = alert.textFields?.first?.text else { return }
print(plan)
self.update(plan, indexNum: indexPath)
}
alert.addAction(action)
present(alert, animated: true)
}
}
| 28.489796 | 127 | 0.610315 |
1c1ff9434489a78688619739b9aa2bbdb548ad5f | 956 | //
// CalendarView.swift
// PersianCalendarMac
//
// Created by Mani Ramezan on 10/12/19.
// Copyright © 2019 Mani Ramezan. All rights reserved.
//
import SwiftUI
import Grallistrix
struct CalendarView: View {
@EnvironmentObject var theme: Theme
@State var currentCalendar: Calendar
let calendars: [Calendar] = [Calendar(identifier: .persian), Calendar(identifier: .gregorian)]
var body: some View {
VStack(spacing: 10) {
HeaderView(currentCalendar: $currentCalendar, calendars: calendars)
WeeksView().environmentObject(theme)
.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))
FooterView()
}
}
}
#if DEBUG
struct CalendarView_Previews: PreviewProvider {
static var previews: some View {
CalendarView(currentCalendar: Calendar(identifier: .persian))
.environmentObject(CalendarView.Theme())
}
}
#endif
| 25.837838 | 98 | 0.658996 |
ede8376d3219529faa491981d5f42d3f98ea3522 | 222 | //
// SelectStorefront.swift
// PremusicCore
//
// Created by 林達也 on 2017/09/13.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
extension Module {
public struct SelectStorefront {}
}
| 15.857143 | 55 | 0.698198 |
71a7c546740762fac7efcc573fefadf1f5377426 | 1,231 | //
// tippUITests.swift
// tippUITests
//
// Created by Debbie Chang on 12/28/15.
// Copyright © 2015 Codepath. All rights reserved.
//
import XCTest
class tippUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.27027 | 182 | 0.659626 |
16fb0df197dc9baaa3e21447bfeeda3559da2d7b | 250 | //
// main.swift
//
// Puzzle solution
// Advent of Code 2020
//
import Foundation
func partOne() -> Int {
return 0
}
func partTwo() -> Int {
return 0
}
print("\(partOne()) part one solution")
print("\(partTwo()) part two solution")
| 12.5 | 39 | 0.604 |
89e8fce6bce15676804cb6b3c4e3a04ac281a76d | 626 | //
// ViewCodeModel.swift
// RickAndMorty
//
// Created by Gabriel Augusto Marson on 31/07/20.
// Copyright © 2020 Gabriel Augusto Marson. All rights reserved.
//
import Foundation
public protocol ViewCodeModel { }
public struct EmptyModel: ViewCodeModel {
public init() { }
}
public protocol ModelManager {
associatedtype SomeModel: ViewCodeModel
var model: SomeModel { get set }
func updateModel(model: SomeModel)
}
public protocol OptionalModelManager {
associatedtype SomeModel: ViewCodeModel
var model: SomeModel? { get set }
func updateModel(model: SomeModel?)
}
| 19.5625 | 65 | 0.704473 |
336e309bd6291417f492c6ebf0fe215b5864c82d | 119 | // Created by Ivan Golikov on 29/09/2019.
// Copyright © 2019 Ivan Golikov. All rights reserved.
import Foundation
| 19.833333 | 55 | 0.731092 |
9b053f009271976797ee88cfd4ff04853d6213c7 | 3,720 | //
// SearchParameterTests.swift
// SwiftFHIR
//
// Generated from FHIR 1.0.2.7202 on 2016-09-16.
// 2016, SMART Health IT.
//
import XCTest
import SwiftFHIR
class SearchParameterTests: XCTestCase {
func instantiateFrom(filename: String) throws -> SwiftFHIR.SearchParameter {
return instantiateFrom(json: try readJSONFile(filename))
}
func instantiateFrom(json: FHIRJSON) -> SwiftFHIR.SearchParameter {
let instance = SwiftFHIR.SearchParameter(json: json)
XCTAssertNotNil(instance, "Must have instantiated a test instance")
return instance
}
func testSearchParameter1() {
do {
let instance = try runSearchParameter1()
try runSearchParameter1(instance.asJSON())
}
catch {
XCTAssertTrue(false, "Must instantiate and test SearchParameter successfully, but threw")
}
}
@discardableResult
func runSearchParameter1(_ json: FHIRJSON? = nil) throws -> SwiftFHIR.SearchParameter {
let inst = (nil != json) ? instantiateFrom(json: json!) : try instantiateFrom(filename: "searchparameter-example-extension.json")
XCTAssertEqual(inst.base, "Patient")
XCTAssertEqual(inst.code, "part-agree")
XCTAssertEqual(inst.contact?[0].telecom?[0].system, "other")
XCTAssertEqual(inst.contact?[0].telecom?[0].value, "http://hl7.org/fhir")
XCTAssertEqual(inst.description_fhir, "Search by url for a participation agreement, which is stored in a DocumentReference")
XCTAssertEqual(inst.id, "example-extension")
XCTAssertEqual(inst.name, "Example Search Parameter on an extension")
XCTAssertEqual(inst.publisher, "Health Level Seven International (FHIR Infrastructure)")
XCTAssertEqual(inst.target?[0], "DocumentReference")
XCTAssertEqual(inst.text?.status, "generated")
XCTAssertEqual(inst.type, "reference")
XCTAssertEqual(inst.url?.absoluteString, "http://hl7.org/fhir/SearchParameter/example-extension")
XCTAssertEqual(inst.xpath, "f:DocumentReference/f:extension[@url='http://example.org/fhir/StructureDefinition/participation-agreement']")
XCTAssertEqual(inst.xpathUsage, "normal")
return inst
}
func testSearchParameter2() {
do {
let instance = try runSearchParameter2()
try runSearchParameter2(instance.asJSON())
}
catch {
XCTAssertTrue(false, "Must instantiate and test SearchParameter successfully, but threw")
}
}
@discardableResult
func runSearchParameter2(_ json: FHIRJSON? = nil) throws -> SwiftFHIR.SearchParameter {
let inst = (nil != json) ? instantiateFrom(json: json!) : try instantiateFrom(filename: "searchparameter-example.json")
XCTAssertEqual(inst.base, "Resource")
XCTAssertEqual(inst.code, "_id")
XCTAssertEqual(inst.contact?[0].name, "[string]")
XCTAssertEqual(inst.contact?[0].telecom?[0].system, "other")
XCTAssertEqual(inst.contact?[0].telecom?[0].value, "http://hl7.org/fhir")
XCTAssertEqual(inst.date?.description, "2013-10-23")
XCTAssertEqual(inst.description_fhir, "Search by resource identifier - e.g. same as the read interaction, but can return included resources")
XCTAssertFalse(inst.experimental ?? true)
XCTAssertEqual(inst.id, "example")
XCTAssertEqual(inst.name, "Example Search Parameter")
XCTAssertEqual(inst.publisher, "Health Level Seven International (FHIR Infrastructure)")
XCTAssertEqual(inst.requirements, "Need to search by identifier for various infrastructural cases - mainly retrieving packages, and matching as part of a chain")
XCTAssertEqual(inst.status, "draft")
XCTAssertEqual(inst.text?.status, "generated")
XCTAssertEqual(inst.type, "token")
XCTAssertEqual(inst.url?.absoluteString, "http://hl7.org/fhir/SearchParameter/example")
XCTAssertEqual(inst.xpath, "f:*/f:id")
XCTAssertEqual(inst.xpathUsage, "normal")
return inst
}
}
| 40 | 163 | 0.753495 |
56fa2149df74535bb93d55f285a20199aff97555 | 5,857 | //
// CoreDataManager.swift
// Nowaste
//
// Created by Gilles Sagot on 23/11/2021.
//
import Foundation
import CoreData
class CoreDataManager {
static let shared = CoreDataManager()
private init() {}
var container = ContainerManager().persistentContainer
private var viewContext: NSManagedObjectContext {
return container!.viewContext
}
//MARK: - ALL ADS
var all: [Ad] {
let requestFavorite: NSFetchRequest<FavoriteAd> = FavoriteAd.fetchRequest()
guard let resultFavorite = try? viewContext.fetch(requestFavorite) else {return []}
var resultAsAd = [Ad]()
for result in resultFavorite {
let ad = Ad(snapshot: ["addedByUser":result.addedByUser as Any, "dateField":result.dateField as Any, "title":result.title as Any, "imageURL":result.imageURL as Any, "description":result.adDescription as Any, "likes":Int(result.likes) as Any, "id": result.id as Any])
resultAsAd.append(ad!)
}
return resultAsAd
}
//MARK: - ADD AD TO FAVORITE
func saveAdToFavorite( userUID:String, id:String, title:String, description:String, imageURL:String, date:Double,likes:Int, profile: Profile, contact: Bool) {
let ad = FavoriteAd(context: CoreDataManager.shared.viewContext)
ad.id = id
ad.likes = Int16(likes)
ad.imageURL = imageURL
ad.title = title
ad.dateField = date
ad.adDescription = description
ad.addedByUser = userUID
// Save context
guard ((try? CoreDataManager.shared.viewContext.save()) != nil) else {return}
let profileTosave = FavoriteProfile(context: CoreDataManager.shared.viewContext)
profileTosave.activeAds = Int16(profile.activeAds)
profileTosave.dateField = profile.dateField
profileTosave.geohash = profile.geohash
profileTosave.id = profile.id
profileTosave.imageURL = profile.imageURL
profileTosave.latitude = profile.latitude
profileTosave.longitude = profile.longitude
profileTosave.userName = profile.userName
profileTosave.ad = ad
guard ((try? CoreDataManager.shared.viewContext.save()) != nil) else {return}
let message = FavoriteMessage(context: CoreDataManager.shared.viewContext)
message.sent = contact
message.ad = ad
guard ((try? CoreDataManager.shared.viewContext.save()) != nil) else {return}
}
//MARK: - DELETE AD
func deleteAd (id:String) {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "FavoriteAd")
let filter = id
let predicate = NSPredicate(format: "id = %@", filter)
fetchRequest.predicate = predicate
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
guard ((try? CoreDataManager.shared.viewContext.execute(deleteRequest)) != nil) else {return}
}
//MARK: - FIND AD
func findAd (id:String)->Bool {
for favorite in CoreDataManager.shared.all {
if favorite.id == id {
return true
}
}
return false
}
//MARK: - DELETE ALL ADS
func deleteAllCoreDataItems () {
//To delete things in core data...
var fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "FavoriteAd")
var deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
guard ((try? CoreDataManager.shared.viewContext.execute(deleteRequest)) != nil)else{return}
fetchRequest = NSFetchRequest(entityName: "FavoriteProfile")
deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
guard ((try? CoreDataManager.shared.viewContext.execute(deleteRequest)) != nil)else{return}
fetchRequest = NSFetchRequest(entityName: "FavoriteMessage")
deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
guard ((try? CoreDataManager.shared.viewContext.execute(deleteRequest)) != nil)else{return}
}
//MARK: - GET PROFILE
func returnProfile (from ad:String)-> [Profile]{
// Request Ingredient
let filter = ad
let predicate = NSPredicate(format: "ad.id = %@", filter)
let requestProfile: NSFetchRequest<FavoriteProfile> = FavoriteProfile.fetchRequest()
requestProfile.predicate = predicate
guard let resultProfiles = try? CoreDataManager.shared.viewContext.fetch(requestProfile) else {return []}
var resultAsProfile = [Profile]()
for result in resultProfiles {
let profile = Profile(snapshot: ["id":result.id as Any, "userName":result.userName as Any, "dateField":result.dateField as Any, "activeAds":Int(result.activeAds) as Any, "imageURL":result.imageURL as Any, "latitude":result.latitude as Any, "longitude": result.longitude as Any, "geohash": result.geohash as Any ])
resultAsProfile.append(profile!)
}
return resultAsProfile
}
//MARK: - GET MESSAGE
func returnMessage (from ad:String)-> Bool{
// Request Ingredient
let filter = ad
let predicate = NSPredicate(format: "ad.id = %@", filter)
let requestMessage: NSFetchRequest<FavoriteMessage> = FavoriteMessage.fetchRequest()
requestMessage.predicate = predicate
guard let resultMessage = try? CoreDataManager.shared.viewContext.fetch(requestMessage) else {return false}
if resultMessage.first == nil {
return false
}else{
return resultMessage.first!.sent
}
}
}
| 34.251462 | 325 | 0.63804 |
cc65c7792ecda2808e5c4ac53c2aa7827f42a604 | 1,501 | //
// CardInfoDecodingTest.swift
// CardValidatorTests
//
// Created by Stanislav Ivanov on 20.10.2019.
// Copyright © 2019 Stanislav Ivanov. All rights reserved.
//
import XCTest
class CardInfoDecodingTest: XCTestCase {
let decoder = JSONDecoder()
func testExampleFromSite() {
// https://binlist.net/
// https://lookup.binlist.net/45717360
let jsonString = """
{
"number": {
"length": 16,
"luhn": true
},
"scheme": "visa",
"type": "debit",
"brand": "Visa/Dankort",
"prepaid": false,
"country": {
"numeric": "208",
"alpha2": "DK",
"name": "Denmark",
"emoji": "🇩🇰",
"currency": "DKK",
"latitude": 56,
"longitude": 10
},
"bank": {
"name": "Jyske Bank",
"url": "www.jyskebank.dk",
"phone": "+4589893300",
"city": "Hjørring"
}
}
"""
guard let data = jsonString.data(using: .utf8) else {
XCTFail()
return
}
var cardInfo: CardNumberInfo?
do {
cardInfo = try self.decoder.decode(CardNumberInfo.self, from: data)
} catch {
XCTFail()
return
}
XCTAssertEqual(cardInfo?.scheme, "visa")
XCTAssertEqual(cardInfo?.type, "debit")
XCTAssertEqual(cardInfo?.brand, "Visa/Dankort")
XCTAssertEqual(cardInfo?.country?.code, "DK")
XCTAssertEqual(cardInfo?.bank?.name, "Jyske Bank")
}
}
| 20.561644 | 79 | 0.532312 |
6107b2d5936728f07a224493fd8fd684b4a04321 | 1,027 | //
// Cylinder.swift
// LiteRay
//
// Created by Matthew Dillard on 3/12/16.
// Copyright © 2016 Matthew Dillard. All rights reserved.
//
import Foundation
import simd
/// Cylinder shape, implemented as a quadric
/// - todo: make this rotatable so it is not always a vertical cylinder
public class Cylinder : Quadric {
public init?(material: Material, position: float3, xy_radius: Float) {
super.init(material: material, position: position, equation: Equation(A: 1, B: 1, J: -(xy_radius * xy_radius)))
if xy_radius <= 0 {
return nil
}
}
public init?(material: Material, position: float3, xz_radius: Float) {
super.init(material: material, position: position, equation: Equation(A: 1, C: 1, J: -(xz_radius * xz_radius)))
if xz_radius <= 0 {
return nil
}
}
public init?(material: Material, position: float3, yz_radius: Float) {
super.init(material: material, position: position, equation: Equation(B: 1, C: 1, J: -(yz_radius * yz_radius)))
if yz_radius <= 0 {
return nil
}
}
}
| 26.333333 | 113 | 0.679649 |
de9d0bc911dd1a63fe047bb6521d7508745df930 | 4,139 | //
// ColorPickMagnifyLayer.swift
// AppAssistant
//
// Created by 王来 on 2020/11/16.
//
import UIKit
class ColorPickMagnifyLayer: CALayer {
struct Const {
static let magnify: CGFloat = 150; // 放大镜尺寸
static let rimThickness: CGFloat = 3.0; // 放大镜边缘的厚度
static let gridNum = 15; // 放大镜网格的数量
static let pixelSkip: CGFloat = 1; // 采集像素颜色时像素的间隔
}
/// 目标视图展示位置
var targetPoint: CGPoint = .zero
/// 获取指定点的颜色值
var pointColorCallBack: ((CGPoint) -> UIColor) = { _ in .clear }
private lazy var gridCirclePath: CGPath = {
let path = CGMutablePath()
path.addArc(center: .init(x: 0, y: 0),
radius: Const.magnify / 2 - Const.rimThickness / 2,
startAngle: 0,
endAngle: .pi * 2.0,
clockwise: true
)
return path
}()
override init() {
super.init()
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
anchorPoint = CGPoint(x: 0.5, y: 1)
bounds = CGRect(x: -Const.magnify / 2, y: -Const.magnify / 2, width: Const.magnify, height: Const.magnify)
let magnifyLayer = CALayer()
magnifyLayer.bounds = bounds
magnifyLayer.position = CGPoint(x: bounds.midX, y: bounds.midY)
magnifyLayer.magnificationFilter = .nearest
magnifyLayer.contents = makeMagnifyImage()?.cgImage
addSublayer(magnifyLayer)
}
override func draw(in ctx: CGContext) {
ctx.addPath(gridCirclePath)
ctx.clip()
let gridSize: CGFloat = (Const.magnify / CGFloat(Const.gridNum)).rounded(.up)
// 由于锚点修改,这里需要偏移
var currentPoint = targetPoint
currentPoint.x -= CGFloat(Const.gridNum) * Const.pixelSkip / 2
currentPoint.y -= CGFloat(Const.gridNum) * Const.pixelSkip / 2
// 放大镜中画出网格,并使用当前点和周围点的颜色进行填充
for index0 in 0 ..< Const.gridNum {
for index1 in 0 ..< Const.gridNum {
let rect = CGRect(
x: gridSize * CGFloat(index1) - Const.magnify / 2,
y: gridSize * CGFloat(index0) - Const.magnify / 2,
width: gridSize,
height: gridSize
)
let color = pointColorCallBack(currentPoint)
ctx.setFillColor(color.cgColor)
ctx.fill(rect)
// 横向寻找下一个相邻点
currentPoint.x += Const.pixelSkip
}
// 一行绘制完毕,横向回归起始点,纵向寻找下一个点
currentPoint.x -= CGFloat(Const.gridNum) * Const.pixelSkip
currentPoint.y += Const.pixelSkip
}
}
}
// MARK: - Private
extension ColorPickMagnifyLayer {
private func makeMagnifyImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
guard let ctx = UIGraphicsGetCurrentContext() else {
return nil
}
ctx.translateBy(x: Const.magnify / 2, y: Const.magnify / 2)
// 绘制裁剪区域
ctx.saveGState()
ctx.addPath(gridCirclePath)
ctx.clip()
ctx.restoreGState()
// 绘制放大镜边缘
ctx.setLineWidth(Const.rimThickness)
ctx.setStrokeColor(UIColor.black.cgColor)
ctx.addPath(gridCirclePath)
ctx.strokePath()
// 绘制两条边缘线中间的内容
ctx.setLineWidth(Const.rimThickness - 1)
ctx.setStrokeColor(UIColor.white.cgColor)
ctx.addPath(gridCirclePath)
ctx.strokePath()
// 绘制中心的选择区域
let gridWidth: CGFloat = (Const.magnify / CGFloat(Const.gridNum)).rounded(.up)
let offset = -(gridWidth + 1) / 2
let selectedRect = CGRect(x: offset, y: offset, width: gridWidth, height: gridWidth)
ctx.addRect(selectedRect)
let color = UIColor.dynamic(with: .black, dark: UIColor.white)
ctx.setStrokeColor(color.cgColor)
ctx.setLineWidth(1.0)
ctx.strokePath()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| 32.085271 | 114 | 0.584682 |
bf63a2bb63d4b83274202734d65b470c122067f8 | 5,017 | //
// EncryptionTests.swift
// Blockstack_Example
//
// Created by Shreyas Thiagaraj on 7/30/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import Blockstack
class EncryptionSpec : QuickSpec {
override func spec() {
describe("Encryption") {
// secp256k1 key pair
let privateKey = "a25629673b468789f8cbf84e24a6b9d97a97c5e12cf3796001dde2927021cdaf"
let publicKey = "04fdfa9031f9ac7b856bf539c0d315a4847c7e2b0b7dd22b40e8da9ee2beaa228acec7cad39526308bd7ab4af9e738203fdc6547a2108324c28874990e86534dc4"
context("with text") {
let content = "all work and no play makes jack a dull boy"
let cipherText = Blockstack.shared.encryptContent(text: content, publicKey: publicKey)
it("can encrypt") {
expect(cipherText).toNot(beNil())
}
it("can decrypt") {
guard let cipher = cipherText else {
fail("Invalid cipherText")
return
}
guard let plainText = Blockstack.shared.decryptContent(content: cipher, privateKey: privateKey)?.plainText else {
fail()
return
}
expect(plainText) == content
}
}
context("with bytes") {
let data = Data(bytes: [0x01, 0x02, 0x03])
let cipherText = Blockstack.shared.encryptContent(bytes: data.bytes, publicKey: publicKey)
it("can encrypt") {
expect(cipherText).toNot(beNil())
}
it("can decrypt") {
guard let cipher = cipherText else {
fail("Invalid cipherText")
return
}
guard let bytes = Blockstack.shared.decryptContent(content: cipher, privateKey: privateKey)?.bytes else {
fail()
return
}
expect(Data(bytes: bytes)) == data
}
}
context("with bad HMAC") {
var goodCipherObject: [String: Any] =
["iv": "62ebe31b41a5a79d7d80aec2ea8b5738",
"ephemeralPK": "0292b08fad355531ab867632dfa688af47c77a94732869783a749bcd159dd8a7d1",
"cipherText": "f5def102dae9d2b97d5230fb7ef77f1702ea69612e899cb238fdfc708a738aa7e4e40538558a859a89b80ba3188665e8",
"mac": "c2cf1e8d2765bde5978de5d323f56f7d22dd2ade9528df9f67640bae9dfe62c5",
"wasString": true]
var evilCipherObject: [String: Any] =
["iv": "8bc9d481a9c81f9654d3daf5629db205",
"ephemeralPK": "03a310890362fc143291a9b46eaa8ff77882441926de7e8ef5459654dd02b8654f",
"cipherText": "a6791f244a6120a4ace2b8e5acd8fd75553cace042a2adadfcb3a20a95aae7b308174de017247ccf5eb4ae8e49bcb4e8",
"mac": "99462eb405f8cc51886571b718acf5a914ac2832be5ba34569726ab720f8ea62",
"wasString": true]
let canDecrypt: ([String: Any]) -> Bool = { cipherObject in
guard let cipherData = try? JSONSerialization.data(withJSONObject: cipherObject, options: []),
let cipherJSON = String(data: cipherData, encoding: String.Encoding.utf8),
let _ = Blockstack.shared.decryptContent(content: cipherJSON, privateKey: privateKey)?.plainText else {
return false
}
return true
}
guard canDecrypt(goodCipherObject), canDecrypt(evilCipherObject) else {
fail("Bad input cipher object")
return
}
// Replace cipherText, keep mac the same
goodCipherObject["cipherText"] = evilCipherObject["cipherText"]
guard let jsonData = try? JSONSerialization.data(withJSONObject: goodCipherObject, options: []),
let corruptedCipherContent = String(data: jsonData, encoding: String.Encoding.utf8) else {
fail("Could not serialize manipulated cipher object to JSON")
return
}
it("will fail") {
let decryptedContent = Blockstack.shared.decryptContent(content: corruptedCipherContent, privateKey: privateKey)
expect(decryptedContent).to(beNil())
}
}
// TODO: Test signIn
// TODO: Test loadUserData
// TODO: Test signOut
// TODO: Test putFile
// TODO: Test getFile
}
}
}
| 44.794643 | 160 | 0.536376 |
f840f957f88bf62593cc57b270cbc38e415f2fb3 | 7,148 | #if canImport(Combine)
import Combine
import Foundation
import SwiftRex
/// A Store Projection made to be used in SwiftUI
///
/// All you need is to create an instance of this class by projecting the main store and providing maps for state and
/// actions. For the consumers, it will act as a real Store, but in fact it's only a proxy to the main store but working
/// in types more close to what a View should know, instead of working on global domain.
///
/// ```
/// ┌────────┐
/// │ Button │────────┐
/// └────────┘ │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┏━━━━━━━━━━━━━━━━━━━━━━━┓
/// ┌──────────────────┐ │ dispatch ┃ ┃░
/// │ Toggle │───┼────────────────────▶│ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─▶ │────────────▶┃ ┃░
/// └──────────────────┘ │ view event f: (Event) → Action app action ┃ ┃░
/// ┌──────────┐ │ │ │ ┃ ┃░
/// │ onAppear │───────┘ ┃ ┃░
/// └──────────┘ │ ObservableViewModel │ ┃ ┃░
/// ┃ ┃░
/// │ a projection of │ projection ┃ Store ┃░
/// the actual store ┃ ┃░
/// │ │ ┃ ┃░
/// ┌────────────────────────┐ ┃ ┃░
/// │ │ │ │ ┌┃─ ─ ─ ─ ─ ┐ ┃░
/// │ @ObservedObject │◀ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ◀─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ◀─ ─ ─ ─ ─ ─ State ┃░
/// │ │ view state │ f: (State) → View │ app state │ Publisher │ ┃░
/// └────────────────────────┘ State ┳ ─ ─ ─ ─ ─ ┃░
/// │ │ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┗━━━━━━━━━━━━━━━━━━━━━━━┛░
/// ▼ ▼ ▼ ░░░░░░░░░░░░░░░░░░░░░░░░░
/// ┌────────┐ ┌────────┐ ┌────────┐
/// │ Text │ │ List │ │ForEach │
/// └────────┘ └────────┘ └────────┘
/// ```
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
open class ObservableViewModel<ViewAction, ViewState>: StoreType, ObservableObject {
private var cancellableBinding: AnyCancellable?
private var store: StoreProjection<ViewAction, ViewState>
@Published public var state: ViewState
public let statePublisher: UnfailablePublisherType<ViewState>
public init<S>(initialState: ViewState, store: S, emitsValue: ShouldEmitValue<ViewState>)
where S: StoreType, S.ActionType == ViewAction, S.StateType == ViewState {
self.state = initialState
self.store = store.eraseToAnyStoreType()
self.statePublisher = store.statePublisher.removeDuplicates(by: emitsValue.shouldRemove).asPublisherType()
self.cancellableBinding = statePublisher.assign(to: \.state, on: self)
}
open func dispatch(_ action: ViewAction, from dispatcher: ActionSource) {
store.dispatch(action, from: dispatcher)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension ObservableViewModel where ViewState: Equatable {
public convenience init<S: StoreType>(initialState: ViewState, store: S)
where S.ActionType == ViewAction, S.StateType == ViewState {
self.init(
initialState: initialState,
store: store,
emitsValue: .whenDifferent
)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension StoreType {
public func asObservableViewModel(
initialState: StateType,
emitsValue: ShouldEmitValue<StateType>
) -> ObservableViewModel<ActionType, StateType> {
.init(initialState: initialState, store: self, emitsValue: emitsValue)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension StoreType where StateType: Equatable {
public func asObservableViewModel(
initialState: StateType
) -> ObservableViewModel<ActionType, StateType> {
.init(initialState: initialState, store: self, emitsValue: .whenDifferent)
}
}
#if DEBUG
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension ObservableViewModel {
/// Mock for using in tests or SwiftUI previews, available in DEBUG mode only
/// You can use if as a micro-redux for tests and SwiftUI previews, for example:
/// ```
/// let mock = ObservableViewModel<(user: String, pass: String, buttonEnabled: Bool), ViewAction>.mock(
/// state: (user: "ozzy", pass: "", buttonEnabled: false),
/// action: { action, state in
/// switch action {
/// case let .userChanged(newUser):
/// state.user = newUser
/// state.buttonEnabled = !state.user.isEmpty && !state.pass.isEmpty
/// case let .passwordChanged(newPass):
/// state.pass = newPass
/// state.buttonEnabled = !state.user.isEmpty && !state.pass.isEmpty
/// case .buttonTapped:
/// print("Button tapped")
/// }
/// }
/// )
/// ```
/// - Parameter state: Initial state mock
/// - Parameter action: a simple reducer function, of type `(ActionType, inout StateType) -> Void`, useful if
/// you want to use in SwiftUI live previews and quickly change an UI property when a
/// button is tapped, for example. It's like a micro-redux for tests and SwiftUI previews.
/// Defaults to do nothing.
/// - Returns: a very simple ObservableViewModel mock, that you can inject in your SwiftUI View for tests or
/// live preview.
public static func mock(state: StateType, action: (@escaping (ActionType, ActionSource, inout StateType) -> Void) = { _, _, _ in })
-> ObservableViewModel<ActionType, StateType> {
let subject = CurrentValueSubject<StateType, Never>(state)
return AnyStoreType<ActionType, StateType>(
action: { viewAction, dispatcher in
var state = subject.value
action(viewAction, dispatcher, &state)
subject.send(state)
},
state: subject.asPublisherType()
).asObservableViewModel(initialState: state, emitsValue: .always)
}
}
#endif
#endif
| 52.948148 | 135 | 0.460968 |
012f314cc6aa1f71a86e1cf45556258a0f189379 | 14,586 | // © 2018–2022 J. G. Pusey (see LICENSE.md)
// swiftlint:disable type_body_length
internal class TableRenderer {
// MARK: Internal Initializers
internal init(_ table: Table) {
self.table = table
}
// MARK: Internal Instance Methods
internal func render(box: Table.Box = .plain) -> String {
self.box = box
_prepareHeader()
_prepareColumnHeaders()
_prepareRows()
_prepareFooter()
_determineColumnWidths()
var result = ""
_renderHeader(into: &result)
_renderColumnHeaders(into: &result)
_renderRows(into: &result)
_renderFooter(into: &result)
return result
}
// MARK: Private Type Methods
private static func _renderBorder(into result: inout String,
widths: [Int],
pipe: Character,
leftJoiner: Character,
centerJoiner: Character,
rightJoiner: Character) {
result.append("\n")
result.append(leftJoiner)
for index in 0..<widths.count {
if index > 0 {
result.append(centerJoiner)
}
result.append(String(pipe).repeat(widths[index] + 2))
}
result.append(rightJoiner)
}
private static func _renderCells(into result: inout String,
widths: [Int],
cells: [Text],
pipe: Character) {
precondition(widths.count == cells.count)
let text: [[String]] = zip(widths, cells).map { $0.1.format(for: $0.0) }
let maxHeight = text.reduce(0) { max($0, $1.count) }
for lineIndex in 0..<maxHeight {
result.append("\n")
result.append(pipe)
for cellIndex in 0..<cells.count {
result.append(" ")
let lines = text[cellIndex]
if lineIndex < lines.count {
result.append(lines[lineIndex])
} else {
result.append(" ".repeat(widths[cellIndex]))
}
result.append(" ")
result.append(pipe)
}
}
}
// MARK: Private Instance Properties
private let table: Table
private var box: Table.Box = .plain
private var columnHeaders: [Text] = []
private var columnWidths: [Int] = []
private var footer = Text()
private var hasColumnHeaders = false
private var hasFooter = false
private var hasHeader = false
private var header = Text()
private var rows: [[Text]] = []
private var tableWidth: Int = 0
// MARK: Private Instance Methods
private func _determineColumnWidths() {
let chromeWidth = max((table.columns.count * 3) + 1, 4)
let maxTableWidth = Format.terminalWidth()
let minTableWidth = min(table.columns.count + chromeWidth,
maxTableWidth)
var minColumnWidths = table.columns.map { $0.minimumWidth ?? 1 }
let maxColumnWidths = table.columns.map { $0.maximumWidth ?? maxTableWidth }
let tableWidthF = footer.maximumDisplayWidth + 4 // add in chrome
let tableWidthH = header.maximumDisplayWidth + 4 // ditto
columnWidths = []
for index in 0..<table.columns.count {
let chWidth: Int
if hasColumnHeaders {
chWidth = _clamp(minColumnWidths[index],
columnHeaders[index].maximumDisplayWidth,
maxColumnWidths[index])
} else {
chWidth = minColumnWidths[index]
}
var rowWidth = 0
rows.forEach { row in
let width = _clamp(minColumnWidths[index],
row[index].maximumDisplayWidth,
maxColumnWidths[index])
if rowWidth < width {
rowWidth = width
}
}
columnWidths.append(max(chWidth, rowWidth))
}
//
// Special handling to make 2-column tables look better:
//
if columnWidths.count == 2 {
let halfTotalWidths = (columnWidths[0] + columnWidths[1]) / 2
minColumnWidths[0] = min(columnWidths[0], halfTotalWidths)
minColumnWidths[1] = min(columnWidths[1], halfTotalWidths)
}
let tableWidthC = columnWidths.reduce(0, +) + chromeWidth
tableWidth = _clamp(minTableWidth,
max(max(tableWidthF, tableWidthH),
tableWidthC),
maxTableWidth)
if tableWidth > tableWidthC {
_increaseColumnWidths(from: tableWidthC - chromeWidth,
to: tableWidth - chromeWidth,
max: maxColumnWidths)
} else if tableWidth < tableWidthC {
_decreaseColumnWidths(from: tableWidthC - chromeWidth,
to: tableWidth - chromeWidth,
min: minColumnWidths)
}
}
private func _decreaseColumnWidths(from fromWidth: Int,
to toWidth: Int,
min minColumnWidths: [Int]) {
var width = fromWidth
//
// First pass, stay at or above minimum column widths:
//
while width > toWidth {
let newWidth = _decrementColumnWidths(from: width,
to: toWidth,
min: minColumnWidths)
guard width > newWidth
else { break }
width = newWidth
}
let loColumnWidths = Array(repeating: 1,
count: minColumnWidths.count)
//
// Second pass, go down to lowest column width:
//
while width > toWidth {
let newWidth = _decrementColumnWidths(from: width,
to: toWidth,
min: loColumnWidths)
guard width > newWidth
else { break }
width = newWidth
}
}
private func _decrementColumnWidths(from fromWidth: Int,
to toWidth: Int,
min minColumnWidths: [Int]) -> Int {
precondition(minColumnWidths.count == columnWidths.count)
var width = fromWidth
for index in 0..<minColumnWidths.count {
guard width > toWidth
else { break }
if columnWidths[index] > minColumnWidths[index] {
columnWidths[index] -= 1
width -= 1
}
}
return width
}
private func _increaseColumnWidths(from fromWidth: Int,
to toWidth: Int,
max maxColumnWidths: [Int]) {
var width = fromWidth
//
// First pass, stay at or below maximum column widths:
//
while width < toWidth {
let newWidth = _incrementColumnWidths(from: width,
to: toWidth,
max: maxColumnWidths)
guard width < newWidth
else { break }
width = newWidth
}
let hiColumnWidths = Array(repeating: toWidth,
count: maxColumnWidths.count)
//
// Second pass, go up to highest column width:
//
while width < toWidth {
let newWidth = _incrementColumnWidths(from: width,
to: toWidth,
max: hiColumnWidths)
guard width < newWidth
else { break }
width = newWidth
}
}
private func _incrementColumnWidths(from fromWidth: Int,
to toWidth: Int,
max maxColumnWidths: [Int]) -> Int {
precondition(maxColumnWidths.count == columnWidths.count)
var width = fromWidth
for index in 0..<maxColumnWidths.count {
guard width < toWidth
else { break }
if columnWidths[index] < maxColumnWidths[index] {
columnWidths[index] += 1
width += 1
}
}
return width
}
private func _prepareColumnHeaders() {
hasColumnHeaders = false
columnHeaders = table.columns.map {
let text = Text($0.header,
$0.alignment ?? .left)
if !text.isEmpty {
hasColumnHeaders = true
}
return text
}
}
private func _prepareFooter() {
footer = Text(table.footer,
.left)
hasFooter = !footer.isEmpty
}
private func _prepareHeader() {
header = Text(table.header,
.center)
hasHeader = !header.isEmpty
}
private func _prepareRows() {
rows = []
let rowCount = table.columns.reduce(0) { max($0, $1.values.count) }
for index in 0..<rowCount {
let row: [Text] = table.columns.map {
if index < $0.values.count {
return Text($0.values[index],
$0.alignment ?? .left)
}
return Text()
}
rows.append(row)
}
}
private func _renderColumnHeaders(into result: inout String) {
guard hasColumnHeaders
else { return }
Self._renderBorder(into: &result,
widths: columnWidths,
pipe: box.h,
leftJoiner: hasHeader ? box.vr : box.dr,
centerJoiner: box.dh,
rightJoiner: hasHeader ? box.vl : box.dl)
Self._renderCells(into: &result,
widths: columnWidths,
cells: columnHeaders,
pipe: box.v)
}
private func _renderFooter(into result: inout String) {
guard hasFooter
else { return }
Self._renderCells(into: &result,
widths: [tableWidth - 4],
cells: [footer],
pipe: box.v)
Self._renderBorder(into: &result,
widths: [tableWidth - 4],
pipe: box.h,
leftJoiner: box.ur,
centerJoiner: box.uh,
rightJoiner: box.ul)
}
private func _renderHeader(into result: inout String) {
guard hasHeader
else { return }
Self._renderBorder(into: &result,
widths: [tableWidth - 4],
pipe: box.h,
leftJoiner: box.dr,
centerJoiner: box.dh,
rightJoiner: box.dl)
Self._renderCells(into: &result,
widths: [tableWidth - 4],
cells: [header],
pipe: box.v)
}
private func _renderRows(into result: inout String) {
Self._renderBorder(into: &result,
widths: columnWidths,
pipe: box.h,
leftJoiner: (hasHeader || hasColumnHeaders) ? box.vr : box.dr,
centerJoiner: hasColumnHeaders ? box.vh : box.dh,
rightJoiner: (hasHeader || hasColumnHeaders) ? box.vl : box.dl)
rows.forEach {
Self._renderCells(into: &result,
widths: columnWidths,
cells: $0,
pipe: box.v)
}
Self._renderBorder(into: &result,
widths: columnWidths,
pipe: box.h,
leftJoiner: hasFooter ? box.vr : box.ur,
centerJoiner: box.uh,
rightJoiner: hasFooter ? box.vl : box.ul)
}
}
internal class Text {
// MARK: Internal Initializers
internal init(_ rawText: String? = nil,
_ alignment: Table.Alignment = .center) {
self.alignment = alignment
self.lines = Self._splitIntoLines(rawText)
}
// MARK: Internal Instance Properties
internal var isEmpty: Bool {
lines.isEmpty
}
internal var maximumDisplayWidth: Int {
lines.reduce(0) { max($0, $1.displayWidth) }
}
// MARK: Internal Instance Methods
internal func format(for width: Int) -> [String] {
lines.flatMap { $0.wrap(width, splitWords: true) }.map { _pad($0, width) }
}
// MARK: Private Type Methods
private static func _splitIntoLines(_ rawText: String?) -> [String] {
guard let text = rawText
else { return [] }
return text
.split(omittingEmptySubsequences: false) { $0.isNewline }
.map { String($0).compress() }
}
// MARK: Private Instance Properties
private let alignment: Table.Alignment
private let lines: [String]
// MARK: Private Instance Methods
private func _pad(_ text: String,
_ width: Int) -> String {
let padWidth = width - text.displayWidth
guard padWidth > 0
else { return text }
switch alignment {
case .center:
let padWidthL = padWidth / 2
let padWidthR = padWidth - padWidthL
return " ".repeat(padWidthL) + text + " ".repeat(padWidthR)
case .left:
return text + " ".repeat(padWidth)
case .right:
return " ".repeat(padWidth) + text
}
}
}
private func _clamp<T>(_ vmin: T,
_ value: T,
_ vmax: T) -> T
where T: Comparable {
vmin > value ? vmin : vmax < value ? vmax : value
}
| 30.261411 | 90 | 0.478952 |
e5ea4b26ccb024c36f7bd6005ae2e56a8a042f1a | 19,854 | //
// HearthstatsAPI.swift
// HSTracker
//
// Created by Benjamin Michotte on 21/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import Alamofire
import CleanroomLogger
extension Deck {
func merge(deck: Deck) {
self.name = deck.name
self.playerClass = deck.playerClass
self.version = deck.version
self.creationDate = deck.creationDate
self.hearthstatsId = deck.hearthstatsId
self.hearthstatsVersionId = deck.hearthstatsVersionId
self.isActive = deck.isActive
self.isArena = deck.isArena
self.removeAllCards()
for card in deck.sortedCards {
for _ in 0...card.count {
self.addCard(card)
}
}
self.statistics = deck.statistics
}
static func fromHearthstatsDict(json: [String: AnyObject]) -> Deck? {
if let name = json["deck"]?["name"] as? String,
klassId = json["deck"]?["klass_id"] as? Int,
playerClass = HearthstatsAPI.heroes[klassId],
version = json["current_version"] as? String,
creationDate = json["deck"]?["created_at"] as? String,
hearthstatsId = json["deck"]?["id"] as? Int,
archived = json["deck"]?["archived"] as? Int,
isArchived = archived.boolValue {
var currentVersion: [String : AnyObject]?
(json["versions"] as? [[String: AnyObject]])?
.forEach { (_version: [String : AnyObject]) in
if _version["version"] as? String == version {
currentVersion = _version
}
}
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let currentVersion = currentVersion,
hearthstatsVersionId = currentVersion["deck_version_id"] as? Int,
date = formatter.dateFromString(creationDate) {
var cards = [Card]()
(json["cards"] as? [[String: String]])?
.forEach({ (_card: [String: String]) in
if let card = Cards.byId(_card["id"]),
_count = _card["count"],
count = Int(_count) {
card.count = count
cards.append(card)
}
})
let deck = Deck(playerClass: playerClass, name: name)
deck.creationDate = date
deck.hearthstatsId = hearthstatsId
deck.hearthstatsVersionId = hearthstatsVersionId
deck.isActive = !isArchived
deck.version = version
cards.forEach({ deck.addCard($0) })
if deck.isValid() {
return deck
}
}
}
return nil
}
}
extension Decks {
func byHearthstatsId(id: Int) -> Deck? {
return decks().filter({ $0.hearthstatsId == id }).first
}
func addOrUpdateMatches(dict: [String: AnyObject]) {
if let existing = decks()
.filter({ $0.hearthstatsId == (dict["deck_id"] as? Int)
&& $0.hearthstatsVersionId == (dict["deck_version_id"] as? Int) }).first {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let resultId = dict["match"]?["result_id"] as? Int,
result = HearthstatsAPI.gameResults[resultId],
coin = dict["match"]?["coin"] as? Bool,
classId = dict["match"]?["oppclass_id"] as? Int,
opponentClass = HearthstatsAPI.heroes[classId],
opponentName = dict["match"]?["oppname"] as? String,
playerRank = dict["ranklvl"] as? Int,
mode = dict["match"]?["mode_id"] as? Int,
playerMode = HearthstatsAPI.gameModes[mode],
date = dict["match"]?["created_at"] as? String,
creationDate = formatter.dateFromString(date) {
let stat = Statistic()
stat.gameResult = result
stat.hasCoin = coin
stat.opponentClass = opponentClass
stat.opponentName = opponentName
stat.playerRank = playerRank
stat.playerMode = playerMode
stat.date = creationDate
existing.addStatistic(stat)
update(existing)
}
}
}
}
enum HearthstatsError: ErrorType {
case NotLogged,
DeckNotSaved
}
struct HearthstatsAPI {
static let gameResults: [Int: GameResult] = [
1: .Win,
2: .Loss,
3: .Draw
]
static let gameModes: [Int: GameMode] = [
1: .Arena,
2: .Casual,
3: .Ranked,
4: .None,
5: .Friendly
]
static let heroes: [Int: CardClass] = [
1: .DRUID,
2: .HUNTER,
3: .MAGE,
4: .PALADIN,
5: .PRIEST,
6: .ROGUE,
7: .SHAMAN,
8: .WARLOCK,
9: .WARRIOR
]
private static let baseUrl = "http://api.hearthstats.net/api/v3"
// MARK: - Authentication
static func login(email: String, password: String,
callback: (success: Bool, message: String) -> ()) {
Alamofire.request(.POST, "\(baseUrl)/users/sign_in",
parameters: ["user_login": ["email": email, "password": password ]], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
if let success = json["success"] as? Bool where success {
let settings = Settings.instance
settings.hearthstatsLogin = json["email"] as? String
settings.hearthstatsToken = json["auth_token"] as? String
callback(success: true, message: "")
} else {
callback(success: false,
message: json["message"] as? String ?? "Unknown error")
}
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false,
message: NSLocalizedString("server error", comment: ""))
}
}
static func logout() {
let settings = Settings.instance
settings.hearthstatsLogin = nil
settings.hearthstatsToken = nil
}
static func isLogged() -> Bool {
let settings = Settings.instance
return settings.hearthstatsLogin != nil && settings.hearthstatsToken != nil
}
static func loadDecks(force: Bool = false,
callback: (success: Bool, added: Int) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
if force {
settings.hearthstatsLastDecksSync = NSDate.distantPast().timeIntervalSince1970
}
try getDecks(settings.hearthstatsLastDecksSync, callback: callback)
}
// MARK: - decks
private static func getDecks(unixTime: Double,
callback: (success: Bool, added: Int) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST,
"\(baseUrl)/decks/after_date?auth_token=\(settings.hearthstatsToken!)",
parameters: ["date": "\(unixTime)"], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value,
status = json["status"] as? Int where status == 200 {
var newDecks = 0
(json["data"] as? [[String: AnyObject]])?.forEach({
newDecks += 1
if let deck = Deck.fromHearthstatsDict($0),
hearthstatsId = deck.hearthstatsId {
if let existing = Decks.instance.byHearthstatsId(hearthstatsId) {
existing.merge(deck)
Decks.instance.update(existing)
} else {
Decks.instance.add(deck)
}
}
})
Settings.instance.hearthstatsLastDecksSync = NSDate().timeIntervalSince1970
callback(success: true, added: newDecks)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false, added: 0)
}
}
static func postDeck(deck: Deck, callback: (success: Bool) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST, "\(baseUrl)/decks?auth_token=\(settings.hearthstatsToken!)",
parameters: [
"name": deck.name ?? "",
"tags": [],
"notes": "",
"cards": deck.sortedCards.map {["id": $0.id, "count": $0.count]},
"class": deck.playerClass.rawValue.capitalizedString,
"version": deck.version
], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value,
data = json["data"] as? [String:AnyObject],
jsonDeck = data["deck"] as? [String:AnyObject],
hearthstatsId = jsonDeck["id"] as? Int,
deckVersions = data["deck_versions"] as? [[String:AnyObject]],
hearthstatsVersionId = deckVersions.first?["id"] as? Int {
deck.hearthstatsId = hearthstatsId
deck.hearthstatsVersionId = hearthstatsVersionId
callback(success: true)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false)
}
}
static func updateDeck(deck: Deck, callback: (success: Bool) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST, "\(baseUrl)/decks/edit?auth_token=\(settings.hearthstatsToken!)",
parameters: [
"deck_id": deck.hearthstatsId!,
"name": deck.name ?? "",
"tags": [],
"notes": "",
"cards": deck.sortedCards.map {["id": $0.id, "count": $0.count]},
"class": deck.playerClass.rawValue.capitalizedString
], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("update deck : \(json)")
callback(success: true)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false)
}
}
static func postDeckVersion(deck: Deck, callback: (success: Bool) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST,
"\(baseUrl)/decks/create_version?auth_token=\(settings.hearthstatsToken!)",
parameters: [
"deck_id": deck.hearthstatsId!,
"cards": deck.sortedCards.map {["id": $0.id, "count": $0.count]},
"version": deck.version
], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value,
data = json["data"] as? [String:AnyObject],
hearthstatsVersionId = data["id"] as? Int {
Log.debug?.message("post deck version : \(json)")
deck.hearthstatsVersionId = hearthstatsVersionId
callback(success: true)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false)
}
}
static func deleteDeck(deck: Deck) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST, "\(baseUrl)/decks/delete?auth_token=\(settings.hearthstatsToken!)",
parameters: ["deck_id": "[\(deck.hearthstatsId)]"], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("delete deck : \(json)")
return
}
}
}
}
// MARK: - matches
static func getGames(unixTime: Double, callback: (success: Bool) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST,
"\(baseUrl)/matches/after_date?auth_token=\(settings.hearthstatsToken!)",
parameters: ["date": "\(unixTime)"], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("get games : \(json)")
(json["data"] as? [[String: AnyObject]])?.forEach({
Decks.instance.addOrUpdateMatches($0)
})
// swiftlint:disable line_length
Settings.instance.hearthstatsLastMatchesSync = NSDate().timeIntervalSince1970
// swiftlint:enable line_length
callback(success: true)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false)
}
}
static func postMatch(game: Game, deck: Deck, stat: Statistic) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
guard let _ = deck.hearthstatsId else { throw HearthstatsError.DeckNotSaved }
guard let _ = deck.hearthstatsVersionId else { throw HearthstatsError.DeckNotSaved }
let startTime: NSDate
if let gameStartDate = game.gameStartDate {
startTime = gameStartDate
} else {
startTime = NSDate()
}
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(name: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
let startAt = formatter.stringFromDate(startTime)
let parameters: [String: AnyObject] = [
"class": deck.playerClass.rawValue.capitalizedString,
"mode": "\(game.currentGameMode)",
"result": "\(game.gameResult)",
"coin": "\(stat.hasCoin)",
"numturns": stat.numTurns,
"duration": stat.duration,
"deck_id": deck.hearthstatsId!,
"deck_version_id": deck.hearthstatsVersionId!,
"oppclass": stat.opponentClass.rawValue.capitalizedString,
"oppname": stat.opponentName,
"notes": stat.note ?? "",
"ranklvl": stat.playerRank,
"oppcards": stat.cards,
"created_at": startAt
]
Log.info?.message("Posting match to Hearthstats \(parameters)")
Alamofire.request(.POST, "\(baseUrl)/matches?auth_token=\(settings.hearthstatsToken!)",
parameters: parameters, encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("post match : \(json)")
return
}
}
}
}
// MARK: - Arena
static func postArenaMatch(game: Game, deck: Deck, stat: Statistic) throws {
guard let _ = Settings.instance.hearthstatsToken else { throw HearthstatsError.NotLogged }
guard let _ = deck.hearthStatsArenaId else {
createArenaRun(game, deck: deck, stat: stat)
return
}
_postArenaMatch(game, deck: deck, stat: stat)
}
private static func _postArenaMatch(game: Game, deck: Deck, stat: Statistic) {
let parameters: [String: AnyObject] = [
"class": deck.playerClass.rawValue.capitalizedString,
"mode": "\(game.currentGameMode)",
"result": "\(game.gameResult)",
"coin": "\(stat.hasCoin)",
"numturns": stat.numTurns,
"duration": stat.duration,
"arena_run_id": deck.hearthStatsArenaId!,
"oppclass": stat.opponentClass.rawValue.capitalizedString,
"oppname": stat.opponentName,
]
Log.info?.message("Posting arena match to Hearthstats \(parameters)")
let url = "\(baseUrl)/matches?auth_token=\(Settings.instance.hearthstatsToken!)"
Alamofire.request(.POST, url,
parameters: parameters, encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("post arena match : \(json)")
return
}
}
}
}
static func createArenaRun(game: Game, deck: Deck, stat: Statistic) {
Log.info?.message("Creating new arena deck")
let parameters: [String: AnyObject] = [
"class": deck.playerClass.rawValue.capitalizedString,
"cards": deck.sortedCards.map {["id": $0.id, "count": $0.count]}
]
let url = "\(baseUrl)/arena_runs/new?auth_token=\(Settings.instance.hearthstatsToken!)"
Alamofire.request(.POST, url,
parameters: parameters, encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value,
data = json["data"] as? [String:AnyObject],
hearthStatsArenaId = data["id"] as? Int {
deck.hearthStatsArenaId = hearthStatsArenaId
Log.debug?.message("Arena run : \(hearthStatsArenaId)")
_postArenaMatch(game, deck: deck, stat: stat)
return
}
}
}
}
}
| 41.10559 | 101 | 0.511887 |
0e6b6480d0d33ca57962b038b54b988b0d6caab3 | 903 | //
// quicksizeTests.swift
// quicksizeTests
//
// Created by Elliot Ball on 21/12/2020.
//
import XCTest
@testable import quicksize
class quicksizeTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.558824 | 111 | 0.665559 |
ed0b506e10119de3c271b1a97d2da64aa158eec9 | 604 | //
// ViewController.swift
// hellopod_mxc
//
// Created by xingchi.mxc on 01/23/2018.
// Copyright (c) 2018 xingchi.mxc. All rights reserved.
//
import UIKit
import hellopod_mxc
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let hello = HelloPods();
print(hello.hello());
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.827586 | 80 | 0.652318 |
5bb3279a8f0d0ac8f40514d60cec30e08f9a0295 | 1,471 | //
// AppDelegate.swift
// DoorDash
//
// Created by Marvin Zhan on 2018-09-11.
// Copyright © 2018 Monster. All rights reserved.
//
import UIKit
import SwiftDate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
SwiftDate.defaultRegion = Region.local
if let storedEnvironment
= ApplicationEnvironment.restore(from: UserDefaults.standard) {
ApplicationEnvironment.replaceCurrentEnvironment(storedEnvironment)
ApplicationEnvironment.replaceCurrentEnvironment(mainBundle: Bundle.main)
} else {
#if DEBUG
let env = Environment.latest
#else
let env = Environment.production
#endif
ApplicationEnvironment.pushEnvironment(env)
}
ApplicationEnvironment.current.dataStore.loadStore {}
if ApplicationSettings.Stored.enableVisualizeDemoMode {
window = SensorVisualizerWindow(frame: UIScreen.main.bounds)
} else {
window = UIWindow(frame: UIScreen.main.bounds)
}
self.window?.makeKeyAndVisible()
self.window?.backgroundColor = UIColor.white
ApplicationDependency.manager.coordinator.start(window: self.window!)
return true
}
}
| 31.978261 | 152 | 0.673691 |
5df1f973d2f746c88647b137887f1121a5f53c4e | 765 | //
// BoolExtension.swift
// YYSwift
//
// Created by Phoenix on 2017/11/16.
// Copyright © 2017年 Phoenix. All rights reserved.
//
// MARK: - Properties
public extension Bool {
/// YYSwift: Return 1 if true, or 0 if false.
///
/// false.int -> 0
/// true.int -> 1
///
var int: Int {
return self ? 1 : 0
}
/// YYSwift: Return "true" if true, or "false" if false.
///
/// false.string -> "false"
/// true.string -> "true"
///
var string: String {
return description
}
/// YYSwift: Return inversed value of bool.
///
/// false.toggled -> true
/// true.toggled -> false
///
var toggled: Bool {
return !self
}
}
| 18.658537 | 60 | 0.49281 |
ed9b2eb5eb91dcf248e1cbe0d1d7d4f9a24b9a44 | 19,253 | //
// Aura
//
// Copyright © 2016 Ayla Networks. All rights reserved.
//
import UIKit
import PDKeychainBindingsController
import iOS_AylaSDK
class SetupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, AylaDeviceWifiStateChangeListener {
private let logTag = "SetupViewController"
/// Setup cell id
fileprivate static let CellId: String = "SetupCellId"
/// Description view to display status
@IBOutlet fileprivate weak var consoleView: AuraConsoleTextView!
/// Table view of scan results
@IBOutlet fileprivate weak var tableView: UITableView!
/// A reserved view for future use.
@IBOutlet fileprivate weak var controlPanel: UIView!
/// AylaSetup instance used by this setup view controller
fileprivate var setup: AylaSetup
/// Current presenting alert controller
fileprivate var alert: UIAlertController? {
willSet(newAlert) {
if let oldAlert = alert {
// If there is an alert presenting to user. dimiss it first.
oldAlert.dismiss(animated: false, completion: nil)
}
}
}
/// Wi-Fi 'state' as provided by the device being set up.
fileprivate var moduleWiFiState: String! = "none" {
willSet(newState){
if newState != moduleWiFiState {
let prompt = "Module Reported WiFi State: '\(newState)'"
addDescription(prompt)
}
}
}
/// Current running connect task
fileprivate var currentTask: AylaConnectTask?
/// Scan results which are presented in table view
fileprivate var scanResults :AylaWifiScanResults?
/// Last used token.
fileprivate var token: String?
/// Default timeout for device cloud connection polling
fileprivate let defaultCloudConfirmationTimeout = 60.0
required init?(coder aDecoder: NSCoder){
// Init setup
setup = AylaSetup(sdkRoot: AylaNetworks.shared())
super.init(coder: aDecoder)
//register as WiFi State listener
setup.addWiFiStateListener(self)
// Monitor connectivity
monitorDeviceConnectivity()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
// Init setup
setup = AylaSetup(sdkRoot: AylaNetworks.shared())
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
// Monitor connectivity
monitorDeviceConnectivity()
}
override func viewDidLoad() {
super.viewDidLoad()
// Assign self as delegate and data source of tableview.
tableView.delegate = self
tableView.dataSource = self
let refreshButton = UIBarButtonItem(barButtonSystemItem:.refresh, target: self, action: #selector(refresh))
navigationItem.rightBarButtonItem = refreshButton
attemptToConnect()
}
fileprivate func updatePrompt(_ prompt: String?) {
navigationController?.navigationBar.topItem?.prompt = prompt
}
/**
Monitor device connectivity by adding KVO to property `connected` of setup device.
*/
fileprivate func monitorDeviceConnectivity() {
// Add observer to setup device connection status.
setup.addObserver(self, forKeyPath: "setupDevice.connected", options: .new, context: nil)
}
/**
Use this method to connect to device again.
*/
@objc fileprivate func refresh() {
// Clean scan results
scanResults = nil
tableView.reloadData()
attemptToConnect()
}
/**
Writes the setupDevice's registrationType string to the consoleView
*/
fileprivate func logRegistrationTypeForSetupDevice(_ setupDevice:AylaSetupDevice){
let registrationType = AylaRegistration.registrationName(from: setupDevice.registrationType)
addDescription("Device will use \(registrationType ?? "nil") Registration Type.")
}
/**
Writes the setupDevice's details to the consoleView
*/
fileprivate func logDetailsForSetupDevice(_ setupDevice:AylaSetupDevice){
let indent = " "
self.addDescription("Device Details:")
addDescription(indent + "DSN: \(setupDevice.dsn )")
addDescription(indent + "FW version: \(setupDevice.version ?? "none")")
addDescription(indent + "FW build: \(setupDevice.build ?? "none")")
addDescription(indent + "LAN IP: \(setupDevice.lanIp )")
addDescription(indent + "MAC: \(setupDevice.mac ?? "none")")
addDescription(indent + "Model: \(setupDevice.model )")
if let features = setupDevice.features {
addDescription(indent + "Features:")
for feature in features {
addDescription(indent + indent + "\(feature)")
}
}
}
/**
Must use this method to start setup for a device.
*/
fileprivate func attemptToConnect() {
updatePrompt("Connecting...")
addDescription("Looking for a device to set up.")
setup.connect(toNewDevice: { (setupDevice) -> Void in
self.addDescription("Found Device")
self.logDetailsForSetupDevice(setupDevice)
// Start fetching AP list from module.
self.fetchFreshAPListWithWiFiScan()
}) { (error) -> Void in
self.updatePrompt("")
self.addDescription("Unable to find device: \(error.aylaServiceDescription)")
let message = "Are you connected to the Wi-Fi access point of the device you wish to set up?\n\nIf not, please tap the button below to move to the Settings application. Navigate to Wi-Fi settings section and select the AP/network name for your device.\n\nOnce the network is joined, you should be redirected here momentarily."
let alert = UIAlertController(title: "No Device Found", message: message, preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Go To Settings App", style:.default, handler: { (action) in
self.dismiss(animated: false, completion: {
UIApplication.shared.openURL(URL(string:UIApplicationOpenSettingsURLString)!)
})
})
let cancelAction = UIAlertAction(title: "Cancel", style:.cancel, handler: { (action) in
self.updatePrompt("No Device Found")
})
alert.addAction(settingsAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: {})
}
}
/**
* Use this method to have the module scan for Wi-Fi access points, then fetch the resulting AP list from setup.
*/
fileprivate func fetchFreshAPListWithWiFiScan() {
addDescription("Device is scanning for Wi-Fi Access Points...")
currentTask = setup.startDeviceScan(forAccessPoints: {
self.addDescription("Scan Complete. Fetching results.")
self.fetchCurrentAPList()
}) { (error) in
let message = "Wi-Fi Scan Failed"
self.updatePrompt(message)
self.displayError(error as NSError, message: message)
}
}
/**
* Use this method to have the setup device scan for Wi-Fi access points.
*/
fileprivate func fetchCurrentAPList(){
currentTask = setup.fetchDeviceAccessPoints({ (scanResults) -> Void in
self.addDescription("Received AP list.")
self.updatePrompt(self.setup.setupDevice?.dsn ?? "")
self.scanResults = scanResults
self.tableView.reloadData()
}, failure: { (error) -> Void in
self.updatePrompt("Error")
let message = "An error occurred while trying to fetch the Wi-Fi scan results."
self.displayError(error as NSError, message: message)
})
}
/**
Use this method to connect device to the input SSID
- parameter ssid: The ssid which device would connect to.
- parameter password: Password of the ssid.
*/
fileprivate func connectToSSID(_ ssid: String, password: String?) {
token = String.generateRandomAlphanumericToken(7)
updatePrompt("Connecting device to '\(ssid)'...")
addDescription("Connecting device to the network '\(ssid)'...")
let tokenString = String(format:"Using Setup Token %@.", token!)
addDescription(tokenString)
setup.connectDeviceToService(withSSID: ssid, password: password, setupToken: token!, latitude: 0.0, longitude: 0.0, success: { (wifiStatus) -> Void in
// Succeeded, go confirming.
self.addDescription("Device reports connection to SSID.")
// Call to confirm connection.
self.confirmConnectionToService()
}) { (error) -> Void in
var message = "Unknown error"
if let errorCode = AylaWifiConnectionError(rawValue: UInt16(error.aylaResponseErrorCode)) {
switch errorCode {
case .connectionTimedOut:
message += "Connection Timed Out"
case .invalidKey:
message += "Invalid Wi-Fi Key Entered"
case .notAuthenticated:
message += "Failed to Authenticate"
case .incorrectKey:
message += "Incorrect Wi-Fi Key Entered"
case .disconnected:
message += "Disconnected from Device"
default:
message += "AylaWifiConnectionError Code \(errorCode.rawValue)"
}
}
self.updatePrompt("Setup Failed")
self.displayError(error as NSError, message: message)
}
}
/**
Use this method to confirm device connnection status with cloud service.
*/
fileprivate func confirmConnectionToService() {
func storeDeviceDetailsInKeychain(){
// Store device info in keychain for use during a later registration attempt.
PDKeychainBindings.shared().setString(self.token, forKey: AuraDeviceSetupTokenKeychainKey)
PDKeychainBindings.shared().setString(self.setup.setupDevice?.dsn, forKey: AuraDeviceSetupDSNKeychainKey)
}
updatePrompt("Confirming device connection status ...")
addDescription("Polling cloud service to confirm device connection.\n Timeout set to \(Int(defaultCloudConfirmationTimeout)) seconds. Please wait...")
let deviceDSN = setup.setupDevice?.dsn
setup.confirmDeviceConnected(withTimeout: defaultCloudConfirmationTimeout, dsn:(deviceDSN)!, setupToken:token!, success: { (setupDevice) -> Void in
self.logRegistrationTypeForSetupDevice(setupDevice)
self.updatePrompt("- Succeeded -")
self.addDescription("- Wi-Fi Setup Complete -")
let alertString = String(format:"Setup for device %@ completed successfully, using the setup token %@.\n\n You may wish to store this token if the device uses AP Mode registration.", (self.setup.setupDevice?.dsn)!, self.token!)
let alert = UIAlertController(title: "Setup Successful", message: alertString, preferredStyle: .alert)
let copyAction = UIAlertAction(title: "Copy Token to Clipboard", style: .default, handler: { (action) -> Void in
UIPasteboard.general.string = self.token!
storeDeviceDetailsInKeychain()
})
let cancelAction = UIAlertAction(title: "No, Thanks", style: .cancel, handler: { (action) -> Void in
storeDeviceDetailsInKeychain()
})
if let sessionManager = AylaNetworks.shared().getSessionManager(withName: AuraSessionOneName) {
var deviceAlreadyRegistered = false
let devices = sessionManager.deviceManager.devices.values.map({ (device) -> AylaDevice in
return device as! AylaDevice
})
for device in devices {
if device.dsn == deviceDSN {
deviceAlreadyRegistered = true
self.addDescription("FYI, Device appears to be registered or shared to you already.");
}
}
if deviceAlreadyRegistered == false {
let registerNowAction = UIAlertAction(title: "Register Device Now", style: .default, handler: { (action) -> Void in
storeDeviceDetailsInKeychain()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let regVC = storyboard.instantiateViewController(withIdentifier: "registrationController")
self.navigationController?.pushViewController(regVC, animated: true)
})
alert.addAction(registerNowAction)
}
}
alert.addAction(copyAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
// Clean scan results
self.scanResults = nil
self.tableView.reloadData()
}) { (error) -> Void in
let message = "Confirmation step has failed."
self.displayError(error as NSError, message: message)
}
}
/**
Use this method to add a description to description text view.
*/
fileprivate func addDescription(_ description: String) {
consoleView.addLogLine(description)
AylaLogD(tag: logTag, flag: 0, message:"Log: \(description)")
}
/**
Display an error with UIAlertController
- parameter error: The error which is going to be displayed.
- parameter message: Message to be displayed along with error.
*/
fileprivate func displayError(_ error:NSError, message: String?) {
if let currentAlert = alert {
currentAlert.dismiss(animated: false, completion: nil)
}
let serviceDescription = error.aylaServiceDescription
var errorText = ""
if let message = message {
errorText = message + "\n\nAylaError: '" + serviceDescription! + "'"
}
let alertController = UIAlertController(title: "Error", message: errorText, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Got it", style: .cancel, handler: nil))
alert = alertController
self.present(alertController, animated: true, completion: nil)
addDescription("Error: \(message ?? "")\n '\(serviceDescription ?? "nil")'")
}
@IBAction fileprivate func cancel(_ sender: AnyObject) {
dismiss(animated: true) { () -> Void in
self.setup.exit()
}
}
deinit {
setup.removeObserver(self, forKeyPath: "setupDevice.connected")
setup.removeWiFiStateListener(self)
}
// MARK: - Table view delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let result = scanResults?.results[indexPath.row] {
// Compose an alert controller to let user input password.
// TODO: If password is not required, the password text field should be removed from alert.
let alertController = UIAlertController(title: "Password Required", message: "Please input password for the network \"\(result.ssid)\".", preferredStyle: .alert)
let connect = UIAlertAction(title: "Connect", style: .default) { (_) in
let password = alertController.textFields![0] as UITextField
self.connectToSSID(result.ssid, password: password.text)
}
connect.isEnabled = false
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
let password = alertController.textFields![0] as UITextField
password.resignFirstResponder()
}
alertController.addTextField { (textField) in
textField.placeholder = "SSID password"
NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
connect.isEnabled = textField.text != ""
}
}
alertController.addAction(connect)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
// Call to wake up main run loop
CFRunLoopWakeUp(CFRunLoopGetCurrent());
}
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
if let result = scanResults?.results[indexPath.row] {
let connectAction = UITableViewRowAction(style: .normal, title:"\(result.signal)" ) { (rowAction:UITableViewRowAction, indexPath:IndexPath) -> Void in
// Edit actions, empty for now.
}
connectAction.backgroundColor = UIColor.darkGray
return [connectAction]
}
return nil
}
// MARK: - Table view datasource
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let results = scanResults?.results as [AylaWifiScanResult]!
let result = results?[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: SetupViewController.CellId)
cell?.textLabel!.text = (result?.ssid)! + "\n \((result?.security)!), Signal: \((result?.signal)!) dBm"
cell!.selectionStyle = UITableViewCellSelectionStyle.none
return cell!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return scanResults?.results.count ?? 0
}
// MARK: - KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object as? AylaSetupDevice === setup.setupDevice {
if let device = object as? AylaSetupDevice {
if !device.connected {
updatePrompt("Lost Connectivity To Device")
}
}
}
}
func wifiStateDidChange(_ state: String) {
moduleWiFiState = state
}
}
| 41.945534 | 343 | 0.599647 |
fbca772d0a6f48ebad1d83f838302ab655347a30 | 3,857 | import UIKit
import WebKit
/**
Markdown View for iOS.
- Note: [How to get height of entire document with javascript](https://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript)
*/
open class MarkdownView: UIView {
private var webView: WKWebView?
fileprivate var intrinsicContentHeight: CGFloat? {
didSet {
self.invalidateIntrinsicContentSize()
}
}
@objc public var isScrollEnabled: Bool = true {
didSet {
webView?.scrollView.isScrollEnabled = isScrollEnabled
}
}
@objc public var onTouchLink: ((URLRequest) -> Bool)?
@objc public var onRendered: ((CGFloat) -> Void)?
public convenience init() {
self.init(frame: CGRect.zero)
}
override init (frame: CGRect) {
super.init(frame : frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override var intrinsicContentSize: CGSize {
if let height = self.intrinsicContentHeight {
return CGSize(width: UIView.noIntrinsicMetric, height: height)
} else {
return CGSize.zero
}
}
@objc public func load(markdown: String?, enableImage: Bool = true) {
guard let markdown = markdown else { return }
let bundle = Bundle(for: MarkdownView.self)
let htmlURL: URL? =
bundle.url(forResource: "index",
withExtension: "html") ??
bundle.url(forResource: "index",
withExtension: "html",
subdirectory: "MarkdownView.bundle")
if let url = htmlURL {
let templateRequest = URLRequest(url: url)
let escapedMarkdown = self.escape(markdown: markdown) ?? ""
let imageOption = enableImage ? "true" : "false"
let script = "window.showMarkdown('\(escapedMarkdown)', \(imageOption));"
let userScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let controller = WKUserContentController()
controller.addUserScript(userScript)
let configuration = WKWebViewConfiguration()
configuration.userContentController = controller
let wv = WKWebView(frame: self.bounds, configuration: configuration)
wv.scrollView.isScrollEnabled = self.isScrollEnabled
wv.translatesAutoresizingMaskIntoConstraints = false
wv.navigationDelegate = self
addSubview(wv)
wv.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
wv.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
wv.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
wv.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
wv.backgroundColor = self.backgroundColor
self.webView = wv
wv.load(templateRequest)
} else {
// TODO: raise error
}
}
private func escape(markdown: String) -> String? {
return markdown.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics)
}
}
extension MarkdownView: WKNavigationDelegate {
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let script = "document.body.scrollHeight;"
webView.evaluateJavaScript(script) { [weak self] result, error in
if let _ = error { return }
if let height = result as? CGFloat {
self?.onRendered?(height)
self?.intrinsicContentHeight = height
}
}
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
switch navigationAction.navigationType {
case .linkActivated:
if let onTouchLink = onTouchLink, onTouchLink(navigationAction.request) {
decisionHandler(.allow)
} else {
decisionHandler(.cancel)
}
default:
decisionHandler(.allow)
}
}
}
| 29.219697 | 162 | 0.688618 |
d912892e03b4f70679786730fedba04d32d84c87 | 1,014 | //
// PermissionManagerInterface.swift
// WWRequestPermission
//
// Created by 王伟 on 2018/4/5.
// Copyright © 2018年 王伟. All rights reserved.
//
import Foundation
public protocol PermissionManagerProtocol : PermissionRequestProtocol, PermissionStatusProtocol {}
public typealias PermissionClosure = (Bool)->()
// 请求接口
public protocol PermissionRequestProtocol {
/**
用户请求权限
param: permission 权限类型
*/
static func request(_ permission: RequestPermissionType, _ complectionHandler: @escaping PermissionClosure)
}
// 状态接口
public protocol PermissionStatusProtocol {
/**
用户还未决定
param: permission 权限类型
*/
static func isNotDetermined(_ permission: RequestPermissionType) -> Bool
/**
用户没有权限或者拒绝
param: permission 权限类型
*/
static func isRestrictOrDenied(_ permission: RequestPermissionType) -> Bool
/**
用户允许
param: permission 权限类型
*/
static func isAuthorized(_ permission: RequestPermissionType) -> Bool
}
| 20.28 | 111 | 0.695266 |
48413c5dadb40c666a7596863f224c7fbe794782 | 1,230 | //
// OverlayContentModifier.swift
// DynamicOverlay
//
// Created by Gaétan Zanella on 03/12/2020.
// Copyright © 2020 Fabernovel. All rights reserved.
//
import SwiftUI
struct OverlayContentModifier<Overlay: View>: ViewModifier {
let overlay: Overlay
func body(content: Content) -> some View {
content.environment(\.overlayContentKey, AnyView(overlay))
}
}
extension View {
func overlayContent<Content: View>(_ content: Content) -> ModifiedContent<Self, OverlayContentModifier<Content>> {
modifier(OverlayContentModifier(overlay: content))
}
}
/// The root view of the overlay content
struct OverlayContentHostingView: View {
/// We use an environment variable to avoid UIViewController allocations each time the content changes.
@Environment(\.overlayContentKey)
var content: AnyView
var body: some View {
content
}
}
private struct OverlayContentKey: EnvironmentKey {
static var defaultValue = AnyView(EmptyView())
}
private extension EnvironmentValues {
var overlayContentKey: AnyView {
set {
self[OverlayContentKey.self] = newValue
}
get {
self[OverlayContentKey.self]
}
}
}
| 22.363636 | 118 | 0.686179 |
71fe48a18baa0c258041cc6952472bbb1ca4e74f | 4,239 | //
// Card.swift
// English Flashcards
//
// Created by Quang Luong on 11/1/20.
//
import UIKit
import os.log
class Card: NSObject, NSCoding {
//MARK: Types
struct PropertyKey {
static let word = "word"
static let definition = "definition"
static let example = "example"
static let lexicalCategory = "lexicalCategory"
static let phoneticSpelling = "phoneticSpelling"
static let audioFile = "audioFile"
static let image = "image"
static let audioURL = "audioURL"
}
//MARK: Properties
var word: String
var definition: String
var example: String
var lexicalCategory: String
var phoneticSpelling: String
var audioFile: String
var audioURL: URL?
//MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("Card")
//MARK: Initialization
init?(word: String, definition: String, example: String, lexicalCategory: String, phoneticSpelling: String, audioFile: String, audioURL: URL?) {
// Initialization should fail if there is no name or if the rating is negative.
guard !word.isEmpty && !definition.isEmpty && !example.isEmpty && !lexicalCategory.isEmpty && !phoneticSpelling.isEmpty && !audioFile.isEmpty else {
return nil
}
self.word = word
self.definition = definition
self.example = example
self.lexicalCategory = lexicalCategory
self.phoneticSpelling = phoneticSpelling
self.audioFile = audioFile
self.audioURL = audioURL
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(word, forKey: PropertyKey.word)
aCoder.encode(definition, forKey: PropertyKey.definition)
aCoder.encode(example, forKey: PropertyKey.example)
aCoder.encode(lexicalCategory, forKey: PropertyKey.lexicalCategory)
aCoder.encode(phoneticSpelling, forKey: PropertyKey.phoneticSpelling)
aCoder.encode(audioFile, forKey: PropertyKey.audioFile)
aCoder.encode(audioURL, forKey: PropertyKey.audioURL)
}
required convenience init?(coder aDecoder: NSCoder) {
// The word is required. If we cannot decode a name string, the initializer should fail.
guard let word = aDecoder.decodeObject(forKey: PropertyKey.word) as? String else {
os_log("Unable to decode the word.", log: OSLog.default, type: .debug)
return nil
}
guard let definition = aDecoder.decodeObject(forKey: PropertyKey.definition) as? String else {
os_log("Unable to decode the definition.", log: OSLog.default, type: .debug)
return nil
}
guard let example = aDecoder.decodeObject(forKey: PropertyKey.example) as? String else {
os_log("Unable to decode the example.", log: OSLog.default, type: .debug)
return nil
}
guard let lexicalCategory = aDecoder.decodeObject(forKey: PropertyKey.lexicalCategory) as? String else {
os_log("Unable to decode the lexicalCategory.", log: OSLog.default, type: .debug)
return nil
}
guard let phoneticSpelling = aDecoder.decodeObject(forKey: PropertyKey.phoneticSpelling) as? String else {
os_log("Unable to decode the phoneticSpelling.", log: OSLog.default, type: .debug)
return nil
}
guard let audioFile = aDecoder.decodeObject(forKey: PropertyKey.audioFile) as? String else {
os_log("Unable to decode the audioFile.", log: OSLog.default, type: .debug)
return nil
}
// Because audioURL is an optional property of Task, just use conditional cast.
let audioURL = aDecoder.decodeObject(forKey: PropertyKey.audioURL) as? URL
// Must call designated initializer.
self.init(word: word, definition: definition, example: example, lexicalCategory: lexicalCategory, phoneticSpelling: phoneticSpelling, audioFile: audioFile, audioURL: audioURL)
}
}
| 40.371429 | 183 | 0.656287 |
389e863000a84ea2b50ee0420aa71d62e11340f3 | 1,205 | //
// SequenceTypeExtension.swift
// FluxWithRxSwiftSample
//
// Created by Yuji Hato on 2016/12/02.
// Copyright © 2016年 dekatotoro. All rights reserved.
//
extension Sequence {
/// Return first matched element index
func find(_ includedElement: (Iterator.Element) -> Bool) -> Int? {
for (index, element) in enumerated() {
if includedElement(element) {
return index
}
}
return nil
}
func findItem(_ includedElement: (Iterator.Element) -> Bool) -> Iterator.Element? {
for item in self where includedElement(item) {
return item
}
return nil
}
}
extension Sequence where Iterator.Element: OptionalType {
/// Return not nil elements
func filterNil() -> [Iterator.Element.Wrapped] {
return flatMap { $0.value }
}
}
extension Sequence where Iterator.Element: Hashable {
typealias E = Iterator.Element
func diff(other: [E]) -> [E] {
let all = self + other
var counter: [E: Int] = [:]
all.forEach { counter[$0] = (counter[$0] ?? 0) + 1 }
return all.filter { (counter[$0] ?? 0) == 1 }
}
}
| 23.173077 | 87 | 0.570124 |
ddf3244e3a81fe9a37429278817144c92acc59bd | 1,260 | //
// AudioEngineMixerNode.swift
// audio_graph
//
// Created by Kaisei Sunaga on 2020/01/31.
//
import Foundation
import AVFoundation
class AudioEngineMixerNode: AudioEngineNode, AudioVolumeEditableNode {
static let nodeName = "audio_mixer_node"
var node: AudioNode
let engineNode: AVAudioNode
let inputConnections: [AudioNodeConnection]
let outputConnections: [AudioNodeConnection]
let shouldAttach: Bool = true
var volume: Double {
didSet {
node.volume = volume
(engineNode as! AVAudioMixerNode).outputVolume = Float(volume)
}
}
init(_ node: AudioNode, inputConnections: [AudioNodeConnection], outputConnections: [AudioNodeConnection]) throws {
guard node.name == AudioEngineMixerNode.nodeName else { throw NSError() }
self.node = node
self.inputConnections = inputConnections
self.outputConnections = outputConnections
let mixer = AVAudioMixerNode()
mixer.volume = Float(node.volume)
for (i, con) in inputConnections.enumerated() {
con.inBus = i
}
outputConnections.first!.outBus = 0
engineNode = mixer
self.volume = node.volume
}
}
| 28 | 119 | 0.651587 |
e24e5fc228b83dbfac67ca35239df00e8d1de575 | 298 | //
// ViewController+Route.swift
// ModuleA
//
// Created by 863hy on 2021/1/7.
//
import Foundation
import URouter
extension ViewController: URouteType {
static func target(with params: Any?) -> UIViewController {
print(params as Any)
return ViewController()
}
}
| 16.555556 | 63 | 0.657718 |
e54adc973d20301916ec78f224defda092d4cca6 | 6,537 | /*:
# Tagged Exercises
1. Conditionally conform Tagged to ExpressibleByStringLiteral in order to restore the ergonomics of initializing our User’s email property. Note that ExpressibleByStringLiteral requires a couple other prerequisite conformances.
*/
struct Tagged<Tag, RawValue> {
let rawValue: RawValue
}
extension Tagged: Decodable where RawValue: Decodable {}
extension Tagged: Equatable where RawValue: Equatable {
static func == (lhs: Tagged<Tag, RawValue>, rhs: Tagged<Tag, RawValue>) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension Tagged: ExpressibleByStringLiteral where RawValue: ExpressibleByStringLiteral {
init(stringLiteral value: RawValue.StringLiteralType) {
self.rawValue = RawValue(stringLiteral: value)
}
}
extension Tagged: ExpressibleByExtendedGraphemeClusterLiteral where RawValue: ExpressibleByExtendedGraphemeClusterLiteral {
init(extendedGraphemeClusterLiteral: RawValue.ExtendedGraphemeClusterLiteralType) {
self.rawValue = RawValue(extendedGraphemeClusterLiteral: extendedGraphemeClusterLiteral)
}
}
extension Tagged: ExpressibleByUnicodeScalarLiteral where RawValue: ExpressibleByUnicodeScalarLiteral {
init(unicodeScalarLiteral: RawValue.UnicodeScalarLiteralType) {
self.rawValue = RawValue(unicodeScalarLiteral: unicodeScalarLiteral)
}
}
enum EmailTag {}
typealias Email = Tagged<EmailTag, String>
struct User {
let name: String
let email: Email
}
User(name: "test", email: "test")
/*:
2. Conditionally conform Tagged to Comparable and sort users by their id in descending order.
*/
extension Tagged: Comparable where RawValue: Comparable {
static func < (lhs: Self, rhs: Self) -> Bool {
lhs.rawValue < rhs.rawValue
}
static func <= (lhs: Self, rhs: Self) -> Bool {
lhs.rawValue <= rhs.rawValue
}
static func >= (lhs: Self, rhs: Self) -> Bool {
lhs.rawValue >= rhs.rawValue
}
static func > (lhs: Self, rhs: Self) -> Bool {
lhs.rawValue > rhs.rawValue
}
}
/*:
3. Let’s explore what happens when you have multiple fields in a struct that you want to strengthen at the type level. Add an age property to User that is tagged to wrap an Int value. Ensure that it doesn’t collide with User.Id. (Consider how we tagged Email.)
*/
extension Tagged: ExpressibleByIntegerLiteral where RawValue: ExpressibleByIntegerLiteral {
init(integerLiteral value: RawValue.IntegerLiteralType) {
self.init(rawValue: RawValue(integerLiteral: value))
}
}
struct UserWithAge {
enum AgeTag {}
typealias Id = Tagged<User, Int>
typealias Age = Tagged<(User, age: ()), Int>
let id: Id
let age: Age
}
let userAge = UserWithAge(id: 1, age: 3)
/*:
4. Conditionally conform Tagged to Numeric and alias a tagged type to Int representing Cents. Explore the ergonomics of using mathematical operators and literals to manipulate these values.
*/
extension Tagged: AdditiveArithmetic where RawValue: AdditiveArithmetic {
static var zero: Self { Tagged(rawValue: RawValue.zero) }
static func + (lhs: Self, rhs: Self) -> Self {
Tagged(rawValue: lhs.rawValue + rhs.rawValue)
}
static func += (lhs: inout Self, rhs: Self) {
lhs = lhs + rhs
}
static func - (lhs: Self, rhs: Self) -> Self {
Tagged(rawValue: lhs.rawValue - rhs.rawValue)
}
static func -= (lhs: inout Self, rhs: Self) {
lhs = lhs - rhs
}
}
extension Tagged: Numeric where RawValue: Numeric {
var magnitude: RawValue.Magnitude { rawValue.magnitude }
init?<T>(exactly source: T) where T : BinaryInteger {
guard let rawValue = RawValue(exactly: source) else { return nil }
self.rawValue = rawValue
}
static func * (lhs: Self, rhs: Self) -> Self {
Tagged(rawValue: lhs.rawValue * rhs.rawValue)
}
static func *= (lhs: inout Self, rhs: Self) {
lhs = lhs * rhs
}
}
enum CentsTag {}
typealias Cents = Tagged<CentsTag, Int>
let one: Cents = 1
let result = one + 3
result.rawValue
/*:
5. Create a tagged type, Light<A> = Tagged<A, Color>, where A can represent whether the light is on or off. Write turnOn and turnOff functions to toggle this state.
*/
struct Color {}
typealias Light<A> = Tagged<A, Color>
enum On {}
enum Off {}
func turnOn(light: Light<Off>) -> Light<On> {
Light(rawValue: light.rawValue)
}
func turnOff(light: Light<On>) -> Light<Off> {
Light(rawValue: light.rawValue)
}
var light = Light<On>(rawValue: Color())
turnOff(light: light)
/*:
6. Write a function, changeColor, that changes a Light’s color when the light is on. This function should produce a compiler error when passed a Light that is off.
*/
func changeColor(light: Light<On>, newColor: Color) -> Light<On> {
Light(rawValue: newColor)
}
/*:
7. Create two tagged types with Double raw values to represent Celsius and Fahrenheit temperatures. Write functions celsiusToFahrenheit and fahrenheitToCelsius that convert between these units.
*/
enum CelsiusTag {}
enum FahrenheitTag {}
typealias Celsius = Tagged<CelsiusTag, Double>
typealias Fahrenheit = Tagged<FahrenheitTag, Double>
func celsiusToFahrenheit(_ value: Celsius) -> Fahrenheit {
Fahrenheit(rawValue: value.rawValue) // TODO: Implement the logic
}
func fahrenheitToCelsius(_ value: Fahrenheit) -> Celsius {
Celsius(rawValue: value.rawValue) // TODO: Implement the logic
}
/*:
8. Create Unvalidated and Validated tagged types so that you can create a function that takes an Unvalidated<User> and returns an Optional<Validated<User>> given a valid user. A valid user may be one with a non-empty name and an email that contains an @.
*/
enum UnvalidatedTag {}
enum ValidatedTag {}
typealias Unvalidated<A> = Tagged<UnvalidatedTag, A>
typealias Validated<A> = Tagged<ValidatedTag, A>
func validate(user: Unvalidated<User>) -> Validated<User>? {
let user = user.rawValue
guard user.name.isEmpty == false else {
return nil
}
guard user.email.rawValue.contains("@") == true else {
return nil
}
return Validated(rawValue: user)
}
let userValid = Unvalidated(rawValue: User(name: "Test", email: "[email protected]"))
validate(user: userValid)
let userInvalidName = Unvalidated(rawValue: User(name: "", email: "@"))
validate(user: userInvalidName)
let userInvalidEmail = Unvalidated(rawValue: User(name: "Test", email: "test.com"))
validate(user: userInvalidEmail)
| 30.834906 | 261 | 0.70231 |
9bff0a9ef5ed0411dbda4db08abd2633e85e6a16 | 1,904 | //
// Color.swift
// SwiftTools
//
// Created by Jeremy Bouillanne on 16/09/16.
// Copyright © 2017 Jeremy Bouillanne. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init(hex: UInt32) {
let red = CGFloat((hex >> 16) & 0xff) / 255.0
let green = CGFloat((hex >> 8) & 0xff) / 255.0
let blue = CGFloat((hex ) & 0xff) / 255.0
self.init(red: red, green: green, blue: blue, alpha: 1)
}
public func translucent(alpha: CGFloat = 0.5) -> UIColor {
return self.withAlphaComponent(alpha)
}
public func lighter() -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
if getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
return UIColor(hue: h,
saturation: s,
brightness: b * 1.2,
alpha: a)
}
return self
}
public func darker() -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
if getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
return UIColor(hue: h,
saturation: s,
brightness: b * 0.75,
alpha: a)
}
return self
}
public func convertedForNavBar() -> UIColor {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
// any R, G or B value under 40 will be negative once converted...
let convertedColors = [red, green, blue].map { convertedColor($0) }
// ...therefore capped to 0
return UIColor(red: convertedColors[0], green: convertedColors[1], blue: convertedColors[2], alpha: alpha)
}
private func convertedColor(_ channel: CGFloat) -> CGFloat {
return (channel * 255 - 40) / (1 - 40 / 255) / 255
}
}
| 27.2 | 110 | 0.560924 |
9b7206e5aedb550220ee780f6b71c7835522f9db | 4,565 | // Copyright (c) 2020 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses 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 Foundation
import MobiusCore
import Nimble
import Quick
private struct Model {}
private enum Event {
case event1
case event2
}
private enum Effect: Equatable {
case effect1
}
/// This is a port of EventHandlerDisposalLogicalRaceRegressionTest to use EventRouter instead of raw connectables.
///
/// The original was a regression test for a set of threading issues in Mobius 0.2. It would fail in two different ways:
///
/// First, by stopping a controller/disposing a loop immediately after dispatching an event, we would consistently hit
/// "cannot accept values when disposed" in ConnectablePublisher.post.
///
/// Second, after disabling or working around that test, we would hit a fatal error in ConnectableClass: "EffectHandler
/// is unable to send Event before any consumer has been set. Send should only be used once the Connectable has been
/// properly connected."
///
/// We had seen small volumes of this second issue in production. (Spotify internal: IOS-42623)
class EventRouterDisposalLogicalRaceRegressionTest: QuickSpec {
// swiftlint:disable:next function_body_length
override func spec() {
describe("Effect Handler connection") {
var controller: MobiusController<Model, Event, Effect>!
var collaborator: EffectCollaborator!
var eventSource: TestEventSource<Event>!
beforeEach {
collaborator = EffectCollaborator()
let effectHandler = EffectRouter<Effect, Event>()
.routeEffects(equalTo: .effect1)
.to(collaborator.makeEffectHandler(replyEvent: .event2))
.asConnectable
eventSource = TestEventSource()
let update = Update<Model, Event, Effect> { _, _ in
.dispatchEffects([.effect1])
}
controller = Mobius.loop(update: update, effectHandler: effectHandler)
.withEventSource(eventSource)
.makeController(from: Model())
controller.connectView(AnyConnectable { _ in
Connection(acceptClosure: { _ in }, disposeClosure: {})
})
}
it("allows stopping a loop immediately after dispatching an event") {
controller.start()
eventSource.dispatch(.event1)
controller.stop()
}
}
}
}
// Stand-in for an object that does something asynchronous and cancellable, e.g. fetch data.
private class EffectCollaborator {
func asyncDoStuff(completion closure: @escaping () -> Void) -> CancellationToken {
let cancelLock = DispatchQueue(label: "Cancel lock")
var cancelled = false
DispatchQueue.global().asyncAfter(deadline: .now()) {
if !cancelLock.sync(execute: { cancelled }) {
closure()
}
}
return CancellationToken {
cancelLock.sync { cancelled = true }
}
}
}
extension EffectCollaborator {
func makeEffectHandler<Effect, Event>(replyEvent: Event) -> AnyEffectHandler<Effect, Event> {
return AnyEffectHandler<Effect, Event> { _, callback in
let cancellationToken = self.asyncDoStuff {
callback.send(replyEvent)
callback.end()
}
return AnonymousDisposable {
cancellationToken.cancel()
}
}
}
}
final class CancellationToken {
private var callback: (() -> Void)?
init(callback: @escaping () -> Void) {
self.callback = callback
}
func cancel() {
let cb = callback
callback = nil
cb?()
}
}
| 34.067164 | 120 | 0.642935 |
ab729aa84f5f2f60f2e70498f5cae9ed566db694 | 1,471 | import Vapor
import AuthProvider
import Sessions
import HTTP
final class Routes: RouteCollection {
let view: ViewRenderer
let uploadDir: String
let passwordMiddleware: PasswordAuthenticationMiddleware<User>
let persistMiddleware: PersistMiddleware<User>
let sessionsMiddleware: SessionsMiddleware
let redirectMiddleware: RedirectMiddleware
init(_ view: ViewRenderer, uploadDir: String) {
self.view = view
self.uploadDir = uploadDir
self.passwordMiddleware = PasswordAuthenticationMiddleware(User.self)
self.persistMiddleware = PersistMiddleware(User.self)
self.sessionsMiddleware = SessionsMiddleware(MemorySessions())
self.redirectMiddleware = RedirectMiddleware.login()
}
func build(_ builder: RouteBuilder) throws {
let adminBuilder = builder.grouped([
self.redirectMiddleware,
self.sessionsMiddleware,
self.persistMiddleware,
self.passwordMiddleware
])
_ = AdminController(view, routeBuilder: adminBuilder)
_ = UploadController(view, uploadDir: uploadDir, routeBuilder: adminBuilder)
let loginBuilder = builder.grouped([
self.sessionsMiddleware,
self.persistMiddleware
])
_ = LoginController(view, routeBuilder: loginBuilder)
_ = SearchController(view, routeBuilder: loginBuilder)
_ = try PageController(view, adminRouteBuilder: adminBuilder, publicRouteBuilder: loginBuilder)
_ = try ArticleController(view, adminRouteBuilder: adminBuilder, publicRouteBuilder: loginBuilder)
}
}
| 30.645833 | 100 | 0.78722 |
09737d5c2b2f5b51776075daddd63078aa642120 | 1,530 | //
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
struct PlaceholderAvatarImage: View {
let firstCharacter: String
var body: some View {
ZStack {
Color(.sRGB, red: 0.05, green: 0.74, blue: 0.55, opacity: 1.0)
Text(firstCharacter)
.padding(4)
.foregroundColor(.white)
// Make the text resizable (i.e. Make it large and then allow it to scale down)
.font(.system(size: 200))
.minimumScaleFactor(0.001)
}
.aspectRatio(1, contentMode: .fill)
}
}
struct PlaceholderAvatarImage_Previews: PreviewProvider {
static var previews: some View {
body.preferredColorScheme(.light)
body.preferredColorScheme(.dark)
}
@ViewBuilder
static var body: some View {
PlaceholderAvatarImage(firstCharacter: "X")
.clipShape(Circle())
.frame(width: 150, height: 100)
}
}
| 30.6 | 95 | 0.639869 |
d9dacbfadf246ac5750ae3b35ff0b316c62d969a | 3,482 | //
// File.swift
//
//
// Created by theunimpossible on 5/21/20.
//
import Foundation
public struct TodaySection: Codable, Hashable, Identifiable, Equatable {
public let name: Name
public var enabled: Bool
public var id: Name { name }
public init(name: Name, enabled: Bool) {
self.name = name
self.enabled = enabled
}
public static func == (lhs: TodaySection, rhs: TodaySection) -> Bool {
lhs.id == rhs.id
}
}
extension TodaySection {
public enum Name: String, Codable {
case events
case specialCharacters
case currentlyAvailable
case collectionProgress
case birthdays
case turnips
case subscribe
case mysteryIsland
case music
case tasks
case chores
case villagerVisits
case dodoCode
case news
case dreamCode
}
public static let defaultSectionList: [TodaySection] = [
TodaySection(name: .events, enabled: true),
TodaySection(name: .news, enabled: true),
TodaySection(name: .specialCharacters, enabled: true),
TodaySection(name: .currentlyAvailable, enabled: true),
TodaySection(name: .collectionProgress, enabled: true),
TodaySection(name: .birthdays, enabled: true),
TodaySection(name: .dodoCode, enabled: true),
TodaySection(name: .dreamCode, enabled: true),
TodaySection(name: .turnips, enabled: true),
TodaySection(name: .tasks, enabled: true),
TodaySection(name: .chores, enabled: true),
TodaySection(name: .subscribe, enabled: true),
TodaySection(name: .music, enabled: true),
TodaySection(name: .mysteryIsland, enabled: true),
TodaySection(name: .villagerVisits, enabled: true),
]
}
extension TodaySection {
public var sectionName: String {
switch name {
case .events: return "Events"
case .specialCharacters: return "Possible visitors"
case .currentlyAvailable: return "Currently Available"
case .collectionProgress: return "Collection Progress"
case .birthdays: return "Today's Birthdays"
case .turnips: return "Turnips"
case .subscribe: return "AC Helper+"
case .mysteryIsland: return "Mystery Islands"
case .music: return "Music player"
case .tasks: return "Today's Tasks"
case .chores: return "Chores"
case .villagerVisits: return "Villager visits"
case .dodoCode: return "Latest Dodo code"
case .news: return "News"
case .dreamCode: return "Latest Dream Code"
}
}
public var iconName: String {
switch name {
case .events: return "flag.fill"
case .specialCharacters: return "clock"
case .currentlyAvailable: return "calendar"
case .collectionProgress: return "chart.pie.fill"
case .birthdays: return "gift.fill"
case .turnips: return "dollarsign.circle.fill"
case .subscribe: return "suit.heart.fill"
case .mysteryIsland: return "sun.haze.fill"
case .music: return "music.note"
case .tasks: return "checkmark.seal.fill"
case .chores: return "checkmark.seal.fill"
case .villagerVisits: return "person.crop.circle.fill.badge.checkmark"
case .dodoCode: return "airplane"
case .news: return "exclamationmark.bubble.fill"
case .dreamCode: return "zzz"
}
}
}
| 33.161905 | 78 | 0.633544 |
ccdcb957ff88daa89a70e37f28bc8379e866a2c6 | 5,678 | //
// SFQRScaner.swift
// SFQRScaner
//
// Created by Stroman on 2021/7/11.
//
import UIKit
import AVFoundation
protocol SFQRScanerProtocol:NSObjectProtocol {
/// 二维码扫描器初始化失败了。
/// - Parameter scanner: 二维码扫描器
func SFQRScanerInitilizationFailed(_ scanner:SFQRScaner) -> Void
/// 扫描完毕的结果是个字符串
/// - Parameters:
/// - scanner: 二维码扫描器
/// - result: 扫描出来的结果,需要被回调出来。
func SFQRScanerGainResult(_ scanner:SFQRScaner,_ result:String?) -> Void
/// 二维码扫描器在处理过程中失败了
/// - Parameter scanner: 扫描器
func SFQRScanerProcessFailed(_ scanner:SFQRScaner) -> Void
}
class SFQRScaner: NSObject,AVCaptureMetadataOutputObjectsDelegate {
// MARK: - lifecycle
deinit {
print("\(type(of: self))释放了")
}
// MARK: - custom methods
private func customInitilizer() -> Void {
}
// MARK: - public interfaces
/// 开始扫描
/// - Returns: 空
/// - Parameters:
/// - containerView: 容器视图
/// - ior: 有效扫描区域,空缺代表的是全面扫描
internal func run(_ containerView:UIView,_ ior:CGRect?) -> Void {
guard AVCaptureDevice.authorizationStatus(for: .video) == .authorized else {
self.delegate?.SFQRScanerInitilizationFailed(self)
return
}
self.device = AVCaptureDevice.default(for: .video)
guard self.device != nil else {
self.delegate?.SFQRScanerInitilizationFailed(self)
return
}
do {
try self.inputDevice = AVCaptureDeviceInput.init(device: self.device!)
} catch {
print(type(of: self),#function,error.localizedDescription)
self.delegate?.SFQRScanerInitilizationFailed(self)
return
}
self.session.canSetSessionPreset(.high)
for iterator in self.session.inputs {
self.session.removeInput(iterator)
}
guard self.session.canAddInput(self.inputDevice!) else {
print(type(of: self),#function,"无法添加输入设备")
self.delegate?.SFQRScanerInitilizationFailed(self)
return
}
self.session.addInput(self.inputDevice!)
for iterator in self.session.outputs {
self.session.removeOutput(iterator)
}
guard self.session.canAddOutput(self.outputMeta) else {
print(type(of: self),#function,"无法添加输入媒介")
self.delegate?.SFQRScanerInitilizationFailed(self)
return
}
self.session.addOutput(self.outputMeta)
guard self.outputMeta.availableMetadataObjectTypes.contains(.qr) else {
self.delegate?.SFQRScanerInitilizationFailed(self)
return
}
if ior != nil {
self.outputMeta.rectOfInterest = ior!
}
self.outputMeta.metadataObjectTypes = [.qr]
self.outputMeta.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
self.previewLayer?.removeFromSuperlayer()
self.previewLayer = AVCaptureVideoPreviewLayer.init(session: self.session)
guard self.previewLayer != nil else {
print(type(of: self),#function,"预览图层创建失败")
self.delegate?.SFQRScanerInitilizationFailed(self)
return
}
self.previewLayer?.videoGravity = .resizeAspectFill
self.previewLayer?.frame = containerView.bounds
containerView.layer.insertSublayer(self.previewLayer!, at: 0)
self.session.startRunning()
self.isRunning = true
}
/// 交给外界控制是否停止识别
/// - Returns: 空
internal func stop() -> Void {
self.session.stopRunning()
self.isRunning = false
}
/// 从图片中读取二维码
/// - Parameter image: 输入的图片
/// - Returns: 读取的信息
internal func readFromImage(_ image:UIImage) {
let targetImage:CGImage? = image.cgImage
guard targetImage != nil else {
self.delegate?.SFQRScanerProcessFailed(self)
return
}
let detector:CIDetector? = CIDetector.init(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])
guard detector != nil else {
self.delegate?.SFQRScanerProcessFailed(self)
return
}
let features:[CIFeature] = detector!.features(in: CIImage.init(cgImage: targetImage!))
if features.count > 0 {
let resultFeature:CIQRCodeFeature = features.first! as! CIQRCodeFeature
self.delegate?.SFQRScanerGainResult(self, resultFeature.messageString)
} else {
self.delegate?.SFQRScanerGainResult(self, nil)
}
}
// MARK: - actions
// MARK: - accessors
weak internal var delegate:SFQRScanerProtocol?
internal var isRunning:Bool = false/*正常情况下它并没有在运行*/
private var device:AVCaptureDevice?
private var inputDevice:AVCaptureDeviceInput?
private var outputMeta:AVCaptureMetadataOutput = {
let result:AVCaptureMetadataOutput = AVCaptureMetadataOutput.init()
return result
}()
private var session:AVCaptureSession = {
let result:AVCaptureSession = AVCaptureSession.init()
return result
}()
private var previewLayer:AVCaptureVideoPreviewLayer?
// MARK: - delegates
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if metadataObjects.count > 0 {
let first:AVMetadataMachineReadableCodeObject = metadataObjects.first! as! AVMetadataMachineReadableCodeObject
self.delegate?.SFQRScanerGainResult(self, first.stringValue)
} else {
self.delegate?.SFQRScanerGainResult(self, nil)
}
}
}
| 37.111111 | 148 | 0.644417 |
ef1de5d7eb5549a6c51335a4f698d3e4f9098f76 | 1,055 | import Foundation
public struct GreedySchedule {
public typealias Job = (w: Int, l: Int)
public static func sortedByDiff(jobs: [Job]) -> [Job] {
return jobs.sorted(by: { return isGreaterByDiff(lhs: $0, rhs: $1) })
}
public static func sortedByRatio(jobs: [Job]) -> [Job] {
return jobs.sorted(by: { return isGreaterByRatio(lhs: $0, rhs: $1) })
}
public static func isGreaterByDiff(lhs: Job, rhs: Job) -> Bool {
return (lhs.w - lhs.l) > (rhs.w - rhs.l) || ( (lhs.w - lhs.l) == (rhs.w - rhs.l) && (lhs.w > rhs.w))
}
public static func isGreaterByRatio(lhs: Job, rhs: Job) -> Bool {
return Double(lhs.w)/Double(lhs.l) > Double(rhs.w)/Double(rhs.l)
}
}
public extension Array where Element == GreedySchedule.Job {
public func weightedCompletionTime() -> Int64 {
var tm = 0
var result: Int64 = 0
for job in self {
tm += job.l
result += Int64(job.w) * Int64(tm)
}
return result
}
}
| 29.305556 | 108 | 0.55545 |
56c05cb5295a0ca258937de9eeb25b60bff5a304 | 5,652 | //
// RemoteUpdateManage.swift
// IosRemoteUpgrade
//
// Created by xialiang on 2019/5/23.
// Copyright © 2019 xialiang. All rights reserved.
//
import HandyJSON
import UIKit
open class RemoteUpdateManage: NSObject {
var timer = Timer()
var taskcarId: String = ""
var isNewTask: Int = 0
var status: Int = -1
var isTimer = 0
/// 获取历史升级任务列表
///
/// - Parameters:
/// - vin: 车辆vin
/// - pi: 页面索引
/// - ps: 页面大小
/// - uDate: 日期时间
public func getUpdateTaskList(vin: String, pi: Int, ps: Int, uDate: String, success: @escaping (UpdateVehicleTaskModel) -> Void, failed: @escaping (String) -> Void) {
NetWorkRequest(.getUpdateTaskList(vin: vin, pi: pi, ps: ps, uDate: uDate), completion: { (jsonString) -> Void in
if let mappedObject = JSONDeserializer<BaseResponse<UpdateVehicleTaskModel>>.deserializeFrom(json: jsonString) {
switch mappedObject.statusCode {
case SUCCESS:
// 从字符串转换为对象实例
success(mappedObject.body)
break
case ERRO_NOT_FOUNT:
failed(ERRO_NOT_FOUNT_MESSAGE)
break
case ERRO_SERVER:
failed(ERRO_SERVER_MESSAGE)
break
case ERRO_UPTATE:
failed(ERRO_UPTATE_MESSAGE)
break
default:
failed(ERRO_NOT_MESSAGE)
break
}
}
}, failed: { (failedCallback) -> Void in
failed(failedCallback)
})
}
/// 查询当前车辆升级任务
///
/// - Parameters:
/// - vin: 车辆vin
/// - uDate: 日期时间
/// - taskcarId: 车辆升级任务id
public func queryCarUpdateTask(vin: String, uDate: String, success: @escaping (CurrentVehicleTaskModel) -> Void, failed: @escaping (String) -> Void) {
if #available(iOS 10.0, *) {
if isTimer == 0 {
timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (_) -> Void in
if self.isNewTask == 0 {
self.taskcarId = ""
} else {
if self.status == 11 {
self.taskcarId = ""
}
}
NetWorkRequest(.queryCarUpdateTask(vin: vin, uDate: uDate, taskcarId: self.taskcarId), completion: { (jsonString) -> Void in
if let mappedObject = JSONDeserializer<BaseResponse<CurrentVehicleTaskModel>>.deserializeFrom(json: jsonString) {
switch mappedObject.statusCode {
case SUCCESS:
if mappedObject.body.result.taskCarId != nil {
self.taskcarId = mappedObject.body.result.taskCarId
self.isNewTask = mappedObject.body.result.isNewTask
self.status = mappedObject.body.result.status
}
// 从字符串转换为对象实例
success(mappedObject.body)
break
case ERRO_NOT_FOUNT:
failed(ERRO_NOT_FOUNT_MESSAGE)
break
case ERRO_SERVER:
failed(ERRO_SERVER_MESSAGE)
break
case ERRO_UPTATE:
failed(ERRO_UPTATE_MESSAGE)
break
default:
failed(ERRO_NOT_MESSAGE)
break
}
}
}, failed: { (failedCallback) -> Void in
failed(failedCallback)
})
})
isTimer = 1
}
} else {
print("版本过低")
}
}
/// 确认升级任务
///
/// - Parameters:
/// - taskcarId: 车辆升级任务id
/// - uDate: 日期时间
/// - type: 确认类型
/// - result: 确认结果
public func confirmUpdate(taskcarId: String, uDate: String, type: Int, result: Int, success: @escaping (UpdateConfirInterfaceModel) -> Void, failed: @escaping (String) -> Void) {
NetWorkRequest(.confirmUpgrade(taskcarId: taskcarId, uDate: uDate, type: type, result: result), completion: { (jsonString) -> Void in
if let mappedObject = JSONDeserializer<BaseResponse<UpdateConfirInterfaceModel>>.deserializeFrom(json: jsonString) {
switch mappedObject.statusCode {
case SUCCESS:
// 从字符串转换为对象实例
success(mappedObject.body)
break
case ERRO_NOT_FOUNT:
failed(ERRO_NOT_FOUNT_MESSAGE)
break
case ERRO_SERVER:
failed(ERRO_SERVER_MESSAGE)
break
case ERRO_UPTATE:
failed(ERRO_UPTATE_MESSAGE)
break
default:
failed(ERRO_NOT_MESSAGE)
break
}
}
}, failed: { (failedCallback) -> Void in
failed(failedCallback)
})
}
/// 清除定时任务
public func clearTask() {
if isTimer == 1 {
timer.invalidate()
isTimer = 0
}
}
}
| 35.54717 | 182 | 0.465145 |
2fa5e1868ecc481ea47f18ee102facb3564c68d1 | 8,150 | //
// YokoTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 30/01/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
/**
A YokoTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable 3D visual effect on the background of the control.
*/
@IBDesignable open class YokoTextField: TextFieldEffects {
/**
The color of the placeholder text.
This property applies a color to the complete placeholder string. The default value for this property is a black color.
*/
@IBInspectable dynamic open var placeholderColor: UIColor? {
didSet {
updatePlaceholder()
}
}
/**
The scale of the placeholder font.
This property determines the size of the placeholder label relative to the font size of the text field.
*/
@IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.7 {
didSet {
updatePlaceholder()
}
}
/**
The view’s foreground color.
The default value for this property is a clear color.
*/
@IBInspectable dynamic open var foregroundColor: UIColor = .black {
didSet {
updateForeground()
}
}
override open var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override open var bounds: CGRect {
didSet {
updateForeground()
updatePlaceholder()
}
}
private let foregroundView = UIView()
private let foregroundLayer = CALayer()
private let borderThickness: CGFloat = 3
private let placeholderInsets = CGPoint(x: 6, y: 6)
private let textFieldInsets = CGPoint(x: 6, y: 6)
// MARK: - TextFieldEffects
override open func drawViewsForRect(_ rect: CGRect) {
updateForeground()
updatePlaceholder()
insertSubview(foregroundView, at: 0)
addSubview(placeholderLabel)
layer.insertSublayer(foregroundLayer, at: 0)
}
override open func animateViewsForTextEntry() {
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: .beginFromCurrentState, animations: {
self.foregroundView.layer.transform = CATransform3DIdentity
}, completion: { _ in
self.animationCompletionHandler?(.textEntry)
})
foregroundLayer.frame = rectForBorder(foregroundView.frame, isFilled: false)
}
override open func animateViewsForTextDisplay() {
if text!.isEmpty {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: .beginFromCurrentState, animations: {
self.foregroundLayer.frame = self.rectForBorder(self.foregroundView.frame, isFilled: true)
self.foregroundView.layer.transform = self.rotationAndPerspectiveTransformForView(self.foregroundView)
}, completion: { _ in
self.animationCompletionHandler?(.textDisplay)
})
}
}
// MARK: - Private
private func updateForeground() {
foregroundView.frame = rectForForeground(frame)
foregroundView.isUserInteractionEnabled = false
foregroundView.layer.transform = rotationAndPerspectiveTransformForView(foregroundView)
foregroundView.backgroundColor = foregroundColor
foregroundLayer.borderWidth = borderThickness
foregroundLayer.borderColor = colorWithBrightnessFactor(foregroundColor, factor: 0.8).cgColor
foregroundLayer.frame = rectForBorder(foregroundView.frame, isFilled: true)
}
private func updatePlaceholder() {
placeholderLabel.font = placeholderFontFromFont(font!)
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder || text!.isNotEmpty {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(_ font: UIFont) -> UIFont! {
let smallerFont = CTFontCreateWithFontDescriptor(font.fontDescriptor, font.pointSize * placeholderFontScale, nil)
return smallerFont
}
private func rectForForeground(_ bounds: CGRect) -> CGRect {
let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y - borderThickness)
return newRect
}
private func rectForBorder(_ bounds: CGRect, isFilled: Bool) -> CGRect {
var newRect = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: isFilled ? borderThickness : 0)
if !CATransform3DIsIdentity(foregroundView.layer.transform) {
newRect.origin = CGPoint(x: 0, y: bounds.origin.y)
}
return newRect
}
private func layoutPlaceholderInTextRect() {
let textRect = self.textRect(forBounds: bounds)
var originX = textRect.origin.x
switch textAlignment {
case .center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height,
width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height)
}
// MARK: -
private func setAnchorPoint(_ anchorPoint:CGPoint, forView view:UIView) {
var newPoint:CGPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)
var oldPoint:CGPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = newPoint.applying(view.transform)
oldPoint = oldPoint.applying(view.transform)
var position = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
private func colorWithBrightnessFactor(_ color: UIColor, factor: CGFloat) -> UIColor {
var hue : CGFloat = 0
var saturation : CGFloat = 0
var brightness : CGFloat = 0
var alpha : CGFloat = 0
if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha)
} else {
return color;
}
}
private func rotationAndPerspectiveTransformForView(_ view: UIView) -> CATransform3D {
setAnchorPoint(CGPoint(x: 0.5, y: 1.0), forView:view)
var rotationAndPerspectiveTransform = CATransform3DIdentity
rotationAndPerspectiveTransform.m34 = 1.0/800
let radians = ((-90) / 180.0 * CGFloat.pi)
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, radians, 1.0, 0.0, 0.0)
return rotationAndPerspectiveTransform
}
// MARK: - Overrides
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y)
return newBounds.insetBy(dx: textFieldInsets.x, dy: 0)
}
override open func textRect(forBounds bounds: CGRect) -> CGRect {
let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y)
return newBounds.insetBy(dx: textFieldInsets.x, dy: 0)
}
}
| 36.877828 | 175 | 0.644172 |
6996a5759f305778bbc7201734bc7b575b743406 | 6,151 | import XCTest
import SwiftUI
@testable import ViewInspector
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
class EnvironmentObjectInjectionTests: XCTestCase {
func testEnvironmentObjectMemoryLayout() throws {
typealias RealType = EnvironmentObject<TestEnvObject1>
XCTAssertEqual(MemoryLayout<RealType>.size, EnvObject.structSize)
var sut = RealType.init()
withUnsafeMutableBytes(of: &sut, { bytes in
let rawPointer = bytes.baseAddress! + EnvObject.seedOffset
rawPointer.assumingMemoryBound(to: Int.self).pointee = 42
})
let seed2 = try Inspector.attribute(label: "_seed", value: sut, type: Int.self)
XCTAssertEqual(seed2, 42)
}
func testEnvironmentObjectForgery() throws {
let obj = TestEnvObject1()
let forgery = EnvObject.Forgery(object: obj)
let sut = unsafeBitCast(forgery, to: EnvironmentObject<TestEnvObject1>.self)
let seed = try Inspector.attribute(label: "_seed", value: sut, type: Int.self)
XCTAssertEqual(seed, 0)
let store = try Inspector.attribute(label: "_store", value: sut, type: TestEnvObject1?.self)
XCTAssertEqual(store?.value1, obj.value1)
}
func testDirectEnvironmentObjectInjection() throws {
let obj1 = TestEnvObject1()
let obj2 = TestEnvObject2()
var sut = EnvironmentObjectInnerView()
sut.inject(environmentObject: obj1)
sut.inject(environmentObject: obj2)
XCTAssertEqual(try sut.inspect().find(ViewType.Text.self).string(), "env_true")
}
func testEnvironmentObjectInjectionDuringSyncInspection() throws {
let obj1 = TestEnvObject1()
let obj2 = TestEnvObject2()
let sut = EnvironmentObjectOuterView()
.environmentObject(obj1)
.environmentObject(obj2)
XCTAssertNoThrow(try sut.inspect().find(text: "env_true"))
try sut.inspect().find(button: "Flag").tap()
XCTAssertNoThrow(try sut.inspect().find(text: "env_false"))
XCTAssertEqual(try sut.inspect().findAll(ViewType.Text.self).first?.string(), "env_false")
}
func testEnvironmentObjectInjectionOnDidAppearInspection() throws {
let obj1 = TestEnvObject1()
let obj2 = TestEnvObject2()
var sut = EnvironmentObjectOuterView()
let exp = sut.on(\.didAppear) { view in
XCTAssertNoThrow(try view.find(text: "env_true"))
try view.find(button: "Flag").tap()
XCTAssertNoThrow(try view.find(text: "env_false"))
}
ViewHosting.host(view: sut.environmentObject(obj1).environmentObject(obj2))
wait(for: [exp], timeout: 0.5)
}
func testEnvironmentObjectInjectionDuringAsyncInspection() throws {
let obj1 = TestEnvObject1()
let obj2 = TestEnvObject2()
let sut = EnvironmentObjectOuterView()
let exp1 = sut.inspection.inspect { view in
XCTAssertNoThrow(try view.find(text: "env_true"))
try view.find(button: "Flag").tap()
XCTAssertNoThrow(try view.find(text: "env_false"))
}
let exp2 = sut.inspection.inspect(after: 0.1) { view in
XCTAssertNoThrow(try view.find(text: "env_false"))
try view.find(button: "Flag").tap()
XCTAssertNoThrow(try view.find(text: "env_true"))
}
ViewHosting.host(view: sut.environmentObject(obj1).environmentObject(obj2))
wait(for: [exp1, exp2], timeout: 0.5)
}
func testMissingEnvironmentObjectErrorForView() throws {
var sut = EnvironmentObjectInnerView()
XCTAssertThrows(try sut.inspect().find(ViewType.Text.self),
"""
Search did not find a match. Possible blockers: EnvironmentObjectInnerView is \
missing EnvironmentObjects: [\"obj2: TestEnvObject2\", \"obj1: TestEnvObject1\"]
""")
sut.inject(environmentObject: TestEnvObject1())
XCTAssertThrows(try sut.inspect().find(ViewType.Text.self),
"""
Search did not find a match. Possible blockers: EnvironmentObjectInnerView is \
missing EnvironmentObjects: [\"obj2: TestEnvObject2\"]
""")
}
}
// MARK: -
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private class TestEnvObject1: ObservableObject {
@Published var value1 = "env"
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private class TestEnvObject2: ObservableObject {
@Published var value2 = true
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private struct EnvironmentObjectInnerView: View, Inspectable {
private var iVar1: Int8 = 0
private var iVar2: Int16 = 0
@EnvironmentObject var obj2: TestEnvObject2
private var iVar3: Int32 = 0
@EnvironmentObject var obj1: TestEnvObject1
@State var flag: Bool = false
private var iVar4: Bool = false
var body: some View {
VStack {
Text(obj1.value1 + "_\(obj2.value2)")
Button("Flag", action: { self.obj2.value2.toggle() })
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private struct EnvironmentObjectOuterView: View, Inspectable {
private var iVar1: Bool = false
@EnvironmentObject var obj1: TestEnvObject1
private var iVar2: Int8 = 0
@EnvironmentObject var obj2: TestEnvObject2
var didAppear: ((Self) -> Void)?
let inspection = Inspection<Self>()
var body: some View {
EnvironmentObjectInnerView()
.modifier(EnvironmentObjectViewModifier())
.onAppear { self.didAppear?(self) }
.onReceive(inspection.notice) { self.inspection.visit(self, $0) }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private struct EnvironmentObjectViewModifier: ViewModifier, Inspectable {
private var iVar1: Bool = false
@EnvironmentObject var obj2: TestEnvObject2
@EnvironmentObject var obj1: TestEnvObject1
private var iVar2: Int8 = 0
func body(content: Self.Content) -> some View {
VStack {
Text(obj1.value1 + "+\(obj2.value2)")
content
}
}
}
| 37.969136 | 100 | 0.6477 |
ab41737896a83092c4602fd42bb75f10b1dde53e | 273 | //
// Reachable.swift
// VidLoader
//
// Created by Petre on 01.09.19.
// Copyright © 2019 Petre. All rights reserved.
//
protocol Reachable {
var connection: Reachability.Connection { get }
func startNotifier() throws
}
extension Reachability: Reachable { }
| 18.2 | 51 | 0.688645 |
1e7cc93aa1ddceaea8a1ea010dd39da66ff44db3 | 814 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift %S/Inputs/SilentPlaygroundsRuntime.swift
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
// XFAIL: *
#sourceLocation(file: "main.swift", line: 31)
func function3(_ x: Int) throws {
}
_ = try! function3(0)
// this test is XFAIL-ed due to the range not including throws
// CHECK: [34:1-34:22] pc before
// CHECK-NEXT: [31:1-31:32] pc before
// CHECK-NEXT: [31:1-31:32] pc after
// CHECK-NEXT: [34:1-34:22] pc after
| 38.761905 | 197 | 0.685504 |
7102675c70960545a21fbbefc3ccd624bb9f542d | 4,035 | /*
Copyright (c) 2015, Apple Inc. 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
import ResearchKit
class ResearchContainerViewController: UIViewController, HealthClientType {
// MARK: HealthClientType
var healthStore: HKHealthStore?
// MARK: Propertues
var contentHidden = false {
didSet {
guard contentHidden != oldValue && isViewLoaded else { return }
childViewControllers.first?.view.isHidden = contentHidden
}
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
if ORKPasscodeViewController.isPasscodeStoredInKeychain() {
toStudy()
} else {
toOnboarding()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let healthStore = healthStore {
segue.destination.injectHealthStore(healthStore)
}
}
// MARK: Unwind segues
@IBAction func unwindToStudy(_ segue: UIStoryboardSegue) {
toStudy()
}
@IBAction func unwindToWithdrawl(_ segue: UIStoryboardSegue) {
toWithdrawl()
}
// MARK: Transitions
func toOnboarding() {
performSegue(withIdentifier: "toOnboarding", sender: self)
}
func toStudy() {
performSegue(withIdentifier: "toStudy", sender: self)
}
func toWithdrawl() {
let viewController = WithdrawViewController()
viewController.delegate = self
present(viewController, animated: true, completion: nil)
}
}
extension ResearchContainerViewController: ORKTaskViewControllerDelegate {
public func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
// Check if the user has finished the `WithdrawViewController`.
if taskViewController is WithdrawViewController {
/*
If the user has completed the withdrawl steps, remove them from
the study and transition to the onboarding view.
*/
if reason == .completed {
ORKPasscodeViewController.removePasscodeFromKeychain()
toOnboarding()
}
// Dismiss the `WithdrawViewController`.
dismiss(animated: true, completion: nil)
}
}
}
| 34.784483 | 153 | 0.693432 |
b9b04b04eb6ebd481e3f52cd90bbcee9cd09289b | 5,896 | /*
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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
protocol OktaOidcHttpApiProtocol {
typealias OktaApiSuccessCallback = ([String: Any]?) -> Void
typealias OktaApiErrorCallback = (OktaOidcError) -> Void
var requestCustomizationDelegate: OktaNetworkRequestCustomizationDelegate? { get set }
func post(_ url: URL,
headers: [String: String]?,
postString: String?,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback)
func post(_ url: URL,
headers: [String: String]?,
postJson: [String: Any]?,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback)
func post(_ url: URL,
headers: [String: String]?,
postData: Data?,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback)
func get(_ url: URL,
headers: [String: String]?,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback)
func fireRequest(_ request: URLRequest,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback)
}
extension OktaOidcHttpApiProtocol {
func post(_ url: URL,
headers: [String: String]?,
postString: String?,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback) {
// Generic POST API wrapper for data passed in as a String
let data = postString != nil ? postString!.data(using: .utf8) : nil
return self.post(url, headers: headers, postData: data, onSuccess: onSuccess, onError: onError)
}
func post(_ url: URL,
headers: [String: String]?,
postJson: [String: Any]?,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback) {
// Generic POST API wrapper for data passed in as a JSON object [String: Any]
let data = postJson != nil ? try? JSONSerialization.data(withJSONObject: postJson as Any, options: []) : nil
return self.post(url, headers: headers, postData: data, onSuccess: onSuccess, onError: onError)
}
func post(_ url: URL,
headers: [String: String]?,
postData: Data?,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback) {
// Generic POST API wrapper
let request = self.setupRequest(url, method: "POST", headers: headers, body: postData)
return self.fireRequest(request, onSuccess: onSuccess, onError: onError)
}
func get(_ url: URL,
headers: [String: String]?,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback) {
// Generic GET API wrapper
let request = self.setupRequest(url, method: "GET", headers: headers)
return self.fireRequest(request, onSuccess: onSuccess, onError: onError)
}
func setupRequest(_ url: URL,
method: String,
headers: [String: String]?,
body: Data? = nil) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method
request.allHTTPHeaderFields = headers != nil ? headers : request.allHTTPHeaderFields
request.addValue(OktaUserAgent.userAgentHeaderValue(), forHTTPHeaderField: OktaUserAgent.userAgentHeaderKey())
if let data = body {
request.httpBody = data
}
return request
}
}
class OktaOidcRestApi: OktaOidcHttpApiProtocol {
weak var requestCustomizationDelegate: OktaNetworkRequestCustomizationDelegate?
func fireRequest(_ request: URLRequest,
onSuccess: @escaping OktaApiSuccessCallback,
onError: @escaping OktaApiErrorCallback) {
let customizedRequest = requestCustomizationDelegate?.customizableURLRequest(request) ?? request
let task = OIDURLSessionProvider.session().dataTask(with: customizedRequest){ data, response, error in
self.requestCustomizationDelegate?.didReceive(response)
guard let data = data,
error == nil,
let httpResponse = response as? HTTPURLResponse else {
let errorMessage = error != nil ? error!.localizedDescription : "No response data"
DispatchQueue.main.async {
onError(OktaOidcError.APIError(errorMessage))
}
return
}
guard 200 ..< 300 ~= httpResponse.statusCode else {
DispatchQueue.main.async {
onError(OktaOidcError.APIError(HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode)))
}
return
}
let responseJson = (try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)) as? [String: Any]
DispatchQueue.main.async {
onSuccess(responseJson)
}
}
task.resume()
}
}
| 42.114286 | 125 | 0.628392 |
ff7f0305fa7dde5f61ce9fd0b85ea9f5cc08d82e | 1,036 | //
// AppDelegate.swift
// Regxr
//
// Created by Luka Kerr on 23/9/17.
// Copyright © 2017 Luka Kerr. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
let defaults = UserDefaults.standard
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Main window
let window = NSApplication.shared.windows.first!
let theme = defaults.string(forKey: "theme") ?? DEFAULT_THEME
if (theme == "Light") {
window.appearance = NSAppearance(named: NSAppearance.Name.vibrantLight)
} else {
window.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
}
// Title bar properties
window.titleVisibility = NSWindow.TitleVisibility.hidden;
window.titlebarAppearsTransparent = true;
window.styleMask.insert(.fullSizeContentView)
window.isOpaque = false
window.invalidateShadow()
}
func applicationWillTerminate(_ aNotification: Notification) {
}
}
| 25.268293 | 77 | 0.708494 |
6ac31b3991f457daede19ae462c3a66a54730d51 | 4,268 | //
// ServerView.swift
// Postgres
//
// Created by Chris on 24/06/16.
// Copyright © 2016 postgresapp. All rights reserved.
//
import Cocoa
class ServerViewController: NSViewController, MainWindowModelConsumer {
@IBOutlet var databaseCollectionView: NSCollectionView!
@objc dynamic var mainWindowModel: MainWindowModel!
override func viewDidLoad() {
super.viewDidLoad()
databaseCollectionView.itemPrototype = self.storyboard?.instantiateController(withIdentifier: "DatabaseCollectionViewItem") as? NSCollectionViewItem
}
@IBAction func startServer(_ sender: AnyObject?) {
guard let server = mainWindowModel.firstSelectedServer else { return }
server.start { (actionStatus) in
if case let .Failure(error) = actionStatus {
self.presentError(error, modalFor: self.view.window!, delegate: nil, didPresent: nil, contextInfo: nil)
}
}
}
@IBAction func stopServer(_ sender: AnyObject?) {
guard let server = mainWindowModel.firstSelectedServer else { return }
server.stop { (actionStatus) in
if case let .Failure(error) = actionStatus {
self.presentError(error, modalFor: self.view.window!, delegate: nil, didPresent: nil, contextInfo: nil)
}
}
}
@IBAction func openPsql(_ sender: AnyObject?) {
guard let server = mainWindowModel.firstSelectedServer else { return }
guard let database = server.firstSelectedDatabase else { return }
let clientApp = UserDefaults.standard.object(forKey: "ClientAppName") as? String ?? "Terminal"
if clientApp == "Postico" {
var urlComponents = URLComponents()
urlComponents.scheme = "postico"
urlComponents.host = "localhost"
urlComponents.port = Int(server.port)
urlComponents.path = "/" + database.name
let url = urlComponents.url!
let success = NSWorkspace.shared.open(url)
if !success {
let alert = NSAlert()
alert.messageText = "Could not open Postico"
alert.informativeText = "Please make sure that you have the latest version of Postico installed, or choose a different client in the preferences"
if let window = sender?.window {
alert.beginSheetModal(for: window, completionHandler: nil)
} else {
alert.runModal()
}
}
return
}
else if clientApp == "Terminal" || clientApp == "iTerm" {
let psql_command = "\(server.binPath)/psql -p\(server.port) \"\(database.name)\""
let routine = "open_"+clientApp
do {
let launcher = ClientLauncher()
try launcher.runSubroutine(routine, parameters: [psql_command])
} catch {
let alert = NSAlert()
alert.messageText = "Could not open \(clientApp)"
alert.informativeText =
"""
Make sure that Postgres.app has permission to automate \(clientApp).
Alternatively, you can also just execute the following command manually to connect to the database:
\(psql_command)
"""
if let window = sender?.window {
alert.beginSheetModal(for: window, completionHandler: nil)
} else {
alert.runModal()
}
}
}
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if let target = segue.destinationController as? SettingsViewController {
guard let server = mainWindowModel.firstSelectedServer else { return }
target.server = server
}
}
}
class ServerViewBackgroundView: NSView {
override var isOpaque: Bool { return true }
override var mouseDownCanMoveWindow: Bool { return true }
override func draw(_ dirtyRect: NSRect) {
NSColor.controlBackgroundColor.setFill()
dirtyRect.fill()
let imgSize = CGFloat(96)
let x = CGFloat(self.bounds.maxX-imgSize-20), y = CGFloat(20)
let imageRect = NSRect(x: x, y: self.bounds.maxY-y-imgSize, width: imgSize, height: imgSize)
if imageRect.intersects(dirtyRect) {
NSImage(named: "BlueElephant")?.draw(in: imageRect)
}
}
}
| 34.144 | 161 | 0.632615 |
09073f20893bb25c586f85fc0880e9328117e815 | 2,615 | //
// File.swift
// Crypto
//
// Created by T D on 2022/2/17.
//
import Foundation
extension Double{
private var currencyFormatter2: NumberFormatter{
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
return formatter
}
func asCurrencyWith2Decimals() -> String{
let number = NSNumber(value: self)
return currencyFormatter2.string(from: number) ?? "$0.00"
}
private var currencyFormatter6: NumberFormatter{
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 6
formatter.minimumFractionDigits = 2
return formatter
}
//Convert Double as a String with 2-6 decimal places
//```
//1.234 to "$1.234"
//```
func asCurrencyWith6Decimals() -> String{
let number = NSNumber(value: self)
return currencyFormatter6.string(from: number) ?? "$0.00"
}
func asNumberString() -> String{
return String(format: "%.2f", self)
}
func asPercentString() -> String{
return asNumberString() + "%"
}
/// Convert a Double to a String with K, M, Bn, Tr abbreviations.
/// ```
/// Convert 12 to 12.00
/// Convert 1234 to 1.23K
/// Convert 123456 to 123.45K
/// Convert 12345678 to 12.34M
/// Convert 1234567890 to 1.23Bn
/// Convert 123456789012 to 123.45Bn
/// Convert 12345678901234 to 12.34Tr
/// ```
func formattedWithAbbreviations() -> String {
let num = abs(Double(self))
let sign = (self < 0) ? "-" : ""
switch num {
case 1_000_000_000_000...:
let formatted = num / 1_000_000_000_000
let stringFormatted = formatted.asNumberString()
return "\(sign)\(stringFormatted)Tr"
case 1_000_000_000...:
let formatted = num / 1_000_000_000
let stringFormatted = formatted.asNumberString()
return "\(sign)\(stringFormatted)Bn"
case 1_000_000...:
let formatted = num / 1_000_000
let stringFormatted = formatted.asNumberString()
return "\(sign)\(stringFormatted)M"
case 1_000...:
let formatted = num / 1_000
let stringFormatted = formatted.asNumberString()
return "\(sign)\(stringFormatted)K"
case 0...:
return self.asNumberString()
default:
return "\(sign)\(self)"
}
}
}
| 28.736264 | 69 | 0.583556 |
9198ad38ff356ef6335770c3726dc24358dbf147 | 1,385 | //
// JGUILabelExtension.swift
// ShoesMall_Swift
//
// Created by spring on 2020/4/15.
// Copyright © 2020 spring. All rights reserved.
//
import UIKit
extension UILabel {
// Label行间距的高度
class func GetLabHeight(lineSpacing:CGFloat, font:UIFont, widthLabel:CGFloat, title:String) -> CGFloat {
if title.count == 0 {
return 0
}
var attrButes:[NSAttributedString.Key : Any]! = nil;
let paraph = NSMutableParagraphStyle()
paraph.lineSpacing = lineSpacing
attrButes = [NSAttributedString.Key.font:font,NSAttributedString.Key.paragraphStyle:paraph]
let size:CGRect = title.boundingRect(with: CGSize(width: widthLabel, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrButes, context: nil)
return size.height
}
/// 动态计算Label宽度
class func GetLabWidth(labelStr:String,font:UIFont,height:CGFloat) -> CGFloat {
if labelStr.count == 0 {
return 0
}
let size = CGSize(width: CGFloat(MAXFLOAT), height: height)
let strSize = labelStr.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil).size
return strSize.width
}
}
| 28.265306 | 211 | 0.639711 |
1ce656b915c1968344ab60429c283dcb9fd4ff60 | 495 | import UIKit
import Flutter
import GoogleMaps
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("AIzaSyBeXMlR9K0vGo8glrh7XkQfIQikusOczcA")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
| 30.9375 | 87 | 0.808081 |
2169dadf257c161b1570b47360f9626cccaf353f | 516 | //
// ViewController.swift
// MediumClapButton
//
// Created by Erencan Evren on 9.08.2018.
// Copyright © 2018 Cemal BAYRI. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.846154 | 80 | 0.674419 |
913fbbbf37ded9d100f9214114b2e890cf842564 | 4,057 | //
// ViewController.swift
// DocumentScannerApp
//
// Created by Steff Blümm on 30.04.18.
// Copyright © 2018 Steff Blümm. All rights reserved.
//
import UIKit
import YesWeScan
import TOCropViewController
class ViewController: UIViewController {
// MARK: private fields
private var scannedImage: UIImage? {
willSet {
set(isVisible: newValue != nil)
} didSet {
imageView.image = scannedImage
}
}
//private var previewingController: UIViewControllerPreviewing
private lazy var tapRecogniser = UITapGestureRecognizer(target: self, action: #selector(editImage))
// MARK: IBOutlets
@IBOutlet private var imageView: UIImageView!
@IBOutlet private var editButton: UIButton!
// MARK: Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: Methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
set(isVisible: false)
self.tapRecogniser.delegate = self
self.view.addGestureRecognizer(tapRecogniser)
addToSiriShortcuts()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
self.imageView.image = nil
self.scannedImage = nil
}
private func set(isVisible: Bool) {
imageView.isHidden = !isVisible
editButton.isHidden = !isVisible
}
}
extension ViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard scannedImage != nil else {
return false
}
return imageView.bounds.contains(self.view.convert(tapRecogniser.location(in: self.view), to: imageView))
}
}
extension ViewController: ScannerViewControllerDelegate {
func scanner(_ scanner: ScannerViewController,
didCaptureImage image: UIImage) {
self.scannedImage = image
navigationController?.popViewController(animated: true)
}
}
extension ViewController: TOCropViewControllerDelegate {
func cropViewController(_ cropViewController: TOCropViewController,
didCropToImage image: UIImage,
rect cropRect: CGRect,
angle: Int) {
self.scannedImage = image
cropViewController.dismiss(animated: true, completion: nil)
}
}
extension ViewController {
@IBAction func scanDocument(_ sender: UIButton) {
openDocumentScanner()
}
@IBAction func editImage(_ sender: UIButton) {
guard let image = self.scannedImage
else { return }
let cropViewController = TOCropViewController(image: image)
cropViewController.delegate = self
present(cropViewController, animated: true)
}
}
extension ViewController {
func addToSiriShortcuts() {
if #available(iOS 12.0, *) {
let identifier = Bundle.main.userActivityIdentifier
let activity = NSUserActivity(activityType: identifier)
activity.title = "Scan Document"
activity.userInfo = ["Document Scanner": "open document scanner"]
activity.isEligibleForSearch = true
activity.isEligibleForPrediction = true
activity.persistentIdentifier = NSUserActivityPersistentIdentifier(identifier)
view.userActivity = activity
activity.becomeCurrent()
}
}
public func openDocumentScanner() {
let scanner = ScannerViewController()
scanner.delegate = self
navigationController?.pushViewController(scanner, animated: true)
navigationController?.setNavigationBarHidden(false, animated: false)
}
}
| 29.613139 | 113 | 0.664037 |
9b6408fe3893b9121a0cccbce54571e0e93d8f91 | 984 | // Copyright 2019 rideOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import CoreLocation
import Foundation
import RxSwift
public protocol VehicleStateSynchronizer {
func synchronizeVehicleState(vehicleId: String,
vehicleCoordinate: CLLocationCoordinate2D,
vehicleHeading: CLLocationDirection) -> Completable
}
public enum VehicleStateSynchronizerError: Error {
case invalidResponse
}
| 33.931034 | 84 | 0.722561 |
7aee65988a25d827c82cc2150f1a916b15780acf | 2,778 | //
// SwizzledMethods.swift
// KeyboardHandler
//
// Created by Arash Goodarzi on 1/7/20.
// Copyright © 2020 Arash Goodarzi. All rights reserved.
//
import UIKit
//MARK: - swizzle
extension NSObject {
static func swizzle(_ firstMethod: Selector, with secondMethod: Selector) {
let _originalMethod = class_getInstanceMethod(self, firstMethod)
let _swizzledMethod = class_getInstanceMethod(self, secondMethod)
guard let swizzledMethod = _swizzledMethod, let originalMethod = _originalMethod else {
return
}
let didAddMethod = class_addMethod(self, firstMethod, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
guard didAddMethod else {
method_exchangeImplementations(originalMethod, swizzledMethod)
return
}
class_replaceMethod(self, secondMethod, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
}
}
//MARK: - swizzleViewLifecycle
extension UIViewController {
static func swizzleViewLifecycle() {
swizzleViewDidLaod()
swizzleViewDidDisappear()
}
static func deswizzleViewLifecycle() {
deswizzleViewDidLaod()
deswizzleViewDidDisappear()
}
}
//MARK: - viewDidLaod
extension UIViewController {
static func swizzleViewDidLaod() {
let originalSelector = #selector(UIViewController.viewDidLoad)
let swizzledSelector = #selector(UIViewController.khViewDidLoad)
swizzle(originalSelector, with: swizzledSelector)
}
static func deswizzleViewDidLaod() {
let originalSelector = #selector(UIViewController.viewDidLoad)
let swizzledSelector = #selector(UIViewController.khViewDidLoad)
swizzle(swizzledSelector, with: originalSelector)
}
@objc func khViewDidLoad() {
self.khViewDidLoad()
Keyboarder.shared.presentingVcDidLoad(viewController: self)
}
}
//MARK: - ViewDidApear
extension UIViewController {
static func swizzleViewDidDisappear() {
let originalSelector = #selector(UIViewController.viewDidDisappear(_:))
let swizzledSelector = #selector(UIViewController.khViewDidDisappear)
swizzle(originalSelector, with: swizzledSelector)
}
static func deswizzleViewDidDisappear() {
let originalSelector = #selector(UIViewController.viewDidDisappear(_:))
let swizzledSelector = #selector(UIViewController.khViewDidDisappear)
swizzle(swizzledSelector, with: originalSelector)
}
@objc func khViewDidDisappear() {
self.khViewDidDisappear()
Keyboarder.shared.presentingVcDidDispappear(viewController: self)
}
}
| 31.213483 | 143 | 0.700864 |
f78f352e81b328d9b562c63814fa37894910566e | 906 | //
// StormViewerTests.swift
// StormViewerTests
//
// Created by Dulio Denis on 1/9/15.
// Copyright (c) 2015 ddApps. All rights reserved.
//
import UIKit
import XCTest
class StormViewerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 24.486486 | 111 | 0.616998 |
bf5c1edc6f6cdf58818d7c06b214515be4529901 | 702 | //
// UserDetailViewModel.swift
// SwiftUI-Combine-Example
//
// Created by Nahuel Jose Roldan on 23/07/2020.
// Copyright © 2020 Ryo Aoyama. All rights reserved.
//
import SwiftUI
import Combine
class UserDetailViewModel: ObservableObject {
@Published var userImage: UIImage = UIImage()
func fetchImage(for user: User) {
let request = URLRequest(url: user.avatar_url)
_ = URLSession.shared.dataTaskPublisher(for: request)
.map { UIImage(data: $0.data) }
.replaceError(with: nil)
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] image in
self?.userImage = image!
})
}
}
| 26 | 61 | 0.616809 |
0388904f03e4b4a5d0047b7167a9781b83849cde | 5,037 | //
// GradeViewController.swift
// SYSUJwxt
//
// Created by benwwchen on 2017/8/17.
// Copyright © 2017年 benwwchen. All rights reserved.
//
import UIKit
class GradeViewController: ListWithFilterViewController,
UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var gradesTableView: UITableView!
// MARK: Properties
var grades = [Grade]()
// MARK: Methods
override func loadData(completion: (() -> Void)? = nil) {
loadSavedFilterData()
var isGetAll = false
var isGetAllTerms = false
var yearInt: Int = 0
var termInt: Int = 0
if self.year == "全部" {
isGetAll = true
} else {
yearInt = Int(self.year.components(separatedBy: "-")[0])!
}
if self.term == "全部" {
isGetAllTerms = true
} else {
termInt = Int(self.term)!
}
let coursesTypeValues = coursesType.map({ CourseType.fromString(string: $0) })
jwxt.getGradeList(year: yearInt, term: termInt, isGetAll: isGetAll, isGetAllTerms: isGetAllTerms) { (success, object) in
if success, let grades = object as? [Grade] {
self.grades.removeAll()
// filter a courseType and append to the table data
let filteredGrades = grades.filter({ coursesTypeValues.contains($0.courseType) })
let sortedFilteredGrades = filteredGrades.sorted(by: { (grade1, grade2) -> Bool in
if grade1.year > grade2.year {
return true
} else if grade1.year == grade2.year {
if grade1.term > grade2.term {
return true
} else if grade1.term == grade2.term {
return grade1.name > grade2.name
}
}
return false
})
self.grades.append(contentsOf: sortedFilteredGrades)
DispatchQueue.main.async {
self.gradesTableView.reloadData()
completion?()
}
}
}
}
// MARK: Table Views
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return grades.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "GradeTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? GradeTableViewCell else {
fatalError("The dequeued cell is not an instance of GradeTableViewCell.")
}
// populate the data
let grade = grades[indexPath.row]
cell.courseNameLabel.text = grade.name
cell.creditLabel.text = "\(grade.credit)"
cell.gpaLabel.text = "\(grade.gpa)"
cell.gradeLabel.text = "\(grade.totalGrade)"
cell.rankingInTeachingClassLabel.text = grade.rankingInTeachingClass
cell.rankingInMajorClassLabel.text = grade.rankingInMajorClass
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.setSelected(false, animated: true)
cell.isSelected = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupRefreshControl(tableView: gradesTableView)
gradesTableView.dataSource = self
gradesTableView.delegate = self
headerTitle = "成绩"
filterType = .grade
initSetup()
}
override func unwindToMainViewController(sender: UIStoryboardSegue) {
super.unwindToMainViewController(sender: sender)
if sender.source is UINavigationController {
print("nav")
}
if sender.source is NotifySettingTableViewController {
print("notify")
}
// save current grades if notification is on
if let _ = (sender.source as? UINavigationController)?.topViewController as? NotifySettingTableViewController,
let year = UserDefaults.standard.string(forKey: "notify.year"),
let yearInt = Int(year.components(separatedBy: "-")[0]),
let term = UserDefaults.standard.string(forKey: "notify.term") {
// save current grades
jwxt.getGradeList(year: yearInt, term: Int(term)!, completion: { (success, object) in
if success, let grades = object as? [Grade] {
UserDefaults.standard.set(grades, forKey: "monitorGrades")
}
})
isUnwindingFromFilter = false
}
}
}
| 34.265306 | 133 | 0.568394 |
5d20fb19da29d11230811a42e4f80ce501da1915 | 5,029 | import CoreUnitTypes
import Foundation
/// Calculate the psychrometric properties of an air sample.
public struct Psychrometrics {
public let atmosphericPressure: Pressure
public let degreeOfSaturation: Double
public let density: DensityOf<MoistAir>
public let dewPoint: DewPoint
public let dryBulb: Temperature
public let enthalpy: EnthalpyOf<MoistAir>
public let humidityRatio: HumidityRatio
public let relativeHumidity: RelativeHumidity
public let units: PsychrometricEnvironment.Units
public let vaporPressure: VaporPressure
public let volume: SpecificVolumeOf<MoistAir>
public let wetBulb: WetBulb
public init(
dryBulb temperature: Temperature,
wetBulb: WetBulb,
pressure totalPressure: Pressure,
units: PsychrometricEnvironment.Units? = nil
) {
self.units = units ?? PsychrometricEnvironment.shared.units
self.atmosphericPressure = totalPressure
self.dryBulb = temperature
self.wetBulb = wetBulb
self.humidityRatio = .init(
dryBulb: temperature, wetBulb: wetBulb, pressure: totalPressure, units: units)
self.degreeOfSaturation = Self.degreeOfSaturation(
dryBulb: temperature, ratio: self.humidityRatio, pressure: totalPressure, units: units)
self.relativeHumidity = .init(
dryBulb: temperature, ratio: self.humidityRatio, pressure: totalPressure, units: units)
self.vaporPressure = .init(ratio: self.humidityRatio, pressure: totalPressure, units: units)
self.enthalpy = .init(dryBulb: temperature, ratio: self.humidityRatio, units: units)
self.volume = .init(
dryBulb: temperature, ratio: humidityRatio, pressure: totalPressure, units: units)
self.dewPoint = .init(dryBulb: temperature, humidity: self.relativeHumidity, units: units)
self.density = .init(for: dryBulb, at: relativeHumidity, pressure: totalPressure, units: units)
}
public init?(
dryBulb temperature: Temperature,
humidity relativeHumidity: RelativeHumidity,
pressure totalPressure: Pressure,
units: PsychrometricEnvironment.Units? = nil
) {
self.units = units ?? PsychrometricEnvironment.shared.units
self.atmosphericPressure = totalPressure
self.dryBulb = temperature
self.relativeHumidity = relativeHumidity
self.humidityRatio = .init(
dryBulb: temperature, humidity: relativeHumidity, pressure: totalPressure, units: units)
guard
let wetBulb = WetBulb(
dryBulb: temperature,
humidity: relativeHumidity,
pressure: totalPressure,
units: units
)
else { return nil }
self.wetBulb = wetBulb
self.degreeOfSaturation = Self.degreeOfSaturation(
dryBulb: temperature, ratio: self.humidityRatio, pressure: totalPressure, units: units)
self.dewPoint = .init(
dryBulb: temperature, ratio: self.humidityRatio, pressure: totalPressure, units: units)
self.vaporPressure = .init(ratio: self.humidityRatio, pressure: totalPressure, units: units)
self.enthalpy = .init(dryBulb: temperature, ratio: self.humidityRatio, units: units)
self.volume = .init(
dryBulb: temperature, ratio: humidityRatio, pressure: totalPressure, units: units)
self.density = .init(for: dryBulb, at: relativeHumidity, pressure: totalPressure, units: units)
}
public init?(
dryBulb temperature: Temperature,
dewPoint: DewPoint,
pressure totalPressure: Pressure,
units: PsychrometricEnvironment.Units? = nil
) {
self.units = units ?? PsychrometricEnvironment.shared.units
self.atmosphericPressure = totalPressure
self.dryBulb = temperature
self.dewPoint = dewPoint
self.humidityRatio = .init(dewPoint: dewPoint, pressure: totalPressure, units: units)
self.relativeHumidity = .init(
dryBulb: temperature, ratio: self.humidityRatio, pressure: totalPressure, units: units)
guard
let wetBulb = WetBulb(
dryBulb: temperature,
ratio: self.humidityRatio,
pressure: totalPressure,
units: units
)
else { return nil }
self.wetBulb = wetBulb
self.degreeOfSaturation = Self.degreeOfSaturation(
dryBulb: temperature, ratio: self.humidityRatio, pressure: totalPressure, units: units)
self.vaporPressure = .init(ratio: self.humidityRatio, pressure: totalPressure, units: units)
self.enthalpy = .init(dryBulb: temperature, ratio: self.humidityRatio, units: units)
self.volume = .init(
dryBulb: temperature, ratio: humidityRatio, pressure: totalPressure, units: units)
self.density = .init(for: dryBulb, at: relativeHumidity, pressure: totalPressure, units: units)
}
public static func degreeOfSaturation(
dryBulb temperature: Temperature,
ratio humidityRatio: HumidityRatio,
pressure totalPressure: Pressure,
units: PsychrometricEnvironment.Units? = nil
) -> Double {
precondition(humidityRatio > 0)
let saturatedRatio = HumidityRatio.init(
dryBulb: temperature, pressure: totalPressure, units: units)
return humidityRatio.rawValue / saturatedRatio.rawValue
}
}
| 41.561983 | 99 | 0.734341 |
fcc3b9dcd9f8acbc21483858cde48b665dbf000d | 11,644 | //
// SingleValueScheduleTableViewController.swift
// Naterade
//
// Created by Nathan Racklyeft on 2/13/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import LoopKit
public enum RepeatingScheduleValueResult<T: RawRepresentable> {
case success(scheduleItems: [RepeatingScheduleValue<T>], timeZone: TimeZone)
case failure(Error)
}
public protocol SingleValueScheduleTableViewControllerSyncSource: class {
func syncScheduleValues(for viewController: SingleValueScheduleTableViewController, completion: @escaping (_ result: RepeatingScheduleValueResult<Double>) -> Void)
func syncButtonTitle(for viewController: SingleValueScheduleTableViewController) -> String
func syncButtonDetailText(for viewController: SingleValueScheduleTableViewController) -> String?
func singleValueScheduleTableViewControllerIsReadOnly(_ viewController: SingleValueScheduleTableViewController) -> Bool
}
open class SingleValueScheduleTableViewController: DailyValueScheduleTableViewController, RepeatingScheduleValueTableViewCellDelegate {
open override func viewDidLoad() {
super.viewDidLoad()
tableView.register(RepeatingScheduleValueTableViewCell.nib(), forCellReuseIdentifier: RepeatingScheduleValueTableViewCell.className)
tableView.register(TextButtonTableViewCell.self, forCellReuseIdentifier: TextButtonTableViewCell.className)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if syncSource == nil {
delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
}
}
// MARK: - State
public var scheduleItems: [RepeatingScheduleValue<Double>] = []
override func addScheduleItem(_ sender: Any?) {
guard !isReadOnly && !isSyncInProgress else {
return
}
tableView.endEditing(false)
var startTime = TimeInterval(0)
var value = 0.0
if scheduleItems.count > 0, let cell = tableView.cellForRow(at: IndexPath(row: scheduleItems.count - 1, section: 0)) as? RepeatingScheduleValueTableViewCell {
let lastItem = scheduleItems.last!
let interval = cell.datePickerInterval
startTime = lastItem.startTime + interval
value = lastItem.value
if startTime >= TimeInterval(hours: 24) {
return
}
}
scheduleItems.append(
RepeatingScheduleValue(
startTime: min(TimeInterval(hours: 23.5), startTime),
value: value
)
)
super.addScheduleItem(sender)
}
override func insertableIndiciesByRemovingRow(_ row: Int, withInterval timeInterval: TimeInterval) -> [Bool] {
return insertableIndices(for: scheduleItems, removing: row, with: timeInterval)
}
var preferredValueFractionDigits: Int {
return 1
}
public weak var syncSource: SingleValueScheduleTableViewControllerSyncSource? {
didSet {
isReadOnly = syncSource?.singleValueScheduleTableViewControllerIsReadOnly(self) ?? false
if isViewLoaded {
tableView.reloadData()
}
}
}
private var isSyncInProgress = false {
didSet {
for cell in tableView.visibleCells {
switch cell {
case let cell as TextButtonTableViewCell:
cell.isEnabled = !isSyncInProgress
cell.isLoading = isSyncInProgress
case let cell as RepeatingScheduleValueTableViewCell:
cell.isReadOnly = isReadOnly || isSyncInProgress
default:
break
}
}
for item in navigationItem.rightBarButtonItems ?? [] {
item.isEnabled = !isSyncInProgress
}
navigationItem.hidesBackButton = isSyncInProgress
}
}
// MARK: - UITableViewDataSource
private enum Section: Int {
case schedule
case sync
}
open override func numberOfSections(in tableView: UITableView) -> Int {
if syncSource != nil {
return 2
}
return 1
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .schedule:
return scheduleItems.count
case .sync:
return 1
}
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .schedule:
let cell = tableView.dequeueReusableCell(withIdentifier: RepeatingScheduleValueTableViewCell.className, for: indexPath) as! RepeatingScheduleValueTableViewCell
let item = scheduleItems[indexPath.row]
let interval = cell.datePickerInterval
cell.timeZone = timeZone
cell.date = midnight.addingTimeInterval(item.startTime)
cell.valueNumberFormatter.minimumFractionDigits = preferredValueFractionDigits
cell.value = item.value
cell.unitString = unitDisplayString
cell.isReadOnly = isReadOnly || isSyncInProgress
cell.delegate = self
if indexPath.row > 0 {
let lastItem = scheduleItems[indexPath.row - 1]
cell.datePicker.minimumDate = midnight.addingTimeInterval(lastItem.startTime).addingTimeInterval(interval)
}
if indexPath.row < scheduleItems.endIndex - 1 {
let nextItem = scheduleItems[indexPath.row + 1]
cell.datePicker.maximumDate = midnight.addingTimeInterval(nextItem.startTime).addingTimeInterval(-interval)
} else {
cell.datePicker.maximumDate = midnight.addingTimeInterval(TimeInterval(hours: 24) - interval)
}
return cell
case .sync:
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
cell.textLabel?.text = syncSource?.syncButtonTitle(for: self)
cell.isEnabled = !isSyncInProgress
cell.isLoading = isSyncInProgress
return cell
}
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .schedule:
return nil
case .sync:
return syncSource?.syncButtonDetailText(for: self)
}
}
open override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
scheduleItems.remove(at: indexPath.row)
super.tableView(tableView, commit: editingStyle, forRowAt: indexPath)
}
}
open override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if sourceIndexPath != destinationIndexPath {
let item = scheduleItems.remove(at: sourceIndexPath.row)
scheduleItems.insert(item, at: destinationIndexPath.row)
guard destinationIndexPath.row > 0, let cell = tableView.cellForRow(at: destinationIndexPath) as? RepeatingScheduleValueTableViewCell else {
return
}
let interval = cell.datePickerInterval
let startTime = scheduleItems[destinationIndexPath.row - 1].startTime + interval
scheduleItems[destinationIndexPath.row] = RepeatingScheduleValue(startTime: startTime, value: scheduleItems[destinationIndexPath.row].value)
// Since the valid date ranges of neighboring cells are affected, the lazy solution is to just reload the entire table view
DispatchQueue.main.async {
tableView.reloadData()
}
}
}
// MARK: - UITableViewDelegate
open override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return super.tableView(tableView, canEditRowAt: indexPath) && !isSyncInProgress
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
switch Section(rawValue: indexPath.section)! {
case .schedule:
break
case .sync:
if let syncSource = syncSource, !isSyncInProgress {
isSyncInProgress = true
syncSource.syncScheduleValues(for: self) { (result) in
DispatchQueue.main.async {
switch result {
case .success(let items, let timeZone):
self.scheduleItems = items
self.timeZone = timeZone
self.tableView.reloadSections([Section.schedule.rawValue], with: .fade)
self.isSyncInProgress = false
self.delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
case .failure(let error):
self.present(UIAlertController(with: error), animated: true) {
self.isSyncInProgress = false
}
}
}
}
}
}
}
open override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
guard sourceIndexPath != proposedDestinationIndexPath, let cell = tableView.cellForRow(at: sourceIndexPath) as? RepeatingScheduleValueTableViewCell else {
return proposedDestinationIndexPath
}
let interval = cell.datePickerInterval
let indices = insertableIndices(for: scheduleItems, removing: sourceIndexPath.row, with: interval)
if indices[proposedDestinationIndexPath.row] {
return proposedDestinationIndexPath
} else {
var closestRow = sourceIndexPath.row
for (index, valid) in indices.enumerated() where valid {
if abs(proposedDestinationIndexPath.row - index) < closestRow {
closestRow = index
}
}
return IndexPath(row: closestRow, section: proposedDestinationIndexPath.section)
}
}
// MARK: - RepeatingScheduleValueTableViewCellDelegate
override public func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let currentItem = scheduleItems[indexPath.row]
scheduleItems[indexPath.row] = RepeatingScheduleValue(
startTime: cell.date.timeIntervalSince(midnight),
value: currentItem.value
)
}
super.datePickerTableViewCellDidUpdateDate(cell)
}
func repeatingScheduleValueTableViewCellDidUpdateValue(_ cell: RepeatingScheduleValueTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let currentItem = scheduleItems[indexPath.row]
scheduleItems[indexPath.row] = RepeatingScheduleValue(startTime: currentItem.startTime, value: cell.value)
}
}
}
| 37.320513 | 194 | 0.646685 |
890a632294d8e8b7b18017abf89cf98ed6a15e49 | 14,520 | // This file was automatically generated and should not be edited.
import Apollo
import Foundation
public final class RepositoryQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"query Repository { repository(owner: \"apollographql\", name: \"apollo-ios\") { __typename issueOrPullRequest(number: 13) { __typename ... on Issue { body ... on UniformResourceLocatable { url } author { __typename avatarUrl } } ... on Reactable { viewerCanReact ... on Comment { author { __typename login } } } } } }"
public let operationName: String = "Repository"
public let operationIdentifier: String? = "63e25c339275a65f43b847e692e42caed8c06e25fbfb3dc8db6d4897b180c9ef"
public init() {
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static let selections: [GraphQLSelection] = [
GraphQLField("repository", arguments: ["owner": "apollographql", "name": "apollo-ios"], type: .object(Repository.selections)),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(repository: Repository? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "repository": repository.flatMap { (value: Repository) -> ResultMap in value.resultMap }])
}
/// Lookup a given repository by the owner and repository name.
public var repository: Repository? {
get {
return (resultMap["repository"] as? ResultMap).flatMap { Repository(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "repository")
}
}
public struct Repository: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Repository"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("issueOrPullRequest", arguments: ["number": 13], type: .object(IssueOrPullRequest.selections)),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(issueOrPullRequest: IssueOrPullRequest? = nil) {
self.init(unsafeResultMap: ["__typename": "Repository", "issueOrPullRequest": issueOrPullRequest.flatMap { (value: IssueOrPullRequest) -> ResultMap in value.resultMap }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// Returns a single issue-like object from the current repository by number.
public var issueOrPullRequest: IssueOrPullRequest? {
get {
return (resultMap["issueOrPullRequest"] as? ResultMap).flatMap { IssueOrPullRequest(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "issueOrPullRequest")
}
}
public struct IssueOrPullRequest: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Issue", "PullRequest"]
public static let selections: [GraphQLSelection] = [
GraphQLTypeCase(
variants: ["Issue": AsIssue.selections],
default: [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("viewerCanReact", type: .nonNull(.scalar(Bool.self))),
GraphQLField("author", type: .object(Author.selections)),
]
)
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public static func makePullRequest(viewerCanReact: Bool, author: Author? = nil) -> IssueOrPullRequest {
return IssueOrPullRequest(unsafeResultMap: ["__typename": "PullRequest", "viewerCanReact": viewerCanReact, "author": author.flatMap { (value: Author) -> ResultMap in value.resultMap }])
}
public static func makeIssue(body: String, url: String, author: AsIssue.Author? = nil, viewerCanReact: Bool) -> IssueOrPullRequest {
return IssueOrPullRequest(unsafeResultMap: ["__typename": "Issue", "body": body, "url": url, "author": author.flatMap { (value: AsIssue.Author) -> ResultMap in value.resultMap }, "viewerCanReact": viewerCanReact])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// Can user react to this subject
public var viewerCanReact: Bool {
get {
return resultMap["viewerCanReact"]! as! Bool
}
set {
resultMap.updateValue(newValue, forKey: "viewerCanReact")
}
}
/// The actor who authored the comment.
public var author: Author? {
get {
return (resultMap["author"] as? ResultMap).flatMap { Author(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "author")
}
}
public struct Author: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Organization", "User", "Bot"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("login", type: .nonNull(.scalar(String.self))),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public static func makeOrganization(login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "Organization", "login": login])
}
public static func makeUser(login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "User", "login": login])
}
public static func makeBot(login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "Bot", "login": login])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The username of the actor.
public var login: String {
get {
return resultMap["login"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "login")
}
}
}
public var asIssue: AsIssue? {
get {
if !AsIssue.possibleTypes.contains(__typename) { return nil }
return AsIssue(unsafeResultMap: resultMap)
}
set {
guard let newValue = newValue else { return }
resultMap = newValue.resultMap
}
}
public struct AsIssue: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Issue"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("body", type: .nonNull(.scalar(String.self))),
GraphQLField("url", type: .nonNull(.scalar(String.self))),
GraphQLField("author", type: .object(Author.selections)),
GraphQLField("viewerCanReact", type: .nonNull(.scalar(Bool.self))),
GraphQLField("author", type: .object(Author.selections)),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(body: String, url: String, author: Author? = nil, viewerCanReact: Bool) {
self.init(unsafeResultMap: ["__typename": "Issue", "body": body, "url": url, "author": author.flatMap { (value: Author) -> ResultMap in value.resultMap }, "viewerCanReact": viewerCanReact])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// Identifies the body of the issue.
public var body: String {
get {
return resultMap["body"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "body")
}
}
/// The HTTP URL for this issue
public var url: String {
get {
return resultMap["url"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "url")
}
}
/// The actor who authored the comment.
public var author: Author? {
get {
return (resultMap["author"] as? ResultMap).flatMap { Author(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "author")
}
}
/// Can user react to this subject
public var viewerCanReact: Bool {
get {
return resultMap["viewerCanReact"]! as! Bool
}
set {
resultMap.updateValue(newValue, forKey: "viewerCanReact")
}
}
public struct Author: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Organization", "User", "Bot"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("avatarUrl", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("login", type: .nonNull(.scalar(String.self))),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public static func makeOrganization(avatarUrl: String, login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "Organization", "avatarUrl": avatarUrl, "login": login])
}
public static func makeUser(avatarUrl: String, login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "User", "avatarUrl": avatarUrl, "login": login])
}
public static func makeBot(avatarUrl: String, login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "Bot", "avatarUrl": avatarUrl, "login": login])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// A URL pointing to the actor's public avatar.
public var avatarUrl: String {
get {
return resultMap["avatarUrl"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "avatarUrl")
}
}
/// The username of the actor.
public var login: String {
get {
return resultMap["login"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "login")
}
}
}
}
}
}
}
}
public final class RepoUrlQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"query RepoURL { repository(owner: \"apollographql\", name: \"apollo-ios\") { __typename url } }"
public let operationName: String = "RepoURL"
public let operationIdentifier: String? = "b55f22bcbfaea0d861089b3fbe06299675a21d11ba7138ace39ecbde606a3dc1"
public init() {
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static let selections: [GraphQLSelection] = [
GraphQLField("repository", arguments: ["owner": "apollographql", "name": "apollo-ios"], type: .object(Repository.selections)),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(repository: Repository? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "repository": repository.flatMap { (value: Repository) -> ResultMap in value.resultMap }])
}
/// Lookup a given repository by the owner and repository name.
public var repository: Repository? {
get {
return (resultMap["repository"] as? ResultMap).flatMap { Repository(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "repository")
}
}
public struct Repository: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Repository"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("url", type: .nonNull(.scalar(String.self))),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(url: String) {
self.init(unsafeResultMap: ["__typename": "Repository", "url": url])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The HTTP URL for this repository
public var url: String {
get {
return resultMap["url"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "url")
}
}
}
}
}
| 35.588235 | 323 | 0.588361 |
deac28711848f9027e1b8b439df70b39c812093a | 1,298 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import UIKit
import EssentialFeed
final class WeakRefVirtualProxy<T: AnyObject> {
private weak var object: T?
init(_ object: T) {
self.object = object
}
}
// MARK: - Feed
extension WeakRefVirtualProxy: FeedErrorView where T: FeedErrorView {
func display(_ viewModel: FeedErrorViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: FeedLoadingView where T: FeedLoadingView {
func display(_ viewModel: FeedLoadingViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: FeedImageView where T: FeedImageView, T.Image == UIImage {
func display(_ model: FeedImageViewModel<UIImage>) {
object?.display(model)
}
}
// MARK: - Image Comments
extension WeakRefVirtualProxy: ImageCommentsErrorView where T: ImageCommentsErrorView {
func display(_ viewModel: ImageCommentsErrorViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: ImageCommentsLoadingView where T: ImageCommentsLoadingView {
func display(_ viewModel: ImageCommentsLoadingViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: ImageCommentsView where T: ImageCommentsView {
func display(_ model: ImageCommentsViewModel) {
object?.display(model)
}
}
| 23.6 | 92 | 0.769646 |
61ef4c3cfd1d6af8dc875cafc1c8bbbd95d991e7 | 1,062 | //
// HeartlineIconStyling.swift
// EvidationMarkdown
//
// Created by Gilbert Lo on 10/10/19.
// Copyright © 2019 Evidation Health, Inc. All rights reserved.
//
import Markdown
public struct HeartlineIconStyling: ItemStyling, TextColorStylingRule, LineHeightStylingRule, BaseFontStylingRule, ContentInsetStylingRule, BoldStylingRule, ItalicStylingRule, TextAlignmentStylingRule, LetterSpacingStylingRule {
public var parent : ItemStyling? = nil
public func isApplicableOn(_ markDownItem: MarkDownItem) -> Bool {
return markDownItem is HeartlineIconBlockMarkDownItem
}
public var baseFont: UIFont? = UIFont.systemFont(ofSize: UIFont.systemFontSize)
public var textColor: UIColor? = UIColor.black
public var contentInsets: UIEdgeInsets = UIEdgeInsets(top:0, left: 0, bottom: 5, right: 0)
public var lineHeight: CGFloat? = 4
public var isBold = false
public var isItalic = false
public var textAlignment:TextAlignment = .left
public var letterSpacing: CGFloat? = nil
public init(){}
}
| 30.342857 | 228 | 0.741996 |
d9938bb2302b16989f1e337eeec3287bb6d483f3 | 3,014 | //
// MyMomentViewController.swift
// Meow
//
// Created by 林武威 on 2017/7/18.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import UIKit
import RxSwift
class MyMomentViewController: UITableViewController {
let disposeBag = DisposeBag()
var items: [Moment] = [Moment]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView(frame: CGRect.zero)
tableView.register(R.nib.momentHomePageTableViewCell)
loadData()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let moment = items[indexPath.row]
//let view = tableView.dequeueReusableCell(withIdentifier: R.nib.momentHomePageTableViewCell.identifier)! as! MomentHomePageTableViewCell
// Reuseable cells incur bug in height calculation
let view = R.nib.momentHomePageTableViewCell.firstView(owner: nil)!
view.configure(model: moment)
view.delegate = self
return view
}
func loadData() {
MeowAPIProvider.shared
.request(.myMoments)
.mapTo(arrayOf: Moment.self)
.subscribe(onNext:{
[weak self]
items in
self?.items = items
//self?.items.append(contentsOf: items)
self?.tableView.reloadData()
})
.addDisposableTo(disposeBag)
}
}
extension MyMomentViewController: MomentCellDelegate {
func didTapAvatar(profile: Profile) {
if let userId = UserManager.shared.currentUser?.userId, userId == profile.userId {
MeViewController.show(from: navigationController!)
} else {
UserProfileViewController.show(profile, from: self)
}
}
func didToggleLike(id: Int, isLiked: Bool) -> Bool {
var liked = isLiked
let request = isLiked ? MeowAPI.unlikeMoment(id: id) : MeowAPI.likeMoment(id: id)
MeowAPIProvider.shared.request(request)
.subscribe(onNext: {
_ in
liked = !isLiked
})
.addDisposableTo(disposeBag)
return liked
}
func didPostComment(moment: Moment, content: String, from cell: MomentHomePageTableViewCell) {
MeowAPIProvider.shared.request(.postComment(item: moment, content: content))
.subscribe(onNext:{
[weak self]
_ in
cell.clearComment()
cell.model!.commentCount! += 1
cell.updateCommentCountLabel()
self?.loadData()
})
}
}
| 31.395833 | 145 | 0.609157 |
463f1ce2eab6983b60a9417cfb122338e5cd851b | 1,130 | //
// shuffledArray.swift
// simpleProfile
//
// Created by Oscar Almazan Lora on 04/03/18.
// Copyright © 2018 d182_oscar_a. All rights reserved.
//
import UIKit
extension MutableCollection {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
let i = index(firstUnshuffled, offsetBy: d)
swapAt(firstUnshuffled, i)
}
}
}
extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Element] {
var result = Array(self)
result.shuffle()
return result
}
}
//let x = [1, 2, 3].shuffled()
// x == [2, 3, 1]
//let fiveStrings = stride(from: 0, through: 100, by: 5).map(String.init).shuffled()
// fiveStrings == ["20", "45", "70", "30", ...]
//var numbers = [1, 2, 3, 4]
//numbers.shuffle()
// numbers == [3, 2, 1, 4]
| 26.27907 | 96 | 0.6 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.