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
|
---|---|---|---|---|---|
87a80e3922d7265bb8877d383b0b1dc3ab653c95 | 964 | //
// PaversFRPTests.swift
// PaversFRPTests
//
// Created by Pi on 22/08/2017.
// Copyright © 2017 Keith. All rights reserved.
//
import XCTest
@testable import PaversFRP
class PaversFRPTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.054054 | 111 | 0.631743 |
4a466158e47ced807d24e06b621f88dbcfea5cbb | 16,523 | //
// JCPhotoBrowser.swift
// JCPhotoBrowser-Swift
//
// Created by Jake on 01/06/2017.
// Copyright © 2017 Jake. All rights reserved.
//
import UIKit
import Kingfisher
enum JCPhotoBrowserInteractiveDismissalStyle {
case scale
case slide
case none
}
enum JCPhotoBrowserPageIndicatorStyle {
case dot
case text
}
enum JCPhotoBrowserImageLoadingStyle {
case determinate
case indeterminate
}
class JCPhotoBrowser: UIViewController , UIScrollViewDelegate{
var dismissalStyle:JCPhotoBrowserInteractiveDismissalStyle = .scale
var pageIndicatorStyle:JCPhotoBrowserPageIndicatorStyle = .dot
var loadingStyle:JCPhotoBrowserImageLoadingStyle = .determinate
let kAnimationDuration:TimeInterval = 0.3
fileprivate var scrollView:UIScrollView!
fileprivate var present = false
fileprivate var startLocation:CGPoint?
fileprivate var photoItems = Array<JCPhotoItem>()
fileprivate var reuseableItemViews = Set<JCPhotoView>()
fileprivate var visibleItemViews = Array<JCPhotoView>()
fileprivate var currentPage:UInt!
fileprivate var pageControl:UIPageControl!
fileprivate var pageLabel:UILabel!
init(_ _photoItems:Array<JCPhotoItem> ,selectedIndex:UInt) {
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = UIModalPresentationStyle.custom
self.modalTransitionStyle = UIModalTransitionStyle.coverVertical
currentPage = selectedIndex
photoItems = _photoItems
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clear
var rect = self.view.bounds
rect.origin.x -= 10.0
rect.size.width += 2 * 10.0
scrollView = UIScrollView.init(frame: rect)
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = self
self.view.addSubview(scrollView)
if pageIndicatorStyle == .dot {
pageControl = UIPageControl.init(frame: CGRect.init(x: 0, y: self.view.bounds.size.height-40, width: self.view.bounds.size.width, height: 20))
pageControl.numberOfPages = photoItems.count
pageControl.currentPage = Int(currentPage)
self.view.addSubview(pageControl)
}else{
pageLabel = UILabel.init(frame: CGRect.init(x: 0, y: self.view.bounds.size.height-40, width: self.view.bounds.size.width, height: 20))
pageLabel.textColor = UIColor.white
pageLabel.font = UIFont.systemFont(ofSize: 16)
pageLabel.textAlignment = NSTextAlignment.center
self.configPageLabelWith(Page: currentPage)
self.view.addSubview(pageLabel)
}
let contentSize = CGSize.init(width: rect.size.width * CGFloat(photoItems.count), height: rect.size.height)
scrollView.contentSize = contentSize
self.addGestureRecognizer()
let contentOffset = CGPoint.init(x: scrollView.frame.size.width * CGFloat(currentPage), y: 0)
scrollView.setContentOffset(contentOffset, animated: false)
if contentOffset.x == 0 {
self.scrollViewDidScroll(scrollView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let item = photoItems[Int(currentPage)]
let photoView = self.photoViewFor(currentPage)
if KingfisherManager.shared.cache.retrieveImageInMemoryCache(forKey: (item.imageUrl?.absoluteString)!) != nil {
self.config(photoView!, item: item)
}else{
photoView?.imageView.image = item.thumbImage
photoView?.resizeImageView()
}
let endRect = photoView?.imageView.frame
var sourceRect:CGRect!
let systemVersion = (UIDevice.current.systemVersion as NSString).floatValue
if systemVersion >= 8.0 && systemVersion < 9.0 {
sourceRect = item.sourceView.superview?.convert((item.sourceView.frame), to: photoView)
}else{
sourceRect = item.sourceView.superview?.convert((item.sourceView.frame), to: photoView)
}
photoView?.imageView.frame = sourceRect
UIView.animate(withDuration:kAnimationDuration , animations: {
photoView?.imageView.frame = endRect!
self.view.backgroundColor = UIColor.black
}) { (finish) in
self.config(photoView!, item: item)
self.present = true
UIApplication.shared.setStatusBarHidden(true, with: UIStatusBarAnimation.fade)
}
}
@objc public func showFrom (_ viewController:UIViewController){
viewController.present(self, animated: false, completion: nil)
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
return UIInterfaceOrientationMask.portrait
}
@objc fileprivate func configPageLabelWith(Page:UInt){
pageLabel.text = "\(Page+1) / \(photoItems.count)"
}
@objc fileprivate func photoViewFor(_ page:UInt) -> JCPhotoView? {
for photoView in visibleItemViews {
if(photoView.tag == Int(page)){
return photoView
}
}
return nil
}
@objc fileprivate func dequeueReuseableItemView() -> JCPhotoView?{
var photoView:JCPhotoView? = reuseableItemViews.first
if photoView == nil {
photoView = JCPhotoView.init(frame: scrollView.frame)
}else{
reuseableItemViews.remove(photoView!)
}
photoView?.tag = -1
return photoView
}
@objc fileprivate func updateReuseableItemView() {
for photoView in visibleItemViews {
if photoView.frame.origin.x + photoView.frame.size.width < scrollView.contentOffset.x - scrollView.frame.size.width ||
photoView.frame.origin.x > scrollView.contentOffset.x + 2 * scrollView.frame.size.width{
photoView.removeFromSuperview()
self.config(photoView, item: nil)
reuseableItemViews.insert(photoView)
visibleItemViews.removeFirst()
}
}
}
@objc fileprivate func configItemViews() {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width + 0.5)
for i in (page-1)...(page+1) {
if i<0 || i>=photoItems.count {
continue
}
var photoView = self.photoViewFor(UInt(i))
if photoView == nil {
photoView = self.dequeueReuseableItemView()
var rect = scrollView.bounds
rect.origin.x = CGFloat(i) * scrollView.bounds.size.width
photoView?.frame = rect
photoView?.tag = i
scrollView.addSubview(photoView!)
visibleItemViews.append(photoView!)
}
if photoView?.item == nil && present {
let item = photoItems[i]
self.config(photoView!, item: item)
}
}
if page != Int(currentPage) && present {
currentPage = UInt(page)
if pageIndicatorStyle == .dot {
pageControl.currentPage = page
}else{
self.configPageLabelWith(Page: currentPage)
}
}
}
@objc fileprivate func dismiss(_ animated:Bool){
for photoView in visibleItemViews {
photoView.cancelCurrentImageLoad()
}
let item = photoItems[Int(currentPage)]
if animated {
UIView.animate(withDuration: kAnimationDuration, animations: {
item.sourceView.alpha = 1
})
}else{
item.sourceView.alpha = 1
}
self.dismiss(animated: false, completion: nil)
}
@objc fileprivate func config(_ photoView:JCPhotoView,item:JCPhotoItem?) {
photoView.set(_item: item, determinate: (loadingStyle == .determinate))
}
//MARK: Gesture
@objc fileprivate func performScaleWith(_ pan:UIPanGestureRecognizer) {
let point = pan.translation(in: self.view)
let location = pan.location(in: self.view)
let velocity = pan.velocity(in: self.view)
let photoView = self.photoViewFor(currentPage)
switch pan.state {
case .began:
startLocation = location
self.handlePanBegin()
break
case .changed:
var percent = 1 - fabs(point.y) / (self.view.frame.size.height / 2)
percent = max(percent, 0)
let s = max(percent, 0.5)
let translation = CGAffineTransform.init(translationX: point.x / s, y: point.y / s)
let scale = CGAffineTransform.init(scaleX: s, y: s)
photoView?.imageView.transform = translation.concatenating(scale)
self.view.backgroundColor = UIColor.init(white: 0, alpha: percent)
break
case .ended: fallthrough
case .cancelled:
if fabs(point.y) > 100.0 || fabs(velocity.y) > 500 {
self.showDismissalAnimation()
}else{
self.showCancellationAnimation()
}
break
default:
break
}
}
@objc fileprivate func performSlideWith(_ pan:UIPanGestureRecognizer) {
let point = pan.translation(in: self.view)
let location = pan.location(in: self.view)
let velocity = pan.velocity(in: self.view)
let photoView = self.photoViewFor(currentPage)
switch pan.state {
case .began:
startLocation = location
self.handlePanBegin()
break
case .changed:
let percent = 1 - fabs(point.y) / (self.view.frame.size.height / 2)
photoView?.imageView.transform = CGAffineTransform.init(translationX: 0, y: point.y)
self.view.backgroundColor = UIColor.init(white: 0, alpha: percent)
break
case .ended: fallthrough
case .cancelled:
if fabs(point.y) > 200.0 || fabs(velocity.y) > 500 {
self.showSlideCompletionAnimationFrom(point: point)
}else{
self.showCancellationAnimation()
}
break
default:
break
}
}
@objc fileprivate func handlePanBegin() {
let photoView = self.photoViewFor(currentPage)
photoView?.cancelCurrentImageLoad()
let item = photoItems[Int(currentPage)]
UIApplication.shared.isStatusBarHidden = false
photoView?.progressLayer.isHidden = true
item.sourceView.alpha = 0
}
//MARK: Gesture Recognizer
@objc fileprivate func addGestureRecognizer() {
let doubleTap = UITapGestureRecognizer.init(target: self, action:#selector(didDoubleTap(_:)))
doubleTap.numberOfTapsRequired = 2
self.view.addGestureRecognizer(doubleTap)
let singleTap = UITapGestureRecognizer.init(target: self, action:#selector(didSingleTap(_:)))
singleTap.numberOfTapsRequired = 1
singleTap.require(toFail: doubleTap)
self.view.addGestureRecognizer(singleTap)
let longPress = UILongPressGestureRecognizer.init(target: self, action:#selector(didLongPress(_:)))
self.view.addGestureRecognizer(longPress)
let pan = UIPanGestureRecognizer.init(target: self, action:#selector(didPan(_:)))
self.view.addGestureRecognizer(pan)
}
@objc fileprivate func didSingleTap(_ tap:UITapGestureRecognizer){
self.showDismissalAnimation()
}
@objc fileprivate func didDoubleTap(_ tap:UITapGestureRecognizer){
let photoView = self.photoViewFor(currentPage)
let item = photoItems[Int(currentPage)]
if !item.finished {
return
}
if (photoView?.zoomScale)! > CGFloat(1) {
photoView?.setZoomScale(1, animated: true)
}else{
let location = tap.location(in: self.view)
let maxZoomScale = photoView?.maximumZoomScale
let width = self.view.bounds.size.width / CGFloat(maxZoomScale!)
let height = self.view.bounds.size.height / CGFloat(maxZoomScale!)
photoView?.zoom(to:CGRect.init(x: location.x - width / 2, y: location.y - height / 2, width: width, height: height), animated: true)
}
}
@objc fileprivate func didLongPress(_ longPress:UILongPressGestureRecognizer){
if longPress.state != .began {
return
}
let photoView = self.photoViewFor(currentPage)
var imageData:NSData?
if photoView?.item.imageUrl != nil{
let path = KingfisherManager.shared.cache.cachePath(forKey: (photoView?.item.imageUrl?.absoluteString)!)
imageData = NSData.init(contentsOfFile: path)
}else if photoView?.item.image != nil{
imageData = (UIImagePNGRepresentation((photoView?.item.image)!)) as NSData?
}else{
return
}
let vc = UIActivityViewController.init(activityItems: [imageData!], applicationActivities: nil)
self.present(vc, animated: true, completion: nil)
}
@objc fileprivate func didPan(_ pan:UIPanGestureRecognizer){
let photoView = self.photoViewFor(currentPage)
if (photoView?.zoomScale)! > CGFloat(1.1) {
return
}
switch dismissalStyle {
case .scale:
self.performScaleWith(pan)
break
case .slide:
self.performSlideWith(pan)
break
default:
break
}
}
//MARK: Animation
@objc fileprivate func showCancellationAnimation() {
let item = photoItems[Int(currentPage)]
let photoView = self.photoViewFor(currentPage)
item.sourceView.alpha = 1
if !item.finished {
photoView?.progressLayer.isHidden = false
}
UIView.animate(withDuration: kAnimationDuration, animations: {
photoView?.imageView.transform = CGAffineTransform.identity
self.view.backgroundColor = UIColor.black
}) { (finish) in
UIApplication.shared.setStatusBarHidden(true, with: UIStatusBarAnimation.fade)
self.config(photoView!, item: item)
}
}
@objc fileprivate func showDismissalAnimation() {
let item = photoItems[Int(currentPage)]
let photoView = self.photoViewFor(currentPage)
photoView?.cancelCurrentImageLoad()
UIApplication.shared.isStatusBarHidden = false
photoView?.progressLayer.isHidden = true
item.sourceView.alpha = 0
var source:CGRect!
let systemVersion = (UIDevice.current.systemVersion as NSString).floatValue
if systemVersion >= 8.0 && systemVersion < 9.0 {
source = item.sourceView.superview?.convert(item.sourceView.frame, to: photoView)
}else{
source = item.sourceView.superview?.convert(item.sourceView.frame, to: photoView)
}
UIView.animate(withDuration: kAnimationDuration, animations: {
photoView?.imageView.frame = source
self.view.backgroundColor = UIColor.clear
}) { (finish) in
self.dismiss(false)
}
}
@objc fileprivate func showSlideCompletionAnimationFrom(point:CGPoint) {
let photoView = self.photoViewFor(currentPage)
let throwToTop = point.y < 0
var toTranslationY = CGFloat(0.0)
if throwToTop {
toTranslationY = -self.view.frame.size.height
}else{
toTranslationY = self.view.frame.size.height
}
UIView.animate(withDuration: kAnimationDuration, animations: {
photoView?.imageView.transform = CGAffineTransform.init(translationX: 0, y: toTranslationY)
self.view.backgroundColor = UIColor.clear
}) { (finish) in
self.dismiss(false)
}
}
//MARK: ScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.updateReuseableItemView()
self.configItemViews()
}
}
| 37.382353 | 154 | 0.618471 |
9b87d48837616bac37d384802f7af335b86a2ece | 1,490 | //
// TitleCheckboxView.swift
// Memorize
//
// Created by Вика on 28/11/2019.
// Copyright © 2019 Vika Olegova. All rights reserved.
//
import UIKit
/// Вьюха с чекбоксом и текстом к нему, которые находятся на одной строке и выравнены по центру
class TitleCheckboxView: UIView {
let checkBox = CheckBox()
let titleLabel = UILabel()
convenience init() {
self.init(frame: .zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(checkBox)
addSubview(titleLabel)
checkBox.heightAnchor.constraint(equalToConstant: 24).isActive = true
checkBox.widthAnchor.constraint(equalToConstant: 24).isActive = true
checkBox.rightAnchor.constraint(equalTo: titleLabel.leftAnchor, constant: -10).isActive = true
checkBox.topAnchor.constraint(equalTo: topAnchor).isActive = true
checkBox.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.863636 | 102 | 0.690604 |
e67f808a292c257e15176e9dd437ec8f88f6fa37 | 351 | //
// TextEdit_it_iOSApp.swift
// TextEdit.it iOS
//
// Created by Mark Howard on 03/05/2021.
//
import SwiftUI
@main
struct TextEdit_it_iOSApp: App {
var body: some Scene {
DocumentGroup(newDocument: TextEdit_it_iOSDocument()) { file in
ContentView(document: file.$document, fileURL: URL(string: "/")!)
}
}
}
| 19.5 | 77 | 0.641026 |
56ee6edb61c2668430b300fbb39fb3fc4712bd20 | 1,188 | //
// VaccinationTests.swift
//
//
// © Copyright IBM Deutschland GmbH 2021
// SPDX-License-Identifier: Apache-2.0
//
@testable import CovPassCommon
import Foundation
import XCTest
class NameTests: XCTestCase {
var sut: Name {
try! JSONDecoder().decode(Name.self, from: Data.json("Name"))
}
func testDecoding() {
XCTAssertEqual(sut.gn, "Erika Dörte")
XCTAssertEqual(sut.fn, "Schmitt Mustermann")
XCTAssertEqual(sut.gnt, "ERIKA<DOERTE")
XCTAssertEqual(sut.fnt, "SCHMITT<MUSTERMANN")
}
func testComparision() {
var name1 = sut
var name2 = sut
XCTAssertEqual(name1, name2)
name1 = sut
name2 = sut
name2.gn = "foo"
XCTAssertNotEqual(name1, name2)
name1 = sut
name2 = sut
name2.fn = "foo"
XCTAssertNotEqual(name1, name2)
name1 = sut
name2 = sut
name2.fn = nil
name2.gn = nil
name2.gnt = "foo"
XCTAssertNotEqual(name1, name2)
name1 = sut
name2 = sut
name2.fn = nil
name2.gn = nil
name2.fnt = "foo"
XCTAssertNotEqual(name1, name2)
}
}
| 21.214286 | 69 | 0.574074 |
4892e71cf9023441a92c9b67e241ac10f9b70991 | 797 | //
// Copyright © 2020 Essential Developer Ltd. All rights reserved.
//
import UIKit
import RxSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
showPaymentForm()
return true
}
private func showPaymentForm() {
let vm = PaymentFormViewModel(service: RandomSuggestionsService())
let vc = PaymentFormViewController(viewModel: vm)
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: vc)
window?.makeKeyAndVisible()
}
}
| 27.482759 | 145 | 0.688833 |
9c79f08e7eace4874af8201b733fdc01529409c3 | 824 | import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var detailDescriptionLabel: UILabel!
func configureView() {
// Update the user interface for the detail item.
if let detail = detailItem {
if let label = detailDescriptionLabel {
label.text = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var detailItem: NSDate? {
didSet {
// Update the view.
configureView()
}
}
}
| 23.542857 | 80 | 0.595874 |
ac1694adc09f669c79739be1a43a24df50c08871 | 6,355 | import AppKit
import Player
import Combine
final class Settings: NSWindow {
private var subs = Set<AnyCancellable>()
init() {
super.init(contentRect: .init(x: 0, y: 0, width: 350, height: 400), styleMask:
[.borderless, .miniaturizable, .closable, .titled, .unifiedTitleAndToolbar, .fullSizeContentView],
backing: .buffered, defer: false)
titlebarAppearsTransparent = true
titleVisibility = .hidden
toolbar = .init()
toolbar!.showsBaselineSeparator = false
collectionBehavior = .fullScreenNone
isReleasedWhenClosed = false
center()
let randomTitle = Label(.key("Random"), .regular())
contentView!.addSubview(randomTitle)
let random = NSPopUpButton(frame: .zero)
random.translatesAutoresizingMaskIntoConstraints = false
random.addItems(withTitles: [.key("Off"), .key("Track"), .key("Album")])
random.target = self
random.action = #selector(self.random)
contentView!.addSubview(random)
let randomSeparator = Separator()
contentView!.addSubview(randomSeparator)
let trackTitle = Label(.key("When.track.finishes"), .regular())
contentView!.addSubview(trackTitle)
let track = NSPopUpButton(frame: .zero)
track.translatesAutoresizingMaskIntoConstraints = false
track.addItems(withTitles: [.key("Stop"), .key("Loop"), .key("Next")])
track.target = self
track.action = #selector(self.track)
contentView!.addSubview(track)
let trackSeparator = Separator()
contentView!.addSubview(trackSeparator)
let albumTitle = Label(.key("When.album.finishes"), .regular())
contentView!.addSubview(albumTitle)
let album = NSPopUpButton(frame: .zero)
album.translatesAutoresizingMaskIntoConstraints = false
album.addItems(withTitles: [.key("Stop"), .key("Loop"), .key("Next")])
album.target = self
album.action = #selector(self.album)
contentView!.addSubview(album)
let albumSeparator = Separator()
contentView!.addSubview(albumSeparator)
let notifications = NSButton(checkboxWithTitle: .key("Notify.on.track"), target: self, action: #selector(self.notifications))
notifications.translatesAutoresizingMaskIntoConstraints = false
notifications.font = .regular()
contentView!.addSubview(notifications)
random.topAnchor.constraint(equalTo: contentView!.topAnchor, constant: 70).isActive = true
random.leftAnchor.constraint(equalTo: contentView!.centerXAnchor, constant: 30).isActive = true
randomTitle.rightAnchor.constraint(equalTo: random.leftAnchor, constant: -20).isActive = true
randomTitle.centerYAnchor.constraint(equalTo: random.centerYAnchor).isActive = true
randomSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true
randomSeparator.topAnchor.constraint(equalTo: random.bottomAnchor, constant: 30).isActive = true
randomSeparator.leftAnchor.constraint(equalTo: contentView!.leftAnchor, constant: 60).isActive = true
randomSeparator.rightAnchor.constraint(equalTo: contentView!.rightAnchor, constant: -60).isActive = true
track.topAnchor.constraint(equalTo: randomSeparator.bottomAnchor, constant: 30).isActive = true
track.leftAnchor.constraint(equalTo: random.leftAnchor).isActive = true
trackTitle.rightAnchor.constraint(equalTo: randomTitle.rightAnchor).isActive = true
trackTitle.centerYAnchor.constraint(equalTo: track.centerYAnchor).isActive = true
trackSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true
trackSeparator.topAnchor.constraint(equalTo: track.bottomAnchor, constant: 30).isActive = true
trackSeparator.leftAnchor.constraint(equalTo: randomSeparator.leftAnchor).isActive = true
trackSeparator.rightAnchor.constraint(equalTo: randomSeparator.rightAnchor).isActive = true
album.topAnchor.constraint(equalTo: trackSeparator.bottomAnchor, constant: 30).isActive = true
album.leftAnchor.constraint(equalTo: random.leftAnchor).isActive = true
albumTitle.rightAnchor.constraint(equalTo: randomTitle.rightAnchor).isActive = true
albumTitle.centerYAnchor.constraint(equalTo: album.centerYAnchor).isActive = true
albumSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true
albumSeparator.topAnchor.constraint(equalTo: album.bottomAnchor, constant: 30).isActive = true
albumSeparator.leftAnchor.constraint(equalTo: randomSeparator.leftAnchor).isActive = true
albumSeparator.rightAnchor.constraint(equalTo: randomSeparator.rightAnchor).isActive = true
notifications.topAnchor.constraint(equalTo: albumSeparator.bottomAnchor, constant: 32).isActive = true
notifications.centerXAnchor.constraint(equalTo: contentView!.centerXAnchor).isActive = true
state.player.config.sink {
random.selectItem(at: .init($0.random.rawValue))
track.selectItem(at: .init($0.trackEnds.rawValue))
album.selectItem(at: .init($0.albumEnds.rawValue))
track.isEnabled = $0.random == .none
album.isEnabled = $0.random == .none
trackTitle.alphaValue = $0.random == .none ? 1 : 0.3
albumTitle.alphaValue = $0.random == .none ? 1 : 0.3
notifications.state = $0.notifications ? .on : .off
}.store(in: &subs)
}
@objc private func random(_ button: NSPopUpButton) {
state.player.config.value.random = Random(rawValue: .init(button.indexOfSelectedItem))!
}
@objc private func track(_ button: NSPopUpButton) {
state.player.config.value.trackEnds = Heuristic(rawValue: .init(button.indexOfSelectedItem))!
}
@objc private func album(_ button: NSPopUpButton) {
state.player.config.value.albumEnds = Heuristic(rawValue: .init(button.indexOfSelectedItem))!
}
@objc private func notifications(_ button: NSButton) {
state.player.config.value.notifications = button.state == .on
}
}
| 49.648438 | 133 | 0.678836 |
1cf069c97b7615d26987bd53f8658385643642b8 | 2,294 | //
// SceneDelegate.swift
// ssbun-ios-example
//
// Created by SSBun on 2021/10/7.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.283019 | 147 | 0.712729 |
1858b3fc9943c9b68590c3fc3075a1cd9bf4ecde | 794 | //
// LineChartView+Style.swift
// PushUps
//
// Created by Andrew Walker on 19/02/2017.
// Copyright © 2017 Andrew Walker. All rights reserved.
//
import Charts
internal extension LineChartView {
// MARK: - Internal Functions
internal func applyGlobalStyle() {
self.backgroundColor = UIColor.clear
self.drawGridBackgroundEnabled = false
self.rightAxis.enabled = false
self.leftAxis.enabled = false
self.xAxis.enabled = false
self.doubleTapToZoomEnabled = false
self.dragEnabled = false
self.noDataText = ""
self.legend.enabled = false
self.chartDescription = nil
self.highlighter = nil
self.setViewPortOffsets(left: 20.0, top: 20.0, right: 20.0, bottom: 20.0)
}
}
| 25.612903 | 81 | 0.641058 |
0a1b63d9ba7253d8510d04c5f01c689cf8d9823c | 20,311 |
// Warning: This file is automatically generated and your changes will be overwritten.
// See `Sources/Codegen/Readme.md` for more details.
/// The data visualized by the radial span of the bars is set in `r`
///
/// - SeeAlso:
/// Documentation for
/// [Python](https://plot.ly/python/reference/#barpolar),
/// [JavaScript](https://plot.ly/javascript/reference/#barpolar) or
/// [R](https://plot.ly/r/reference/#barpolar)
public struct BarPolar<RData, ThetaData>: Trace, PolarSubplot where RData: Plotable, ThetaData: Plotable {
public let type: String = "barpolar"
public let animatable: Bool = false
/// Determines whether or not this trace is visible.
///
/// If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the
/// legend itself is visible).
public var visible: Shared.Visible? = nil
/// Determines whether or not an item corresponding to this trace is shown in the legend.
public var showLegend: Bool? = nil
/// Sets the legend group for this trace.
///
/// Traces part of the same legend group hide/show at the same time when toggling legend items.
public var legendGroup: String? = nil
/// Sets the opacity of the trace.
public var opacity: Double? = nil
/// Sets the trace name.
///
/// The trace name appear as the legend item and on hover.
public var name: String? = nil
/// Assign an id to this trace, Use this to provide object constancy between traces during
/// animations and transitions.
public var uid: String? = nil
/// Assigns id labels to each datum.
///
/// These ids for object constancy of data points during animation. Should be an array of strings,
/// not numbers or any other type.
public var ids: [String]? = nil
/// Assigns extra data each datum.
///
/// This may be useful when listening to hover, click and selection events. Note that, *scatter*
/// traces also appends customdata items in the markers DOM elements
public var customData: [String]? = nil
/// Assigns extra meta information associated with this trace that can be used in various text
/// attributes.
///
/// Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text`
/// `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the
/// trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the
/// index or key of the `meta` item in question. To access trace `meta` in layout attributes, use
/// `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index.
public var meta: Data<Anything>? = nil
/// Array containing integer indices of selected points.
///
/// Has an effect only for traces that support selections. Note that an empty array means an empty
/// selection where the `unselected` are turned on for all points, whereas, any other non-array
/// values means no selection all where the `selected` and `unselected` styles have no effect.
public var selectedPoints: Anything? = nil
public var hoverLabel: Shared.HoverLabel? = nil
public var stream: Shared.Stream? = nil
public var transforms: [Transform] = []
/// Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords`
/// traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`.
///
/// Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are
/// controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`,
/// `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible
/// with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are
/// tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app
/// can add/remove traces before the end of the `data` array, such that the same trace has a
/// different index, you can still preserve user-driven changes if you give each trace a `uid` that
/// stays with it as it moves.
public var uiRevision: Anything? = nil
/// Sets the radial coordinates
public var r: RData? = nil
/// Sets the angular coordinates
public var theta: ThetaData? = nil
/// Alternate to `r`.
///
/// Builds a linear space of r coordinates. Use with `dr` where `r0` is the starting coordinate and
/// `dr` the step.
public var r0: Anything? = nil
/// Sets the r coordinate step.
public var dr: Double? = nil
/// Alternate to `theta`.
///
/// Builds a linear space of theta coordinates. Use with `dtheta` where `theta0` is the starting
/// coordinate and `dtheta` the step.
public var theta0: Anything? = nil
/// Sets the theta coordinate step.
///
/// By default, the `dtheta` step equals the subplot's period divided by the length of the `r`
/// coordinates.
public var dTheta: Double? = nil
/// Sets the unit of input *theta* values.
///
/// Has an effect only when on *linear* angular axes.
public var thetaUnit: Shared.ThetaUnit? = nil
/// Sets where the bar base is drawn (in radial axis units).
///
/// In *stack* barmode, traces that set *base* will be excluded and drawn in *overlay* mode instead.
public var base: Data<Anything>? = nil
/// Shifts the angular position where the bar is drawn (in *thetatunit* units).
public var offset: Data<Double>? = nil
/// Sets the bar angular width (in *thetaunit* units).
public var width: Data<Double>? = nil
/// Sets hover text elements associated with each bar.
///
/// If a single string, the same string appears over all bars. If an array of string, the items are
/// mapped in order to the this trace's coordinates.
public var text: Data<String>? = nil
/// Same as `text`.
public var hoverText: Data<String>? = nil
public var marker: Shared.Marker? = nil
/// Determines which trace information appear on hover.
///
/// If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set,
/// click and hover events are still fired.
public var hoverInfo: Shared.PolarHoverInfo? = nil
/// Template string used for rendering the information that appear on hover box.
///
/// Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example
/// "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example
/// "Price: %{y:$.2f}".
/// https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_format for details on
/// the formatting syntax. Dates are formatted using d3-time-format's syntax
/// %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}".
/// https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md#format for details on
/// the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as
/// event data described at this link https://plot.ly/javascript/plotlyjs-events/#event-data.
/// Additionally, every attributes that can be specified per-point (the ones that are `arrayOk:
/// true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for
/// example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag
/// `<extra></extra>`.
public var hoverTemplate: Data<String>? = nil
public struct Selected: Encodable {
public struct Marker: Encodable {
/// Sets the marker opacity of selected points.
public var opacity: Double? = nil
/// Sets the marker color of selected points.
public var color: Color? = nil
/// Creates `Marker` object with specified properties.
///
/// - Parameters:
/// - opacity: Sets the marker opacity of selected points.
/// - color: Sets the marker color of selected points.
public init(opacity: Double? = nil, color: Color? = nil) {
self.opacity = opacity
self.color = color
}
}
public var marker: Marker? = nil
public struct TextFont: Encodable {
/// Sets the text font color of selected points.
public var color: Color? = nil
/// Creates `TextFont` object with specified properties.
///
/// - Parameters:
/// - color: Sets the text font color of selected points.
public init(color: Color? = nil) {
self.color = color
}
}
public var textFont: TextFont? = nil
/// Decoding and encoding keys compatible with Plotly schema.
enum CodingKeys: String, CodingKey {
case marker
case textFont = "textfont"
}
/// Creates `Selected` object with specified properties.
public init(marker: Marker? = nil, textFont: TextFont? = nil) {
self.marker = marker
self.textFont = textFont
}
}
public var selected: Selected? = nil
public struct Unselected: Encodable {
public struct Marker: Encodable {
/// Sets the marker opacity of unselected points, applied only when a selection exists.
public var opacity: Double? = nil
/// Sets the marker color of unselected points, applied only when a selection exists.
public var color: Color? = nil
/// Creates `Marker` object with specified properties.
///
/// - Parameters:
/// - opacity: Sets the marker opacity of unselected points, applied only when a selection exists.
/// - color: Sets the marker color of unselected points, applied only when a selection exists.
public init(opacity: Double? = nil, color: Color? = nil) {
self.opacity = opacity
self.color = color
}
}
public var marker: Marker? = nil
public struct TextFont: Encodable {
/// Sets the text font color of unselected points, applied only when a selection exists.
public var color: Color? = nil
/// Creates `TextFont` object with specified properties.
///
/// - Parameters:
/// - color: Sets the text font color of unselected points, applied only when a selection exists.
public init(color: Color? = nil) {
self.color = color
}
}
public var textFont: TextFont? = nil
/// Decoding and encoding keys compatible with Plotly schema.
enum CodingKeys: String, CodingKey {
case marker
case textFont = "textfont"
}
/// Creates `Unselected` object with specified properties.
public init(marker: Marker? = nil, textFont: TextFont? = nil) {
self.marker = marker
self.textFont = textFont
}
}
public var unselected: Unselected? = nil
/// Sets a reference between this trace's data coordinates and a polar subplot.
///
/// If *polar* (the default value), the data refer to `layout.polar`. If *polar2*, the data refer to
/// `layout.polar2`, and so on.
public var subplot: Layout.Polar = Layout.Polar(uid: 1)
/// Decoding and encoding keys compatible with Plotly schema.
enum CodingKeys: String, CodingKey {
case type
case visible
case showLegend = "showlegend"
case legendGroup = "legendgroup"
case opacity
case name
case uid
case ids
case customData = "customdata"
case meta
case selectedPoints = "selectedpoints"
case hoverLabel = "hoverlabel"
case stream
case transforms
case uiRevision = "uirevision"
case r
case theta
case r0
case dr
case theta0
case dTheta = "dtheta"
case thetaUnit = "thetaunit"
case base
case offset
case width
case text
case hoverText = "hovertext"
case marker
case hoverInfo = "hoverinfo"
case hoverTemplate = "hovertemplate"
case selected
case unselected
case subplot
}
/// Creates `BarPolar` object from the most frequently used properties.
///
/// - Parameters:
/// - name: Sets the trace name.
/// - r: Sets the radial coordinates
/// - theta: Sets the angular coordinates
/// - text: Sets hover text elements associated with each bar.
/// - hoverText: Same as `text`.
/// - marker:
public init(name: String? = nil, r: RData? = nil, theta: ThetaData? = nil, text: Data<String>? =
nil, hoverText: Data<String>? = nil, marker: Shared.Marker? = nil) {
self.name = name
self.r = r
self.theta = theta
self.text = text
self.hoverText = hoverText
self.marker = marker
}
/// Creates `BarPolar` object with specified properties.
///
/// - Parameters:
/// - visible: Determines whether or not this trace is visible.
/// - showLegend: Determines whether or not an item corresponding to this trace is shown in the
/// legend.
/// - legendGroup: Sets the legend group for this trace.
/// - opacity: Sets the opacity of the trace.
/// - name: Sets the trace name.
/// - uid: Assign an id to this trace, Use this to provide object constancy between traces during
/// animations and transitions.
/// - ids: Assigns id labels to each datum.
/// - customData: Assigns extra data each datum.
/// - meta: Assigns extra meta information associated with this trace that can be used in various
/// text attributes.
/// - selectedPoints: Array containing integer indices of selected points.
/// - hoverLabel:
/// - stream:
/// - transforms:
/// - uiRevision: Controls persistence of some user-driven changes to the trace: `constraintrange`
/// in `parcoords` traces, as well as some `editable: true` modifications such as `name` and
/// `colorbar.title`.
/// - r: Sets the radial coordinates
/// - theta: Sets the angular coordinates
/// - r0: Alternate to `r`.
/// - dr: Sets the r coordinate step.
/// - theta0: Alternate to `theta`.
/// - dTheta: Sets the theta coordinate step.
/// - thetaUnit: Sets the unit of input *theta* values.
/// - base: Sets where the bar base is drawn (in radial axis units).
/// - offset: Shifts the angular position where the bar is drawn (in *thetatunit* units).
/// - width: Sets the bar angular width (in *thetaunit* units).
/// - text: Sets hover text elements associated with each bar.
/// - hoverText: Same as `text`.
/// - marker:
/// - hoverInfo: Determines which trace information appear on hover.
/// - hoverTemplate: Template string used for rendering the information that appear on hover box.
/// - selected:
/// - unselected:
/// - subplot: Sets a reference between this trace's data coordinates and a polar subplot.
public init(visible: Shared.Visible? = nil, showLegend: Bool? = nil, legendGroup: String? = nil,
opacity: Double? = nil, name: String? = nil, uid: String? = nil, ids: [String]? = nil,
customData: [String]? = nil, meta: Data<Anything>? = nil, selectedPoints: Anything? = nil,
hoverLabel: Shared.HoverLabel? = nil, stream: Shared.Stream? = nil, transforms: [Transform] =
[], uiRevision: Anything? = nil, r: RData? = nil, theta: ThetaData? = nil, r0: Anything? = nil,
dr: Double? = nil, theta0: Anything? = nil, dTheta: Double? = nil, thetaUnit: Shared.ThetaUnit?
= nil, base: Data<Anything>? = nil, offset: Data<Double>? = nil, width: Data<Double>? = nil,
text: Data<String>? = nil, hoverText: Data<String>? = nil, marker: Shared.Marker? = nil,
hoverInfo: Shared.PolarHoverInfo? = nil, hoverTemplate: Data<String>? = nil, selected: Selected?
= nil, unselected: Unselected? = nil, subplot: Layout.Polar = Layout.Polar(uid: 1)) {
self.visible = visible
self.showLegend = showLegend
self.legendGroup = legendGroup
self.opacity = opacity
self.name = name
self.uid = uid
self.ids = ids
self.customData = customData
self.meta = meta
self.selectedPoints = selectedPoints
self.hoverLabel = hoverLabel
self.stream = stream
self.transforms = transforms
self.uiRevision = uiRevision
self.r = r
self.theta = theta
self.r0 = r0
self.dr = dr
self.theta0 = theta0
self.dTheta = dTheta
self.thetaUnit = thetaUnit
self.base = base
self.offset = offset
self.width = width
self.text = text
self.hoverText = hoverText
self.marker = marker
self.hoverInfo = hoverInfo
self.hoverTemplate = hoverTemplate
self.selected = selected
self.unselected = unselected
self.subplot = subplot
}
/// Encodes the object in a format compatible with Plotly.
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(type, forKey: .type)
try container.encodeIfPresent(visible, forKey: .visible)
try container.encodeIfPresent(showLegend, forKey: .showLegend)
try container.encodeIfPresent(legendGroup, forKey: .legendGroup)
try container.encodeIfPresent(opacity, forKey: .opacity)
try container.encodeIfPresent(name, forKey: .name)
try container.encodeIfPresent(uid, forKey: .uid)
try container.encodeIfPresent(ids, forKey: .ids)
try container.encodeIfPresent(customData, forKey: .customData)
try container.encodeIfPresent(meta, forKey: .meta)
try container.encodeIfPresent(selectedPoints, forKey: .selectedPoints)
try container.encodeIfPresent(hoverLabel, forKey: .hoverLabel)
try container.encodeIfPresent(stream, forKey: .stream)
var transformsContainer = container.nestedUnkeyedContainer(forKey: .transforms)
for transform in transforms { try transform.encode(to: transformsContainer.superEncoder()) }
try container.encodeIfPresent(uiRevision, forKey: .uiRevision)
if let r = self.r {
try r.encode(toPlotly: container.superEncoder(forKey: .r))
}
if let theta = self.theta {
try theta.encode(toPlotly: container.superEncoder(forKey: .theta))
}
try container.encodeIfPresent(r0, forKey: .r0)
try container.encodeIfPresent(dr, forKey: .dr)
try container.encodeIfPresent(theta0, forKey: .theta0)
try container.encodeIfPresent(dTheta, forKey: .dTheta)
try container.encodeIfPresent(thetaUnit, forKey: .thetaUnit)
try container.encodeIfPresent(base, forKey: .base)
try container.encodeIfPresent(offset, forKey: .offset)
try container.encodeIfPresent(width, forKey: .width)
try container.encodeIfPresent(text, forKey: .text)
try container.encodeIfPresent(hoverText, forKey: .hoverText)
try container.encodeIfPresent(marker, forKey: .marker)
try container.encodeIfPresent(hoverInfo, forKey: .hoverInfo)
try container.encodeIfPresent(hoverTemplate, forKey: .hoverTemplate)
try container.encodeIfPresent(selected, forKey: .selected)
try container.encodeIfPresent(unselected, forKey: .unselected)
try container.encode("polar\(subplot.uid)", forKey: .subplot)
}
} | 44.250545 | 112 | 0.628625 |
1665bcd4530b0dfe569d8cd293549873a808a42e | 1,562 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/basic.swiftmodule %S/basic.swift
// RUN: %target-swift-frontend -emit-ir -module-name Foo %s -I %t -g -o - | %FileCheck %s
// RUN: %target-swift-frontend -c -module-name Foo %s -I %t -g -o %t.o
// RUN: %llvm-dwarfdump %t.o | %FileCheck --check-prefix=DWARF %s
// CHECK-DAG: ![[FOOMODULE:[0-9]+]] = !DIModule({{.*}}, name: "Foo", includePath: "{{.*}}test{{.*}}DebugInfo{{.*}}"
// CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[THISFILE:[0-9]+]], entity: ![[FOOMODULE]]
// CHECK-DAG: ![[THISFILE]] = !DIFile(filename: "Imports.swift", directory: "{{.*}}test/DebugInfo")
// CHECK-DAG: ![[SWIFTFILE:[0-9]+]] = !DIFile(filename: "Swift.swiftmodule"
// CHECK-DAG: ![[SWIFTMODULE:[0-9]+]] = !DIModule({{.*}}, name: "Swift"
// CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[THISFILE]], entity: ![[SWIFTMODULE]]
// CHECK-DAG: ![[BASICMODULE:[0-9]+]] = !DIModule({{.*}}, name: "basic"
// CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[THISFILE]], entity: ![[BASICMODULE]]
import basic
import typealias Swift.Optional
func markUsed<T>(_ t: T) {}
markUsed(basic.foo(1, 2))
// DWARF: .debug_info
// DWARF: DW_TAG_module
// DWARF: DW_AT_name {{.*}}"Foo"
// DWARF: DW_AT_LLVM_include_path
// DWARF: DW_TAG_module
// DWARF: DW_AT_name {{.*}}"Swift"
// DWARF: DW_AT_LLVM_include_path
// DWARF: DW_TAG_module
// DWARF: DW_AT_name {{.*}}"basic"
// DWARF-NOT: "Swift.Optional"
// DWARF-DAG: file_names{{.*}} Imports.swift
| 44.628571 | 115 | 0.650448 |
717f7788431faa49061d278dc4ef68ed90c07e22 | 829 | //
// String+Extension.swift
// ppp
//
// Created by PixelPlex Developer on 5/28/19.
// Copyright © 2019 PixelPlex. All rights reserved.
//
import Foundation
import CommonCrypto
extension String {
func sha1() -> String {
let data = Data(self.utf8)
var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA1($0, CC_LONG(data.count), &digest)
}
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joined()
}
subscript (bounds: CountableClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: max(0, bounds.lowerBound))
let end = index(startIndex, offsetBy: min(count, min(count, bounds.upperBound)))
return String(self[start...end])
}
}
| 28.586207 | 88 | 0.626055 |
fc4c5dbe2b294ea2d834d82f7e85e4a22adf43dc | 993 | // RUN: %empty-directory(%t)
// RUN: touch %t/file1.swift %t/file2.swift %t/file3.swift
// RUN: echo 'public func main() {}' >%t/main.swift
//
// RUN: %target-swiftc_driver -driver-skip-execution -c -emit-module -module-name main -driver-print-jobs %s -experimental-emit-module-separately %t/file1.swift %t/file2.swift %t/file3.swift %t/main.swift 2>^1 | %FileCheck -check-prefix NORMAL %s
// RUN: %target-swiftc_driver -driver-skip-execution -c -emit-module -module-name main -driver-print-jobs -incremental %s -experimental-emit-module-separately %t/file1.swift %t/file2.swift %t/file3.swift %t/main.swift 2>^1 | %FileCheck -check-prefix INCREMENTAL %s
// Just test that we eat this argument. Only the new driver knows what to do
// here. The legacy driver will just fall back to a merge-modules job as usual.
// NORMAL: swift
// NORMAL-NOT: -experimental-emit-module-separately
// INCREMENTAL: swift
// INCREMENTAL: -merge-modules
// INCREMENTAL-NOT: -experimental-emit-module-separately
| 62.0625 | 264 | 0.738167 |
87265516b5a4f2a9a1e3e141d211b40cc1a22770 | 5,723 | //
// ViewController.swift
// Time Ticker
//
// Created by omrobbie on 27/08/20.
// Copyright © 2020 omrobbie. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var btnGoalTime: NSPopUpButton!
@IBOutlet weak var lblTitle: NSTextField!
@IBOutlet weak var lblRemaining: NSTextField!
@IBOutlet weak var btnInOut: NSButton!
@IBOutlet weak var lblInOut: NSTextField!
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var progressIndicator: NSProgressIndicator!
private var currentPeriod: Period?
private var timer: Timer?
private var periods = [Period]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
btnGoalTime.removeAllItems()
btnGoalTime.addItems(withTitles: titles())
getPeriods()
}
private func titles() -> [String] {
var titles = [String]()
for number in 1...40 {
titles.append("\(number)h")
}
return titles
}
private func updateView() {
let goalTime = btnGoalTime.indexOfSelectedItem + 1
lblTitle.stringValue = "Goal: \(goalTime) Hour\(goalTime == 1 ? "" : "s")"
if currentPeriod == nil {
btnInOut.title = "IN"
lblInOut.isHidden = true
lblInOut.stringValue = ""
} else {
btnInOut.title = "OUT"
lblInOut.isHidden = false
lblInOut.stringValue = "Currently: \(currentPeriod!.currentlyPeriod())"
}
lblRemaining.stringValue = remainingTimeAsString()
let ratio = totalTimeInterval() / goalTimeInterval()
progressIndicator.doubleValue = ratio
}
private func getPeriods() {
if let context = (NSApp.delegate as? AppDelegate)?.persistentContainer.viewContext {
if let name = Period.entity().name {
let fetchRequest = NSFetchRequest<Period>(entityName: name)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "outDate", ascending: false)]
if var periods = try? context.fetch(fetchRequest) {
for i in 0..<periods.count {
let period = periods[i]
if period.outDate == nil {
currentPeriod = period
startTimer()
periods.remove(at: i)
break
}
}
self.periods = periods
}
}
}
tableView.reloadData()
updateView()
}
private func startTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (_) in
self.updateView()
})
}
private func totalTimeInterval() -> TimeInterval {
var time = 0.0
for period in periods {
time += period.time()
}
if let currentPeriod = self.currentPeriod {
time += currentPeriod.time()
}
return time
}
private func goalTimeInterval() -> TimeInterval {
return Double(btnGoalTime.indexOfSelectedItem + 1) * 60 * 60
}
private func remainingTimeAsString() -> String {
let remainingTime = goalTimeInterval() - totalTimeInterval()
if remainingTime <= 0 {
return "Finished! \(Period.stringFromDates(date1: Date(), date2: Date(timeIntervalSinceNow: totalTimeInterval())))"
} else {
return "Remaining: \(Period.stringFromDates(date1: Date(), date2: Date(timeIntervalSinceNow: remainingTime)))"
}
}
@IBAction func btnGoalTimeChanged(_ sender: Any) {
updateView()
}
@IBAction func btnInOutTapped(_ sender: Any) {
if currentPeriod == nil {
// check in
if let context = (NSApp.delegate as? AppDelegate)?.persistentContainer.viewContext {
currentPeriod = Period(context: context)
currentPeriod?.inDate = Date()
}
startTimer()
} else {
// check out
currentPeriod!.outDate = Date()
currentPeriod = nil
timer?.invalidate()
timer = nil
getPeriods()
}
updateView()
(NSApp.delegate as? AppDelegate)?.saveAction(nil)
}
@IBAction func btnResetTapped(_ sender: Any) {
if let context = (NSApp.delegate as? AppDelegate)?.persistentContainer.viewContext {
for period in periods {
context.delete(period)
}
if let currentPeriod = self.currentPeriod {
context.delete(currentPeriod)
self.currentPeriod = nil
}
getPeriods()
}
}
}
extension ViewController: NSTableViewDelegate, NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return periods.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: self) as? PeriodCell
let period = periods[row]
cell?.lblTimeRange.stringValue = "\(period.prettyInDate()) - \(period.prettyOutDate())"
cell?.lblTimeTotal.stringValue = "\(Period.stringFromDates(date1: Date(), date2: Date(timeIntervalSinceNow: period.time())))"
return cell
}
}
class PeriodCell: NSTableCellView {
@IBOutlet weak var lblTimeRange: NSTextField!
@IBOutlet weak var lblTimeTotal: NSTextField!
}
| 30.441489 | 133 | 0.58361 |
3864b03aed08c1fdc6c00ce93aa646dcc255ed69 | 14,047 | //
// General+Config.swift
// TTBaseUIKit
//
// Created by Truong Quang Tuan on 4/11/19.
// Copyright © 2019 Truong Quang Tuan. All rights reserved.
//
import Foundation
import UIKit
public final class Fonts {
static func podFont(name: String, size: CGFloat) -> UIFont {
//Why do extra work if its available.
if let font = UIFont(name: name, size: size) {return font}
let bundle = Bundle(for: Fonts.self) //get the current bundle
var urlBundle:URL?
// For test local
if let url = bundle.url(forResource: name, withExtension: "ttf") {
urlBundle = url
}
// If this framework is added using CocoaPods, resources is placed under a subdirectory
if let url = bundle.url(forResource: name, withExtension: "ttf", subdirectory: "TTBaseUIKit.bundle") {
urlBundle = url
}
if let url = bundle.url(forResource: name, withExtension: "ttf", subdirectory: "Frameworks/TTBaseUIKit.framework") {
urlBundle = url
}
guard let url = urlBundle else { return UIFont() }
guard let data = NSData(contentsOf: url) else { return UIFont() }
guard let provider = CGDataProvider(data: data) else { return UIFont() } //convert the data into a provider
guard let cgFont = CGFont(provider) else { return UIFont() }//convert provider to cgfont
let fontName = cgFont.postScriptName as String? ?? ""//crashes if can't get name
CTFontManagerRegisterGraphicsFont(cgFont, nil) //Registers the font, like the plist
return UIFont(name: fontName, size: size) ?? UIFont()
}
}
extension UIFont {
public static func getFontIcon(ProWithSize size:CGFloat) -> UIFont {
return Fonts.podFont(name: Config.Value.fontImageNamePro, size: size)
}
public static func getFontIcon(FreeWithSize size:CGFloat) -> UIFont {
return Fonts.podFont(name: Config.Value.fontImageNameFree, size: size)
}
}
extension UISegmentedControl {
public func removeBorders(withColor nornal:UIColor, selected:UIColor, hightLight:UIColor) {
setBackgroundImage(imageWithColor(color: nornal), for: .normal, barMetrics: .default)
setBackgroundImage(imageWithColor(color: hightLight), for: .highlighted, barMetrics: .default)
setBackgroundImage(imageWithColor(color: selected), for: .selected, barMetrics: .default)
setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
}
// create a 1x1 image with this color
private func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor);
context!.fill(rect);
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
}
extension UIImage {
/// to rotate root image by degree
///
public static func imageRotatedByDegrees(oldImage: UIImage, deg degrees: CGFloat) -> UIImage {
//Calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox: UIView = UIView(frame: CGRect(x: 0, y: 0, width: oldImage.size.width, height: oldImage.size.height))
let t: CGAffineTransform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi / 180)
rotatedViewBox.transform = t
let rotatedSize: CGSize = rotatedViewBox.frame.size
//Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap: CGContext = UIGraphicsGetCurrentContext()!
//Move the origin to the middle of the image so we will rotate and scale around the center.
bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
//Rotate the image context
bitmap.rotate(by: (degrees * CGFloat.pi / 180))
//Now, draw the rotated/scaled image into the context
bitmap.scaleBy(x: 1.0, y: -1.0)
bitmap.draw(oldImage.cgImage!, in: CGRect(x: -oldImage.size.width / 2, y: -oldImage.size.height / 2, width: oldImage.size.width, height: oldImage.size.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/// to rotate root image by radians
///
public func rotate(radians: CGFloat) -> UIImage {
let rotatedSize = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: CGFloat(radians)))
.integral.size
UIGraphicsBeginImageContext(rotatedSize)
if let context = UIGraphicsGetCurrentContext() {
let origin = CGPoint(x: rotatedSize.width / 2.0,
y: rotatedSize.height / 2.0)
context.translateBy(x: origin.x, y: origin.y)
context.rotate(by: radians)
draw(in: CGRect(x: -origin.y, y: -origin.x,
width: size.width, height: size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rotatedImage ?? self
}
return self
}
public class func resizeImage(_ image: UIImage, newWidth: CGFloat) -> UIImage {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: newHeight), false, UIScreen.main.scale)
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return (newImage ?? UIImage())
}
public static func fontAwesomeIconWithName(nameString: String, size: CGSize, iconColor: UIColor, backgroundColor: UIColor = UIColor.clear) -> UIImage? {
#if targetEnvironment(macCatalyst)
return nil
#else
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = NSTextAlignment.center
if nameString.contains("") { return nil }
// Taken from FontAwesome.io's Fixed Width Icon CSS
let fontAspectRatio: CGFloat = 1.28571429
let fontSize = min(size.width / fontAspectRatio, size.height)
let fontName:UIFont = UIFont.getFontIcon(ProWithSize: fontSize)
let attributedString = NSAttributedString(string: nameString, attributes: [NSAttributedString.Key.font: fontName, NSAttributedString.Key.foregroundColor: iconColor, NSAttributedString.Key.backgroundColor: backgroundColor, NSAttributedString.Key.paragraphStyle: paragraph])
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
attributedString.draw(in: CGRect(x: 0, y: (size.height - fontSize) / 2, width: size.width, height: fontSize))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
#endif
}
public convenience init?(fromTTBaseUIKit name:String) {
let url = Bundle(for: Fonts.self).url(forResource: name, withExtension: "", subdirectory: "TTBaseUIKit.bundle")
self.init(named: url?.path ?? "")
self.accessibilityIdentifier = name
}
public static func noImage() -> UIImage? {
let image = UIImage(fromTTBaseUIKit: Config.Value.noImageName)
image?.accessibilityIdentifier = Config.Value.noImageName
return image
}
public static func logoDef() -> UIImage? {
let image = UIImage(fromTTBaseUIKit: Config.Value.logoDefName)
image?.accessibilityIdentifier = Config.Value.logoDefName
return image
}
public static func noImageOption1() -> UIImage? {
let image = UIImage(fromTTBaseUIKit: "img.NoImage1.png")
image?.accessibilityIdentifier = "img.NoImage1.png"
return image
}
public static func noImageOption2() -> UIImage? {
let image = UIImage(fromTTBaseUIKit: "img.NoImage2.png")
image?.accessibilityIdentifier = "img.NoImage2.png"
return image
}
public func tinted(with color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
color.set()
withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
public func addImagePadding(x: CGFloat, y: CGFloat) -> UIImage? {
let width: CGFloat = size.width + x
let height: CGFloat = size.height + y
UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0)
let origin: CGPoint = CGPoint(x: (width - size.width) / 2, y: (height - size.height) / 2)
draw(at: origin)
let imageWithPadding = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithPadding
}
}
extension UIImageView {
public static func viewNoImage() -> UIImageView {
let imageView:UIImageView = UIImageView()
imageView.image = UIImage(fromTTBaseUIKit: Config.Value.noImageName)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}
}
extension CGFloat {
public static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension CALayer {
public func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
border.name = "BORDER"
switch edge {
case UIRectEdge.top:
border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness)
break
case UIRectEdge.bottom:
border.frame = CGRect(x: 0, y: self.frame.height - thickness, width: self.frame.width, height: thickness)
break
case UIRectEdge.left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.frame.height)
break
case UIRectEdge.right:
border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: self.frame.height)
break
default:
//For Center Line
border.frame = CGRect(x: self.frame.width/2 - thickness, y: 0, width: thickness, height: self.frame.height)
break
}
border.name = "BORDER." + edge.rawValue.description
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
}
//MARK:// NSMutableAttributedString
extension NSMutableAttributedString {
@discardableResult public func addBoldStypeForExistText(_ text: String, textColor:UIColor, systemFontsize:CGFloat) -> NSMutableAttributedString {
guard let substringRange = self.string.range(of: text) else { return self}
let nsRange = NSRange(substringRange, in: self.string)
let attrs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: systemFontsize, weight: .bold), .foregroundColor : textColor]
self.addAttributes(attrs, range: nsRange)
return self
}
@discardableResult public func addStrikethroughStypeForExistText(_ text: String, textColor:UIColor, systemFontsize:CGFloat) -> NSMutableAttributedString{
guard let substringRange = self.string.range(of: text) else { return self}
let nsRange = NSRange(substringRange, in: self.string)
var attrs: [NSAttributedString.Key: Any] = [.strikethroughStyle: NSNumber(integerLiteral: NSUnderlineStyle.single.rawValue)]
attrs[.font] = UIFont.systemFont(ofSize: systemFontsize)
attrs[.foregroundColor] = textColor
self.addAttributes(attrs, range: nsRange)
return self
}
@discardableResult public func textStyle(withText text: String, textColor:UIColor, font:UIFont) -> NSMutableAttributedString {
let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor : textColor]
let boldString = NSMutableAttributedString(string:text, attributes: attrs)
append(boldString)
return self
}
@discardableResult public func bold(_ text: String, textColor:UIColor, systemFontsize:CGFloat) -> NSMutableAttributedString {
let attrs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: systemFontsize, weight: .bold), .foregroundColor : textColor]
let boldString = NSMutableAttributedString(string:text, attributes: attrs)
append(boldString)
return self
}
@discardableResult public func normal(_ text: String, textColor:UIColor, systemFontsize:CGFloat) -> NSMutableAttributedString {
let attrs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: systemFontsize, weight: .regular), .foregroundColor : textColor]
let nomalString = NSMutableAttributedString(string:text, attributes: attrs)
append(nomalString)
return self
}
@discardableResult public func strikethrough(_ text: String, textColor:UIColor, systemFontsize:CGFloat) -> NSMutableAttributedString {
var attrs: [NSAttributedString.Key: Any] = [.strikethroughStyle: NSNumber(integerLiteral: NSUnderlineStyle.single.rawValue)]
attrs[.font] = UIFont.systemFont(ofSize: systemFontsize)
attrs[.foregroundColor] = textColor
let nomalString = NSMutableAttributedString(string:text, attributes: attrs)
append(nomalString)
return self
}
}
| 44.034483 | 284 | 0.661494 |
036396c6019342e287f5559017b76dc8bd198579 | 3,813 | //
// Class10useruserIdattendedAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
import Alamofire
open class Class10useruserIdattendedAPI {
/**
.
- parameter userId: (path) the user's userId
- parameter p: (query) the number of the result page (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getUserAttendedSetlistsGET(userId: String, p: Int? = nil, completion: @escaping ((_ data: SfmSetlists?,_ error: Error?) -> Void)) {
getUserAttendedSetlistsGETWithRequestBuilder(userId: userId, p: p).execute { (response, error) -> Void in
completion(response?.body, error)
}
}
/**
.
- GET /1.0/user/{userId}/attended
- examples: [{contentType=application/json, example={
"setlist" : [ {
"artist" : {
"mbid" : "b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d",
"tmid" : 735610,
"name" : "The Beatles",
"sortName" : "Beatles, The",
"disambiguation" : "John, Paul, George and Ringo",
"url" : "https://www.setlist.fm/setlists/the-beatles-23d6a88b.html"
},
"venue" : {
"city" : { },
"url" : "https://www.setlist.fm/venue/compaq-center-san-jose-ca-usa-6bd6ca6e.html",
"id" : "6bd6ca6e",
"name" : "Compaq Center"
},
"tour" : {
"name" : "North American Tour 1964"
},
"set" : [ {
"name" : "...",
"encore" : 12345,
"song" : [ { }, { } ]
}, {
"name" : "...",
"encore" : 12345,
"song" : [ { }, { } ]
} ],
"info" : "Recorded and published as 'The Beatles at the Hollywood Bowl'",
"url" : "https://www.setlist.fm/setlist/the-beatles/1964/hollywood-bowl-hollywood-ca-63de4613.html",
"id" : "63de4613",
"versionId" : "7be1aaa0",
"eventDate" : "23-08-1964",
"lastUpdated" : "2013-10-20T05:18:08.000+0000"
}, {
"artist" : {
"mbid" : "...",
"tmid" : 12345,
"name" : "...",
"sortName" : "...",
"disambiguation" : "...",
"url" : "..."
},
"venue" : {
"city" : { },
"url" : "...",
"id" : "...",
"name" : "..."
},
"tour" : {
"name" : "..."
},
"set" : [ {
"name" : "...",
"encore" : 12345,
"song" : [ { }, { } ]
}, {
"name" : "...",
"encore" : 12345,
"song" : [ { }, { } ]
} ],
"info" : "...",
"url" : "...",
"id" : "...",
"versionId" : "...",
"eventDate" : "...",
"lastUpdated" : "..."
} ],
"total" : 42,
"page" : 1,
"itemsPerPage" : 20
}}]
- parameter userId: (path) the user's userId
- parameter p: (query) the number of the result page (optional)
- returns: RequestBuilder<SfmSetlists>
*/
open class func getUserAttendedSetlistsGETWithRequestBuilder(userId: String, p: Int? = nil) -> RequestBuilder<SfmSetlists> {
var path = "/1.0/user/{userId}/attended"
let userIdPreEscape = "\(userId)"
let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
path = path.replacingOccurrences(of: "{userId}", with: userIdPostEscape, options: .literal, range: nil)
let URLString = SwaggerClientAPI.basePath + path
let parameters: [String:Any]? = nil
var url = URLComponents(string: URLString)
url?.queryItems = APIHelper.mapValuesToQueryItems([
"p": p?.encodeToJSON()
])
let requestBuilder: RequestBuilder<SfmSetlists>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
}
| 30.261905 | 151 | 0.551796 |
5dd78251e4279850c5a2d3c694cb046d0c227ed7 | 1,521 |
import UIKit
var imageCache = [String: UIImage]()
class CustomImageView: UIImageView {
var lastImgUrlUsedToLoadImage: String?
func loadImage(with urlString: String) {
// set image to nil
self.image = nil
// set lastImgUrlUsedToLoadImage
lastImgUrlUsedToLoadImage = urlString
// check if image exists in cache
if let cachedImage = imageCache[urlString] {
self.image = cachedImage
return
}
// url for image location
guard let url = URL(string: urlString) else { return }
// fetch contents of URL
URLSession.shared.dataTask(with: url) { (data, response, error) in
// handle error
if let error = error {
print("Failed to load image with error", error.localizedDescription)
}
if self.lastImgUrlUsedToLoadImage != url.absoluteString {
return
}
// image data
guard let imageData = data else { return }
// create image using image data
let photoImage = UIImage(data: imageData)
// set key and value for image cache
imageCache[url.absoluteString] = photoImage
// set image
DispatchQueue.main.async {
self.image = photoImage
}
}.resume()
}
}
| 27.160714 | 84 | 0.516765 |
505ed1b0c5c9995b0bc45aa233212d11a8e515e9 | 13,846 | //
// UserAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
open class UserAPI {
/**
Create user
- parameter body: (body) Created user object
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Create user
- POST /user
- This can only be done by the logged in user.
- parameter body: (body) Created user object
- returns: RequestBuilder<Void>
*/
open class func createUserWithRequestBuilder(body: User) -> RequestBuilder<Void> {
let path = "/user"
let URLString = PetstoreClientAPI.basePath + path
let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true)
}
/**
Creates list of users with given input array
- parameter body: (body) List of user object
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Creates list of users with given input array
- POST /user/createWithArray
- parameter body: (body) List of user object
- returns: RequestBuilder<Void>
*/
open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> {
let path = "/user/createWithArray"
let URLString = PetstoreClientAPI.basePath + path
let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true)
}
/**
Creates list of users with given input array
- parameter body: (body) List of user object
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Creates list of users with given input array
- POST /user/createWithList
- parameter body: (body) List of user object
- returns: RequestBuilder<Void>
*/
open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> {
let path = "/user/createWithList"
let URLString = PetstoreClientAPI.basePath + path
let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true)
}
/**
Delete user
- parameter username: (path) The name that needs to be deleted
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Delete user
- DELETE /user/{username}
- This can only be done by the logged in user.
- parameter username: (path) The name that needs to be deleted
- returns: RequestBuilder<Void>
*/
open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder<Void> {
var path = "/user/{username}"
let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String: Any]? = nil
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Get user by user name
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) {
getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Get user by user name
- GET /user/{username}
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- returns: RequestBuilder<User>
*/
open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder<User> {
var path = "/user/{username}"
let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String: Any]? = nil
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Logs user into the system
- parameter username: (query) The user name for login
- parameter password: (query) The password for login in clear text
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) {
loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Logs user into the system
- GET /user/login
- responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)]
- parameter username: (query) The user name for login
- parameter password: (query) The password for login in clear text
- returns: RequestBuilder<String>
*/
open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder<String> {
let path = "/user/login"
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String: Any]? = nil
var url = URLComponents(string: URLString)
url?.queryItems = APIHelper.mapValuesToQueryItems([
"username": username.encodeToJSON(),
"password": password.encodeToJSON()
])
let requestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Logs out current logged in user session
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Logs out current logged in user session
- GET /user/logout
- returns: RequestBuilder<Void>
*/
open class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> {
let path = "/user/logout"
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String: Any]? = nil
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Updated user
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Updated user
- PUT /user/{username}
- This can only be done by the logged in user.
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object
- returns: RequestBuilder<Void>
*/
open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder<Void> {
var path = "/user/{username}"
let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true)
}
}
| 43.404389 | 205 | 0.665896 |
16027d101d73ec498cf4d7109c98b000b0b23ab3 | 5,860 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
#if canImport(AppStoreConnectModels)
import AppStoreConnectModels
import AppStoreConnectSharedCode
#endif
extension AppStoreConnect.AppStoreVersions {
public enum AppStoreVersionsRoutingAppCoverageGetToOneRelated {
public static let service = APIService<Response>(
id: "appStoreVersions-routingAppCoverage-get_to_one_related", tag: "AppStoreVersions",
method: "GET", path: "/v1/appStoreVersions/{id}/routingAppCoverage", hasBody: false,
securityRequirement: SecurityRequirement(type: "itc-bearer-token", scopes: []))
/** the fields to include for returned resources of type routingAppCoverages */
public enum ASCFieldsroutingAppCoverages: String, Codable, Equatable, CaseIterable {
case appStoreVersion = "appStoreVersion"
case assetDeliveryState = "assetDeliveryState"
case fileName = "fileName"
case fileSize = "fileSize"
case sourceFileChecksum = "sourceFileChecksum"
case uploadOperations = "uploadOperations"
case uploaded = "uploaded"
}
public final class Request: APIRequest<Response> {
public struct Options {
/** the id of the requested resource */
public var id: String
/** the fields to include for returned resources of type routingAppCoverages */
public var fieldsroutingAppCoverages: [ASCFieldsroutingAppCoverages]?
public init(id: String, fieldsroutingAppCoverages: [ASCFieldsroutingAppCoverages]? = nil) {
self.id = id
self.fieldsroutingAppCoverages = fieldsroutingAppCoverages
}
}
public var options: Options
public init(options: Options) {
self.options = options
super.init(service: AppStoreVersionsRoutingAppCoverageGetToOneRelated.service)
}
/// convenience initialiser so an Option doesn't have to be created
public convenience init(
id: String, fieldsroutingAppCoverages: [ASCFieldsroutingAppCoverages]? = nil
) {
let options = Options(id: id, fieldsroutingAppCoverages: fieldsroutingAppCoverages)
self.init(options: options)
}
public override var path: String {
return super.path.replacingOccurrences(of: "{" + "id" + "}", with: "\(self.options.id)")
}
public override var queryParameters: [String: Any] {
var params: [String: Any] = [:]
if let fieldsroutingAppCoverages = options.fieldsroutingAppCoverages?.encode().map({
String(describing: $0)
}).joined(separator: ",") {
params["fields[routingAppCoverages]"] = fieldsroutingAppCoverages
}
return params
}
}
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
public typealias SuccessType = ASCRoutingAppCoverageResponse
/** Related resource */
case status200(ASCRoutingAppCoverageResponse)
/** Parameter error(s) */
case status400(ASCErrorResponse)
/** Forbidden error */
case status403(ASCErrorResponse)
/** Not found error */
case status404(ASCErrorResponse)
public var success: ASCRoutingAppCoverageResponse? {
switch self {
case .status200(let response): return response
default: return nil
}
}
public var failure: ASCErrorResponse? {
switch self {
case .status400(let response): return response
case .status403(let response): return response
case .status404(let response): return response
default: return nil
}
}
/// either success or failure value. Success is anything in the 200..<300 status code range
public var responseResult: APIResponseResult<ASCRoutingAppCoverageResponse, ASCErrorResponse>
{
if let successValue = success {
return .success(successValue)
} else if let failureValue = failure {
return .failure(failureValue)
} else {
fatalError("Response does not have success or failure response")
}
}
public var response: Any {
switch self {
case .status200(let response): return response
case .status400(let response): return response
case .status403(let response): return response
case .status404(let response): return response
}
}
public var statusCode: Int {
switch self {
case .status200: return 200
case .status400: return 400
case .status403: return 403
case .status404: return 404
}
}
public var successful: Bool {
switch self {
case .status200: return true
case .status400: return false
case .status403: return false
case .status404: return false
}
}
public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws {
switch statusCode {
case 200:
self = try .status200(decoder.decode(ASCRoutingAppCoverageResponse.self, from: data))
case 400: self = try .status400(decoder.decode(ASCErrorResponse.self, from: data))
case 403: self = try .status403(decoder.decode(ASCErrorResponse.self, from: data))
case 404: self = try .status404(decoder.decode(ASCErrorResponse.self, from: data))
default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data)
}
}
public var description: String {
return "\(statusCode) \(successful ? "success" : "failure")"
}
public var debugDescription: String {
var string = description
let responseString = "\(response)"
if responseString != "()" {
string += "\n\(responseString)"
}
return string
}
}
}
}
| 33.485714 | 99 | 0.656485 |
e09b894cf1e70ad760e1175bb040907eb4f2ab31 | 430 | //
// DoesEmailExist.swift
// Pods
//
// Created by Timmy Nguyen on 2/16/18.
//
//
import Foundation
import ObjectMapper
public class DoesEmailExist: BaseApiResponseModel {
public var emailExists: Bool?
required public init?(map: Map){
super.init(map: map)
}
override public func mapping(map: Map) {
super.mapping(map: map)
emailExists <- map["emailExists"]
}
}
| 17.2 | 51 | 0.618605 |
62807eaa77d0a72ca44a903266f773db8ecb3f52 | 14,188 | // RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -enable-experimental-concurrency | %FileCheck --enable-var-scope %s
// REQUIRES: concurrency
actor MyActor {
private var p: Int
// CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC6calleeyySiYaF : $@convention(method) @async (Int, @guaranteed MyActor) -> () {
// CHECK-NOT: hop_to_executor
// CHECK: } // end sil function '$s4test7MyActorC6calleeyySiYaF'
nonisolated func callee(_ x: Int) async {
print(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC14throwingCalleeyySiYaKF : $@convention(method) @async (Int, @guaranteed MyActor) -> @error Error {
// CHECK-NOT: hop_to_executor{{ }}
// CHECK: } // end sil function '$s4test7MyActorC14throwingCalleeyySiYaKF'
nonisolated func throwingCallee(_ x: Int) async throws {
print(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC0A13AsyncFunctionyyYaKF : $@convention(method) @async (@guaranteed MyActor) -> @error Error {
// CHECK: hop_to_executor %0 : $MyActor
// CHECK: = apply {{.*}} : $@convention(method) @async (Int, @guaranteed MyActor) -> ()
// CHECK-NEXT: hop_to_executor %0 : $MyActor
// CHECK: try_apply {{.*}}, normal bb1, error bb2
// CHECK: bb1({{.*}}):
// CHECK-NEXT: hop_to_executor %0 : $MyActor
// CHECK: bb2({{.*}}):
// CHECK-NEXT: hop_to_executor %0 : $MyActor
// CHECK: } // end sil function '$s4test7MyActorC0A13AsyncFunctionyyYaKF'
func testAsyncFunction() async throws {
await callee(p)
try await throwingCallee(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC0A22ConsumingAsyncFunctionyyYaF : $@convention(method) @async (@owned MyActor) -> () {
// CHECK: [[BORROWED_SELF:%[0-9]+]] = begin_borrow %0 : $MyActor
// CHECK: hop_to_executor [[BORROWED_SELF]] : $MyActor
// CHECK: = apply {{.*}} : $@convention(method) @async (Int, @guaranteed MyActor) -> ()
// CHECK-NEXT: hop_to_executor [[BORROWED_SELF]] : $MyActor
// CHECK: } // end sil function '$s4test7MyActorC0A22ConsumingAsyncFunctionyyYaF'
__consuming func testConsumingAsyncFunction() async {
await callee(p)
}
// CHECK-LABEL: sil private [ossa] @$s4test7MyActorC0A7ClosureSiyYaFSiyYaXEfU_ : $@convention(thin) @async (@guaranteed MyActor) -> Int {
// CHECK: [[COPIED_SELF:%[0-9]+]] = copy_value %0 : $MyActor
// CHECK: [[BORROWED_SELF:%[0-9]+]] = begin_borrow [[COPIED_SELF]] : $MyActor
// CHECK: hop_to_executor [[BORROWED_SELF]] : $MyActor
// CHECK: = apply
// CHECK: } // end sil function '$s4test7MyActorC0A7ClosureSiyYaFSiyYaXEfU_'
func testClosure() async -> Int {
return await { () async in p }()
}
// CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC13dontInsertHTESiyF : $@convention(method) (@guaranteed MyActor) -> Int {
// CHECK-NOT: hop_to_executor
// CHECK: } // end sil function '$s4test7MyActorC13dontInsertHTESiyF'
func dontInsertHTE() -> Int {
return p
}
init() {
p = 27
}
}
@globalActor
struct GlobalActor {
static var shared: MyActor = MyActor()
}
// CHECK-LABEL: sil hidden [ossa] @$s4test0A11GlobalActoryyYaF : $@convention(thin) @async () -> () {
// CHECK: [[F:%[0-9]+]] = function_ref @$s4test11GlobalActorV6sharedAA02MyC0Cvau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: [[P:%[0-9]+]] = apply [[F]]() : $@convention(thin) () -> Builtin.RawPointer
// CHECK: [[A:%[0-9]+]] = pointer_to_address %2 : $Builtin.RawPointer to [strict] $*MyActor
// CHECK: [[ACC:%[0-9]+]] = begin_access [read] [dynamic] [[A]] : $*MyActor
// CHECK: [[L:%[0-9]+]] = load [copy] [[ACC]] : $*MyActor
// CHECK: [[B:%[0-9]+]] = begin_borrow [[L]] : $MyActor
// CHECK: hop_to_executor [[B]] : $MyActor
// CHECK: } // end sil function '$s4test0A11GlobalActoryyYaF'
@GlobalActor
func testGlobalActor() async {
}
// CHECK-LABEL: sil private [ossa] @$s4test0A22GlobalActorWithClosureyyYaFyyYaXEfU_ : $@convention(thin) @async () -> () {
// CHECK: [[F:%[0-9]+]] = function_ref @$s4test11GlobalActorV6sharedAA02MyC0Cvau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: [[P:%[0-9]+]] = apply [[F]]() : $@convention(thin) () -> Builtin.RawPointer
// CHECK: [[A:%[0-9]+]] = pointer_to_address %2 : $Builtin.RawPointer to [strict] $*MyActor
// CHECK: [[ACC:%[0-9]+]] = begin_access [read] [dynamic] [[A]] : $*MyActor
// CHECK: [[L:%[0-9]+]] = load [copy] [[ACC]] : $*MyActor
// CHECK: [[B:%[0-9]+]] = begin_borrow [[L]] : $MyActor
// CHECK: hop_to_executor [[B]] : $MyActor
// CHECK: } // end sil function '$s4test0A22GlobalActorWithClosureyyYaFyyYaXEfU_'
@GlobalActor
func testGlobalActorWithClosure() async {
await { () async in }()
}
@globalActor
struct GenericGlobalActorWithGetter<T> {
static var shared: MyActor { return MyActor() }
}
// CHECK-LABEL: sil hidden [ossa] @$s4test0A28GenericGlobalActorWithGetteryyYaF : $@convention(thin) @async () -> () {
// CHECK: [[MT:%[0-9]+]] = metatype $@thin GenericGlobalActorWithGetter<Int>.Type
// CHECK: [[F:%[0-9]+]] = function_ref @$s4test28GenericGlobalActorWithGetterV6sharedAA02MyD0CvgZ : $@convention(method) <τ_0_0> (@thin GenericGlobalActorWithGetter<τ_0_0>.Type) -> @owned MyActor
// CHECK: [[A:%[0-9]+]] = apply [[F]]<Int>([[MT]]) : $@convention(method) <τ_0_0> (@thin GenericGlobalActorWithGetter<τ_0_0>.Type) -> @owned MyActor
// CHECK: [[B:%[0-9]+]] = begin_borrow [[A]] : $MyActor
// CHECK: hop_to_executor [[B]] : $MyActor
// CHECK: } // end sil function '$s4test0A28GenericGlobalActorWithGetteryyYaF'
@GenericGlobalActorWithGetter<Int>
func testGenericGlobalActorWithGetter() async {
}
actor RedActorImpl {
// CHECK-LABEL: sil hidden [ossa] @$s4test12RedActorImplC5helloyySiF : $@convention(method) (Int, @guaranteed RedActorImpl) -> () {
// CHECK-NOT: hop_to_executor
// CHECK: } // end sil function '$s4test12RedActorImplC5helloyySiF'
func hello(_ x : Int) {}
}
actor BlueActorImpl {
// CHECK-LABEL: sil hidden [ossa] @$s4test13BlueActorImplC4poke6personyAA03RedcD0C_tYaF : $@convention(method) @async (@guaranteed RedActorImpl, @guaranteed BlueActorImpl) -> () {
// CHECK: bb0([[RED:%[0-9]+]] : @guaranteed $RedActorImpl, [[BLUE:%[0-9]+]] : @guaranteed $BlueActorImpl):
// CHECK: hop_to_executor [[BLUE]] : $BlueActorImpl
// CHECK-NOT: hop_to_executor
// CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK-NOT: hop_to_executor
// CHECK: [[METH:%[0-9]+]] = class_method [[RED]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> ()
// CHECK: hop_to_executor [[RED]] : $RedActorImpl
// CHECK-NEXT: {{%[0-9]+}} = apply [[METH]]([[INTARG]], [[RED]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> ()
// CHECK-NEXT: hop_to_executor [[BLUE]] : $BlueActorImpl
// CHECK-NOT: hop_to_executor
// CHECK: } // end sil function '$s4test13BlueActorImplC4poke6personyAA03RedcD0C_tYaF'
func poke(person red : RedActorImpl) async {
await red.hello(42)
}
// CHECK-LABEL: sil hidden [ossa] @$s4test13BlueActorImplC14createAndGreetyyYaF : $@convention(method) @async (@guaranteed BlueActorImpl) -> () {
// CHECK: bb0([[BLUE:%[0-9]+]] : @guaranteed $BlueActorImpl):
// CHECK: hop_to_executor [[BLUE]] : $BlueActorImpl
// CHECK: [[RED:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}) : $@convention(method) (@thick RedActorImpl.Type) -> @owned RedActorImpl
// CHECK: [[REDBORROW:%[0-9]+]] = begin_borrow [[RED]] : $RedActorImpl
// CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[METH:%[0-9]+]] = class_method [[REDBORROW]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> ()
// CHECK: hop_to_executor [[REDBORROW]] : $RedActorImpl
// CHECK-NEXT: = apply [[METH]]([[INTARG]], [[REDBORROW]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> ()
// CHECK-NEXT: hop_to_executor [[BLUE]] : $BlueActorImpl
// CHECK: end_borrow [[REDBORROW]] : $RedActorImpl
// CHECK: destroy_value [[RED]] : $RedActorImpl
// CHECK: } // end sil function '$s4test13BlueActorImplC14createAndGreetyyYaF'
func createAndGreet() async {
let red = RedActorImpl() // <- key difference from `poke` is local construction of the actor
await red.hello(42)
}
}
@globalActor
struct RedActor {
static var shared: RedActorImpl { RedActorImpl() }
}
@globalActor
struct BlueActor {
static var shared: BlueActorImpl { BlueActorImpl() }
}
// CHECK-LABEL: sil hidden [ossa] @$s4test5redFnyySiF : $@convention(thin) (Int) -> () {
// CHECK-NOT: hop_to_executor{{ }}
// CHECK: } // end sil function '$s4test5redFnyySiF'
@RedActor func redFn(_ x : Int) {}
// CHECK-LABEL: sil hidden [ossa] @$s4test6blueFnyyYaF : $@convention(thin) @async () -> () {
// ---- switch to blue actor, since we're an async function ----
// CHECK: [[MT:%[0-9]+]] = metatype $@thin BlueActor.Type
// CHECK: [[F:%[0-9]+]] = function_ref @$s4test9BlueActorV6sharedAA0bC4ImplCvgZ : $@convention(method) (@thin BlueActor.Type) -> @owned BlueActorImpl
// CHECK: [[B:%[0-9]+]] = apply [[F]]([[MT]]) : $@convention(method) (@thin BlueActor.Type) -> @owned BlueActorImpl
// CHECK: [[BLUEEXE:%[0-9]+]] = begin_borrow [[B]] : $BlueActorImpl
// CHECK: hop_to_executor [[BLUEEXE]] : $BlueActorImpl
// ---- evaluate the argument to redFn ----
// CHECK: [[LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 100
// CHECK: [[INTMT:%[0-9]+]] = metatype $@thin Int.Type
// CHECK: [[CTOR:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[ARG:%[0-9]+]] = apply [[CTOR]]([[LIT]], [[INTMT]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// ---- prepare to invoke redFn ----
// CHECK: [[CALLEE:%[0-9]+]] = function_ref @$s4test5redFnyySiF : $@convention(thin) (Int) -> ()
// ---- obtain and hop to RedActor's executor ----
// CHECK: [[REDMT:%[0-9]+]] = metatype $@thin RedActor.Type
// CHECK: [[GETTER:%[0-9]+]] = function_ref @$s4test8RedActorV6sharedAA0bC4ImplCvgZ : $@convention(method) (@thin RedActor.Type) -> @owned RedActorImpl
// CHECK: [[R:%[0-9]+]] = apply [[GETTER]]([[REDMT]]) : $@convention(method) (@thin RedActor.Type) -> @owned RedActorImpl
// CHECK: [[REDEXE:%[0-9]+]] = begin_borrow [[R]] : $RedActorImpl
// CHECK: hop_to_executor [[REDEXE]] : $RedActorImpl
// ---- now invoke redFn, hop back to Blue, and clean-up ----
// CHECK-NEXT: {{%[0-9]+}} = apply [[CALLEE]]([[ARG]]) : $@convention(thin) (Int) -> ()
// CHECK-NEXT: hop_to_executor [[BLUEEXE]] : $BlueActorImpl
// CHECK: end_borrow [[REDEXE]] : $RedActorImpl
// CHECK: destroy_value [[R]] : $RedActorImpl
// CHECK: end_borrow [[BLUEEXE]] : $BlueActorImpl
// CHECK: destroy_value [[B]] : $BlueActorImpl
// CHECK-NOT: hop_to_executor
// CHECK: } // end sil function '$s4test6blueFnyyYaF'
@BlueActor func blueFn() async {
await redFn(100)
}
// CHECK-LABEL: sil hidden [ossa] @$s4test20unspecifiedAsyncFuncyyYaF : $@convention(thin) @async () -> () {
// CHECK-NOT: hop_to_executor
// CHECK: [[BORROW:%[0-9]+]] = begin_borrow {{%[0-9]+}} : $RedActorImpl
// CHECK-NEXT: [[PREV_EXEC:%.*]] = builtin "getCurrentExecutor"()
// CHECK-NEXT: hop_to_executor [[BORROW]] : $RedActorImpl
// CHECK-NEXT: {{%[0-9]+}} = apply {{%[0-9]+}}({{%[0-9]+}}) : $@convention(thin) (Int) -> ()
// CHECK-NEXT: hop_to_executor [[PREV_EXEC]]
// CHECK-NEXT: end_borrow [[BORROW]] : $RedActorImpl
// CHECK-NOT: hop_to_executor
// CHECK: } // end sil function '$s4test20unspecifiedAsyncFuncyyYaF'
func unspecifiedAsyncFunc() async {
await redFn(200)
}
// CHECK-LABEL: sil hidden [ossa] @$s4test27anotherUnspecifiedAsyncFuncyyAA12RedActorImplCYaF : $@convention(thin) @async (@guaranteed RedActorImpl) -> () {
// CHECK: bb0([[RED:%[0-9]+]] : @guaranteed $RedActorImpl):
// CHECK-NOT: hop_to_executor
// CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK-NOT: hop_to_executor
// CHECK: [[METH:%[0-9]+]] = class_method [[RED]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> ()
// CHECK-NEXT: [[PREV_EXEC:%.*]] = builtin "getCurrentExecutor"()
// CHECK-NEXT: hop_to_executor [[RED]] : $RedActorImpl
// CHECK-NEXT: {{%[0-9]+}} = apply [[METH]]([[INTARG]], [[RED]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> ()
// CHECK-NEXT: hop_to_executor [[PREV_EXEC]]
// CHECK: } // end sil function '$s4test27anotherUnspecifiedAsyncFuncyyAA12RedActorImplCYaF'
func anotherUnspecifiedAsyncFunc(_ red : RedActorImpl) async {
await red.hello(12);
}
// CHECK-LABEL: sil hidden [ossa] @$s4test0A20GlobalActorFuncValueyyyyXEYaF
// CHECK: function_ref @$s4test8RedActorV6sharedAA0bC4ImplCvgZ
// CHECK: hop_to_executor [[RED:%[0-9]+]] : $RedActorImpl
// CHECK-NEXT: apply
// CHECK-NEXT: hop_to_executor [[PREV:%[0-9]+]] : $Optional<Builtin.Executor>
func testGlobalActorFuncValue(_ fn: @RedActor () -> Void) async {
await fn()
}
func acceptAsyncSendableClosureInheriting<T>(@_inheritActorContext _: @Sendable () async -> T) { }
extension MyActor {
func synchronous() { }
// CHECK-LABEL: sil private [ossa] @$s4test7MyActorC0A10InheritingyyFyyYaYbXEfU_
// CHECK: debug_value [[SELF:%[0-9]+]] : $MyActor
// CHECK-NEXT: [[COPY:%[0-9]+]] = copy_value [[SELF]] : $MyActor
// CHECK-NEXT: [[BORROW:%[0-9]+]] = begin_borrow [[COPY]] : $MyActor
// CHECK-NEXT: hop_to_executor [[BORROW]] : $MyActor
func testInheriting() {
acceptAsyncSendableClosureInheriting {
synchronous()
}
}
}
| 53.539623 | 199 | 0.639977 |
62a05b9fb9428226402c9a03ceac8e7ef73edb12 | 227 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol b{func a<i:H}struct B<T where h:d{typealias f=a.c | 45.4 | 87 | 0.76652 |
3937594744b80db69c3e75172154a9e2d88c7cfd | 3,456 | //
// AuthenticationViewController.swift
// HeyBeach
//
import UIKit
protocol AuthenticationViewControllerIn {
func handleSignUpSuccess()
func displaySignUpErrorMessage(_ viewModel: AuthenticationModel.SignUp.ViewModel.Failure)
func handleSignInSuccess()
func displaySignInErrorMessage(_ viewModel: AuthenticationModel.SignIn.ViewModel.Failure)
}
protocol AuthenticationViewControllerOut {
func signUp(_ request: AuthenticationModel.SignUp.Request)
func signIn(_ request: AuthenticationModel.SignIn.Request)
}
class AuthenticationViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var textField_email: UITextField!
@IBOutlet weak var textField_password: UITextField!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
// MARK: - Properties
var output: AuthenticationViewControllerOut?
private let configurator = AuthenticationConfigurator()
// MARK: - UIViewController
override func awakeFromNib() {
super.awakeFromNib()
configurator.configure(viewController: self)
}
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Actions
@IBAction func tapped_on_main_view(_ sender: Any) {
self.view.endEditing(true)
}
@IBAction func button_signIn_touchUpInside(_ sender: Any) {
guard let email = textField_email.text, email != "", let password = textField_password.text, password != "" else { return }
activityIndicator.isHidden = false
let request = AuthenticationModel.SignIn.Request(email: email, password: password)
output?.signIn(request)
}
@IBAction func button_signUp_touchUpInside(_ sender: Any) {
guard let email = textField_email.text, email != "", let password = textField_password.text, password != "" else { return }
activityIndicator.isHidden = false
let request = AuthenticationModel.SignUp.Request(email: email, password: password)
output?.signUp(request)
}
}
// MARK: - AuthenticationViewControllerIn
extension AuthenticationViewController: AuthenticationViewControllerIn {
func handleSignUpSuccess() {
activityIndicator.isHidden = true
performSegue(withIdentifier: "Authentication-TabBar-Segue", sender: self)
}
func displaySignUpErrorMessage(_ viewModel: AuthenticationModel.SignUp.ViewModel.Failure) {
activityIndicator.isHidden = true
let alertController = UIAlertController(title: "", message: viewModel.message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
func handleSignInSuccess() {
activityIndicator.isHidden = true
performSegue(withIdentifier: "Authentication-TabBar-Segue", sender: self)
}
func displaySignInErrorMessage(_ viewModel: AuthenticationModel.SignIn.ViewModel.Failure) {
activityIndicator.isHidden = true
let alertController = UIAlertController(title: "", message: viewModel.message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
| 37.978022 | 131 | 0.712095 |
147f300207c0ae89ca0619ed61be5c53ed8212cc | 549 | // B0RN BKLYN Inc.
// PROJECT: CheeseVapor
//
// Copyright © 2019 JESSICA JEAN JOSEPH. All rights reserved.
// MIT License
import Vapor
/// Creates an instance of `Application`. This is called from `main.swift` in the run target.
public func app(_ env: Environment) throws -> Application {
var config = Config.default()
var env = env
var services = Services.default()
try configure(&config, &env, &services)
let app = try Application(config: config, environment: env, services: services)
try boot(app)
return app
}
| 28.894737 | 93 | 0.690346 |
cccb5748dc06a3fd7f76f4e54fc3b883ab36a4e7 | 283 | //
// AlarmTime.swift
// ClockApp
//
// Created by BS-272 on 9/2/21.
//
import Foundation
struct AlarmTime: Identifiable {
let id: String = "alarm"
var minute: String = ""
var hour: String = ""
var meridium: String = ""
var weekdays : [Bool] = []
}
| 15.722222 | 34 | 0.568905 |
f55aaa216cca25c8b641487e778b475b8af71bf3 | 512 | //
// AppDelegate.swift
// scenekitterraingeneration
//
// Created by Zach Eriksen on 12/12/18.
// Copyright © 2018 ol. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 18.962963 | 71 | 0.716797 |
48aef2b7ea94f47357ae5069427a12ba1ae540c3 | 2,776 | //
// HScrollViewController.swift
// WeiBo-SwiftUI
//
// Created by MGBook on 2020/4/28.
// Copyright © 2020 MGBook. All rights reserved.
//
import SwiftUI
struct HScrollViewController<Content: View>: UIViewControllerRepresentable {
let pageWidth: CGFloat
let contentSize: CGSize
let content: Content //scrollView上的东西
@Binding var leftPercent: CGFloat
init(pageWidth: CGFloat, contentSize: CGSize, leftPercent: Binding<CGFloat>, @ViewBuilder content: () -> Content) {
self.pageWidth = pageWidth
self.contentSize = contentSize
self._leftPercent = leftPercent
self.content = content()
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
// 创建UIViewController
func makeUIViewController(context: Context) -> UIViewController {
let scrollView = UIScrollView()
scrollView.bounces = false
scrollView.isPagingEnabled = true
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = context.coordinator
context.coordinator.scrollView = scrollView
let vc = UIViewController()
vc.view.addSubview(scrollView)
// 把content 内容添加到scrollView上,SwiftUI的view添加到 UIKit的view上来,转一下,桥接
let host = UIHostingController(rootView: content)
vc.addChild(host)
scrollView.addSubview(host.view)
host.didMove(toParent: vc) //告诉host已经添加到vc上来了
context.coordinator.host = host
return vc
}
// 更新
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
// 取出来
let scrollView = context.coordinator.scrollView!
scrollView.frame = CGRect(x: 0, y: 0, width: pageWidth, height: contentSize.height)
scrollView.contentSize = contentSize
// 当前滑动到什么地方
scrollView.setContentOffset(CGPoint(x: leftPercent * (contentSize.width - pageWidth), y: 0), animated: true)
context.coordinator.host.view.frame = CGRect(origin: .zero, size: contentSize)
}
class Coordinator: NSObject, UIScrollViewDelegate {
// 添加一些会用到的属性
let parent: HScrollViewController
var scrollView: UIScrollView! //! 否则初始化必须传参数
var host: UIHostingController<Content>!
init(_ parent: HScrollViewController) {
self.parent = parent
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// 更新绑定值,拖拽之后,改变view
withAnimation {
parent.leftPercent = scrollView.contentOffset.x < parent.pageWidth * 0.5 ? 0 : 1
}
// print("--- End")
}
}
}
| 33.853659 | 120 | 0.645893 |
641c0a5445551ee67e44001225702eae1fe14488 | 383 | //
// Panel.swift
// InAppBrowser
//
// Created by Watanabe Toshinori on 2020/05/01.
// Copyright © 2020 Watanabe Toshinori. All rights reserved.
//
import Foundation
struct Panel: Identifiable {
enum PanelType {
case alert(() -> Void)
case confirm((Bool) -> Void)
}
var id = UUID().uuidString
let message: String
let type: PanelType
}
| 15.32 | 61 | 0.626632 |
75ccdac942bbce377c658be8ef9341a2a595f115 | 7,099 | // Generated from /Users/luizfernandosilva/Documents/Projetos/objcgrammar/two-step-processing/ObjectiveCPreprocessorParser.g4 by ANTLR 4.9.1
import Antlr4
/**
* This interface defines a complete generic visitor for a parse tree produced
* by {@link ObjectiveCPreprocessorParser}.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
open class ObjectiveCPreprocessorParserVisitor<T>: ParseTreeVisitor<T> {
/**
* Visit a parse tree produced by {@link ObjectiveCPreprocessorParser#objectiveCDocument}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitObjectiveCDocument(_ ctx: ObjectiveCPreprocessorParser.ObjectiveCDocumentContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by {@link ObjectiveCPreprocessorParser#text}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitText(_ ctx: ObjectiveCPreprocessorParser.TextContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by {@link ObjectiveCPreprocessorParser#code}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitCode(_ ctx: ObjectiveCPreprocessorParser.CodeContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorImport}
* labeled alternative in {@link ObjectiveCPreprocessorParser#directive}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorImport(_ ctx: ObjectiveCPreprocessorParser.PreprocessorImportContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorConditional}
* labeled alternative in {@link ObjectiveCPreprocessorParser#directive}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorConditional(_ ctx: ObjectiveCPreprocessorParser.PreprocessorConditionalContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorDef}
* labeled alternative in {@link ObjectiveCPreprocessorParser#directive}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorDef(_ ctx: ObjectiveCPreprocessorParser.PreprocessorDefContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorPragma}
* labeled alternative in {@link ObjectiveCPreprocessorParser#directive}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorPragma(_ ctx: ObjectiveCPreprocessorParser.PreprocessorPragmaContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorError}
* labeled alternative in {@link ObjectiveCPreprocessorParser#directive}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorError(_ ctx: ObjectiveCPreprocessorParser.PreprocessorErrorContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorWarning}
* labeled alternative in {@link ObjectiveCPreprocessorParser#directive}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorWarning(_ ctx: ObjectiveCPreprocessorParser.PreprocessorWarningContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorDefine}
* labeled alternative in {@link ObjectiveCPreprocessorParser#directive}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorDefine(_ ctx: ObjectiveCPreprocessorParser.PreprocessorDefineContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by {@link ObjectiveCPreprocessorParser#directive_text}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitDirective_text(_ ctx: ObjectiveCPreprocessorParser.Directive_textContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by {@link ObjectiveCPreprocessorParser#path_directive}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPath_directive(_ ctx: ObjectiveCPreprocessorParser.Path_directiveContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorParenthesis}
* labeled alternative in {@link ObjectiveCPreprocessorParser#preprocessor_expression}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorParenthesis(_ ctx: ObjectiveCPreprocessorParser.PreprocessorParenthesisContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorNot}
* labeled alternative in {@link ObjectiveCPreprocessorParser#preprocessor_expression}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorNot(_ ctx: ObjectiveCPreprocessorParser.PreprocessorNotContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorBinary}
* labeled alternative in {@link ObjectiveCPreprocessorParser#preprocessor_expression}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorBinary(_ ctx: ObjectiveCPreprocessorParser.PreprocessorBinaryContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorConstant}
* labeled alternative in {@link ObjectiveCPreprocessorParser#preprocessor_expression}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorConstant(_ ctx: ObjectiveCPreprocessorParser.PreprocessorConstantContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorConditionalSymbol}
* labeled alternative in {@link ObjectiveCPreprocessorParser#preprocessor_expression}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorConditionalSymbol(_ ctx: ObjectiveCPreprocessorParser.PreprocessorConditionalSymbolContext) -> T {
fatalError(#function + " must be overridden")
}
/**
* Visit a parse tree produced by the {@code preprocessorDefined}
* labeled alternative in {@link ObjectiveCPreprocessorParser#preprocessor_expression}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitPreprocessorDefined(_ ctx: ObjectiveCPreprocessorParser.PreprocessorDefinedContext) -> T {
fatalError(#function + " must be overridden")
}
} | 34.629268 | 140 | 0.746021 |
ef10dc38f183d04bbb3b53b32dc2434f606956ba | 1,602 | //
// PersonCell.swift
// AAShare
//
// Created by Chen Tom on 24/01/2017.
// Copyright © 2017 Chen Zheng. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
import Realm
import RealmSwift
class PersonCell: BaseTableViewCell {
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var selectImageView: UIImageView!
var person: Person!
var realm: Realm!
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target:self, action:#selector(imageTapped))
selectImageView.isUserInteractionEnabled = true
selectImageView.addGestureRecognizer(tap)
}
@objc private func imageTapped() {
try! realm.write {
self.person.selected = !self.person.selected
}
updateImageView(select: self.person.selected)
}
private func updateImageView(select: Bool) {
let name = select ? "radio_select" : "radio_unselect"
selectImageView.image = UIImage(named: name)
}
func updateUi( person: Person, canSelect: Bool) {
self.person = person
nameLabel.text = self.person.name
selectImageView.isHidden = !canSelect
updateImageView(select: self.person.selected)
}
func updateUi( inRealm: Realm, person: Person, canSelect: Bool) {
self.person = person
self.realm = inRealm
nameLabel.text = self.person.name
selectImageView.isHidden = !canSelect
updateImageView(select: self.person.selected)
}
}
| 27.152542 | 84 | 0.657303 |
e4d515ad053c88974622321e8c064fef6d47ca02 | 7,856 | //
// CameraController.swift
// FinalProject
//
// Created by hieungq on 8/21/20.
// Copyright © 2020 Asiantech. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
final class CameraController: NSObject {
// MARK: - Propertis
var captureSession: AVCaptureSession?
var frontCamera: AVCaptureDevice?
var rearCamera: AVCaptureDevice?
var currentCameraPosition: CameraPosition?
var frontCameraInput: AVCaptureDeviceInput?
var rearCameraInput: AVCaptureDeviceInput?
var photoOutput: AVCapturePhotoOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
var flashMode = AVCaptureDevice.FlashMode.off
var photoCaptureCompletion: ((UIImage?, Error?) -> Void)?
enum CameraControllerError: Swift.Error {
case captureSessionAlreadyRunning
case captureSessionIsMissing
case inputsAreInvalid
case invalidOperation
case noCamerasAvailable
case unknown
}
enum CameraPosition {
case front
case rear
}
func displayPreview(onView view: UIView) throws {
guard let captureSession = captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing }
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
previewLayer?.connection?.videoOrientation = .portrait
previewLayer?.frame = view.bounds
if let previewLayer = previewLayer {
view.layer.insertSublayer(previewLayer, at: 0)
}
}
func switchCameras() throws {
guard let currentCameraPosition = currentCameraPosition, let captureSession = captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing }
captureSession.beginConfiguration()
switch currentCameraPosition {
case .front:
try switchToRearCamera()
case .rear:
try switchToFrontCamera()
}
captureSession.commitConfiguration()
}
func switchToFrontCamera() throws {
guard let captureSession = captureSession,
let frontCamera = frontCamera,
let rearCameraInput = rearCameraInput,
captureSession.inputs.contains(rearCameraInput) else { throw CameraControllerError.invalidOperation }
captureSession.removeInput(rearCameraInput)
frontCameraInput = try AVCaptureDeviceInput(device: frontCamera)
if let frontCameraInput = frontCameraInput, captureSession.canAddInput(frontCameraInput) {
captureSession.addInput(frontCameraInput)
currentCameraPosition = .front
} else {
throw CameraControllerError.invalidOperation
}
}
func switchToRearCamera() throws {
guard let inputs = captureSession?.inputs,
let frontCameraInput = frontCameraInput, inputs.contains(frontCameraInput),
let rearCamera = rearCamera,
let captureSession = captureSession else { throw CameraControllerError.invalidOperation }
captureSession.removeInput(frontCameraInput)
rearCameraInput = try AVCaptureDeviceInput(device: rearCamera)
if let rearCameraInput = rearCameraInput, captureSession.canAddInput(rearCameraInput) {
captureSession.addInput(rearCameraInput)
currentCameraPosition = .rear
} else {
throw CameraControllerError.invalidOperation
}
}
func captureImage(completion: @escaping (UIImage?, Error?) -> Void) {
guard let captureSession = captureSession, captureSession.isRunning else { completion(nil, CameraControllerError.captureSessionIsMissing); return }
let settings = AVCapturePhotoSettings()
settings.flashMode = flashMode
photoOutput?.capturePhoto(with: settings, delegate: self)
photoCaptureCompletion = completion
}
}
// MARK: - Extension
extension CameraController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?,
previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?,
resolvedSettings: AVCaptureResolvedPhotoSettings,
bracketSettings: AVCaptureBracketedStillImageSettings?,
error: Error?) {
if let error = error {
photoCaptureCompletion?(nil, error)
} else if let buffer = photoSampleBuffer, let data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: buffer, previewPhotoSampleBuffer: nil),
let image = UIImage(data: data) {
photoCaptureCompletion?(image, nil)
} else {
photoCaptureCompletion?(nil, CameraControllerError.unknown)
}
}
}
// MARK: - Prepare
extension CameraController {
func prepare(completionHandler: @escaping (Error?) -> Void) {
DispatchQueue(label: "prepare").async {
do {
self.createCaptureSession()
try self.configureCaptureDevices()
try self.configureDeviceInputs()
try self.configurePhotoOutput()
} catch {
DispatchQueue.main.async {
completionHandler(error)
}
}
DispatchQueue.main.async {
completionHandler(nil)
}
}
}
func createCaptureSession() {
captureSession = AVCaptureSession()
}
func configureCaptureDevices() throws {
let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .unspecified)
let cameras = session.devices.compactMap { $0 }
guard !cameras.isEmpty else { throw CameraControllerError.noCamerasAvailable }
for camera in cameras {
if camera.position == .front {
frontCamera = camera
}
if camera.position == .back {
rearCamera = camera
try camera.lockForConfiguration()
camera.focusMode = .continuousAutoFocus
camera.unlockForConfiguration()
}
}
}
func configureDeviceInputs() throws {
guard let captureSession = captureSession else { throw CameraControllerError.captureSessionIsMissing }
if let rearCamera = rearCamera {
rearCameraInput = try AVCaptureDeviceInput(device: rearCamera)
if let rearCameraInput = rearCameraInput, captureSession.canAddInput(rearCameraInput) { captureSession.addInput(rearCameraInput)
}
currentCameraPosition = .rear
} else if let frontCamera = frontCamera {
frontCameraInput = try AVCaptureDeviceInput(device: frontCamera)
if let frontCameraInput = frontCameraInput, captureSession.canAddInput(frontCameraInput) {
captureSession.addInput(frontCameraInput)
} else {
throw CameraControllerError.inputsAreInvalid
}
currentCameraPosition = .front
} else {
throw CameraControllerError.noCamerasAvailable
}
}
func configurePhotoOutput() throws {
guard let captureSession = captureSession else { throw CameraControllerError.captureSessionIsMissing }
photoOutput = AVCapturePhotoOutput()
photoOutput?.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])], completionHandler: nil)
if let photoOutput = photoOutput, captureSession.canAddOutput(photoOutput) {
captureSession.addOutput(photoOutput)
}
captureSession.startRunning()
}
}
| 37.769231 | 187 | 0.67057 |
509eb6ce23b3acac786212689a0e112c4ad3a589 | 1,128 | //
// MovieCoordinator.swift
// ios-recruiting-hsa
//
// Created by Hans Fehrmann on 5/28/19.
// Copyright © 2019 Hans Fehrmann. All rights reserved.
//
import Foundation
import UIKit
class ArticleCoordinator: Coordinator {
private let navigationController: UINavigationController
private let appDependencies: AppDependencies
init(navigationController: UINavigationController, appDependencies: AppDependencies) {
self.navigationController = navigationController
self.appDependencies = appDependencies
}
func start() {
let controller = ListArticlesWireframe.viewController(
withDelegate: self,
appDependencies: appDependencies
)
navigationController.viewControllers = [controller]
}
}
extension ArticleCoordinator: ListArticlesViewDelegate {
func favoriteMovieView(
_ viewController: ListArticlesViewController,
didSelect article: Article
) {
let controller = ShowArticleWireframe.viewController(article: article)
navigationController.pushViewController(controller, animated: true)
}
}
| 27.512195 | 90 | 0.726064 |
3937911ec7f09c82591e4d565eb186a92ee6f372 | 1,071 | // web3swift
//
// Created by Alex Vlasov.
// Copyright © 2018 Alex Vlasov. All rights reserved.
//
import Foundation
//import secp256k1_swift
//import EthereumAddress
public class PlainKeystore: AbstractKeystore {
public var isHDKeystore: Bool = false
private var privateKey: Data
public var addresses: [EthereumAddress]?
public func UNSAFE_getPrivateKeyData(password: String = "", account: EthereumAddress) throws -> Data {
return self.privateKey
}
public convenience init?(privateKey: String) {
guard let privateKeyData = Data.fromHex(privateKey) else {return nil}
self.init(privateKey: privateKeyData)
}
public init?(privateKey: Data) {
guard SECP256K1.verifyPrivateKey(privateKey: privateKey) else {return nil}
guard let publicKey = Web3.Utils.privateToPublic(privateKey, compressed: false) else {return nil}
guard let address = Web3.Utils.publicToAddress(publicKey) else {return nil}
self.addresses = [address]
self.privateKey = privateKey
}
}
| 28.184211 | 106 | 0.699346 |
18b8b12ccbcc659d2200f3259ccab6021a55254d | 6,013 | //
// ViewController.swift
// SimilarImageForiOS
//
// Created by famulei on 03/07/2017.
// Copyright © 2017 famulei. All rights reserved.
//
import Cocoa
import CoreGraphics
class ViewController: NSViewController, NSFetchedResultsControllerDelegate {
var images: Dictionary<String, Image> = [String:Image]();
var selectedPath: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBOutlet var openFolder: NSButton!
@IBAction func openFolderAction(_ sender: NSButton) {
let panel = NSOpenPanel()
panel.canChooseDirectories = true;
panel.canChooseFiles = false;
panel.beginSheetModal(for: self.view.window!) { (result) in
if result == NSModalResponseOK {
self.prepareImages(url: panel.urls.first!)
}
}
}
func prepareImages(url: URL) {
selectedPath = url.path;
getImages(url: url);
for (key, image) in images {
let originImage = NSImage(contentsOfFile: (image.imageArray.last!));
let hashMeta = covertToGrey(forImage: resize(forImage: originImage!, size: CGSize(width: 8, height: 8)))
images[key]?.imageHash = hashMeta.2.map { (i) -> String in
String(i)
}.joined();
}
var sameImages: Dictionary<String, [Image]> = [:]
for (_, image) in images {
var isSame = false;
for (imgHash, images) in sameImages {
if isSameImage(firstHash: image.imageHash, secondHash: imgHash) {
// 是同一个图片
sameImages[imgHash]?.append(image);
isSame = true;
break;
}
}
if isSame == false {
// 没有任何相同的,自己创建一组
sameImages[image.imageHash] = [image];
}
}
// 输出结果
let dict = sameImages.filter {
return $1.count > 1;
}
_ = dict.map { (key, value) -> [Image] in
print("======== 相似的图片 指纹(\(key)) =========")
_ = value.map({ (image: Image) -> Image in
print(" 图片地址=== \(image.imageArray.first!) 指纹(\(image.imageHash))");
return image
})
return value;
}
}
func resize(forImage image: NSImage, size: CGSize) -> NSImage {
let img = NSImage(size: CGSize(width: size.width / 2, height: size.height / 2))
img.lockFocus();
let ctx = NSGraphicsContext.current();
ctx?.imageInterpolation = .high;
image.draw(in: NSRect(x: 0, y: 0, width: size.width / 2, height: size.height / 2));
img.unlockFocus();
return img;
}
func covertToGrey(forImage image: NSImage) -> ([[Float]], Float, [Int]) {
var imageRect = NSRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let bitmap = NSBitmapImageRep(cgImage: image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)!)
var greyArray: [[Float]] = [];
var totalGrey: Float = 0;
for x in 0..<Int(bitmap.pixelsWide) {
greyArray.append([]);
for y in 0..<Int(bitmap.pixelsHigh) {
let red = (bitmap.colorAt(x: x, y: y)?.redComponent)! * 255;
let green = (bitmap.colorAt(x: x, y: y)?.greenComponent)! * 255;
let blue = (bitmap.colorAt(x: x, y: y)?.blueComponent)! * 255;
let greyValue = red * (299/1000) + green * (587/1000) + blue * (114 / 1000);
totalGrey += Float(greyValue);
greyArray[x].append(Float(greyValue))
}
}
let avgGrey = totalGrey / Float(bitmap.pixelsWide * bitmap.pixelsHigh)
var imgHash: [Int] = [];
for x in 0..<Int(greyArray.count) {
for y in 0..<Int(greyArray[x].count) {
if greyArray[x][y] > avgGrey {
imgHash.append(1);
} else {
imgHash.append(0);
}
}
}
return (pixelsGrey: greyArray, avgGrey: avgGrey, imgHash: imgHash);
}
func isSameImage(firstHash hash1:String, secondHash hash2:String) -> Bool {
if hash1.characters.count != hash2.characters.count {
return false;
}
let thredHold: Int = 5;
var count: Int = 0;
for index in hash1.characters.indices {
if hash1[index] != hash2[index] {
count += 1;
if count >= thredHold {
break;
}
}
}
if count >= thredHold {
return false
} else {
return true
}
}
/// 获取url 下的所有图片
///
/// - Parameter url: 图片地址
func getImages(url: URL) {
if let paths = FileManager.default.subpaths(atPath: url.path) {
for filePath in paths {
extraImagePath(path: filePath)
}
}
}
func extraImagePath(path: String) {
if path.hasSuffix(".png") {
let imageInfo = path.components(separatedBy: "@")
var key = "";
if imageInfo.count == 1 {
// 没有尺寸的图片
key = imageInfo.first!.components(separatedBy: ".png").first!;
} else {
key = imageInfo.first!;
}
if images[key] == nil {
var image = Image()
image.imageUrl = key;
image.imageArray.append(self.selectedPath! + "/" + path);
images[key] = image;
} else {
images[key]?.imageArray.append(self.selectedPath! + "/" + path);
}
}
}
}
| 31.317708 | 117 | 0.495925 |
db5c764ef0cb8d05fe55d72e85355224e641aa83 | 14,948 | //
// Copyright (c) Vatsal Manot
//
import Swift
import SwiftUI
#if os(iOS) || os(macOS) || targetEnvironment(macCatalyst)
/// A specialized view for receiving search-related information from the user.
public struct SearchBar: DefaultTextInputType {
@Binding fileprivate var text: String
fileprivate var searchTokens: Binding<[SearchToken]>?
var customAppKitOrUIKitClass: AppKitOrUIKitSearchBar.Type?
#if os(iOS) || targetEnvironment(macCatalyst)
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
@ObservedObject private var keyboard = Keyboard.main
#endif
private let onEditingChanged: (Bool) -> Void
private let onCommit: () -> Void
private var isInitialFirstResponder: Bool?
private var isFocused: Binding<Bool>? = nil
private var placeholder: String?
#if os(iOS) || targetEnvironment(macCatalyst)
private var appKitOrUIKitFont: UIFont?
private var appKitOrUIKitForegroundColor: UIColor?
private var appKitOrUIKitSearchFieldBackgroundColor: UIColor?
private var searchBarStyle: UISearchBar.Style = .minimal
private var iconImageConfiguration: [UISearchBar.Icon: AppKitOrUIKitImage] = [:]
#endif
private var showsCancelButton: Bool?
private var onCancel: () -> Void = { }
#if os(iOS) || targetEnvironment(macCatalyst)
private var returnKeyType: UIReturnKeyType?
private var enablesReturnKeyAutomatically: Bool?
private var isSecureTextEntry: Bool = false
private var textContentType: UITextContentType? = nil
private var keyboardType: UIKeyboardType?
#endif
public init<S: StringProtocol>(
_ title: S,
text: Binding<String>,
onEditingChanged: @escaping (Bool) -> Void = { _ in },
onCommit: @escaping () -> Void = { }
) {
self.placeholder = String(title)
self._text = text
self.onCommit = onCommit
self.onEditingChanged = onEditingChanged
}
public init(
text: Binding<String>,
onEditingChanged: @escaping (Bool) -> Void = { _ in },
onCommit: @escaping () -> Void = { }
) {
self._text = text
self.onCommit = onCommit
self.onEditingChanged = onEditingChanged
}
}
#if os(iOS) || targetEnvironment(macCatalyst)
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
extension SearchBar: UIViewRepresentable {
public typealias UIViewType = UISearchBar
public func makeUIView(context: Context) -> UIViewType {
let uiView = _UISearchBar()
uiView.delegate = context.coordinator
if context.environment.isEnabled {
DispatchQueue.main.async {
if (isInitialFirstResponder ?? isFocused?.wrappedValue) ?? false {
uiView.becomeFirstResponder()
}
}
}
return uiView
}
public func updateUIView(_ uiView: UIViewType, context: Context) {
context.coordinator.base = self
_updateUISearchBar(uiView, environment: context.environment)
}
func _updateUISearchBar(
_ uiView: UIViewType,
environment: EnvironmentValues
) {
uiView.isUserInteractionEnabled = environment.isEnabled
style: do {
uiView.searchTextField.autocorrectionType = environment.disableAutocorrection.map({ $0 ? .no : .yes }) ?? .default
if (appKitOrUIKitFont != nil || environment.font != nil) || appKitOrUIKitForegroundColor != nil || appKitOrUIKitSearchFieldBackgroundColor != nil {
if let font = appKitOrUIKitFont ?? environment.font?.toUIFont() {
uiView.searchTextField.font = font
}
if let foregroundColor = appKitOrUIKitForegroundColor {
uiView.searchTextField.textColor = foregroundColor
}
if let backgroundColor = appKitOrUIKitSearchFieldBackgroundColor {
uiView.searchTextField.backgroundColor = backgroundColor
}
}
if let placeholder = placeholder {
uiView.placeholder = placeholder
}
assignIfNotEqual(searchBarStyle, to: &uiView.searchBarStyle)
for (icon, image) in iconImageConfiguration {
if uiView.image(for: icon, state: .normal) == nil { // FIXME: This is a performance hack.
uiView.setImage(image, for: icon, state: .normal)
}
}
assignIfNotEqual(environment.tintColor?.toUIColor(), to: &uiView.tintColor)
if let showsCancelButton = showsCancelButton {
if uiView.showsCancelButton != showsCancelButton {
uiView.setShowsCancelButton(showsCancelButton, animated: true)
}
}
}
keyboard: do {
assignIfNotEqual(returnKeyType ?? .default, to: &uiView.returnKeyType)
assignIfNotEqual(keyboardType ?? .default, to: &uiView.keyboardType)
assignIfNotEqual(enablesReturnKeyAutomatically ?? false, to: &uiView.enablesReturnKeyAutomatically)
}
data: do {
if uiView.text != text {
uiView.text = text
}
if let searchTokens = searchTokens?.wrappedValue {
if uiView.searchTextField.tokens.map(\._SwiftUIX_text) != searchTokens.map(\.text) {
uiView.searchTextField.tokens = searchTokens.map({ .init($0) })
}
} else {
if !uiView.searchTextField.tokens.isEmpty {
uiView.searchTextField.tokens = []
}
}
}
updateResponderChain: do {
if let uiView = uiView as? _UISearchBar, environment.isEnabled {
DispatchQueue.main.async {
if let isFocused = isFocused, uiView.window != nil {
uiView.isFirstResponderBinding = isFocused
if isFocused.wrappedValue && !uiView.isFirstResponder {
uiView.becomeFirstResponder()
} else if !isFocused.wrappedValue && uiView.isFirstResponder {
uiView.resignFirstResponder()
}
}
}
}
}
}
public class Coordinator: NSObject, UISearchBarDelegate {
var base: SearchBar
init(base: SearchBar) {
self.base = base
}
public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
base.onEditingChanged(true)
}
public func searchBar(_ searchBar: UIViewType, textDidChange searchText: String) {
base.text = searchText
}
public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
true
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
base.onEditingChanged(false)
}
public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
base.onCancel()
}
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
base.onCommit()
}
}
public func makeCoordinator() -> Coordinator {
Coordinator(base: self)
}
}
#elseif os(macOS)
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
extension SearchBar: NSViewRepresentable {
public typealias NSViewType = NSSearchField
public func makeNSView(context: Context) -> NSViewType {
let nsView = NSSearchField(string: placeholder ?? "")
nsView.delegate = context.coordinator
nsView.target = context.coordinator
nsView.action = #selector(context.coordinator.performAction(_:))
nsView.bezelStyle = .roundedBezel
nsView.cell?.sendsActionOnEndEditing = false
nsView.isBordered = false
nsView.isBezeled = true
return nsView
}
public func updateNSView(_ nsView: NSSearchField, context: Context) {
context.coordinator.base = self
if nsView.stringValue != text {
nsView.stringValue = text
}
}
final public class Coordinator: NSObject, NSSearchFieldDelegate {
var base: SearchBar
init(base: SearchBar) {
self.base = base
}
public func controlTextDidChange(_ notification: Notification) {
guard let textField = notification.object as? NSTextField else {
return
}
base.text = textField.stringValue
}
public func controlTextDidBeginEditing(_ notification: Notification) {
base.onEditingChanged(true)
}
public func controlTextDidEndEditing(_ notification: Notification) {
base.onEditingChanged(false)
}
@objc
fileprivate func performAction(_ sender: NSTextField?) {
base.onCommit()
}
}
public func makeCoordinator() -> Coordinator {
Coordinator(base: self)
}
}
#endif
// MARK: - API -
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
extension SearchBar {
public func customAppKitOrUIKitClass(_ cls: AppKitOrUIKitSearchBar.Type) -> Self {
then({ $0.customAppKitOrUIKitClass = cls })
}
}
extension SearchBar {
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
public func isInitialFirstResponder(_ isInitialFirstResponder: Bool) -> Self {
then({ $0.isInitialFirstResponder = isInitialFirstResponder })
}
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
public func focused(_ isFocused: Binding<Bool>) -> Self {
then({ $0.isFocused = isFocused })
}
}
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
extension SearchBar {
public func searchTokens(_ tokens: Binding<[SearchToken]>) -> Self {
then({ $0.searchTokens = tokens })
}
}
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
extension SearchBar {
#if os(iOS) || os(macOS) || targetEnvironment(macCatalyst)
public func placeholder(_ placeholder: String) -> Self {
then({ $0.placeholder = placeholder })
}
#endif
#if os(iOS) || targetEnvironment(macCatalyst)
public func font(_ font: UIFont) -> Self {
then({ $0.appKitOrUIKitFont = font })
}
public func foregroundColor(_ foregroundColor: AppKitOrUIKitColor) -> Self {
then({ $0.appKitOrUIKitForegroundColor = foregroundColor })
}
@_disfavoredOverload
public func foregroundColor(_ foregroundColor: Color) -> Self {
then({ $0.appKitOrUIKitForegroundColor = foregroundColor.toUIColor() })
}
public func textFieldBackgroundColor(_ backgroundColor: UIColor) -> Self {
then({ $0.appKitOrUIKitSearchFieldBackgroundColor = backgroundColor })
}
@_disfavoredOverload
public func textFieldBackgroundColor(_ backgroundColor: Color) -> Self {
then({ $0.appKitOrUIKitSearchFieldBackgroundColor = backgroundColor.toUIColor() })
}
public func searchBarStyle(_ searchBarStyle: UISearchBar.Style) -> Self {
then({ $0.searchBarStyle = searchBarStyle })
}
public func iconImage(_ icon: UISearchBar.Icon, _ image: AppKitOrUIKitImage) -> Self {
then({ $0.iconImageConfiguration[icon] = image })
}
public func showsCancelButton(_ showsCancelButton: Bool) -> Self {
then({ $0.showsCancelButton = showsCancelButton })
}
public func onCancel(perform action: @escaping () -> Void) -> Self {
then({ $0.onCancel = action })
}
public func returnKeyType(_ returnKeyType: UIReturnKeyType) -> Self {
then({ $0.returnKeyType = returnKeyType })
}
public func enablesReturnKeyAutomatically(_ enablesReturnKeyAutomatically: Bool) -> Self {
then({ $0.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically })
}
public func isSecureTextEntry(_ isSecureTextEntry: Bool) -> Self {
then({ $0.isSecureTextEntry = isSecureTextEntry })
}
public func textContentType(_ textContentType: UITextContentType?) -> Self {
then({ $0.textContentType = textContentType })
}
public func keyboardType(_ keyboardType: UIKeyboardType) -> Self {
then({ $0.keyboardType = keyboardType })
}
#endif
}
// MARK: - Auxiliary Implementation -
#if os(iOS) || targetEnvironment(macCatalyst)
private final class _UISearchBar: UISearchBar {
var isFirstResponderBinding: Binding<Bool>?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult
override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
isFirstResponderBinding?.wrappedValue = result
return result
}
@discardableResult
override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
isFirstResponderBinding?.wrappedValue = !result
return result
}
}
#endif
#endif
// MARK: - Development Preview -
#if os(iOS) || targetEnvironment(macCatalyst)
@available(macCatalystApplicationExtension, unavailable)
@available(iOSApplicationExtension, unavailable)
@available(tvOSApplicationExtension, unavailable)
struct SearchBar_Previews: PreviewProvider {
static var previews: some View {
SearchBar("Search...", text: .constant(""))
.searchBarStyle(.minimal)
}
}
#endif
| 33.144124 | 159 | 0.632258 |
332f43daaab33e25e9a510fd924db2c4e6c1b962 | 10,857 | //
// SecureMessaging.swift
// NFCTest
//
// Created by Andy Qua on 09/06/2019.
// Copyright © 2019 Andy Qua. All rights reserved.
//
import Foundation
import FirebaseCrashlytics
public enum SecureMessagingSupportedAlgorithms {
case DES
case AES
}
#if !os(macOS)
import CoreNFC
/// This class implements the secure messaging protocol.
/// The class is a new layer that comes between the reader and the iso7816.
/// It gives a new transmit method that takes an APDU object formed by the iso7816 layer,
/// ciphers it following the doc9303 specification, sends the ciphered APDU to the reader
/// layer and returns the unciphered APDU.
@available(iOS 13, *)
public class SecureMessaging {
private var ksenc : [UInt8]
private var ksmac : [UInt8]
private var ssc : [UInt8]
private let algoName : SecureMessagingSupportedAlgorithms
private let padLength : Int
public init( encryptionAlgorithm : SecureMessagingSupportedAlgorithms = .DES, ksenc : [UInt8], ksmac : [UInt8], ssc : [UInt8]) {
self.ksenc = ksenc
self.ksmac = ksmac
self.ssc = ssc
self.algoName = encryptionAlgorithm
self.padLength = algoName == .DES ? 8 : 16
}
/// Protect the apdu following the doc9303 specification
func protect(apdu : NFCISO7816APDU ) throws -> NFCISO7816APDU {
Log.debug("\t\tSSC: \(binToHexRep(self.ssc))")
self.ssc = self.incSSC()
let paddedSSC = algoName == .DES ? self.ssc : [UInt8](repeating: 0, count: 8) + ssc
Log.debug("\tIncrement SSC with 1")
Log.debug("\t\tSSC: \(binToHexRep(self.ssc))")
let cmdHeader = self.maskClassAndPad(apdu: apdu)
var do87 : [UInt8] = []
var do97 : [UInt8] = []
var tmp = "Concatenate CmdHeader"
if apdu.data != nil {
tmp += " and DO87"
do87 = try self.buildD087(apdu: apdu)
}
let isMSE = apdu.instructionCode == 0x22
if apdu.expectedResponseLength > 0 && (isMSE ? apdu.expectedResponseLength < 256 : true) {
tmp += " and DO97"
do97 = try self.buildD097(apdu: apdu)
}
let M = cmdHeader + do87 + do97
Log.debug("\(tmp)")
Log.debug("\tM: \(binToHexRep(M))")
Log.debug("Compute MAC of M")
let N = pad(paddedSSC + M, blockSize:padLength)
Log.debug("\tConcatenate SSC and M and add padding")
Log.debug("\t\tN: \(binToHexRep(N))")
var CC = mac(algoName: algoName, key: self.ksmac, msg: N)
if CC.count > 8 {
CC = [UInt8](CC[0..<8])
}
Log.debug("\tCompute MAC over N with KSmac")
Log.debug("\t\tCC: \(binToHexRep(CC))")
let do8e = self.buildD08E(mac: CC)
// If dataSize > 255 then it will be encoded in 3 bytes with the first byte being 0x00
// otherwise its a single byte of size
let size = do87.count + do97.count + do8e.count
var dataSize: [UInt8]
if size > 255 {
dataSize = [0x00] + intToBin(size, pad: 4)
} else {
dataSize = intToBin(size)
}
var protectedAPDU = [UInt8](cmdHeader[0..<4]) + dataSize
protectedAPDU += do87 + do97 + do8e
// If the data is more that 255, specify the we are using extended length (0x00, 0x00)
// Thanks to @filom for the fix!
if size > 255 {
protectedAPDU += [0x00,0x00]
} else {
protectedAPDU += [0x00]
}
Log.debug("Construct and send protected APDU")
Log.debug("\tProtectedAPDU: \(binToHexRep(protectedAPDU))")
let newAPDU = NFCISO7816APDU(data:Data(protectedAPDU))!
return newAPDU
}
/// Unprotect the APDU following the iso7816 specification
func unprotect(rapdu : ResponseAPDU ) throws -> ResponseAPDU {
var needCC = false
var do87 : [UInt8] = []
var do87Data : [UInt8] = []
var do99 : [UInt8] = []
//var do8e : [UInt8] = []
var offset = 0
self.ssc = self.incSSC()
let paddedSSC = algoName == .DES ? self.ssc : [UInt8](repeating: 0, count: 8) + ssc
Log.debug("\tIncrement SSC with 1")
Log.debug("\t\tSSC: \(binToHexRep(self.ssc))")
// Check for a SM error
if(rapdu.sw1 != 0x90 || rapdu.sw2 != 0x00) {
return rapdu
}
let rapduBin = rapdu.data + [rapdu.sw1, rapdu.sw2]
Log.debug("Receive response APDU of MRTD's chip")
Log.debug("\tRAPDU: \(binToHexRep(rapduBin))")
// DO'87'
// Mandatory if data is returned, otherwise absent
if rapduBin[0] == 0x87 {
let (encDataLength, o) = try asn1Length([UInt8](rapduBin[1...]))
offset = 1 + o
if rapduBin[offset] != 0x1 {
throw NFCPassportReaderError.D087Malformed
}
do87 = [UInt8](rapduBin[0 ..< offset + Int(encDataLength)])
do87Data = [UInt8](rapduBin[offset+1 ..< offset + Int(encDataLength)])
offset += Int(encDataLength)
needCC = true
}
//DO'99'
// Mandatory, only absent if SM error occurs
do99 = [UInt8](rapduBin[offset..<offset+4])
let sw1 = rapduBin[offset+2]
let sw2 = rapduBin[offset+3]
offset += 4
needCC = true
if do99[0] != 0x99 && do99[1] != 0x02 {
//SM error, return the error code
return ResponseAPDU(data: [], sw1: sw1, sw2: sw2)
}
// DO'8E'
//Mandatory if DO'87' and/or DO'99' is present
if rapduBin[offset] == 0x8E {
let ccLength : Int = Int(binToHex(rapduBin[offset+1]))
let CC = [UInt8](rapduBin[offset+2 ..< offset+2+ccLength])
// do8e = [UInt8](rapduBin[offset ..< offset+2+ccLength])
// CheckCC
var tmp = ""
if do87.count > 0 {
tmp += " DO'87"
}
if do99.count > 0 {
tmp += " DO'99"
}
Log.debug("Verify RAPDU CC by computing MAC of \(tmp)")
let K = pad(paddedSSC + do87 + do99, blockSize:padLength)
Log.debug("\tConcatenate SSC and \(tmp) and add padding")
Log.debug("\t\tK: \(binToHexRep(K))")
Log.debug("\tCompute MAC with KSmac")
var CCb = mac(algoName: algoName, key: self.ksmac, msg: K)
if CCb.count > 8 {
CCb = [UInt8](CC[0..<8])
}
Log.debug("\t\tCC: \(binToHexRep(CCb))")
let res = (CC == CCb)
Log.debug("\tCompare CC with data of DO'8E of RAPDU")
Log.debug("\t\t\(binToHexRep(CC)) == \(binToHexRep(CCb)) ? \(res)")
if !res {
Crashlytics.crashlytics().setCustomValue("CC is not equal to data of DO'8E' of RAPDU", forKey: FirebaseCustomKeys.errorInfo)
throw NFCPassportReaderError.InvalidResponseChecksum
}
}
else if needCC {
Crashlytics.crashlytics().setCustomValue("DO'8E' is missing", forKey: FirebaseCustomKeys.errorInfo)
throw NFCPassportReaderError.MissingMandatoryFields
}
var data : [UInt8] = []
if do87Data.count > 0 {
let dec : [UInt8]
if algoName == .DES {
dec = tripleDESDecrypt(key: self.ksenc, message: do87Data, iv: [0,0,0,0,0,0,0,0])
} else {
// for AES the IV is the ssc with AES/EBC/NOPADDING
let paddedssc = [UInt8](repeating: 0, count: 8) + ssc
let iv = AESECBEncrypt(key: ksenc, message: paddedssc)
dec = AESDecrypt(key: self.ksenc, message: do87Data, iv: iv)
}
// There is a payload
data = unpad(dec)
Log.debug("Decrypt data of DO'87 with KSenc")
Log.debug("\tDecryptedData: \(binToHexRep(data))")
}
Log.debug("Unprotected APDU: [\(binToHexRep(data))] \(binToHexRep(sw1)) \(binToHexRep(sw2))" )
return ResponseAPDU(data: data, sw1: sw1, sw2: sw2)
}
func maskClassAndPad(apdu : NFCISO7816APDU ) -> [UInt8] {
Log.debug("Mask class byte and pad command header")
let res = pad([0x0c, apdu.instructionCode, apdu.p1Parameter, apdu.p2Parameter], blockSize: padLength)
Log.debug("\tCmdHeader: \(binToHexRep(res))")
return res
}
func buildD087(apdu : NFCISO7816APDU) throws -> [UInt8] {
let cipher = [0x01] + self.padAndEncryptData(apdu)
let res = try [0x87] + toAsn1Length(cipher.count) + cipher
Log.debug("Build DO'87")
Log.debug("\tDO87: \(binToHexRep(res))")
return res
}
func padAndEncryptData(_ apdu : NFCISO7816APDU) -> [UInt8] {
// Pad the data, encrypt data with KSenc and build DO'87
let data = [UInt8](apdu.data!)
let paddedData = pad( data, blockSize: padLength )
let enc : [UInt8]
if algoName == .DES {
enc = tripleDESEncrypt(key: self.ksenc, message: paddedData, iv: [0,0,0,0,0,0,0,0])
} else {
// for AES the IV is the ssc with AES/EBC/NOPADDING
let paddedssc = [UInt8](repeating: 0, count: 8) + ssc
let iv = AESECBEncrypt(key: ksenc, message: paddedssc)
enc = AESEncrypt(key: self.ksenc, message: paddedData, iv: iv)
}
Log.debug("Pad data")
Log.debug("\tData: \(binToHexRep(paddedData))")
Log.debug("Encrypt data with KSenc")
Log.debug("\tEncryptedData: \(binToHexRep(enc))")
return enc
}
func incSSC() -> [UInt8] {
let val = binToHex(self.ssc) + 1
// This needs to be fully zero padded - to 8 bytes = i.e. if SSC is 1 it should return [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1]
// NOT [0x1]
return withUnsafeBytes(of: val.bigEndian, Array.init)
}
func buildD08E(mac : [UInt8]) -> [UInt8] {
let res : [UInt8] = [0x8E, UInt8(mac.count)] + mac
Log.debug("Build DO'8E")
Log.debug("\tDO8E: \(binToHexRep(res))" )
return res
}
func buildD097(apdu : NFCISO7816APDU) throws -> [UInt8] {
let le = apdu.expectedResponseLength
var binLe = intToBin(le)
if (le == 256 || le == 65536) {
binLe = [0x00] + (le > 256 ? [0x00] : [])
}
let res : [UInt8] = try [0x97] + toAsn1Length(binLe.count) + binLe
Log.debug("Build DO'97")
Log.debug("\tDO97: \(res)")
return res
}
}
#endif
| 36.555556 | 140 | 0.547389 |
fefe65761ee50b00422af4b97ed3f72311d944da | 3,807 | //
// TrendingPeopleThisWeekFixture.swift
// TMDBTests
//
// Created by Tuyen Le on 12.06.20.
// Copyright © 2020 Tuyen Le. All rights reserved.
//
import Foundation
let trendingPeopleThisWeekFixture = Data("""
{
"page": 1,
"results": [
{
"known_for_department": "Acting",
"adult": false,
"id": 287,
"profile_path": "/tJiSUYst4ddIaz1zge2LqCtu9tw.jpg",
"name": "Brad Pitt",
"known_for": [
{
"poster_path": "/bptfVGEQuv6vDTIMVCHjJ9Dz8PX.jpg",
"popularity": 34.693,
"vote_count": 19370,
"video": false,
"media_type": "movie",
"id": 550,
"adult": false,
"backdrop_path": "/8iVyhmjzUbvAGppkdCZPiyEHSoF.jpg",
"original_language": "en",
"original_title": "Fight Club",
"genre_ids": [
18
],
"title": "Fight Club",
"vote_average": 8.4,
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \\"fight clubs\\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"release_date": "1999-10-15"
},
{
"poster_path": "/7sfbEnaARXDDhKm0CZ7D7uc2sbo.jpg",
"popularity": 32.049,
"vote_count": 14827,
"video": false,
"media_type": "movie",
"id": 16869,
"adult": false,
"backdrop_path": "/8pEnePgGyfUqj8Qa6d91OZQ6Aih.jpg",
"original_language": "en",
"original_title": "Inglourious Basterds",
"genre_ids": [
28,
18,
53,
10752
],
"title": "Inglourious Basterds",
"vote_average": 8.2,
"overview": "In Nazi-occupied France during World War II, a group of Jewish-American soldiers known as \\"The Basterds\\" are chosen specifically to spread fear throughout the Third Reich by scalping and brutally killing Nazis. The Basterds, lead by Lt. Aldo Raine soon cross paths with a French-Jewish teenage girl who runs a movie theater in Paris which is targeted by the soldiers.",
"release_date": "2009-08-18"
},
{
"poster_path": "/6yoghtyTpznpBik8EngEmJskVUO.jpg",
"popularity": 46.953,
"vote_count": 13154,
"video": false,
"media_type": "movie",
"id": 807,
"adult": false,
"backdrop_path": "/4U4q1zjIwCZTNkp6RKWkWPuC7uI.jpg",
"original_language": "en",
"original_title": "Se7en",
"genre_ids": [
80,
9648,
53
],
"title": "Se7en",
"vote_average": 8.3,
"overview": "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the \\"seven deadly sins\\" in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case.",
"release_date": "1995-09-22"
}
],
"gender": 2,
"popularity": 23.428,
"media_type": "person"
}
],
"total_pages": 1000,
"total_results": 20000
}
""".utf8)
| 40.5 | 423 | 0.529814 |
f45cdf4d883a96e73d6c144ef07740af423c0664 | 3,391 | // Artist Collection 첫번째 Section의 Header View
// SupplementaryView.swift
// BeBrav
//
// Created by 공지원 on 23/01/2019.
// Copyright © 2019 bumslap. All rights reserved.
//
import UIKit
class ArtistDetailHeaderView: UICollectionReusableView {
//MARK: - Outlet
public let artistNameTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.text = ""
textField.textAlignment = .center
textField.font = UIFont.boldSystemFont(ofSize: 32)
textField.textColor = .white
textField.isEnabled = false
return textField
}()
public let artistIntroTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.text = ""
textField.textAlignment = .center
textField.font = UIFont.systemFont(ofSize: 20)
textField.textColor = .white
textField.backgroundColor = #colorLiteral(red: 0.1780431867, green: 0.1711916029, blue: 0.2278442085, alpha: 1)
textField.isEnabled = false
return textField
}()
// MARK:- Properties
public var isEditMode = false {
didSet {
artistNameTextField.isEnabled = isEditMode
artistIntroTextField.isEnabled = isEditMode
if isEditMode {
artistNameTextField.becomeFirstResponder()
}
}
}
//MARK: - Initialize
override init(frame: CGRect) {
super.init(frame: frame)
setLayout()
artistNameTextField.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Touches began
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if artistNameTextField.isFirstResponder {
artistNameTextField.resignFirstResponder()
} else {
artistIntroTextField.resignFirstResponder()
}
}
//MARK: - Set Layout
private func setLayout() {
addSubview(artistNameTextField)
addSubview(artistIntroTextField)
backgroundColor = #colorLiteral(red: 0.1780431867, green: 0.1711916029, blue: 0.2278442085, alpha: 1)
artistNameTextField.topAnchor.constraint(equalTo: topAnchor, constant: 30).isActive = true
artistNameTextField.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 70).isActive = true
artistNameTextField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -70).isActive = true
artistIntroTextField.topAnchor.constraint(equalTo: artistNameTextField.bottomAnchor, constant: 18).isActive = true
artistIntroTextField.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -30).isActive = true
artistIntroTextField.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 40).isActive = true
artistIntroTextField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -40).isActive = true
}
}
//MARK: - Text Field Delegate
extension ArtistDetailHeaderView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 35.322917 | 122 | 0.66765 |
728ab077d3ba41ca0c0d6fed820cc0132a05feb0 | 5,213 | //
// SessionCollectionController.swift
// IvyLifts
//
// Created by Mike Chu on 12/24/18.
// Copyright © 2018 Mike Lin. All rights reserved.
//
import UIKit
/// This class is a collection view that loads exercises from WeeklyOverViewCollection controller and displays the 4 workouts to do
/// in a collectionView display. On clicking any of the cells, the navigationController will push ExerciseEntryController
class SessionCollectionController: UICollectionViewController {
/// The exercises that define each cell.
var exercises: [FitnessGoal] = [] {
didSet {
self.collectionView.reloadData()
/// Once we find out how many exercises there are, let entriesCollection populate empty lists in order to
/// match the number of cells created and have them map to some empty list corresponding w/ the cell's index.item
for _ in exercises {
self.entriesCollection.append(contentsOf: [[]])
}
}
}
/// An array of SetEntry arrays, which serves to cache any recorded data passed from ExerciseEntryController through it's delegate.
/// Once this array is populated, the collectionView will pass in the list of SetEntrys corresponding to the cell that
/// recorded those set entries. That way, there is no need to re-make those list of Entries again, it is automatically populated.
/// The cells of WorkoutCollectionController use this collection to populate their own collectionViews, which list the sets that
/// have been recorded but on the cell.
var entriesCollection: [[Entry]] = [] {
didSet {
log.debug("Setting entries")
log.debug(entriesCollection)
self.collectionView.reloadData()
}
}
// MARK: - View lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
}
/// Make TabBar disappear once this view is pushed
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = true
log.warning(entriesCollection)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.tabBarController?.tabBar.isHidden = false
}
func setupCollectionView() {
self.collectionView.backgroundColor = UIColor.background()
self.collectionView.register(SessionCollectionCell.self, forCellWithReuseIdentifier: "cellID")
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! SessionCollectionCell
cell.model = exercises[indexPath.item]
/// Pass the entries collected from ExerciseEntryController to the cells in this collectionView, which then
/// populate their own collectionView with the entries recorded
cell.entries = entriesCollection[indexPath.item]
return cell
}
/// Creates the exerciseEntryController and if we have an collection of entries from it, then we load the
/// exerciseEntryController's collectionView with these structs
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
log.info("Transitioning to ExerciseEntryController")
let exerciseEntryController = EntryController()
exerciseEntryController.exercise = exercises[indexPath.item]
exerciseEntryController.index = indexPath.item
exerciseEntryController.delegate = self
exerciseEntryController.setEntries = entriesCollection[indexPath.item]
self.navigationController?.pushViewController(exerciseEntryController, animated: true)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return exercises.count
}
}
extension SessionCollectionController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 15
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = collectionView.frame.height/CGFloat(exercises.count + 1)
return CGSize(width: view.frame.width - 32, height: height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
}
}
extension SessionCollectionController: ExerciseEntryDelegate {
func passRecordedEntries(entries: [Entry], for index: Int) {
log.debug("Entries collected from index \(index)")
log.debug(entries)
self.entriesCollection[index] = entries
}
}
| 44.555556 | 170 | 0.710723 |
38e4f7c248e55465710bcd4da57a0823af004b75 | 3,463 | //
// Datagram+Streams.swift
// SwiftIO
//
// Created by Jonathan Wight on 8/18/15.
//
// Copyright (c) 2014, Jonathan Wight
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * 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.
//
// 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 HOLDER 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 SwiftUtilities
extension Datagram: BinaryInputStreamable, BinaryOutputStreamable {
public static func readFrom(stream: BinaryInputStream) throws -> Datagram {
let jsonLength = Int32(networkEndian: try stream.read())
guard jsonLength >= 0 else {
throw Error.Generic("Negative length")
}
let jsonBuffer: DispatchData <Void> = try stream.readData(length: Int(jsonLength))
let jsonData = jsonBuffer.data as! NSData
let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions()) as! [String: AnyObject]
guard let address = json["address"] as? String else {
throw Error.Generic("Could not get from address")
}
guard let port = json["port"] as? Int else {
throw Error.Generic("Could not get from port")
}
guard let absoluteTime = json["timestamp"] as? Double else {
throw Error.Generic("Could not get from port")
}
let dataLength = Int32(networkEndian: try stream.read())
guard dataLength >= 0 else {
throw Error.Generic("Negative length")
}
let data: DispatchData <Void> = try stream.readData(length: Int(dataLength))
let datagram = try Datagram(from: Address(address: address, port: UInt16(port)), timestamp: Timestamp(absoluteTime: absoluteTime), data: data)
return datagram
}
public func writeTo(stream: BinaryOutputStream) throws {
let metadata: [String: AnyObject] = [
"address": from.address,
"port": Int(from.port ?? 0),
"timestamp": timestamp.absoluteTime,
]
let json = try NSJSONSerialization.dataWithJSONObject(metadata, options: NSJSONWritingOptions())
try stream.write(Int32(networkEndian: Int32(json.length)))
try stream.write(json)
try stream.write(Int32(networkEndian: Int32(data.length)))
try stream.write(data)
}
}
| 41.722892 | 150 | 0.691308 |
875dd464c1414e2771f511143e4df38362a8158d | 973 | //
// String+Regular.swift
// 正则表达式
//
// Created by zhangping on 15/11/10.
// Copyright © 2015年 zhangping. All rights reserved.
//
import Foundation
extension String {
func linkSource() -> String {
// 匹配的规则
let pattern = ">(.*?)</a>"
let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
// 匹配第一项
let result = regular.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.characters.count))
let count = result?.numberOfRanges ?? 0
// 判断count是否>1
if count > 1 {
// 获取对应的范围
let range = result!.rangeAtIndex(1) //rangeAtIndex(n),n是匹配到的第几项索引,得到range再用字符串截取既可以拿到匹配出来的结果
let text = (self as NSString).substringWithRange(range)
return text
} else {
return "未知来源"
}
}
} | 27.027778 | 154 | 0.596095 |
6ae8b50b1747bbedb3dea9065a49a3bb1004a913 | 1,807 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import AWSLambdaEvents
import AWSLambdaRuntimeCore
import Hummingbird
import NIOCore
import NIOHTTP1
extension HBLambda where In == APIGateway.Request {
/// Specialization of HBLambda.request where `In` is `APIGateway.Request`
public func request(context: Lambda.Context, application: HBApplication, from: In) throws -> HBRequest {
var request = try HBRequest(context: context, application: application, from: from)
// store api gateway request so it is available in routes
request.extensions.set(\.apiGatewayRequest, value: from)
return request
}
}
extension HBLambda where Out == APIGateway.Response {
/// Specialization of HBLambda.request where `Out` is `APIGateway.Response`
public func output(from response: HBResponse) -> Out {
return response.apiResponse()
}
}
// conform `APIGateway.Request` to `APIRequest` so we can use HBRequest.init(context:application:from)
extension APIGateway.Request: APIRequest {}
// conform `APIGateway.Response` to `APIResponse` so we can use HBResponse.apiReponse()
extension APIGateway.Response: APIResponse {}
extension HBRequest {
/// `APIGateway.Request` that generated this `HBRequest`
public var apiGatewayRequest: APIGateway.Request {
self.extensions.get(\.apiGatewayRequest)
}
}
| 36.14 | 108 | 0.674045 |
ef80230e7baf0c9bf87ca39006690754b24f75d9 | 1,650 | //
// SportsFormNameCollectionViewCell.swift
// Uplift
//
// Created by Artesia Ko on 5/24/20.
// Copyright © 2020 Cornell AppDev. All rights reserved.
//
import UIKit
class SportsFormNameCollectionViewCell: UICollectionViewCell {
private let divider = UIView()
private let textField = UITextField()
override init(frame: CGRect) {
super.init(frame: frame)
textField.font = ._16MontserratMedium
textField.textColor = .primaryBlack
textField.placeholder = "Game Name"
textField.delegate = self
textField.returnKeyType = .done
contentView.addSubview(textField)
divider.backgroundColor = .gray01
contentView.addSubview(divider)
setupConstraints()
}
func setupConstraints() {
let dividerHeight = 1
let horizontalPadding = 16
textField.snp.makeConstraints { make in
make.top.bottom.equalToSuperview()
make.leading.trailing.equalToSuperview().inset(horizontalPadding)
}
divider.snp.makeConstraints { make in
make.leading.trailing.bottom.equalToSuperview()
make.height.equalTo(dividerHeight)
}
}
func getSportName() -> String {
return textField.text ?? ""
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension SportsFormNameCollectionViewCell: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 26.612903 | 77 | 0.634545 |
64b8910f4513cd7ae2b1c10049db2fb68c56b3c8 | 749 | import XCTest
import VXSwiftUtils
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.827586 | 111 | 0.602136 |
4a19a3bfea82e3f80288bcc50854a7f85e8726ad | 1,167 | //
// TabBarView.swift
// SwiftUIStarterKitApp
//
// Created by Osama Naeem on 02/08/2019.
// Copyright © 2019 NexThings. All rights reserved.
//
import SwiftUI
struct TabbarView: View {
var body: some View {
TabView {
NavigationView {
ActivitiesContentView(activtiesData: Activities(data: ActivitiesMockStore.activityData, items: ActivitiesMockStore.activities))
}
.tag(0)
.tabItem {
Image("activity-1")
.resizable()
Text("Activities")
}
NavigationView {
ActivitiesCartView(ShoppingCartItemsData: ActivitiesCart(data: ActivitiesMockStore.shoppingCartData))
}
.tag(1)
.tabItem {
Image("shopping-cart-icon")
Text("Cart")
}
NavigationView {
AccountView()
}
.tag(2)
.tabItem {
Image("profile-glyph-icon")
Text("Account")
}
}
}
}
| 24.829787 | 143 | 0.468723 |
71f432165c8a5c054ff4e6318432e90ef0c9afc7 | 237 | //
// FirebaseError.swift
// QuizApp
//
// Created by oguzparlak on 27.02.2020.
// Copyright © 2020 Oguz Parlak. All rights reserved.
//
import Foundation
enum FirebaseError: Error {
case encodingError
case decodingError
}
| 15.8 | 54 | 0.700422 |
3aea0dae250dc14c0663594541785bc7a73e8df3 | 2,150 | //
// AppDelegate.swift
// FindAPrimeNumber
//
// Created by Jason Shultz on 9/18/15.
// Copyright © 2015 HashRocket. 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.754884 |
1a8044369a012d847acc72e4c310f09cd556ee25 | 1,547 | /**
* (C) Copyright IBM Corp. 2019.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
Details about the training data.
*/
public struct TrainingDataObject: Codable, Equatable {
/**
The name of the object.
*/
public var object: String?
/**
Defines the location of the bounding box around the object.
*/
public var location: Location?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case object = "object"
case location = "location"
}
/**
Initialize a `TrainingDataObject` with member variables.
- parameter object: The name of the object.
- parameter location: Defines the location of the bounding box around the object.
- returns: An initialized `TrainingDataObject`.
*/
public init(
object: String? = nil,
location: Location? = nil
)
{
self.object = object
self.location = location
}
}
| 26.672414 | 86 | 0.67033 |
081ca535bd8fbe5918b466cc5c4f7331983bc74f | 7,109 | //
// SignUpVC.swift
// Instagram
//
// Created by 刘铭 on 16/6/23.
// Copyright © 2016年 刘铭. All rights reserved.
//
import UIKit
import AVOSCloud
class SignUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var avaImg: UIImageView!
@IBOutlet weak var usernameTxt: UITextField!
@IBOutlet weak var passwordTxt: UITextField!
@IBOutlet weak var repeatPasswordTxt: UITextField!
@IBOutlet weak var emailTxt: UITextField!
@IBOutlet weak var fullnameTxt: UITextField!
@IBOutlet weak var bioTxt: UITextField!
@IBOutlet weak var webTxt: UITextField!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var signUpBtn: UIButton!
@IBOutlet weak var cancelBtn: UIButton!
// 根据需要,设置滚动视图的高度
var scrollViewHeight: CGFloat = 0
// 获取虚拟键盘的大小
var keyboard: CGRect = CGRect()
override func viewDidLoad() {
super.viewDidLoad()
// 滚动视图的frame size
scrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
scrollView.contentSize.height = self.view.frame.height
scrollViewHeight = self.view.frame.height
// 检测键盘出现或消失的状态
NotificationCenter.default.addObserver(self, selector: #selector(showKeyboard), name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(hideKeyboard), name: Notification.Name.UIKeyboardWillHide, object: nil)
let hideTap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboardTap))
hideTap.numberOfTapsRequired = 1
self.view.isUserInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
// 改变avaImg的外观为圆形
avaImg.layer.cornerRadius = avaImg.frame.width / 2
avaImg.clipsToBounds = true
let imgTap = UITapGestureRecognizer(target: self, action: #selector(loadImg))
imgTap.numberOfTapsRequired = 1
avaImg.isUserInteractionEnabled = true
avaImg.addGestureRecognizer(imgTap)
// UI元素布局
avaImg.frame = CGRect(x: self.view.frame.width / 2 - 40, y: 40, width: 80, height: 80)
let viewWidth = self.view.frame.width
usernameTxt.frame = CGRect(x: 10, y: avaImg.frame.origin.y + 90, width: viewWidth - 20, height: 30)
passwordTxt.frame = CGRect(x: 10, y: usernameTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30)
repeatPasswordTxt.frame = CGRect(x: 10, y: passwordTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30)
emailTxt.frame = CGRect(x: 10, y: repeatPasswordTxt.frame.origin.y + 60, width: viewWidth - 20, height: 30)
fullnameTxt.frame = CGRect(x: 10, y: emailTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30)
bioTxt.frame = CGRect(x: 10, y: fullnameTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30)
webTxt.frame = CGRect(x: 10, y: bioTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30)
signUpBtn.frame = CGRect(x: 20, y: webTxt.frame.origin.y + 50, width: viewWidth / 4, height: 30)
cancelBtn.frame = CGRect(x: viewWidth - viewWidth / 4 - 20, y: signUpBtn.frame.origin.y, width: viewWidth / 4, height: 30)
//设置背景图
let bg = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
bg.image = UIImage(named: "bg.jpg")
bg.layer.zPosition = -1
self.view.addSubview(bg)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 调出照片获取器选择照片
func loadImg(recognizer: UITapGestureRecognizer) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
// 关联选择好的照片图像到image view
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
avaImg.image = info[UIImagePickerControllerEditedImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
// 用户取消获取器操作时调用的方法
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
// 隐藏视图中的虚拟键盘
func hideKeyboardTap(recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}
func showKeyboard(notification: Notification) {
// 定义keyboard大小
let rect = ((notification.userInfo?[UIKeyboardFrameEndUserInfoKey]!)!) as! NSValue
keyboard = rect.cgRectValue()
// 当虚拟键盘出现以后,将滚动视图的实际高度缩小为屏幕高度减去键盘的高度。
UIView.animate(withDuration: 0.4) {
self.scrollView.frame.size.height = self.scrollViewHeight - self.keyboard.size.height
}
}
func hideKeyboard(notification: Notification) {
// 当虚拟键盘消失后,将滚动视图的实际高度改变为屏幕的高度值。
UIView.animate(withDuration: 0.4) {
self.scrollView.frame.size.height = self.view.frame.height
}
}
// 注册按钮被点击
@IBAction func signUpBtn_click(_ sender: AnyObject) {
print("注册按钮被按下!")
// 隐藏keyboard
self.view.endEditing(true)
if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || repeatPasswordTxt.text!.isEmpty || emailTxt.text!.isEmpty || fullnameTxt.text!.isEmpty || bioTxt.text!.isEmpty || webTxt.text!.isEmpty {
let alert = UIAlertController(title: "请注意", message: "请填写好所有的字段", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
return
}
// 如果两次输入的密码不同
if passwordTxt.text != repeatPasswordTxt.text {
let alert = UIAlertController(title: "请注意", message: "两次输入的密码不一致", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
return
}
let user = AVUser()
user.username = usernameTxt.text?.lowercased()
user.email = emailTxt.text?.lowercased()
user.password = passwordTxt.text
user["fullname"] = fullnameTxt.text?.lowercased()
user["bio"] = bioTxt.text
user["web"] = webTxt.text?.lowercased()
user["gender"] = ""
// 转换头像数据并发送到服务器
let avaData = UIImageJPEGRepresentation(avaImg.image!, 0.5)
let avaFile = AVFile(name: "ava.jpg", data: avaData)
user["ava"] = avaFile
// 保存信息到服务器
user.signUpInBackground { (success:Bool, error:NSError?) in
if success {
print("用户注册成功!")
// 记住登陆的用户
UserDefaults.standard.set(user.username, forKey: "username")
UserDefaults.standard.synchronize()
// 从AppDelegate类中调用login方法
let appDelegate: AppDelegate = UIApplication.shared().delegate as! AppDelegate
appDelegate.login()
}else {
print(error?.localizedDescription)
}
}
}
// 取消按钮被点击
@IBAction func cancelBtn_click(_ sender: AnyObject) {
self.view.endEditing(true)
self.dismiss(animated: true, completion: nil)
}
}
| 35.019704 | 201 | 0.68772 |
abb7772b5b7585187709db0c436529737d86fe77 | 5,600 | //
// AcnGatewayiOS
//
// Copyright © 2016 Arrow Electronics. All rights reserved.
//
import Foundation
import CoreBluetooth
import AcnSDK
class OnSemiRSL10: BleDevice {
// services UUIDS
static let TelemetryServiceUUID = CBUUID(string: "E093F3B5-00A3-A9E5-9ECA-40016E0EDC24")
static let LedServiceUUID = CBUUID(string: "669A0C20-0008-1A8F-E711-BED9307A52B3")
static let MotorServiceUUID = CBUUID(string: "669A0C20-0008-1A8F-E711-6DDAC07892D0")
static let RotorServiceUUID = CBUUID(string: "669A0C20-0008-1A8F-E711-6DDAD0F05DE1")
static let AdvertisementName = "Arrow_BB-GEVK"
static let DeviceTypeName = "onsemi-ble"
override var deviceName: String {
return deviceType.rawValue
}
override var deviceTypeName: String {
return OnSemiRSL10.DeviceTypeName
}
override var lookupName: String? {
return OnSemiRSL10.AdvertisementName
}
static func isValidAdvertisingName(_ advName: String) -> Bool {
let name = advName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).lowercased()
return ( name == OnSemiRSL10.AdvertisementName.lowercased() )
}
/// returns mac address from advertising data, or nil
/// - Parameter - data - data section from advertisment data
/// - returns: hex MAC address string with xx:xx:xx:xx:xx:xx or nil
static func macAddressFromData(_ data: Data) -> String? {
guard data.count == 10 else {
return nil
}
return String(format: "%02x:%02x:%02x:%02x:%02x:%02x", data[9], data[8], data[7], data[6], data[5], data[4])
}
private(set) var ledService: OnSemiRSL10LedService?
private(set) var motorService: OnSemiRSL10MotorService?
private(set) var rotorService: OnSemiRSL10RotorService?
init() {
super.init(DeviceType.OnSemiRSL10)
deviceTelemetry = [
Telemetry(type: SensorType.light, label: "Light"),
Telemetry(type: SensorType.pir, label: "Movement Detector")
]
deviceProperties = OnSemiRSL10Properties.sharedInstance
deviceProperties?.reload()
}
/// update states for various services in the cloud
func updateCloudState(_ state: StateModel, serviceName: String = "") {
guard let hid = loadDeviceId() else {
print("[OnSemiRSL10] - UpdateCloudState() for \(serviceName), device hid is nil!")
return
}
print( "[OnSemiRSL10] - UpdateCloudState() for \(serviceName)..." )
ArrowConnectIot.sharedInstance.deviceApi.deviceStateUpdate(hid: hid, state: state) { success in
if !success {
print("[OnSemiRSL10] - UpdateCloudState() failed to update state for \(serviceName)!")
}
}
}
// update service states gotten from the cloud
override func updateStates(states: [String : Any]) {
print("[OnSemiRSL10] - updateStates")
ledService?.updateStates(states: states)
motorService?.updateStates(states: states)
rotorService?.updateStates(states: states)
}
override func disable() {
super.disable()
motorService?.stopNotification()
}
override func createSensors(_ service: CBService) {
switch service.uuid {
case OnSemiRSL10.TelemetryServiceUUID:
createTelemetrySensors(service: service)
case OnSemiRSL10.LedServiceUUID:
ledService = OnSemiRSL10LedService(service: service)
ledService?.device = self
ledService?.requestLedValue(0)
ledService?.requestLedValue(1)
case OnSemiRSL10.MotorServiceUUID:
motorService = OnSemiRSL10MotorService(service: service)
motorService?.device = self
motorService?.requestMotorValue(0)
motorService?.requestMotorValue(1)
case OnSemiRSL10.RotorServiceUUID:
rotorService = OnSemiRSL10RotorService(service: service)
rotorService?.device = self
rotorService?.requestRotorValue()
default:
break
}
}
func createTelemetrySensors(service: CBService) {
guard let chars = service.characteristics else {
print("[OnSemiRSL10] - createTelemetrySensors - service chars is nil")
return
}
var sensor: BleSensorProtocol?
for char in chars {
sensor = nil
switch char.uuid {
case LightSensor.SensorUUID:
sensor = OnSemiRSL10.LightSensor(char: char)
case PirSensor.SensorUUID:
sensor = OnSemiRSL10.PirSensor(service)
default:
break
}
if sensor != nil {
sensorMap[char.uuid] = sensor
}
}
}
// MARK: - BLE char delegate
/// get updates for chars
override func charChanged(char: CBCharacteristic) {
if let ledService = ledService, ledService.updateData(char: char) {
return
}
if let motorService = motorService, motorService.updateData(char: char) {
return
}
if let rotorService = rotorService, rotorService.updateData(char: char) {
return
}
super.charChanged(char: char)
}
}
| 32 | 117 | 0.599286 |
de81e78b6b534445e0b2f341c5b568ceaa74c9de | 1,347 | //
// AppDelegate.swift
// Photos
//
// Created by Priyal PORWAL on 04/07/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.405405 | 179 | 0.74536 |
207ebd1b8576c345293e3f7cd20a9fe44d9ef86b | 1,192 | //
// Copyright (c) 2019 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import Foundation
extension URLSession: AdyenCompatible {}
public extension AdyenScope where Base: URLSession {
func dataTask(with url: URL, completion: @escaping ((Result<Data, Error>) -> Void)) -> URLSessionDataTask {
return base.dataTask(with: url, completionHandler: { data, _, error in
if let error = error {
completion(.failure(error))
} else if let data = data {
completion(.success(data))
} else {
fatalError("Invalid response.")
}
})
}
func dataTask(with urlRequest: URLRequest, completion: @escaping ((Result<Data, Error>) -> Void)) -> URLSessionDataTask {
return base.dataTask(with: urlRequest, completionHandler: { data, _, error in
if let error = error {
completion(.failure(error))
} else if let data = data {
completion(.success(data))
} else {
fatalError("Invalid response.")
}
})
}
}
| 33.111111 | 125 | 0.573826 |
38fdbcf4c5bdb47e72dfcdd7616d6d2ae528efc3 | 9,340 | //===-------------------- SyntaxData.swift - Syntax Data ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file contains modifications from the Silt Langauge project. These
// modifications are released under the MIT license, a copy of which is
// available in the repository.
//
//===----------------------------------------------------------------------===//
import Foundation
/// SyntaxData is the underlying storage for each Syntax node.
/// It's modelled as an array that stores and caches a SyntaxData for each raw
/// syntax node in its layout. It is up to the specific Syntax nodes to maintain
/// the correct layout of their SyntaxData backing stores.
///
/// SyntaxData is an implementation detail, and should not be exposed to clients
/// of libSyntax.
///
/// The following relationships are preserved:
/// parent.cachedChild(at: indexInParent) === self
/// raw.layout.count == childCaches.count
/// pathToRoot.first === indexInParent
final class SyntaxData: Equatable {
let raw: RawSyntax
let indexInParent: Int
weak var parent: SyntaxData?
let childCaches: [LazyNonThreadSafeCache<SyntaxData>]
private let positionCache: LazyNonThreadSafeCache<Box<AbsolutePosition>>
fileprivate func calculatePosition() -> AbsolutePosition {
guard let parent = parent else {
// If this node is SourceFileSyntax, its location is the start of the file.
return AbsolutePosition.startOfFile
}
// If the node is the first child of its parent, the location is same with
// the parent's location.
guard indexInParent != 0 else { return parent.position }
// Otherwise, the location is same with the previous sibling's location
// adding the stride of the sibling.
for idx in (0..<indexInParent).reversed() {
if let sibling = parent.cachedChild(at: idx) {
return sibling.position + sibling.raw.totalLength
}
}
return parent.position
}
/// The position of the start of this node's leading trivia
var position: AbsolutePosition {
return positionCache.value({ return Box(calculatePosition()) }).value
}
/// The position of the start of this node's content, skipping its trivia
var positionAfterSkippingLeadingTrivia: AbsolutePosition {
return position + raw.leadingTriviaLength
}
/// The end position of this node's content, excluding its trivia
var endPosition: AbsolutePosition {
return positionAfterSkippingLeadingTrivia + raw.contentLength
}
/// The end position of this node's trivia
var endPositionAfterTrailingTrivia: AbsolutePosition {
return endPosition + raw.trailingTriviaLength
}
/// Creates a SyntaxData with the provided raw syntax, pointing to the
/// provided index, in the provided parent.
/// - Parameters:
/// - raw: The raw syntax underlying this node.
/// - indexInParent: The index in the parent's layout where this node will
/// reside.
/// - parent: The parent of this node, or `nil` if this node is the root.
required init(raw: RawSyntax, indexInParent: Int = 0,
parent: SyntaxData? = nil) {
self.raw = raw
self.indexInParent = indexInParent
self.parent = parent
self.childCaches = raw.layout.map { _ in LazyNonThreadSafeCache<SyntaxData>() }
self.positionCache = LazyNonThreadSafeCache<Box<AbsolutePosition>>()
}
/// Returns the child data at the provided index in this data's layout.
/// This child is cached and will be used in subsequent accesses.
/// - Note: This function traps if the index is out of the bounds of the
/// data's layout.
///
/// - Parameter index: The index to create and cache.
/// - Returns: The child's data at the provided index.
func cachedChild(at index: Int) -> SyntaxData? {
if raw.layout[index] == nil { return nil }
return childCaches[index].value { realizeChild(index) }
}
/// Returns the child data at the provided cursor in this data's layout.
/// This child is cached and will be used in subsequent accesses.
/// - Note: This function traps if the cursor is out of the bounds of the
/// data's layout.
///
/// - Parameter cursor: The cursor to create and cache.
/// - Returns: The child's data at the provided cursor.
func cachedChild<CursorType: RawRepresentable>(
at cursor: CursorType) -> SyntaxData?
where CursorType.RawValue == Int {
return cachedChild(at: cursor.rawValue)
}
/// Walks up the provided node's parent tree looking for the receiver.
/// - parameter data: The potential child data.
/// - returns: `true` if the receiver exists in the parent chain of the
/// provided data.
/// - seealso: isDescendent(of:)
func isAncestor(of data: SyntaxData) -> Bool {
return data.isDescendent(of: self)
}
/// Walks up the receiver's parent tree looking for the provided node.
/// - parameter data: The potential ancestor data.
/// - returns: `true` if the data exists in the parent chain of the receiver.
/// - seealso: isAncestor(of:)
func isDescendent(of data: SyntaxData) -> Bool {
if data == self { return true }
var node = self
while let parent = node.parent {
if parent == data { return true }
node = parent
}
return false
}
/// Creates a copy of `self` and recursively creates `SyntaxData` nodes up to
/// the root.
/// - parameter newRaw: The new RawSyntax that will back the new `Data`
/// - returns: A tuple of both the new root node and the new data with the raw
/// layout replaced.
func replacingSelf(
_ newRaw: RawSyntax) -> (root: SyntaxData, newValue: SyntaxData) {
// If we have a parent already, then ask our current parent to copy itself
// recursively up to the root.
if let parent = parent {
let (root, newParent) = parent.replacingChild(newRaw, at: indexInParent)
let newMe = newParent.cachedChild(at: indexInParent)!
return (root: root, newValue: newMe)
} else {
// Otherwise, we're already the root, so return the new data as both the
// new root and the new data.
let newMe = SyntaxData(raw: newRaw, indexInParent: indexInParent,
parent: nil)
return (root: newMe, newValue: newMe)
}
}
/// Creates a copy of `self` with the child at the provided index replaced
/// with a new SyntaxData containing the raw syntax provided.
///
/// - Parameters:
/// - child: The raw syntax for the new child to replace.
/// - index: The index pointing to where in the raw layout to place this
/// child.
/// - Returns: The new root node created by this operation, and the new child
/// syntax data.
/// - SeeAlso: replacingSelf(_:)
func replacingChild(_ child: RawSyntax?,
at index: Int) -> (root: SyntaxData, newValue: SyntaxData) {
let newRaw = raw.replacingChild(index, with: child)
return replacingSelf(newRaw)
}
/// Creates a copy of `self` with the child at the provided cursor replaced
/// with a new SyntaxData containing the raw syntax provided.
///
/// - Parameters:
/// - child: The raw syntax for the new child to replace.
/// - cursor: A cursor that points to the index of the child you wish to
/// replace
/// - Returns: The new root node created by this operation, and the new child
/// syntax data.
/// - SeeAlso: replacingSelf(_:)
func replacingChild<CursorType: RawRepresentable>(_ child: RawSyntax?,
at cursor: CursorType) -> (root: SyntaxData, newValue: SyntaxData)
where CursorType.RawValue == Int {
return replacingChild(child, at: cursor.rawValue)
}
/// Creates the child's syntax data for the provided cursor.
///
/// - Parameter cursor: The cursor pointing into the raw syntax's layout for
/// the child you're creating.
/// - Returns: A new SyntaxData for the specific child you're
/// creating, whose parent is pointing to self.
func realizeChild<CursorType: RawRepresentable>(
_ cursor: CursorType) -> SyntaxData
where CursorType.RawValue == Int {
return realizeChild(cursor.rawValue)
}
/// Creates the child's syntax data for the provided index.
///
/// - Parameter cursor: The cursor pointing into the raw syntax's layout for
/// the child you're creating.
/// - Returns: A new SyntaxData for the specific child you're
/// creating, whose parent is pointing to self.
func realizeChild(_ index: Int) -> SyntaxData {
return SyntaxData(raw: raw.layout[index]!,
indexInParent: index,
parent: self)
}
/// Tells whether two SyntaxData nodes have the same identity.
/// This is not structural equality.
/// - Returns: True if both datas are exactly the same.
static func ==(lhs: SyntaxData, rhs: SyntaxData) -> Bool {
return lhs === rhs
}
}
| 40.258621 | 83 | 0.661563 |
d6e0fcd6303c463ac004b93efad83ef23737a54f | 5,485 | //
// FuzzingTests.swift
// Starscream
//
// Created by Dalton Cherry on 1/28/19.
// Copyright © 2019 Vluxe. All rights reserved.
//
import XCTest
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
@testable import Starscream
class FuzzingTests: XCTestCase {
var websocket: WebSocket!
var server: MockServer!
var uuid = ""
override func setUp() {
super.setUp()
let s = MockServer()
let _ = s.start(address: "", port: 0)
server = s
let transport = MockTransport(server: s)
uuid = transport.uuid
let url = URL(string: "http://vluxe.io/ws")! //domain doesn't matter with the mock transport
let request = URLRequest(url: url)
websocket = WebSocket(request: request, engine: WSEngine(transport: transport))
}
override func tearDown() {
super.tearDown()
}
func runWebsocket(timeout: TimeInterval = 10, serverAction: @escaping ((ServerEvent) -> Bool)) {
let e = expectation(description: "Websocket event timeout")
server.onEvent = { event in
let done = serverAction(event)
if done {
e.fulfill()
}
}
websocket.onEvent = { event in
switch event {
case .text(let string):
self.websocket.write(string: string)
case .binary(let data):
self.websocket.write(data: data)
case .ping(_):
break
case .pong(_):
break
case .connected(_):
break
case .disconnected(let reason, let code):
print("reason: \(reason) code: \(code)")
case .error(_):
break
case .viabilityChanged(_):
break
case .reconnectSuggested(_):
break
case .cancelled:
break
}
}
websocket.connect()
waitForExpectations(timeout: timeout) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func sendMessage(string: String, isBinary: Bool) {
let payload = string.data(using: .utf8)!
let code: FrameOpCode = isBinary ? .binaryFrame : .textFrame
runWebsocket { event in
switch event {
case .connected(let conn, _):
conn.write(data: payload, opcode: code)
case .text(let conn, let text):
if text == string && !isBinary {
conn.write(data: Data(), opcode: .connectionClose)
return true //success!
} else {
XCTFail("text does not match: source: [\(string)] response: [\(text)]")
}
case .binary(let conn, let data):
if payload.count == data.count && isBinary {
conn.write(data: Data(), opcode: .connectionClose)
return true //success!
} else {
XCTFail("binary does not match: source: [\(payload.count)] response: [\(data.count)]")
}
case .disconnected(_, _, _):
return false
default:
XCTFail("recieved unexpected server event: \(event)")
}
return false
}
}
//These are the Autobahn test cases as unit tests
/// MARK : - Framing cases
// case 1.1.1
func testCase1() {
sendMessage(string: "", isBinary: false)
}
// case 1.1.2
func testCase2() {
sendMessage(string: String(repeating: "*", count: 125), isBinary: false)
}
// case 1.1.3
func testCase3() {
sendMessage(string: String(repeating: "*", count: 126), isBinary: false)
}
// case 1.1.4
func testCase4() {
sendMessage(string: String(repeating: "*", count: 127), isBinary: false)
}
// case 1.1.5
func testCase5() {
sendMessage(string: String(repeating: "*", count: 128), isBinary: false)
}
// case 1.1.6
func testCase6() {
sendMessage(string: String(repeating: "*", count: 65535), isBinary: false)
}
// case 1.1.7, 1.1.8
func testCase7() {
sendMessage(string: String(repeating: "*", count: 65536), isBinary: false)
}
// case 1.2.1
func testCase9() {
sendMessage(string: "", isBinary: true)
}
// case 1.2.2
func testCase10() {
sendMessage(string: String(repeating: "*", count: 125), isBinary: true)
}
// case 1.2.3
func testCase11() {
sendMessage(string: String(repeating: "*", count: 126), isBinary: true)
}
// case 1.2.4
func testCase12() {
sendMessage(string: String(repeating: "*", count: 127), isBinary: true)
}
// case 1.2.5
func testCase13() {
sendMessage(string: String(repeating: "*", count: 128), isBinary: true)
}
// case 1.2.6
func testCase14() {
sendMessage(string: String(repeating: "*", count: 65535), isBinary: true)
}
// case 1.2.7, 1.2.8
func testCase15() {
sendMessage(string: String(repeating: "*", count: 65536), isBinary: true)
}
//TODO: the rest of them.
}
| 29.021164 | 106 | 0.519417 |
f7c684153e1d0abad46712bf50d551f934b8e16e | 11,805 | //
// Copyright (c) 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseMLCommon
@objc(ViewController)
class ViewController: UIViewController, UINavigationControllerDelegate {
// MARK: - Properties
/// A map of `ModelInterpreterManager` instances where the key is remote+local model name string.
private lazy var modelInterpreterManagerMap = [String: ModelInterpreterManager]()
/// The `ModelInterpreterManager` for the current remote and local models.
private lazy var manager = ModelInterpreterManager()
/// Indicates whether the download model button was selected.
private var downloadModelButtonSelected = false
/// An image picker for accessing the photo library or camera.
private var imagePicker = UIImagePickerController()
/// The currently selected remote model type.
private var currentRemoteModelType: RemoteModelType {
precondition(Thread.isMainThread)
guard let type = RemoteModelType(rawValue: modelControl.selectedSegmentIndex) else {
preconditionFailure("Invalid remote model type for selected segment index.")
}
return type
}
/// The currently selected local model type.
private var currentLocalModelType: LocalModelType {
precondition(Thread.isMainThread)
guard let type = LocalModelType(rawValue: modelControl.selectedSegmentIndex) else {
preconditionFailure("Invalid local model type for selected segment index.")
}
return type
}
private var isModelQuantized: Bool {
return isRemoteModelDownloaded ?
currentRemoteModelType == .quantized :
currentLocalModelType == .quantized
}
private var isRemoteModelDownloaded: Bool {
return UserDefaults.standard.bool(forKey: currentRemoteModelType.downloadCompletedKey)
}
// MARK: - IBOutlets
/// A segmented control for changing models (0 = float, 1 = quantized, 2 = invalid).
@IBOutlet private var modelControl: UISegmentedControl!
@IBOutlet private var imageView: UIImageView!
@IBOutlet private var resultsTextView: UITextView!
@IBOutlet private var detectButton: UIBarButtonItem!
@IBOutlet private var cameraButton: UIBarButtonItem!
@IBOutlet private var downloadModelButton: UIBarButtonItem!
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(named: Constant.defaultImage)
imagePicker.delegate = self
if !UIImagePickerController.isCameraDeviceAvailable(.front) ||
!UIImagePickerController.isCameraDeviceAvailable(.rear) {
cameraButton.isEnabled = false
}
updateModelInterpreterManager()
setUpRemoteModel()
setUpLocalModel()
}
// MARK: - IBActions
@IBAction func detectObjects(_ sender: Any) {
updateResultsText()
guard let image = imageView.image else {
updateResultsText("Image must not be nil.\n")
return
}
if !downloadModelButtonSelected {
updateResultsText("Loading the local model...\n")
if !manager.loadLocalModel(isModelQuantized: (currentLocalModelType == .quantized)) {
updateResultsText("Failed to load the local model.")
return
}
}
var newResultsTextString = "Starting inference...\n"
if let currentText = resultsTextView.text {
newResultsTextString = currentText + newResultsTextString
}
updateResultsText(newResultsTextString)
let remoteModelType = currentRemoteModelType
DispatchQueue.global(qos: .userInitiated).async {
let imageData = self.manager.scaledImageData(from: image)
self.manager.detectObjects(in: imageData) { (results, error) in
guard error == nil, let results = results, !results.isEmpty else {
var errorString = error?.localizedDescription ?? Constant.failedToDetectObjectsMessage
errorString = "Inference error: \(errorString)"
print(errorString)
self.updateResultsText(errorString)
return
}
var inferenceMessageString = "Inference results using "
if self.downloadModelButtonSelected {
UserDefaults.standard.set(true, forKey: remoteModelType.downloadCompletedKey)
inferenceMessageString += "`\(remoteModelType.description)` remote model:\n"
} else {
inferenceMessageString += "`\(self.currentLocalModelType.description)` local model:\n"
}
self.updateResultsText(inferenceMessageString +
"\(self.detectionResultsString(fromResults: results))")
}
}
}
@IBAction func openPhotoLibrary(_ sender: Any) {
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true)
}
@IBAction func openCamera(_ sender: Any) {
imagePicker.sourceType = .camera
present(imagePicker, animated: true)
}
@IBAction func downloadModel(_ sender: Any) {
updateResultsText()
downloadModelButtonSelected = true
updateResultsText(isRemoteModelDownloaded ?
"Remote model loaded. Select the `Detect` button to start the inference." :
"Downloading remote model...This text view will notify you when the downloaded model is " +
"ready to be used."
)
if !manager.loadRemoteModel(isModelQuantized: (currentRemoteModelType == .quantized)) {
updateResultsText("Failed to load the remote model.")
}
}
@IBAction func modelSwitched(_ sender: Any) {
updateResultsText()
updateModelInterpreterManager()
setUpLocalModel()
setUpRemoteModel()
}
// MARK: - Private
/// Updates the `ModelInterpreterManager` instance based on the current remote and local models.
private func updateModelInterpreterManager() {
precondition(Thread.isMainThread)
let key = currentRemoteModelType.description + "\(currentRemoteModelType.rawValue)" +
currentLocalModelType.description + "\(currentLocalModelType.rawValue)"
manager = modelInterpreterManagerMap[key] ?? ModelInterpreterManager()
modelInterpreterManagerMap[key] = manager
}
/// Sets up the currently selected remote model.
private func setUpRemoteModel() {
let modelName = currentRemoteModelType.description
if !manager.setUpRemoteModel(name: modelName) {
updateResultsText("\(resultsTextView.text ?? "")\nFailed to set up the `\(modelName)` " +
"remote model.")
}
}
/// Sets up the local model.
private func setUpLocalModel() {
let modelName = currentLocalModelType.description
if !manager.setUpLocalModel(name: modelName, filename: modelName) {
updateResultsText("\(resultsTextView.text ?? "")\nFailed to set up the local model.")
}
}
/// Updates the `downloadCompletedKey` in the User Defaults to true for the given remote model.
private func updateUserDefaults(for remoteModel: RemoteModel) {
let type = RemoteModelType.allCases.first { $0.description == remoteModel.name }
guard let key = type?.downloadCompletedKey else { return }
UserDefaults.standard.set(true, forKey: key)
}
/// Returns a string representation of the detection results.
private func detectionResultsString(
fromResults results: [(label: String, confidence: Float)]?
) -> String {
guard let results = results else { return Constant.failedToDetectObjectsMessage }
return results.reduce("") { (resultString, result) -> String in
let (label, confidence) = result
return resultString + "\(label): \(String(describing: confidence))\n"
}
}
/// Updates the results text view with the given text. The default is `nil`, so calling
/// `updateResultsText()` will clear the results.
private func updateResultsText(_ text: String? = nil) {
let updater = { self.resultsTextView.text = text }
if Thread.isMainThread { updater(); return }
DispatchQueue.main.async { updater() }
}
/// Updates the image view with a scaled version of the given image.
private func updateImageView(with image: UIImage) {
let orientation = UIApplication.shared.statusBarOrientation
let imageWidth = image.size.width
let imageHeight = image.size.height
guard imageWidth > .ulpOfOne, imageHeight > .ulpOfOne else {
self.imageView.image = image
print("Failed to update image view because image has invalid size: \(image.size)")
return
}
var scaledImageWidth: CGFloat = 0.0
var scaledImageHeight: CGFloat = 0.0
switch orientation {
case .portrait, .portraitUpsideDown, .unknown:
scaledImageWidth = imageView.bounds.size.width
scaledImageHeight = imageHeight * scaledImageWidth / imageWidth
case .landscapeLeft, .landscapeRight:
scaledImageWidth = imageWidth * scaledImageHeight / imageHeight
scaledImageHeight = imageView.bounds.size.height
}
DispatchQueue.global(qos: .userInitiated).async {
// Scale image while maintaining aspect ratio so it displays better in the UIImageView.
let scaledImage = image.scaledImage(
with: CGSize(width: scaledImageWidth, height: scaledImageHeight)
)
DispatchQueue.main.async {
self.imageView.image = scaledImage ?? image
}
}
}
}
// MARK: - UIImagePickerControllerDelegate
extension ViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
updateResultsText()
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
updateImageView(with: pickedImage)
}
dismiss(animated: true)
}
}
// MARK: - Constants
private enum Constant {
static let defaultImage = "grace_hopper.jpg"
static let failedToDetectObjectsMessage = "Failed to detect objects in image."
}
private enum RemoteModelType: Int, CustomStringConvertible {
case quantized = 0
case float = 1
case invalid = 2
var downloadCompletedKey: String {
switch self {
case .quantized:
return "FIRRemoteModel1DownloadCompleted"
case .float:
return "FIRRemoteModel2DownloadCompleted"
case .invalid:
return "FIRRemoteInvalidModel"
}
}
// MARK: - CustomStringConvertible
// REPLACE THESE REMOTE MODEL NAMES WITH ONES THAT ARE UPLOADED TO YOUR FIREBASE CONSOLE.
var description: String {
switch self {
case .quantized:
return "image-classification-quant-v2"
case .float:
return "image-classification-float-v2"
case .invalid:
return "invalid_model"
}
}
}
private enum LocalModelType: Int, CustomStringConvertible {
case quantized = 0
case float = 1
case invalid = 2
// MARK: - CustomStringConvertible
var description: String {
switch self {
case .quantized:
return MobileNet.quantizedModelInfo.name
case .float:
return MobileNet.floatModelInfo.name
case .invalid:
return MobileNet.invalidModelInfo.name
}
}
}
// MARK: - Extensions
#if !swift(>=4.2)
extension UIImagePickerController {
public typealias InfoKey = String
}
extension UIImagePickerController.InfoKey {
public static let originalImage = UIImagePickerControllerOriginalImage
}
#endif // !swift(>=4.2)
#if swift(>=4.2)
extension RemoteModelType: CaseIterable {}
#else
extension RemoteModelType {
static let allCases: [RemoteModelType] = [.quantized, .float, .invalid]
}
#endif // swift(>=4.2)
| 34.41691 | 142 | 0.719949 |
ed8a3e6d0fde5d2692aa12cbb436fa07e5db73ed | 3,590 | //
// PlayerInterface.swift
// FAVplayer
//
// Created by clement perez on 1/10/18.
// Copyright © 2018 com.frequency. All rights reserved.
//
import Foundation
import JavaScriptCore
/*!
@potocol This interface exposes the Swift player functions to the Javascript SDK
*/
@objc internal protocol JS2SwiftPlayerInterface : JSExport{
/*!
@method load:
@abstract Loads a mediaUrl in the player
@param mediaUrl
@discussion Use this method to load a specified mediaUrl in the player
The video playback will play automatically once the player item is loaded and ready to be played
*/
func load(mediaUrl: String) // will be called loadWithMediaUrl in javascript
/*!
@method play:
@abstract Starts or resume the playback of the video
*/
func play()
/*!
@method pause:
@abstract Pauses the playback of the video
*/
func pause()
/*!
@method seekTo:
@abstract Changes to progress of the playback of the video to the specified time in millisecond
@param progressInMs
*/
func seekTo(progressInMs: Double) // will be called seekToWithProgressInMs
/*!
@method getCurrentTime:
@abstract Get the current progress of the playback of the video in millisecond
@param progressInMs
@return The progress in millisecond
*/
func getCurrentTime() -> Double
/*!
@method getDuration:
@abstract Get the duration of the video in millisecond
@return The duration in millisecond
*/
func getDuration() -> Double // in ms
/*!
@method getState:
@abstract Get the current state of the playback
@return The string value of the PlaybackState
*/
func getState() -> String
/*!
@method lock:
@abstract Prevents the player from being paused or seeked
*/
func lock()
/*!
@method unlock:
@abstract Allows the player to be paused or seeked
*/
func unlock()
/*!
@method adCanSkip:
@abstract Method called when the ad has reach the offset after wich it can be skipped
func adCanSkip()
*/
/*!
@method add:
@abstract Allows to subscribe to a eventListner and specify a javascript function to be called back when the event is fired
@param eventListener
@param callback
*/
func add(eventListener: String, callback : String) // will be called addWithEventListenerCallback
/*!
@method remove:
@abstract Allows to remove the subscribed eventListner
@param eventListener
@param callback
*/
func remove(eventListener: String, callback : String)
/*!
@method onAd:
@abstract onAd event is fired when an ad related event occurs
@discussion See AdEvents for the possible values
*/
func onAd(title: String, duration: String, offset: String)
}
/*!
@potocol This interface is exposes methods of the PlayerService to the javascript code.
*/
@objc protocol JSCallbackInterface : JSExport{
/*!
@method onServiceReady:
@abstract Callback to inform the player that the service is loaded and initialized
@discussion No function to the service should be called before the service is ready.
*/
func onServiceReady()
}
| 28.951613 | 137 | 0.610864 |
394a38f4926bfa0c38b9da0504fc2111bbc4f485 | 2,107 | // swift-tools-version: 5.6
//
// Package.swift
//
// Copyright (c) 2022 Christian Gossain
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import PackageDescription
let package = Package(
name: "GenericResultsController",
platforms: [.iOS(.v12)],
products: [
.library(name: "GenericResultsController", targets: ["GenericResultsController"]),
],
dependencies: [
.package(url: "https://github.com/cgossain/Debounce.git", .upToNextMajor(from: "1.5.1")),
.package(url: "https://github.com/cgossain/Dwifft.git", .upToNextMajor(from: "0.10.0")),
],
targets: [
.target(
name: "GenericResultsController",
dependencies: [
.product(name: "Debounce", package: "Debounce"),
.product(name: "Dwifft", package: "Dwifft"),
]
),
.testTarget(
name: "GenericResultsControllerTests",
dependencies: [
"GenericResultsController"
]
),
],
swiftLanguageVersions: [.v5]
)
| 38.309091 | 97 | 0.664926 |
f71689553984739b91c97de1a513a42a9535b4a3 | 549 | //
// StarredFeedDelegate.swift
// NetNewsWire
//
// Created by Brent Simmons on 11/19/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import Articles
import Account
// Main thread only.
struct StarredFeedDelegate: SmartFeedDelegate {
let nameForDisplay = NSLocalizedString("Starred", comment: "Starred pseudo-feed title")
let fetchType: FetchType = .starred
func fetchUnreadCount(for account: Account, callback: @escaping (Int) -> Void) {
account.fetchUnreadCountForStarredArticles(callback)
}
}
| 22.875 | 88 | 0.757741 |
894af01cefe50c90a695e6905031b79810d4c877 | 6,568 | // Groot.swift
//
// Copyright (c) 2014-2016 Guillermo Gonzalez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreData
extension NSManagedObjectContext {
internal var managedObjectModel: NSManagedObjectModel? {
if let persistentStoreCoordinator = persistentStoreCoordinator {
return persistentStoreCoordinator.managedObjectModel
}
if let parent = parent {
return parent.managedObjectModel
}
return nil
}
}
extension NSManagedObject {
internal static func entity(inManagedObjectContext context: NSManagedObjectContext) -> NSEntityDescription {
guard let model = context.managedObjectModel else {
fatalError("Could not find managed object model for the provided context.")
}
let className = String(describing: self)
for entity in model.entities {
if entity.managedObjectClassName == className {
return entity
}
}
fatalError("Could not locate the entity for \(className).")
}
}
/// Creates or updates a set of managed objects from JSON data.
///
/// - parameter name: The name of an entity.
/// - parameter data: A data object containing JSON data.
/// - parameter context: The context into which to fetch or insert the managed objects.
///
/// - returns: An array of managed objects
public func objects(withEntityName name: String, fromJSONData data: Data, inContext context: NSManagedObjectContext) throws -> [NSManagedObject] {
return try GRTJSONSerialization.objects(withEntityName: name, fromJSONData: data, in: context)
}
/// Creates or updates a set of managed objects from JSON data.
///
/// - parameter data: A data object containing JSON data.
/// - parameter context: The context into which to fetch or insert the managed objects.
///
/// - returns: An array of managed objects.
public func objects<T: NSManagedObject>(fromJSONData data: Data, inContext context: NSManagedObjectContext) throws -> [T] {
let entity = T.entity(inManagedObjectContext: context)
let managedObjects = try objects(withEntityName: entity.name!, fromJSONData: data, inContext: context)
return managedObjects as! [T]
}
public typealias JSONDictionary = [String: Any]
/// Creates or updates a managed object from a JSON dictionary.
///
/// This method converts the specified JSON dictionary into a managed object of a given entity.
///
/// - parameter name: The name of an entity.
/// - parameter dictionary: A dictionary representing JSON data.
/// - parameter context: The context into which to fetch or insert the managed objects.
///
/// - returns: A managed object.
public func object(withEntityName name: String, fromJSONDictionary dictionary: JSONDictionary, inContext context: NSManagedObjectContext) throws -> NSManagedObject {
return try GRTJSONSerialization.object(withEntityName: name, fromJSONDictionary: dictionary, in: context)
}
/// Creates or updates a managed object from a JSON dictionary.
///
/// This method converts the specified JSON dictionary into a managed object.
///
/// - parameter dictionary: A dictionary representing JSON data.
/// - parameter context: The context into which to fetch or insert the managed objects.
///
/// - returns: A managed object.
public func object<T: NSManagedObject>(fromJSONDictionary dictionary: JSONDictionary, inContext context: NSManagedObjectContext) throws -> T {
let entity = T.entity(inManagedObjectContext: context)
let managedObject = try object(withEntityName: entity.name!, fromJSONDictionary: dictionary, inContext: context)
return managedObject as! T
}
public typealias JSONArray = [Any]
/// Creates or updates a set of managed objects from a JSON array.
///
/// - parameter name: The name of an entity.
/// - parameter array: An array representing JSON data.
/// - parameter context: The context into which to fetch or insert the managed objects.
///
/// - returns: An array of managed objects.
public func objects(withEntityName name: String, fromJSONArray array: JSONArray, inContext context: NSManagedObjectContext) throws -> [NSManagedObject] {
return try GRTJSONSerialization.objects(withEntityName: name, fromJSONArray: array, in: context)
}
/// Creates or updates a set of managed objects from a JSON array.
///
/// - parameter array: An array representing JSON data.
/// - parameter context: The context into which to fetch or insert the managed objects.
///
/// - returns: An array of managed objects.
public func objects<T: NSManagedObject>(fromJSONArray array: JSONArray, inContext context: NSManagedObjectContext) throws -> [T] {
let entity = T.entity(inManagedObjectContext: context)
let managedObjects = try objects(withEntityName: entity.name!, fromJSONArray: array, inContext: context)
return managedObjects as! [T]
}
/// Converts a managed object into a JSON representation.
///
/// - parameter object: The managed object to use for JSON serialization.
///
/// - returns: A JSON dictionary.
public func json(fromObject object: NSManagedObject) -> JSONDictionary {
return GRTJSONSerialization.jsonDictionary(from: object) as! JSONDictionary;
}
/// Converts an array of managed objects into a JSON representation.
///
/// - parameter objects: The array of managed objects to use for JSON serialization.
///
/// - returns: A JSON array.
public func json(fromObjects objects: [NSManagedObject]) -> JSONArray {
return GRTJSONSerialization.jsonArray(from: objects)
}
| 41.834395 | 165 | 0.735079 |
f9e108ac009fb028f9133453b2a2eeedb23b480d | 1,706 | //
// NPBaseViewController.swift
// NPBaseKit
//
// Created by 李永杰 on 2020/4/10.
// Copyright © 2020 NewPath. All rights reserved.
//
import UIKit
import SnapKit
open class NPBaseViewController: UIViewController {
open var contentView: UIView!
open var navigationBar: NPNavigationBar!
open override func viewDidLoad() {
super.viewDidLoad()
self.view.theme_backgroundColor = "Global.ViewControllerBackgroundColor"
addContentView()
}
open func addNavigationBar() {
navigationBar = NPNavigationBar.npNavigtionBar()
self.view.addSubview(navigationBar)
}
open func removeNavigationBar() {
if self.navigationBar != nil {
self.navigationBar.removeFromSuperview()
self.navigationBar = nil
}
}
open func addContentView() {
contentView = UIView()
contentView.backgroundColor = .white
self.view.addSubview(contentView)
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let haveNavigationBar = self.navigationBar != nil
if haveNavigationBar {
navigationBar.snp.makeConstraints { (make) in
make.top.left.right.equalToSuperview()
make.height.equalTo(kNavigationBarHeight)
}
contentView.snp.makeConstraints { (make) in
make.top.equalTo(navigationBar.snp.bottom)
make.left.bottom.right.equalToSuperview()
}
} else {
contentView.snp.makeConstraints { (make) in
make.top.left.bottom.right.equalToSuperview()
}
}
}
}
| 27.967213 | 80 | 0.617233 |
1d3647daad1bdd1a5374d7e68d90bc933dc2502f | 152 | import Foundation
/// Defines a resource.
public struct Resource: Decodable {
/// ID that uniquely identifies the resource.
public let id: String
}
| 16.888889 | 46 | 0.743421 |
227bcbcac1dba6a3a4a2360545a17dfb39b90cbb | 3,328 | // Copyright 2020 (c) Andrea Scuderi - https://github.com/swift-sprinter
//
// 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 SotoDynamoDB
import AWSLambdaEvents
import AWSLambdaRuntime
import AsyncHTTPClient
import Logging
import NIO
import ProductService
enum Operation: String {
case create = "build/Products.create"
case read = "build/Products.read"
case update = "build/Products.update"
case delete = "build/Products.delete"
case list = "build/Products.list"
}
struct EmptyResponse: Codable {}
struct ProductLambda: LambdaHandler {
typealias In = APIGateway.V2.Request
typealias Out = APIGateway.V2.Response
let dbTimeout: Int64 = 30
let region: Region
let db: SotoDynamoDB.DynamoDB
let service: ProductService
let tableName: String
let operation: Operation
var httpClient: HTTPClient
static func currentRegion() -> Region {
if let awsRegion = Lambda.env("AWS_REGION") {
let value = Region(rawValue: awsRegion)
return value
} else {
return .useast1
}
}
static func tableName() throws -> String {
guard let tableName = Lambda.env("PRODUCTS_TABLE_NAME") else {
throw APIError.tableNameNotFound
}
return tableName
}
init(context: Lambda.InitializationContext) throws {
guard let handler = Lambda.env("_HANDLER"),
let operation = Operation(rawValue: handler) else {
throw APIError.invalidHandler
}
self.operation = operation
self.region = Self.currentRegion()
let lambdaRuntimeTimeout: TimeAmount = .seconds(dbTimeout)
let timeout = HTTPClient.Configuration.Timeout(
connect: lambdaRuntimeTimeout,
read: lambdaRuntimeTimeout
)
let configuration = HTTPClient.Configuration(timeout: timeout)
self.httpClient = HTTPClient(
eventLoopGroupProvider: .shared(context.eventLoop),
configuration: configuration
)
let awsClient = AWSClient(httpClientProvider: .shared(self.httpClient))
self.db = SotoDynamoDB.DynamoDB(client: awsClient, region: region)
self.tableName = try Self.tableName()
self.service = ProductService(
db: db,
tableName: tableName
)
}
func handle(
context: Lambda.Context, event: APIGateway.V2.Request,
callback: @escaping (Result<APIGateway.V2.Response, Error>) -> Void
) {
let _ = ProductLambdaHandler(service: service, operation: operation)
.handle(context: context, event: event)
.always { (result) in
callback(result)
}
}
}
| 32 | 79 | 0.645132 |
39484f69dad56eb8c5dff2091d4fcee742fb4036 | 26,426 | /// warning types
@objc
public enum MjtWarning: Int32, CustomStringConvertible, CaseIterable {
case inertia = 0
case contactfull
case cnstrfull
case vgeomfull
case badqpos
case badqvel
case badqacc
case badctrl
public var description: String {
switch self {
case .inertia:
return "inertia"
case .contactfull:
return "contactfull"
case .cnstrfull:
return "cnstrfull"
case .vgeomfull:
return "vgeomfull"
case .badqpos:
return "badqpos"
case .badqvel:
return "badqvel"
case .badqacc:
return "badqacc"
case .badctrl:
return "badctrl"
}
}
}
@objc
public enum MjtTimer: Int32, CustomStringConvertible, CaseIterable {
case step = 0
case forward
case inverse
case position
case velocity
case actuation
case acceleration
case constraint
case posKinematics
case posInertia
case posCollision
case posMake
case posProject
public var description: String {
switch self {
case .step:
return "step"
case .forward:
return "forward"
case .inverse:
return "inverse"
case .position:
return "position"
case .velocity:
return "velocity"
case .actuation:
return "actuation"
case .acceleration:
return "acceleration"
case .constraint:
return "constraint"
case .posKinematics:
return "posKinematics"
case .posInertia:
return "posInertia"
case .posCollision:
return "posCollision"
case .posMake:
return "posMake"
case .posProject:
return "posProject"
}
}
}
/// disable default feature bitflags
public struct MjtDisableBit: OptionSet, CustomStringConvertible, CaseIterable {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static let constraint = MjtDisableBit(rawValue: 1 << 0)
public static let equality = MjtDisableBit(rawValue: 1 << 1)
public static let frictionloss = MjtDisableBit(rawValue: 1 << 2)
public static let limit = MjtDisableBit(rawValue: 1 << 3)
public static let contact = MjtDisableBit(rawValue: 1 << 4)
public static let passive = MjtDisableBit(rawValue: 1 << 5)
public static let gravity = MjtDisableBit(rawValue: 1 << 6)
public static let clampctrl = MjtDisableBit(rawValue: 1 << 7)
public static let warmstart = MjtDisableBit(rawValue: 1 << 8)
public static let filterparent = MjtDisableBit(rawValue: 1 << 9)
public static let actuation = MjtDisableBit(rawValue: 1 << 10)
public static let refsafe = MjtDisableBit(rawValue: 1 << 11)
public static let allCases: [MjtDisableBit] = [
.constraint, .equality, .frictionloss, .limit, .contact, .passive, .gravity, .clampctrl,
.warmstart, .filterparent, .actuation, .refsafe,
]
public var description: String {
switch self {
case .constraint:
return "constraint"
case .equality:
return "equality"
case .frictionloss:
return "frictionloss"
case .limit:
return "limit"
case .contact:
return "contact"
case .passive:
return "passive"
case .gravity:
return "gravity"
case .clampctrl:
return "clampctrl"
case .warmstart:
return "warmstart"
case .filterparent:
return "filterparent"
case .actuation:
return "actuation"
case .refsafe:
return "refsafe"
default:
return "MjtDisableBit(rawValue: \(rawValue))"
}
}
}
/// enable optional feature bitflags
public struct MjtEnableBit: OptionSet, CustomStringConvertible, CaseIterable {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static let override = MjtEnableBit(rawValue: 1 << 0)
public static let energy = MjtEnableBit(rawValue: 1 << 1)
public static let fwdinv = MjtEnableBit(rawValue: 1 << 2)
public static let sensornoise = MjtEnableBit(rawValue: 1 << 3)
public static let multiccd = MjtEnableBit(rawValue: 1 << 4)
public static let allCases: [MjtEnableBit] = [
.override, .energy, .fwdinv, .sensornoise, .multiccd,
]
public var description: String {
switch self {
case .override:
return "override"
case .energy:
return "energy"
case .fwdinv:
return "fwdinv"
case .sensornoise:
return "sensornoise"
case .multiccd:
return "multiccd"
default:
return "MjtEnableBit(rawValue: \(rawValue))"
}
}
}
/// type of degree of freedom
@objc
public enum MjtJoint: Int32, CustomStringConvertible {
case free = 0
case ball
case slide
case hinge
public var description: String {
switch self {
case .free:
return "free"
case .ball:
return "ball"
case .slide:
return "slide"
case .hinge:
return "hinge"
}
}
}
/// type of geometric shape
@objc
public enum MjtGeom: Int32, CustomStringConvertible, CaseIterable {
case plane = 0
case hfield
case sphere
case capsule
case ellipsoid
case cylinder
case box
case mesh
case arrow = 100
case arrow1
case arrow2
case line
case skin
case label
case none = 1001
public var description: String {
switch self {
case .plane:
return "plane"
case .hfield:
return "hfield"
case .sphere:
return "sphere"
case .capsule:
return "capsule"
case .ellipsoid:
return "ellipsoid"
case .cylinder:
return "cylinder"
case .box:
return "box"
case .mesh:
return "mesh"
case .arrow:
return "arrow"
case .arrow1:
return "arrow1"
case .arrow2:
return "arrow2"
case .line:
return "line"
case .skin:
return "skin"
case .label:
return "label"
case .none:
return "none"
}
}
}
/// tracking mode for camera and light
@objc
public enum MjtCamLight: Int32, CustomStringConvertible {
case fixed = 0
case track
case trackcom
case targetbody
case targetbodycom
public var description: String {
switch self {
case .fixed:
return "fixed"
case .track:
return "track"
case .trackcom:
return "trackcom"
case .targetbody:
return "targetbody"
case .targetbodycom:
return "targetbodycom"
}
}
}
/// type of texture
@objc
public enum MjtTexture: Int32, CustomStringConvertible {
case _2d = 0
case cube
case skybox
public var description: String {
switch self {
case ._2d:
return "_2d"
case .cube:
return "cube"
case .skybox:
return "skybox"
}
}
}
/// integrator mode
@objc
public enum MjtIntegrator: Int32, CustomStringConvertible {
case euler = 0
case rk4
case implicit
public var description: String {
switch self {
case .euler:
return "euler"
case .rk4:
return "rk4"
case .implicit:
return "implicit"
}
}
}
/// collision mode for selecting geom pairs
@objc
public enum MjtCollision: Int32, CustomStringConvertible {
case all = 0
case pair
case `dynamic`
public var description: String {
switch self {
case .all:
return "all"
case .pair:
return "pair"
case .`dynamic`:
return "dynamic"
}
}
}
/// type of friction cone
@objc
public enum MjtCone: Int32, CustomStringConvertible {
case pyramidal = 0
case elliptic
public var description: String {
switch self {
case .pyramidal:
return "pyramidal"
case .elliptic:
return "elliptic"
}
}
}
/// type of constraint Jacobian
@objc
public enum MjtJacobian: Int32, CustomStringConvertible {
case dense = 0
case sparse
case auto
public var description: String {
switch self {
case .dense:
return "dense"
case .sparse:
return "sparse"
case .auto:
return "auto"
}
}
}
/// constraint solver algorithm
@objc
public enum MjtSolver: Int32, CustomStringConvertible {
case pgs = 0
case cg
case newton
public var description: String {
switch self {
case .pgs:
return "pgs"
case .cg:
return "cg"
case .newton:
return "newton"
}
}
}
/// type of equality constraint
@objc
public enum MjtEq: Int32, CustomStringConvertible {
case connect = 0
case weld
case joint
case tendon
case distance
public var description: String {
switch self {
case .connect:
return "connect"
case .weld:
return "weld"
case .joint:
return "joint"
case .tendon:
return "tendon"
case .distance:
return "distance"
}
}
}
/// type of tendon wrap object
@objc
public enum MjtWrap: Int32, CustomStringConvertible {
case none = 0
case joint
case pulley
case site
case sphere
case cylinder
public var description: String {
switch self {
case .none:
return "none"
case .joint:
return "joint"
case .pulley:
return "pulley"
case .site:
return "site"
case .sphere:
return "sphere"
case .cylinder:
return "cylinder"
}
}
}
/// type of actuator transmission
@objc
public enum MjtTrn: Int32, CustomStringConvertible {
case joint = 0
case jointinparent
case slidercrank
case tendon
case site
case undefined = 1000
public var description: String {
switch self {
case .joint:
return "joint"
case .jointinparent:
return "jointinparent"
case .slidercrank:
return "slidercrank"
case .tendon:
return "tendon"
case .site:
return "site"
case .undefined:
return "undefined"
}
}
}
/// type of actuator dynamics
@objc
public enum MjtDyn: Int32, CustomStringConvertible {
case none = 0
case integrator
case filter
case muscle
case user
public var description: String {
switch self {
case .none:
return "none"
case .integrator:
return "integrator"
case .filter:
return "filter"
case .muscle:
return "muscle"
case .user:
return "user"
}
}
}
/// type of actuator gain
@objc
public enum MjtGain: Int32, CustomStringConvertible {
case fixed = 0
case muscle
case user
public var description: String {
switch self {
case .fixed:
return "fixed"
case .muscle:
return "muscle"
case .user:
return "user"
}
}
}
/// type of actuator bias
@objc
public enum MjtBias: Int32, CustomStringConvertible {
case none = 0
case affine
case muscle
case user
public var description: String {
switch self {
case .none:
return "none"
case .affine:
return "affine"
case .muscle:
return "muscle"
case .user:
return "user"
}
}
}
/// type of MujoCo object
@objc
public enum MjtObj: Int32, CustomStringConvertible {
case unknown = 0
case body
case xbody
case joint
case dof
case geom
case site
case camera
case light
case mesh
case skin
case hfield
case texture
case material
case pair
case exclude
case equality
case tendon
case actuator
case sensor
case numeric
case text
case tuple
case key
public var description: String {
switch self {
case .unknown:
return "unknown"
case .body:
return "body"
case .xbody:
return "xbody"
case .joint:
return "joint"
case .dof:
return "dof"
case .geom:
return "geom"
case .site:
return "site"
case .camera:
return "camera"
case .light:
return "light"
case .mesh:
return "mesh"
case .skin:
return "skin"
case .hfield:
return "hfield"
case .texture:
return "texture"
case .material:
return "material"
case .pair:
return "pair"
case .exclude:
return "exclude"
case .equality:
return "equality"
case .tendon:
return "tendon"
case .actuator:
return "actuator"
case .sensor:
return "sensor"
case .numeric:
return "numeric"
case .text:
return "text"
case .tuple:
return "tuple"
case .key:
return "key"
}
}
}
/// type of constraint
@objc
public enum MjtConstraint: Int32, CustomStringConvertible {
case equality = 0
case frictionDof
case frictionTendon
case limitJoint
case limitTendon
case contactFrictionless
case contactPyramidal
case contactElliptic
public var description: String {
switch self {
case .equality:
return "equality"
case .frictionDof:
return "frictionDof"
case .frictionTendon:
return "frictionTendon"
case .limitJoint:
return "limitJoint"
case .limitTendon:
return "limitTendon"
case .contactFrictionless:
return "contactFrictionless"
case .contactPyramidal:
return "contactPyramidal"
case .contactElliptic:
return "contactElliptic"
}
}
}
/// constraint state
@objc
public enum MjtConstraintState: Int32, CustomStringConvertible {
case satisfied = 0
case quadratic
case linearneg
case linearpos
case cone
public var description: String {
switch self {
case .satisfied:
return "satisfied"
case .quadratic:
return "quadratic"
case .linearneg:
return "linearneg"
case .linearpos:
return "linearpos"
case .cone:
return "cone"
}
}
}
/// type of sensor
@objc
public enum MjtSensor: Int32, CustomStringConvertible {
case touch = 0
case accelerometer
case velocimeter
case gyro
case force
case torque
case magnetometer
case rangefinder
case jointpos
case jointvel
case tendonpos
case tendonvel
case actuatorpos
case actuatorvel
case actuatorfrc
case ballquat
case ballangvel
case jointlimitpos
case jointlimitvel
case jointlimitfrc
case tendonlimitpos
case tendonlimitvel
case tendonlimitfrc
case framepos
case framequat
case framexaxis
case frameyaxis
case framezaxis
case framelinvel
case frameangvel
case framelinacc
case frameangacc
case subtreecom
case subtreelinvel
case subtreeangmom
case user
public var description: String {
switch self {
case .touch:
return "touch"
case .accelerometer:
return "accelerometer"
case .velocimeter:
return "velocimeter"
case .gyro:
return "gyro"
case .force:
return "force"
case .torque:
return "torque"
case .magnetometer:
return "magnetometer"
case .rangefinder:
return "rangefinder"
case .jointpos:
return "jointpos"
case .jointvel:
return "jointvel"
case .tendonpos:
return "tendonpos"
case .tendonvel:
return "tendonvel"
case .actuatorpos:
return "actuatorpos"
case .actuatorvel:
return "actuatorvel"
case .actuatorfrc:
return "actuatorfrc"
case .ballquat:
return "ballquat"
case .ballangvel:
return "ballangvel"
case .jointlimitpos:
return "jointlimitpos"
case .jointlimitvel:
return "jointlimitvel"
case .jointlimitfrc:
return "jointlimitfrc"
case .tendonlimitpos:
return "tendonlimitpos"
case .tendonlimitvel:
return "tendonlimitvel"
case .tendonlimitfrc:
return "tendonlimitfrc"
case .framepos:
return "framepos"
case .framequat:
return "framequat"
case .framexaxis:
return "framexaxis"
case .frameyaxis:
return "frameyaxis"
case .framezaxis:
return "framezaxis"
case .framelinvel:
return "framelinvel"
case .frameangvel:
return "frameangvel"
case .framelinacc:
return "framelinacc"
case .frameangacc:
return "frameangacc"
case .subtreecom:
return "subtreecom"
case .subtreelinvel:
return "subtreelinvel"
case .subtreeangmom:
return "subtreeangmom"
case .user:
return "user"
}
}
}
/// computation stage
@objc
public enum MjtStage: Int32, CustomStringConvertible {
case none = 0
case pos
case vel
case acc
public var description: String {
switch self {
case .none:
return "none"
case .pos:
return "pos"
case .vel:
return "vel"
case .acc:
return "acc"
}
}
}
/// data type for sensors
@objc
public enum MjtDataType: Int32, CustomStringConvertible {
case real = 0
case positive
case axis
case quaternion
public var description: String {
switch self {
case .real:
return "real"
case .positive:
return "positive"
case .axis:
return "axis"
case .quaternion:
return "quaternion"
}
}
}
/// mode for actuator length range computation
@objc
public enum MjtLRMode: Int32, CustomStringConvertible {
case none = 0
case muscle
case muscleuser
case all
public var description: String {
switch self {
case .none:
return "none"
case .muscle:
return "muscle"
case .muscleuser:
return "muscleuser"
case .all:
return "all"
}
}
}
/// grid position for overlay
@objc
public enum MjtGridPos: Int32, CustomStringConvertible {
case topleft = 0
case topright
case bottomleft
case bottomright
public var description: String {
switch self {
case .topleft:
return "topleft"
case .topright:
return "topright"
case .bottomleft:
return "bottomleft"
case .bottomright:
return "bottomright"
}
}
}
/// OpenGL framebuffer option
@objc
public enum MjtFramebuffer: Int32, CustomStringConvertible {
case window = 0
case offscreen
public var description: String {
switch self {
case .window:
return "window"
case .offscreen:
return "offscreen"
}
}
}
/// font scale, used at context creation
@objc
public enum MjtFontScale: Int32, CustomStringConvertible {
case _50 = 50
case _100 = 100
case _150 = 150
case _200 = 200
case _250 = 250
case _300 = 300
public var description: String {
switch self {
case ._50:
return "_50"
case ._100:
return "_100"
case ._150:
return "_150"
case ._200:
return "_200"
case ._250:
return "_250"
case ._300:
return "_300"
}
}
}
/// font type, used at each text operation
@objc
public enum MjtFont: Int32, CustomStringConvertible {
case normal = 0
case shadow
case big
public var description: String {
switch self {
case .normal:
return "normal"
case .shadow:
return "shadow"
case .big:
return "big"
}
}
}
/// mouse button
@objc
public enum MjtButton: Int32, CustomStringConvertible {
case none = 0
case left
case right
case middle
public var description: String {
switch self {
case .none:
return "none"
case .left:
return "left"
case .right:
return "right"
case .middle:
return "middle"
}
}
}
/// mouse and keyboard event type
@objc
public enum MjtEvent: Int32, CustomStringConvertible {
case none = 0
case move
case press
case release
case scroll
case key
case resize
public var description: String {
switch self {
case .none:
return "none"
case .move:
return "move"
case .press:
return "press"
case .release:
return "release"
case .scroll:
return "scroll"
case .key:
return "key"
case .resize:
return "resize"
}
}
}
/// UI item type
@objc
public enum MjtItem: Int32, CustomStringConvertible, CaseIterable {
case end = -2
case section = -1
case separator = 0
case `static`
case button
case checkint
case checkbyte
case radio
case radioline
case select
case sliderint
case slidernum
case editint
case editnum
case edittxt
public var description: String {
switch self {
case .end:
return "end"
case .section:
return "section"
case .separator:
return "separator"
case .`static`:
return "static"
case .button:
return "button"
case .checkint:
return "checkint"
case .checkbyte:
return "checkbyte"
case .radio:
return "radio"
case .radioline:
return "radioline"
case .select:
return "select"
case .sliderint:
return "sliderint"
case .slidernum:
return "slidernum"
case .editint:
return "editint"
case .editnum:
return "editnum"
case .edittxt:
return "edittxt"
}
}
}
/// bitflags for mjvGeom category
public struct MjtCatBit: OptionSet, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static let `static` = MjtCatBit(rawValue: 1)
public static let `dynamic` = MjtCatBit(rawValue: 2)
public static let decor = MjtCatBit(rawValue: 4)
public static let all = MjtCatBit(rawValue: 7)
public var description: String {
switch self {
case .`static`:
return "static"
case .`dynamic`:
return "dynamic"
case .decor:
return "decor"
case .all:
return "all"
default:
return "MjtCatBit(rawValue: \(rawValue))"
}
}
}
/// mouse interaction mode
@objc
public enum MjtMouse: Int32, CustomStringConvertible {
case none = 0
case rotateV
case rotateH
case moveV
case moveH
case zoom
case select
public var description: String {
switch self {
case .none:
return "none"
case .rotateV:
return "rotateV"
case .rotateH:
return "rotateH"
case .moveV:
return "moveV"
case .moveH:
return "moveH"
case .zoom:
return "zoom"
case .select:
return "select"
}
}
}
/// mouse perturbations
public struct MjtPertBit: OptionSet, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static let translate = MjtPertBit(rawValue: 1)
public static let rotate = MjtPertBit(rawValue: 2)
public var description: String {
switch self {
case .translate:
return "translate"
case .rotate:
return "rotate"
default:
return "MjtPertBit(rawValue: \(rawValue))"
}
}
}
/// abstract camera type
@objc
public enum MjtCamera: Int32, CustomStringConvertible {
case free = 0
case tracking
case fixed
case user
public var description: String {
switch self {
case .free:
return "free"
case .tracking:
return "tracking"
case .fixed:
return "fixed"
case .user:
return "user"
}
}
}
/// object labeling
@objc
public enum MjtLabel: Int32, CustomStringConvertible, CaseIterable {
case none = 0
case body
case joint
case geom
case site
case camera
case light
case tendon
case actuator
case constraint
case skin
case selection
case selpnt
case contactforce
public var description: String {
switch self {
case .none:
return "none"
case .body:
return "body"
case .joint:
return "joint"
case .geom:
return "geom"
case .site:
return "site"
case .camera:
return "camera"
case .light:
return "light"
case .tendon:
return "tendon"
case .actuator:
return "actuator"
case .constraint:
return "constraint"
case .skin:
return "skin"
case .selection:
return "selection"
case .selpnt:
return "selpnt"
case .contactforce:
return "contactforce"
}
}
}
/// frame visualization
@objc
public enum MjtFrame: Int32, CustomStringConvertible, CaseIterable {
case none = 0
case body
case geom
case site
case camera
case light
case contact
case world
public var description: String {
switch self {
case .none:
return "none"
case .body:
return "body"
case .geom:
return "geom"
case .site:
return "site"
case .camera:
return "camera"
case .light:
return "light"
case .contact:
return "contact"
case .world:
return "world"
}
}
}
/// flags enabling model element visualization
@objc
public enum MjtVisFlag: Int32, CustomStringConvertible, CaseIterable {
case convexhull = 0
case texture
case joint
case actuator
case camera
case light
case tendon
case rangefinder
case constraint
case inertia
case sclinertia
case pertforce
case pertobj
case contactpoint
case contactforce
case contactsplit
case transparent
case autoconnect
case com
case select
case `static`
case skin
public var description: String {
switch self {
case .convexhull:
return "convexhull"
case .texture:
return "texture"
case .joint:
return "joint"
case .actuator:
return "actuator"
case .camera:
return "camera"
case .light:
return "light"
case .tendon:
return "tendon"
case .rangefinder:
return "rangefinder"
case .constraint:
return "constraint"
case .inertia:
return "inertia"
case .sclinertia:
return "sclinertia"
case .pertforce:
return "pertforce"
case .pertobj:
return "pertobj"
case .contactpoint:
return "contactpoint"
case .contactforce:
return "contactforce"
case .contactsplit:
return "contactsplit"
case .transparent:
return "transparent"
case .autoconnect:
return "autoconnect"
case .com:
return "com"
case .select:
return "select"
case .`static`:
return "static"
case .skin:
return "skin"
}
}
}
/// flags enabling rendering effects
@objc
public enum MjtRndFlag: Int32, CustomStringConvertible, CaseIterable {
case shadow = 0
case wireframe
case reflection
case additive
case skybox
case fog
case haze
case segment
case idcolor
public var description: String {
switch self {
case .shadow:
return "shadow"
case .wireframe:
return "wireframe"
case .reflection:
return "reflection"
case .additive:
return "additive"
case .skybox:
return "skybox"
case .fog:
return "fog"
case .haze:
return "haze"
case .segment:
return "segment"
case .idcolor:
return "idcolor"
}
}
}
/// type of stereo rendering
@objc
public enum MjtStereo: Int32, CustomStringConvertible {
case none = 0
case quadbuffered
case sidebyside
public var description: String {
switch self {
case .none:
return "none"
case .quadbuffered:
return "quadbuffered"
case .sidebyside:
return "sidebyside"
}
}
}
| 20.580997 | 92 | 0.639787 |
335a3ed40f0eeea2e6a1906605a792c5f1a21533 | 4,279 | //
// PeersListViewController.swift
// SkyWay-iOS-Sample
//
// Author: <a href={@docRoot}/author.html}>Author</a>
// Copyright: <a href={@docRoot}/copyright.html}>Copyright</a>
//
import UIKit
class PeersListViewController: UITableViewController {
static let CellIdentifier = "ITEMS"
var items: Array<String>?
var callback: UIViewController?
override init(style: UITableViewStyle) {
super.init(style: style)
self.items = nil
self.callback = nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
self.items = nil
self.callback = nil
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.allowsSelection = true
self.tableView.allowsMultipleSelection = false
self.navigationItem.title = "Select Target's PeerID"
let bbiBack: UIBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.cancel))
self.navigationItem.leftBarButtonItem = bbiBack
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: PeersListViewController.CellIdentifier)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.tableView.delegate = nil
self.tableView.dataSource = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
guard let items = self.items else {
return 0
}
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: PeersListViewController.CellIdentifier, for: indexPath)
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: PeersListViewController.CellIdentifier)
cell?.separatorInset = UIEdgeInsets.zero
}
if let items = self.items {
let iRow = indexPath.row
if items.count > iRow {
cell?.textLabel?.text = items[iRow]
}
}
return cell!
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let strTo = self.items?[indexPath.row]
if let callback = self.callback {
callback.dismiss(animated: true, completion: {
if let dcvc: DataConnectionViewController = callback as? DataConnectionViewController {
if dcvc.responds(to: #selector(dcvc.callingTo(strDestId:))) {
dcvc.performSelector(inBackground: #selector(dcvc.callingTo(strDestId:)), with: strTo)
}
} else if let mcvc: MediaConnectionViewController = callback as? MediaConnectionViewController {
if mcvc.responds(to: #selector(mcvc.callingTo(strDestId:))) {
mcvc.performSelector(inBackground: #selector(mcvc.callingTo(strDestId:)), with: strTo)
}
}
})
} else {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: -
func cancel() {
if let callback = self.callback {
callback.dismiss(animated: true, completion: nil)
} else {
self.dismiss(animated: true, completion: nil)
}
}
}
| 35.07377 | 152 | 0.636831 |
f96e913ed99e72d2f5117696b6c3e5b7babc5bd4 | 2,298 | //
// SceneDelegate.swift
// AudioWaveformGraph
//
// Created by John Scalo on 12/11/20.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 44.192308 | 147 | 0.714099 |
22ea7f6658f5e12cc0b9e478bd397652e88decae | 30,542 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basics
import PackageModel
import PackageLoading
import SPMTestSupport
import TSCBasic
import XCTest
class TargetSourcesBuilderTests: XCTestCase {
func testBasicFileContentsComputation() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: ["some2"],
sources: nil,
resources: [
.init(rule: .copy, path: "some/path/toBeCopied")
],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift",
"/some/path.swift",
"/some2/path2.swift",
"/.some2/hello.swift",
"/Hello.something/hello.txt",
"/file",
"/path/to/file.xcodeproj/pbxproj",
"/path/to/somefile.txt",
"/some/path/toBeCopied/cool/hello.swift",
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageLocation: "test",
packagePath: .root,
target: target,
path: .root,
defaultLocalization: nil,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
let contents = builder.computeContents().map{ $0.pathString }.sorted()
XCTAssertEqual(contents, [
"/Bar.swift",
"/Foo.swift",
"/Hello.something/hello.txt",
"/file",
"/path/to/somefile.txt",
"/some/path.swift",
"/some/path/toBeCopied",
])
XCTAssertNoDiagnostics(observability.diagnostics)
}
func testDirectoryWithExt() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: ["some2"],
sources: nil,
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/some2/hello.swift",
"/Hello.something/hello.txt",
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageLocation: "test",
packagePath: .root,
target: target,
path: .root,
defaultLocalization: nil,
toolsVersion: .v5_3,
fileSystem: fs,
observabilityScope: observability.topScope
)
let contents = builder.computeContents().map{ $0.pathString }.sorted()
XCTAssertEqual(contents, [
"/Hello.something",
])
XCTAssertNoDiagnostics(observability.diagnostics)
}
func testBasicRuleApplication() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: ["some2"],
sources: nil,
resources: [
.init(rule: .process, path: "path"),
.init(rule: .copy, path: "some/path/toBeCopied"),
],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift",
"/some/path.swift",
"/some2/path2.swift",
"/.some2/hello.swift",
"/Hello.something/hello.txt",
"/file",
"/path/to/file.xcodeproj/pbxproj",
"/path/to/somefile.txt",
"/path/to/somefile2.txt",
"/some/path/toBeCopied/cool/hello.swift",
])
let somethingRule = FileRuleDescription(
rule: .processResource,
toolsVersion: .minimumRequired,
fileTypes: ["something"])
build(target: target, additionalFileRules: [somethingRule], toolsVersion: .v5, fs: fs) { _, _, _, _, _, _, _ in
// No diagnostics
}
}
func testDoesNotErrorWithAdditionalFileRules() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: nil,
resources: [],
publicHeadersPath: nil,
type: .regular
)
let files = [
"/Foo.swift",
"/Bar.swift",
"/Baz.something"
]
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: files)
let somethingRule = FileRuleDescription(
rule: .compile,
toolsVersion: .v5_5,
fileTypes: ["something"]
)
build(target: target, additionalFileRules: [somethingRule], toolsVersion: .v5_5, fs: fs) { sources, _, _, _, _, _, _ in
XCTAssertEqual(
sources.paths.map(\.pathString).sorted(),
files.sorted()
)
}
}
func testResourceConflicts() throws {
// Conflict between processed resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Resources")
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/foo.txt",
"/Resources/Sub/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(diagnostic: "multiple resources named 'foo.txt' in target 'Foo'", severity: .error, metadata: expectedMetadata)
diagnostics.checkUnordered(diagnostic: "found 'Resources/foo.txt'", severity: .info, metadata: expectedMetadata)
diagnostics.checkUnordered(diagnostic: "found 'Resources/Sub/foo.txt'", severity: .info, metadata: expectedMetadata)
}
}
// Conflict between processed and copied resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Processed"),
.init(rule: .copy, path: "Copied/foo.txt"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Processed/foo.txt",
"/Copied/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(diagnostic: "multiple resources named 'foo.txt' in target 'Foo'", severity: .error, metadata: expectedMetadata)
diagnostics.checkUnordered(diagnostic: "found 'Processed/foo.txt'", severity: .info, metadata: expectedMetadata)
diagnostics.checkUnordered(diagnostic: "found 'Copied/foo.txt'", severity: .info, metadata: expectedMetadata)
}
}
// No conflict between processed and copied in sub-path resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Processed"),
.init(rule: .copy, path: "Copied"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Processed/foo.txt",
"/Copied/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, _, _, diagnostics in
// No diagnostics
}
}
// Conflict between copied directory resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .copy, path: "A/Copy"),
.init(rule: .copy, path: "B/Copy"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/A/Copy/foo.txt",
"/B/Copy/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(diagnostic: "multiple resources named 'Copy' in target 'Foo'", severity: .error, metadata: expectedMetadata)
diagnostics.checkUnordered(diagnostic: "found 'A/Copy'", severity: .info, metadata: expectedMetadata)
diagnostics.checkUnordered(diagnostic: "found 'B/Copy'", severity: .info, metadata: expectedMetadata)
}
}
// Conflict between processed localizations.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "A"),
.init(rule: .process, path: "B"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/A/en.lproj/foo.txt",
"/B/EN.lproj/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(diagnostic: "multiple resources named 'en.lproj/foo.txt' in target 'Foo'", severity: .error, metadata: expectedMetadata)
diagnostics.checkUnordered(diagnostic: "found 'A/en.lproj/foo.txt'", severity: .info, metadata: expectedMetadata)
diagnostics.checkUnordered(diagnostic: "found 'B/EN.lproj/foo.txt'", severity: .info, metadata: expectedMetadata)
}
}
// Conflict between processed localizations and copied resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "A"),
.init(rule: .copy, path: "B/en.lproj"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/A/EN.lproj/foo.txt",
"/B/en.lproj/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(
diagnostic: "resource 'B/en.lproj' in target 'Foo' conflicts with other localization directories",
severity: .error,
metadata: expectedMetadata
)
}
}
}
func testLocalizationDirectoryIgnoredOn5_2() throws {
let target = try TargetDescription(name: "Foo")
let fs = InMemoryFileSystem(emptyFiles:
"/en.lproj/Localizable.strings"
)
build(target: target, toolsVersion: .v5_2, fs: fs) { _, resources, _, _, _, _, _ in
XCTAssert(resources.isEmpty)
// No diagnostics
}
}
func testLocalizationDirectorySubDirectory() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Processed"),
.init(rule: .copy, path: "Copied")
])
let fs = InMemoryFileSystem(emptyFiles:
"/Processed/en.lproj/sub/Localizable.strings",
"/Copied/en.lproj/sub/Localizable.strings"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(
diagnostic: "localization directory 'Processed/en.lproj' in target 'Foo' contains sub-directories, which is forbidden",
severity: .error,
metadata: expectedMetadata
)
}
}
func testExplicitLocalizationInLocalizationDirectory() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Resources", localization: .base),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/en.lproj/Localizable.strings"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(
diagnostic: .contains("""
resource 'Resources/en.lproj/Localizable.strings' in target 'Foo' is in a localization directory \
and has an explicit localization declaration
"""),
severity: .error,
metadata: expectedMetadata
)
}
}
func testMissingDefaultLocalization() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Resources"),
.init(rule: .process, path: "Image.png", localization: .default),
.init(rule: .process, path: "Icon.png", localization: .base),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/en.lproj/Localizable.strings",
"/Resources/en.lproj/Icon.png",
"/Resources/fr.lproj/Localizable.strings",
"/Resources/fr.lproj/Sign.png",
"/Resources/Base.lproj/Storyboard.storyboard",
"/Image.png",
"/Icon.png"
)
build(target: target, defaultLocalization: "fr", toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(
diagnostic: .contains("resource 'Icon.png' in target 'Foo' is missing the default localization 'fr'"),
severity: .warning,
metadata: expectedMetadata
)
}
}
func testLocalizedAndUnlocalizedResources() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Resources"),
.init(rule: .process, path: "Image.png", localization: .default),
.init(rule: .process, path: "Icon.png", localization: .base),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/en.lproj/Localizable.strings",
"/Resources/Localizable.strings",
"/Resources/Base.lproj/Storyboard.storyboard",
"/Resources/Storyboard.storyboard",
"/Resources/Image.png",
"/Resources/Icon.png",
"/Image.png",
"/Icon.png"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.checkUnordered(
diagnostic: .contains("resource 'Localizable.strings' in target 'Foo' has both localized and un-localized variants"),
severity: .warning,
metadata: expectedMetadata
)
diagnostics.checkUnordered(
diagnostic: .contains("resource 'Storyboard.storyboard' in target 'Foo' has both localized and un-localized variants"),
severity: .warning,
metadata: expectedMetadata
)
diagnostics.checkUnordered(
diagnostic: .contains("resource 'Image.png' in target 'Foo' has both localized and un-localized variants"),
severity: .warning,
metadata: expectedMetadata
)
diagnostics.checkUnordered(
diagnostic: .contains("resource 'Icon.png' in target 'Foo' has both localized and un-localized variants"),
severity: .warning,
metadata: expectedMetadata
)
}
}
func testLocalizedResources() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Processed"),
.init(rule: .copy, path: "Copied"),
.init(rule: .process, path: "Other/Launch.storyboard", localization: .base),
.init(rule: .process, path: "Other/Image.png", localization: .default),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Processed/foo.txt",
"/Processed/En-uS.lproj/Localizable.stringsdict",
"/Processed/en-US.lproj/Localizable.strings",
"/Processed/fr.lproj/Localizable.strings",
"/Processed/fr.lproj/Localizable.stringsdict",
"/Processed/Base.lproj/Storyboard.storyboard",
"/Copied/en.lproj/Localizable.strings",
"/Other/Launch.storyboard",
"/Other/Image.png"
)
build(target: target, defaultLocalization: "fr", toolsVersion: .v5_3, fs: fs) { _, resources, _, _, identity, location, diagnostics in
XCTAssertEqual(Set(resources), [
Resource(rule: .process, path: AbsolutePath("/Processed/foo.txt"), localization: nil),
Resource(rule: .process, path: AbsolutePath("/Processed/En-uS.lproj/Localizable.stringsdict"), localization: "en-us"),
Resource(rule: .process, path: AbsolutePath("/Processed/en-US.lproj/Localizable.strings"), localization: "en-us"),
Resource(rule: .process, path: AbsolutePath("/Processed/fr.lproj/Localizable.strings"), localization: "fr"),
Resource(rule: .process, path: AbsolutePath("/Processed/fr.lproj/Localizable.stringsdict"), localization: "fr"),
Resource(rule: .process, path: AbsolutePath("/Processed/Base.lproj/Storyboard.storyboard"), localization: "Base"),
Resource(rule: .copy, path: AbsolutePath("/Copied"), localization: nil),
Resource(rule: .process, path: AbsolutePath("/Other/Launch.storyboard"), localization: "Base"),
Resource(rule: .process, path: AbsolutePath("/Other/Image.png"), localization: "fr"),
])
}
}
func testLocalizedImage() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/fr.lproj/Image.png",
"/Foo/es.lproj/Image.png"
)
build(target: try TargetDescription(name: "Foo"), defaultLocalization: "fr", toolsVersion: .v5_3, fs: fs) { _, resources, _, _, identity, location, diagnostics in
XCTAssertEqual(Set(resources), [
Resource(rule: .process, path: AbsolutePath("/Foo/fr.lproj/Image.png"), localization: "fr"),
Resource(rule: .process, path: AbsolutePath("/Foo/es.lproj/Image.png"), localization: "es"),
])
}
}
func testInfoPlistResource() throws {
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process, path: "Resources"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/Processed/Info.plist"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(
diagnostic: .contains("resource 'Resources/Processed/Info.plist' in target 'Foo' is forbidden"),
severity: .error,
metadata: expectedMetadata
)
}
}
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .copy, path: "Resources/Copied/Info.plist"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/Copied/Info.plist"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, location, diagnostics in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: identity, location: location)
expectedMetadata.targetName = target.name
diagnostics.check(
diagnostic: .contains("resource 'Resources/Copied/Info.plist' in target 'Foo' is forbidden"),
severity: .error,
metadata: expectedMetadata
)
}
}
}
func build(
target: TargetDescription,
defaultLocalization: String? = nil,
additionalFileRules: [FileRuleDescription] = [],
toolsVersion: ToolsVersion,
fs: FileSystem,
file: StaticString = #file,
line: UInt = #line,
checker: (Sources, [Resource], [AbsolutePath], [AbsolutePath], PackageIdentity, String, DiagnosticsTestResult) -> ()
) {
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageLocation: "/test",
packagePath: .root,
target: target,
path: .root,
defaultLocalization: defaultLocalization,
additionalFileRules: additionalFileRules,
toolsVersion: toolsVersion,
fileSystem: fs,
observabilityScope: observability.topScope
)
do {
let (sources, resources, headers, others) = try builder.run()
testDiagnostics(observability.diagnostics, file: file, line: line) { diagnostics in
checker(sources, resources, headers, others, builder.packageIdentity, builder.packageLocation, diagnostics)
}
} catch {
XCTFail(error.localizedDescription, file: file, line: line)
}
}
func testMissingExclude() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: ["fakeDir", "../../fileOutsideRoot.py"],
sources: nil,
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift"
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageLocation: "/test",
packagePath: .root,
target: target,
path: .root,
defaultLocalization: nil,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
testDiagnostics(observability.diagnostics) { result in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: builder.packageIdentity, location: builder.packageLocation)
expectedMetadata.targetName = target.name
result.checkUnordered(diagnostic: "Invalid Exclude '/fileOutsideRoot.py': File not found.", severity: .warning, metadata: expectedMetadata)
result.checkUnordered(diagnostic: "Invalid Exclude '/fakeDir': File not found.", severity: .warning, metadata: expectedMetadata)
}
}
func testMissingResource() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: nil,
resources: [.init(rule: .copy, path: "../../../Fake.txt"),
.init(rule: .process, path: "NotReal")],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift"
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageLocation: "/test",
packagePath: .root,
target: target,
path: .root,
defaultLocalization: nil,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
_ = try builder.run()
testDiagnostics(observability.diagnostics) { result in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: builder.packageIdentity, location: builder.packageLocation)
expectedMetadata.targetName = target.name
result.checkUnordered(diagnostic: "Invalid Resource '../../../Fake.txt': File not found.", severity: .warning, metadata: expectedMetadata)
result.checkUnordered(diagnostic: "Invalid Resource 'NotReal': File not found.", severity: .warning, metadata: expectedMetadata)
}
}
func testMissingSource() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: ["InvalidPackage.swift",
"DoesNotExist.swift",
"../../Tests/InvalidPackageTests/InvalidPackageTests.swift"],
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift"
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageLocation: "/test",
packagePath: .root,
target: target,
path: .root,
defaultLocalization: nil,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
testDiagnostics(observability.diagnostics) { result in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: builder.packageIdentity, location: builder.packageLocation)
expectedMetadata.targetName = target.name
result.checkUnordered(diagnostic: "Invalid Source '/InvalidPackage.swift': File not found.", severity: .warning, metadata: expectedMetadata)
result.checkUnordered(diagnostic: "Invalid Source '/DoesNotExist.swift': File not found.", severity: .warning, metadata: expectedMetadata)
result.checkUnordered(diagnostic: "Invalid Source '/Tests/InvalidPackageTests/InvalidPackageTests.swift': File not found.", severity: .warning, metadata: expectedMetadata)
}
}
func testXcodeSpecificResourcesAreNotIncludedByDefault() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: ["File.swift"],
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/File.swift",
"/Foo.xcdatamodel"
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageLocation: "/test",
packagePath: .root,
target: target,
path: .root,
defaultLocalization: nil,
toolsVersion: .v5_5,
fileSystem: fs,
observabilityScope: observability.topScope
)
_ = try builder.run()
testDiagnostics(observability.diagnostics) { result in
var expectedMetadata = ObservabilityMetadata.packageMetadata(identity: builder.packageIdentity, location: builder.packageLocation)
expectedMetadata.targetName = target.name
result.check(diagnostic: "found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target\n /Foo.xcdatamodel\n", severity: .warning, metadata: expectedMetadata)
}
}
func testDocCFilesDoNotCauseWarningOutsideXCBuild() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: ["File.swift"],
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/File.swift",
"/Foo.docc"
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageLocation: "test",
packagePath: .root,
target: target,
path: .root,
defaultLocalization: nil,
additionalFileRules: FileRuleDescription.swiftpmFileTypes,
toolsVersion: .v5_5,
fileSystem: fs,
observabilityScope: observability.topScope
)
_ = try builder.run()
XCTAssertNoDiagnostics(observability.diagnostics)
}
}
| 39.613489 | 212 | 0.575503 |
64b7ddd72ff1b5c68c40fc3dc756f3ee316dafbe | 17,857 | import UIKit
let input = """
qtmdwspah
sqwdamhpt
phwdaqsmt
stmdqwhap
pqawdhtms
bgsickuztovfwa
yiozauvgfsbtkwc
zygijavmtfkcuwobs
fvsuwtiadzrncboklg
dxgieku
dihnxkgf
mqybtd
yqbtd
btydq
rgpbcfxtzoewy
otbyrfgwxzpec
yocrwtebzxgfp
qcpngeodrszaky
ocaqrngsyuz
xwenu
nwsxuye
xapwvhsktlmr
twpslarxhvkm
vhlwmrapxkts
pmkxraswvlth
ksrxpvtmwahl
xhcepbdsltvk
khcdptsixbg
spbjtdchxk
cbkxspqtdrh
kaishmtdl
jcnprqigt
pjqtekodlmwcaginxfzrushbv
iuyzsfaxcvrotdmklgebpnjwqh
dirxeqbswlonhzumgafvckptj
zqpitfrjnmhvuxbcdlwkogase
khncmsfdzlgwpvriotxujbaeq
motb
twm
mvt
nomt
euwhdnlaxbtjiqz
dquxjznhtlwebia
atzdwxqiunhlebj
jnwlzxdiuaheqbt
jnktcwaovpbqzei
qcrljzskbvo
tangojspuvlwbryeicz
eujvkaporgwdilbyfscztn
pjrisxqwdoyze
cvyzmjlqxsgpeirw
xieqwcajzslryp
xjpzerwqyamis
rftxglbkpqnchvajs
cnsvqgpurtjfeb
m
mcx
wramgjy
mv
meacfoiqpbzy
zmvqpaibegoyfc
oiyzmaengcfbpq
uiaqprbycmzfoe
qjdnecvmsr
sdmecpqn
gt
tg
bndhmeupwszlqiycofkt
fcrptkulhixjnazvmdg
nrcytwdaozvbmhsjuk
owarihdekqzslvnxmubyfpj
suzlnmxvkwjyodhbrag
fz
zf
zefpk
fz
fz
zfnqcdhvjwxa
hxfazjcwd
xzhtajkfwcd
weusntyxblcdqpvgfzoam
oxiyslgabqvdhnwzm
jneuovbpgfxlsmkwd
kjbwonlspfdumcegthv
omvfbgejaiwnkdulsp
orfgdlbqjkvhumpewns
mhb
hb
dhjxb
boh
af
tzlbugdkq
j
qhgnav
ngvahqp
gvnqha
hoer
oufeq
u
gmy
td
naguhdzsmcxlye
pglwjsvxzduc
uosgxqzldct
xugcszld
qcxsgtlzoud
uoxacitdkeh
kypudjgbsefi
bjywqhgcps
uaybelqkjpiwc
yblwqpjec
jwvyrcpbqzt
qjgywbocp
cuvwxkmrnliodphaj
rvuzcdxknphol
hprvkucdonsxl
qtgjunkhaovbw
wkgvotljhbq
blfvtr
vrtfby
mbtvjdfnr
xbftpvrh
svbrhptf
rijakd
kadnijer
kqdwjifar
jdrihkmaz
ejnirkfda
ysukmtloxgjhvnwp
qjxlwnvpyzsgbutomd
gxpdqomijnhkyws
vyqgxmjpowhsnik
mnxqhgykwiopjs
fm
u
fc
zd
yplnbikosxj
welcjifhgnzupo
izfpwljnodctheg
dtlhgznwepcojif
hzwvgpcifnjleo
wgpqvtcnjofhlezi
azhipsvbx
xwbip
ixpb
xbip
bpxi
yxhpltiuvzorefqnwm
azwiylnohxmejqurftvp
hvuzwfxmnqyeltpro
kwxghtdyfreqmplvzuon
n
f
a
f
xfoaj
ofsqb
eqfo
canrzup
znarcpu
pzcnrua
czaupnr
puchnzra
hwxtaqvsci
rhxylbskwcjmoid
svqexwhaic
whxisc
xfamongdyrhjpizqbtswl
tsnermfbvidyqcwhlxuzg
jz
zj
zj
mohrs
rom
mro
orm
rnwbshdkxv
vkrjwsdthnxb
kjwrxhsvnb
rnbhvxowas
lbdahrf
ralbfhd
lhfadbr
radhflb
wztomybdgaqhu
rmuohgyqbdz
dgzqrumoayhb
hgqdmyubjpeoz
mgdquhzoyb
xiy
yix
bixoy
xyi
xiy
xvzqjwfkhctgeayu
kdjmlrow
vnlu
ulnvg
wluvn
lvun
btmcqewifuh
gqvakfzrmyuicsjpdbo
npfy
yznfx
ynf
b
b
b
b
b
zuhkqwfpm
mqpzwkhf
pnwfqchkzm
kfumpqzhw
qzwhkmpfu
pcevtdhgylnmsxaqiuzkr
pxanvcgiquethzksmylrd
vdszgiqyautrpxhcnmlek
bhru
ubhr
uhvopbr
trbizhud
omnpx
yp
cpf
p
fuhokrpewbyvlnjcdmqi
pcijvmskndtwohxylqeurf
cdvfhebukmjrqnolwpiy
qpwhymlcfjrndoeuivk
xwehzfud
wupfdexz
xbdh
jxdhb
hmkbuyl
rtcefpsaui
jlfsy
oknuy
kvpy
hcgzs
hegzs
sapzhd
vnhjbqk
bkvqnhjd
vhnkqjb
jhnkqvb
bnhjkvq
myjnp
wkyjamn
kmyjna
rupvd
pvrud
rpdvu
kvnlmhgizwdbjsxf
nmfdkzgjxlbvsiwh
zmsphibqwglkejfxrvn
ge
eg
g
g
ga
eivbk
vikeb
bkiyve
puvf
fvup
uvfp
pvuf
fvup
rydhgfbmpktzvlewjusn
wqgfnovcerskjad
ekrfsjgvowndcxq
muco
ouse
pxoihbg
bogpxhi
aik
k
k
qa
aq
aq
aq
snezvhbkwa
nvzuaksbh
zbvalskhn
xposdbmhnavgzk
thvfcbznkulas
jaxdfucymsghp
hfxaqcwunsjgmkpyd
glfdjpuzxacyhm
sp
ps
cesof
vsu
s
svu
sv
s
t
te
t
epnq
oeyqn
nqe
qen
qne
taxpglnzkejswbo
zekwtongjpbxas
gasokxnzbejpwty
wanzsfbgpxjeotk
wzxaengjkbptfso
imftvao
vtmif
pbjelcf
prnhgwqem
xopmzg
zfoxg
xzgo
ozxg
gmcybniqevotjda
ytiebavgdqojcnm
mr
m
f
n
mnhpxfircz
cihmvrxzyf
ygibvxud
ykubiqxgvd
xydibeuv
buvqdyxi
budxiyv
zjpqlmftionbgu
tzbfgjiqoumapn
nzcjuftibompqg
aztbmoiqnjfgup
chpnjmvlw
hlbrdvqemcnwp
pnkvcmlwh
lmcyfwpvhn
ynlmcjvipawh
kzhxeqfa
feaxqzkh
hzxkaeqf
zfqhexka
fqxahkze
blwqdpy
yqdaniplwbe
jhxbrwdylngqs
qwtdylukzvbm
asobzdl
jahzxpdy
daksz
zadufl
ahunxksgp
sakhpun
nukathps
uzhnsapk
pmusknahz
yzmogwp
tbqcp
bnpcr
xhp
dhyxojbvrqnml
nkr
rnc
wngra
kmdynhutpjlvxaroce
pbwohkjtmyfnzg
tjoikmhypnsq
zduqkfivgjo
oizvjfuqbd
zvjuqrfigdo
vudqiozjf
oidvqyzuftj
usmo
sm
sm
ms
njf
f
glft
auh
hwiavfug
xevqipr
gwxdmlsuakcyf
iltoavmycurph
luhcarivtomxy
yihcratumoevxl
louhcvmiytra
miqzdtolhrcayuvwg
xwtcmqso
xdnimfbyr
okimydfr
uhgzfyjqat
evjdtmcoxiklhpgwq
qgnxbkftmhiy
ixqrakuhngytm
hfzpe
uefphkb
afmwhqpek
fvpoygjinlhexds
oly
byoal
yol
koly
oyl
k
k
k
k
k
ofhrz
xhpruzq
zrh
hwgrbedykvsmzin
ginxcsjevrwyqz
egysvqncxzrij
syvgzcnreqijx
zcvxgsjrqenyi
qyfvzirnjcgxes
eyxfutwoqjbrvkgds
xsfjoutrbeqwkvgyd
vqwtjgdbrsfoyukxe
vfurtykqgebjwosdx
eypubrkojqvdsgtfwx
odwmeztifrjxn
nrgmwlxc
vgkxwrlnm
tz
tz
rtz
daze
ezyad
ujqdozgh
goujdmqkzh
jghuqdzo
gjozdqhu
erdnakojyfzchvxg
hfekdrnctgvzpyjaxom
hwi
wih
hiw
hiw
krqdscaoiwhnyz
rwjaknoxyidzsqhpc
rnyqdawcoskifghz
wahrqznyvdcskiuo
swlakrxjmtpv
inaylxhdjwkmsvur
qbxavfrlewkcsjm
ucxvtw
ue
u
lu
oztxeqjvgb
tpdbjgoqe
spyqunh
uypnhqs
fdw
safw
wfjh
wfomxi
lwfsdn
daibtezjo
qtxeaizjmdb
aoejitbkzd
etadizjb
jkeynazqvobiflrushcwtgdmxp
wnrjequcdxlkmtfobihsvy
iksvuebxtjwmhfrdqyocln
gkxq
pkw
kw
swy
ywsn
jzqurhixawto
gaojpfrzciq
izoxrtqawj
asoihjqzutr
wijlermdyzhstf
zjlrwfsdhmtiey
elymwztijfrdhs
qatxy
tyq
nja
yha
a
gfsav
kha
uebolhvntdkfsxap
fpnlskhdeuobva
oahteupksbvdlnf
oeulbvhdpfksna
ansgphkrfdlovebu
vpe
vedp
pev
pev
pev
zacfpshmrequykt
tuzarfpmknwc
pzuimacvfktr
cjeqourh
eouqcljr
rojueqc
ykoi
koyi
koyi
kiyo
fvkhuntrmpz
ckngmxirpuzvat
rfuvksnozpath
bntdrlyvkzupj
rukwpvtzcn
wczery
eczwrby
wrzcey
xjndayl
hnlyaxdj
lndayxj
ynjdlaxt
j
j
j
tj
awhrfvjbzduistx
gnyhcmteop
ym
y
sy
my
zkai
ajiz
aiz
aiz
ikaz
irgsokuwy
lnxtcqsiwmf
busyvhzidw
qxhpynjewsfmkd
hwpqenfkydm
aedbfmx
fwexa
jgckhspy
zpusakfeb
izpev
sdepzu
znpwe
pqjgehtxzr
vqmlkjznbeiofahucdtsgw
utmvhgqedbocfwkszjlain
yfbqzaspnlgotrdjxuhvkemiwc
idglcasthofkuemnbjwqzv
uqhdebp
chdbquepl
qedzphbu
hupdqbe
qbedhpu
ehnv
t
aksmbzu
wvlhktdqpjmsirz
fznykbsem
ksgmz
kzxsymc
vnoetrhlgkcmqxdp
nvdqtkolcrhxep
pxcedrnhoiltqvk
elrxnhitcpqdokv
ymuxitzqsagrkofcvbj
tauxskfigjymro
cnfdjwbxkisp
cpydkbjxwsifn
cipnkbufswdjrx
ybkxihfwejnscdp
yueaplwitfdvkoxnbjcmrqgz
jvlfmxoakzwiegpbdnrquct
manwikovgbpuhrcfesjlzxtqd
lptzwxfn
fpnxtlz
nxtflegzpj
dkpuyaefsijvlrhgqxmnt
bshiwokugpflvtmzeqxnyja
in
n
xzou
ng
gn
epqbvmi
vqembi
bvmeqizu
mbeqiv
cjapgriulbzeq
ugiqdzcvpobjlrek
zqleircpubjg
cirjuqbzgepl
nhpsreikdjzo
hkjsnodipzer
znoidphekjrs
dezf
edfz
efdz
rdfze
nzitsqrfp
qiznrfspt
rfqizspnt
nsqizrptf
xntrkogqfapj
nioagqtmrfkjyp
is
sgdi
qsity
pe
ep
ep
ep
uhvpiwdgsfr
uwlpcqrezykovni
aevu
ae
ea
ae
djzfhxmas
msdxhz
zexhdsymt
dxzshktm
dzemshxg
msqiuvncoltxejg
cqxfmsonlvute
wmfblsrogvjinpc
rplfngicojbkvwms
cfbolhnjvrsimwgk
gmisflrwnkcjbov
vmwrcbosjngfuil
kbxitoqvzajudfnsgmyc
ikfwcxzgvtjedmsyouqnab
aqknmufjiypcvxbgodstz
eshyzxbqncuomfpwgk
gzcxqpmhljeoyuikbfrn
bzhxveutpfyaqmkcong
evqyuicpfhl
yquckvlpiejf
anf
szydm
qt
qt
qt
mfyovqgpnlbcxidauzh
cqniopdhfgxlauvzbmy
idxofbaylmcznuvqhpg
qbcpihzogydlfvmnwuxa
qgvcumyizpnabxdfhol
btwjlohyfaq
ydlwprkj
rhisamcj
csirha
srcaih
icshar
mejydkgtnfovuzix
enuvirjogdmkyxztf
xefomztvkungysdijc
jxdginfktapovyzueqhm
fioktdsnemgjuzyxv
hrztvexlkob
lwekirhbxdzqtmo
etxv
arxtvue
exvft
fwdnqsomhtryxvcgzej
eczwytuhfsgmdqnxoj
ycdsqwznhftgjmkoxe
tsjnexcafwmhygzbvqod
xovcfts
cfsopxvdt
xoscfvt
osfxtvc
w
rc
t
zs
ik
lzm
zpl
romqvb
mvo
uy
y
y
y
govwliuabszqp
goiabwfusvzlpnq
qpiwgbvaosulz
apvguizblwsqo
s
m
s
s
ozpiljymxhswnfuevt
emvbwshnylzxpjti
nveblmzchtwjiypsx
nldfsb
sfblndt
sdblfn
bnflds
ndslbf
ieg
idew
wonxsab
wbsaoxn
nobaxws
wasbnox
alscukjbf
lsbjakfc
jxcduqioabwpyhlzef
ialdxwfzycqjhbepuo
jfzypowishadclxbueq
riydchjfnwqvtmbpsaloxe
dsbwfintzelormhvxcaqpyj
ejomaiyqsxcthfvpdlwbnr
lrycvtunboifgxawqemhpjd
xvtiafqrdwnoymclepbhj
jsydqempfvntrhui
miyefthpuqsrvnj
zsvyrmhbtuelpqinfja
nuphytvreqmfsji
cltvanwuh
tulachoyvwn
tuwclvanh
bixkgozashw
hakibzoswmx
poxkblmhqjftwsdcn
bhtykpvzjxuiengao
j
j
j
cqodguxrzles
loxqcrgeszudw
ocsdqruxglze
rugqoyxesdzlcf
ulzdorxgsqec
yvz
vyz
mfq
sztdnk
py
zawgmj
jawgz
gwapjz
sgzajw
ekoadscpwhg
jsuchbxmfyzlnwq
wlkrqcjux
xuqjclr
gjrqlcxu
afcosnhvprzblxtwd
abszvxoglnctfhpwr
bjhlvzfwceayksxtun
tzvnxrhwlmsfacbd
igreocyhquzjmvlx
liowjethfkqszvmxdyu
ljeqkvwpdazgocf
cqgdyvmjuwpeotainsr
mhoylsckuzxbiaevq
vyczxkjeoapsbifu
kxbdosyzavujiec
mwsfxbkjqazpiohgnyldc
xqgnadblfkwpcomshiy
wgvsalrhqbmieyxodpfnkc
eurqfmtkvjbosh
vyqrhkotfblmseu
brtfqkvoheums
rvtksmehoubqf
uwftdoarkmvqgehbcps
ctyalrqdxskjuoh
dlathrokujqxs
hxsqukdoaltjr
osrqkautljxdh
zfdlxtr
sburlzxd
zlrdx
ocfb
cbfo
uykhxqrtmnc
ahigrcuptnxdqmk
tckz
ktzc
vzgtxhkums
kvzmhtgus
sgthkzumv
vzxsgmkuht
znqmuhvkswgt
jtdwk
ydkti
kdt
dkjt
mwxehozbnqpad
ryjdeblzwxnpoucqahmtg
liumaz
izulam
zauloim
miludzaqr
rzkjguslxohwnfdivm
ofulwkhisgvjmnrxzd
dikwvojugxzfrmnlsh
sxjdzkcuworbnvgflmih
vlmxrzikndhwjofgus
fzqnodmx
a
v
lfoeh
leovfh
hofsle
djku
kjud
dukj
qtiwbxfhlzjnokvpadruymgse
onurjdisvgzwaqkybftlhpmex
fnmqwuhtyjrkepbgildovxasz
marndljbkegqxtupviscywfhzo
fdbqehtxkavjimzwporsugyln
aqkonbhvfdljigp
phaqrlkbjdin
phldcbkaumjvinq
iplbjxeykqhdazn
zsl
sz
xsyzh
zs
xdhlq
ndlkxjyu
xlde
xdl
blwmairvkofcuq
tedokrvbqm
pw
p
iqrbnglofs
grwuylifvkbq
yl
yl
xaizpuhlqo
kiloxm
ilkox
puaorhzmtvfg
mutoegrhzafv
lrzmpt
dpqyihnsa
jfiodcs
spi
swni
isn
ohdmyvlpbxjnqzfrswiuaeg
ceafhrujqtndivbxpwzsmg
mvoxyd
tvdoymx
xdymov
py
y
nutogsehiczykpmdvf
ngmueistpxkfodhvzrcy
yuhczioegpvmnfktsd
zp
z
zbc
z
z
creyt
uisfmova
er
dltugzhniyjro
lizndhrutojyg
jhgnzytuordli
lhgotuznirjydc
xtrckznswlueia
ivnwstaeulrkzjc
kcwaleiuznqrts
rkwiunqzatsecl
y
pqnae
ofm
fl
y
czoi
smvbnd
tzi
tzanvx
azgnjx
ingjzyuae
anrhzkq
eqhafrbmw
rjscmwxz
lrgnyfeukdvmiqwpt
tarsmxwveqdhjbk
xrajvebtdmwkh
taojykmefwbdzrxuvnp
wbdtmjrevakx
ctilgkbmaredjwvx
wp
p
p
zprwtogmdu
orwdmtzuxpg
omwputzdgr
umgrtpwozd
wgzdrtpmou
xtkjsm
ylqptfjmk
pzgyknr
kyorpngz
pnzykgra
rtsiypahgecuvj
rsudtcgjiheyvp
rpyehvtijcgsu
cyprhvestgjui
uvigershtyjpc
jlmhtfbsoq
gbtohjsqm
mbstojqh
mhkecsqtabjox
xrhinjamvo
hproxvnma
mzscorhnx
utwprfqjyhsvzaomcb
yesrijzcagmhbwoutvpnqk
porcxwmyutzajbhqsv
uvrcpyzsmhajowtqb
ycpwuzovatbsmjqhr
fbkgycqutlmw
wuybgqmlcfk
xycgbkqmulwf
bgcfwyuqklm
vntsimju
boegqz
edotgsi
dgoism
iogds
gdstio
sogdixz
fdi
ifd
rx
v
x
qibkwyvmtxargjldc
bykzitxevgrwsnqflcdjm
dborhtpxjsflciveyq
xbuijhdqafnsrvepozytcl
qhlopsdtebcjyfrixv
hlvdyqxtcroegfjbisp
ormifqdhyvxjpclebst
qtzumogwrclaiex
iburltzgexdocwapq
ixuwtoqlegnrzc
xizeklwrugtqhoj
iynjbsahtvfeurqkgd
rtnwjgeukyadicflq
deytfqknlpjuairgc
oy
to
po
wyj
q
vatgy
xegndfrv
smgv
sgzbacv
ifmepunrdszgh
mvgdesianluzpfrh
eypfughdnmszitr
nepugsfimzrdh
fzuiqesnjcdwoxmhkpbrg
goycuvjqnpix
ytwnigvcjq
bsiczfhkne
gwxp
ojdl
a
uvgm
kaxzjpmwutcqnv
isadmolbtrfugxyhcj
vxqhfryiakbn
txhqbavyknri
ptbqifxcwyjgordls
dbpvkeauyc
kovpawxf
ovwxkpfa
xbknwjpcoaftq
oxapvfkw
ybjvaftkzheqgiuposnmxc
ungfezmiskqvyjaphobxtc
yjqimsvbktaonpeucfzhgrx
nepvgsifuqytahxzmjkocb
qmaexzipshcvjkfyonutgb
u
u
u
u
tpgqyvjaedlkbhwr
nytwkpqlvmgrbehxjad
vsruxht
rdmb
rfb
khqyd
ycj
aidrbmzkxvt
yzvbkiorxamdt
mzwvhblrxtn
vqalzwcbrxjmtnd
wlvnrtxmzcbg
ow
ow
ewuob
wo
gl
mnacgl
lg
gul
kdflg
oqvd
qodvy
qdvo
qvoda
rd
fus
thoi
rtnz
tqagrnlb
wemlvjbhuqcfrtodkxzn
pjbtruvdmhowfznlxekq
eoyadnxbuktqshgwfmvzirlj
kumotnwel
lmezwoutkn
nuemkwlot
efnlduohmtkw
mhaubleozw
zwulbhmo
mhbzouwl
hmwulbzo
hvjpdoiswzbenma
ojndsepwhiq
dwsjnhiope
tsohjdpwien
joipwhesnd
edbhi
fisdhbe
r
v
v
v
ezlc
czei
azlcei
czie
eynczs
ngfuhekmzxvopy
twogyeknxvmhbjzpuf
zxpfnygeomukvh
ktxduimz
vtgmurjiqk
mtkbuia
uykwh
kuyhnw
dzjqnwbrouh
qfncpvszdeg
cydmlqnz
dzqtn
xga
hmxpdg
fnxgeu
nxeogu
nsxrgu
xngurs
jvmudzscnalhwktry
lrvucmjkwztsyna
wyruzcjxlbtemsknva
yzwvklpcqustojrmnai
zyjntswcuarkmvl
zq
qz
qz
qz
zqt
gbpnqrxu
dqnxyvwhbtgi
csqmbfjeaokxlz
rdtuqpxnbzj
yzsnpu
fcnrzpou
penzu
nvukhlmizwpag
tdvfgahbiw
gtbpsdo
ucdprxmznhbw
rcumdzpwnx
dxnpzrmcuw
drpxcmnzuw
zxwcnpmrdu
dhouqlfvsakg
uaofqkdsvhgl
uoalfhvqsgkd
klgvfudqosah
auhslqfkgvdo
qkwfimrogubyhljda
shuprevacxlndiqfjwy
crpsetajviwmqhl
szqdpfvimaekgbj
geyqpl
gzqlei
qleg
kcfipzjwyugsrtahboneqxdm
uwkcmtdfopayenqbshxi
eudhcyfpwamoxvkqlistnb
yfqbtnwuzsdl
lszfnquwbtyd
fsjznbdwytulq
bfgldzqyutwsn
n
uv
vjfzuhqgaypbmcd
hqmbpsjyugrvfzatndc
ovfazbdipqxeclykjgum
vmbzptjwydaguncfrq
k
w
k
k
eipruzqndlys
elrysidnzqu
pzlgeciqys
wjvrdxmunfsb
kdy
kd
kd
dlk
kd
yretjs
g
kahzubo
rjd
r
hlxpawm
xmyeltpqw
gmpxicbv
burmxc
ozxmsfjdn
dtskziwy
qxzycupgs
iflherjytpxg
thienjgrfxly
heyftrgjlix
igyfjurphtexl
gtyxrjleihf
nuswkhz
xosqihvwfrez
hgszyw
ukphojt
hotkpzju
htupjbko
mjpkouhd
luhsi
shliu
lihqsu
iqr
ybndlhzrgwtmkf
rxcuq
j
j
j
j
rwqsbyoe
fweujxcoliya
mpowrey
wvn
wv
frbuexwg
xmqgdwfeb
rbyjsiqxtfcvlup
vqpuyrifcsjxtlb
yvtqirslxpjfbcu
vsribxjcufylqpt
ikcvoguphqtyjdswzexa
ptjocgxiuhwavydsqzek
ipcuohvqdwyxsetkagjz
vpgdhzqckoywxaijuest
erhdoyugavcq
doqsvahugec
cnhezgfavbuixdo
lhgvknmequsctapxzbjdorf
fodnxkrlqthcubmzvpjaeg
fcvqmordxhklpybujgenatz
nlmbxvpcokearhdzjtqufg
uthcdpbvojlqewrknafgxzmi
hwjpevzgrtmoqknydfs
jvzstyfdhgkoqpmw
ncw
gwivun
wnl
nxw
najwbzdrke
ckyowhxblrt
flabyrdwctk
lbwripvjtykcs
pn
eonwtzp
yxsirvqhcm
fapu
njwb
lsjdymwpz
zmrhuajxvewysp
lyisuvcbdqxotkmh
bkmrldugxsycohqitv
xlhcvtmyqibdosuk
hscubvoelkyqdximt
mb
mjbf
rbm
zvqlg
gnlvjbz
zvdgl
dslgvzt
vczwgl
bem
yqpgj
dxflhwokatuvnzs
irqc
jqp
gqolch
hnozqgcl
dnhwl
hdo
fduc
lug
lug
gurkal
lgu
ulg
uahmzdyxbr
htkmwpcxbqy
cbhyxmp
ajv
mjt
j
ji
bfpygmtxajnk
kpnmfbxtgayj
pcynamktgbjxf
tfympjvqxgnkab
x
x
x
mxf
vqx
wlzsgdhixr
hgcoaiwpbluv
wyhlig
iwfnlhqgs
jfgqihmxwlr
cqrdbpoehiwfuzvgalxm
ularwipqxcfedozmbvg
vurqezjkoysgpalbfimxwcdt
mcvfzqplaxwrgoebiud
mydhxfvgzcleojiq
ixcozgyvjdfl
njxuwiaovpycslrzgdf
gfwtnr
mojdinwkf
rfnwqhcg
wfn
lwise
arl
trzbvl
bal
y
y
y
y
sayqdimthfrpjvgn
crdphnmayqbgf
sfgtqwbzej
pnmlcyitj
yvtng
tyn
nyutg
ytgenh
onpty
bleicngomsqhwfdy
mrbnfygxpiwucoldqshke
cqdeimynwhsfoblg
gqesldbcijmwhonfy
enblgcmfwdhyqois
ufmsgkbcxz
xfsckzmub
umbkoxzhrsvcnf
kzmcsbfxgu
tuiwqd
hbtdou
t
t
t
t
t
ureltqfji
ohzkrul
oievpqgs
sqdvopigle
easvqpkgio
upkr
urpk
wrbipknheldxjfm
rhjexfldkwpb
lhrpejxfwbdk
drybxszfetlnwjigk
fngbltzjywsroixk
hodteualp
dtrpuile
tqrbsjni
sbcirnqt
rsbaitqv
qbsrit
gbtsriq
ovjmetdznlw
dtjvlmonze
zdjntemolvw
mlouvjngzkdter
ckrnly
rclkyn
cyjlkrnh
crynkl
ylckrn
zjk
zkj
djkz
jzk
jzk
xoj
mjro
kjuxro
ybsjeahf
zhwvtialqegufxmrcj
hwljxrecaqmztgifv
vgibmzlxwrdeacfqhjt
nxicerwtzolfgky
hogmsvdplbweja
w
clq
i
gi
cilrkspgjqmw
xhvadtlyfjobnzue
ckytg
nqtyg
gyxbt
kygtc
fwcd
wfc
oebwhmil
fdwxr
lomdtfsihk
sfyitokldmh
dimyotfkls
iovdstlmkfj
smulideqtfok
frazxb
ahfbxz
bafzx
aftbxpz
ubdarimsqvgtlhfjze
eqfrvhsguzjamtidl
hjidpgrc
vrp
zpxwsulqrona
drhpftvi
kbrdhype
xidcskygjwmbzr
bsqexaypghjkv
tgxmy
atxym
txym
qjrbmxtluews
ulbrwtjsxqop
fzbksturwmxlqj
tbxvnsjqriuwcl
edhvzwqxojuplbkyf
wfphdjyczxvlkbqo
jhxbpkvyfzdloqw
yhmlfwoqkjpvdxbz
qfmxikhozbvwydplj
seyq
yogxm
jzbgatxhrplowqsyecvdn
nzjvohtguxpydsrlcewab
apzf
zanwg
pza
az
sapxfnyhbowujlcdveqiztkm
tzskjxqcoebdunyfphi
caruks
rhlwsv
cnswqfaztmdh
uxszromtanqdfb
cjnmstxqvdik
qmjdcksitxvn
cjktvxqmdnis
cjnrsqdkxptivm
oq
qaion
omq
qo
kzymeqtbasgn
cuktvbsorim
lpjxwhdf
knflw
ezvkn
yuhakrnc
vidhwxfrmnsyuct
rzumskdfeqx
p
p
duicxvgnbeopfzlqyrks
skdetoclpbmzqfghwixr
gfozcdskprxeaiqbml
plkhqcifedxbgosrz
ydtjolrxzefiaschwng
tdoerngfhzwxjcylia
zrawdytxhcojlgenfi
ghvjqlifws
sfiqklwjehrgv
q
q
s
a
s
et
tme
a
a
a
a
a
qng
g
wg
nvmlaui
audrigo
atnjdu
hybxcpszkwuq
fnu
zmngdceqikxyuapwv
ciwyqekgamdzvp
ikcpavfgbwmerqyz
mcvyjezqxrpkiu
wlfatnmghs
awkqenuiorcd
lkuowsracdtzqgei
joxhucpqrmfyvikawe
cdn
ndc
fybj
bjfy
byjucsf
flybjx
zfcphgxqno
zhmxyncpqr
iqhwaclzupsne
oscpyvdebfhz
pbonsjyrelkfxvz
wfpvyigbmaeztoqus
ypbfhaivmkx
xpjfhikyoca
wkzvxlebarsmcdpi
xidcbpswmazekr
zsxwidpmekacrb
pwczxsedakirbm
vfupqwdshxygkmrzol
wslmypfkogrxzqdvh
qwlxsrfzpgdomvyhk
cmkdiapszuyb
bkpyduimascz
vjpxmdzfwkuq
eycbgsnhltmapxo
xmnklfpugdewtj
okzerxjuihqcptdmysf
yajvhbtowixds
dvynabxjiwhs
asydoixzbh
ihjdxbasyk
lifxrbspedahyumcg
snragze
gmszrnae
egrazsn
ensragz
odi
odi
ido
odi
mvogdzfker
veongkrpzmdf
vgekmrzdfo
ombjdfqykergvz
hzsormkdgfve
l
l
l
ly
kgnpliuwmsebhjfrcyqxotvazd
mzqryvgsftauxpcknehbiwojld
vczkrabfmhpyjteui
merjtikybvaugz
aieydktjrmzvubg
yeslqoibauvtkmrjz
vi
vip
eigv
vix
iv
mcuknbexfowszpvtyi
ztmfwonvcsapqxyieb
etowynxzcpirmbvsf
wjfnyvopzetkmiusbcx
ywhqemsx
banksxwemy
ymsexw
smyewx
szxeywm
yvqtnsahzpwebgr
zgtjnevyapwbhrs
jzynhrpvwgsbat
obtynrfwslcahvzgpm
eytrpagzwsjvbkhn
ynwutpmvhj
mvwjpuyt
wupzyjvmt
kwnyatozcmdqbpsvejfrxug
vkzjaogfmqsxhnyctpu
cozypjmtvlxquakgfnsi
qrwtgecs
daley
emh
qmbjwe
qebfwjm
qewjm
qjiwem
dqc
tad
qdcs
zrvjnfpe
zpefunyvqc
fzpvern
pnefvz
envpfz
nduhkvstxqmbfyr
ufmhbtkqvxdnpy
hdntqxuvmbkfy
ot
o
yv
xp
evkrifstpzgbahl
vzkmdtchgseajyfub
bgtnkxvheoaqifsz
wxec
wfuie
awmj
ghsnkvwbqor
mcexwf
teosna
tnkb
ptm
t
r
na
ykx
jdl
mzjtp
xbpj
tzrkxba
xnbjmgosv
mhxbw
j
j
j
j
xn
lrvt
htg
mr
hafkb
fkab
afbk
zlyxomawvuib
vxwzbaymolui
tcdfzgx
ql
luo
uh
ixtbluahoeqgsv
eovsiglhuqanxtb
ntychjig
chyijtgn
hcnjtiyg
tgjnhiyc
tgjiychn
khomqatzscydwunfe
ygoazrdukh
zokbrlyaudjh
uojynifthzvcgqp
phnvryfbtucl
sbeizdtjopxu
nouqbeykmszd
cga
gca
cag
hiogxbslyptfc
pilwxcthogysb
holsibtcypfgx
oahyr
pkjro
qgfkj
gjzk
jgvk
kw
wk
kw
wk
bxvmnks
sfmbva
fsocn
ygfopn
wbarmxtfyjzenicvlhps
aefdirlyvzjpwtcmnh
rqymwfzjpevchiaotnl
lietnypmcrvhowfjaz
ztjcehympnavirlwf
gqsnyhtafdcbki
yncbhxiakgpqt
mikyzoxflndetbp
ebqdwiopkhyfxnl
jbscverlgfyauo
bkewpj
n
solnxmfr
ybxa
ybxa
xyba
byax
abxy
sgbo
sg
unvqlyhzdaxrcwg
dxvhaugicrzqnlw
mrplcqatdxzbuvgnwh
vzaurnhdgqlxwc
ucdwavqhylxrngz
frhdaek
fpuwosv
qm
m
smg
"""
let groups = input
.components(separatedBy: "\n\n")
.map {
$0
.components(separatedBy: .whitespacesAndNewlines)
.map {
$0.reduce(into: Set<Character>()) { accu, new in accu.insert(new) }
}
}
.map { group -> Set<Character> in
let result = group[0]
return group.reduce(into: result) { accu, new in accu = accu.intersection(new) }
}
.reduce(0) { accu, new in accu + new.count }
print(groups)
| 8.225242 | 88 | 0.866271 |
2fc45b28c81a7abd77a0bd78749b4ebd82f80006 | 535 | //
// BarData.swift
// FLCharts
//
// Created by Francesco Leoni on 09/01/22.
// Copyright © 2021 Francesco Leoni All rights reserved.
//
import UIKit
public struct BarData: Equatable {
/// The name of the bar.
public var name: String
/// The values of the bar.
public var values: [CGFloat]
/// The sum of the bar values.
public var total: CGFloat { values.reduce(0, +) }
public init(name: String, values: [CGFloat]) {
self.name = name
self.values = values
}
}
| 19.814815 | 57 | 0.601869 |
29e61f94887726a6672d4400a9e93d10585d6823 | 422 | import Foundation
extension URLRequest {
public func debugLog() -> String {
var description = "\(self)"
if let headers = self.allHTTPHeaderFields {
description.append("\n\(headers)")
}
if let httpBody = self.httpBody, let dataString = String(data: httpBody, encoding: .utf8) {
description.append("\n\(dataString)")
}
return description
}
}
| 26.375 | 99 | 0.592417 |
0a222c14ba493457ecba35af4bbce82c4067e7ab | 9,413 | /*
* 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
#if SWIFT_PACKAGE
import OktaOidc_AppAuth
#endif
open class OktaOidcStateManager: NSObject, NSSecureCoding {
public static var supportsSecureCoding = true
@objc open var authState: OKTAuthState
@objc open var accessibility: CFString
@objc open var accessToken: String? {
// Return the known accessToken if it hasn't expired
guard let tokenResponse = self.authState.lastTokenResponse,
let token = tokenResponse.accessToken,
let tokenExp = tokenResponse.accessTokenExpirationDate,
tokenExp.timeIntervalSince1970 > Date().timeIntervalSince1970 else {
return nil
}
return token
}
@objc open var idToken: String? {
// Return the known idToken if it is valid
guard let tokenResponse = self.authState.lastTokenResponse,
let token = tokenResponse.idToken,
validateToken(idToken: token) == nil else {
return nil
}
return token
}
@objc open var refreshToken: String? {
return self.authState.refreshToken
}
var restAPI: OktaOidcHttpApiProtocol = OktaOidcRestApi()
@objc public init(authState: OKTAuthState,
accessibility: CFString = kSecAttrAccessibleWhenUnlockedThisDeviceOnly) {
self.authState = authState
self.accessibility = accessibility
OktaOidcConfig.setupURLSession()
super.init()
}
@objc required public convenience init?(coder decoder: NSCoder) {
guard let state = decoder.decodeObject(forKey: "authState") as? OKTAuthState else {
return nil
}
self.init(
authState: state,
accessibility: decoder.decodeObject(forKey: "accessibility") as! CFString
)
}
@objc public func encode(with coder: NSCoder) {
coder.encode(self.authState, forKey: "authState")
coder.encode(self.accessibility, forKey: "accessibility")
}
@objc public func validateToken(idToken: String?) -> Error? {
guard let idToken = idToken,
let tokenObject = OKTIDToken(idTokenString: idToken) else {
return OktaOidcError.JWTDecodeError
}
if tokenObject.expiresAt.timeIntervalSinceNow < 0 {
return OktaOidcError.JWTValidationError("ID Token expired")
}
return nil
}
// Decodes the payload of a JWT
@objc public static func decodeJWT(_ token: String) throws -> [String: Any] {
let payload = token.split(separator: ".")
guard payload.count > 1 else {
return [:]
}
var encodedPayload = "\(payload[1])"
if encodedPayload.count % 4 != 0 {
let padding = 4 - encodedPayload.count % 4
encodedPayload += String(repeating: "=", count: padding)
}
guard let data = Data(base64Encoded: encodedPayload, options: []) else {
throw OktaOidcError.JWTDecodeError
}
let jsonObject = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
guard let result = jsonObject as? [String: Any] else {
throw OktaOidcError.JWTDecodeError
}
return result
}
@objc public func renew(callback: @escaping ((OktaOidcStateManager?, Error?) -> Void)) {
authState.setNeedsTokenRefresh()
authState.performAction { accessToken, idToken, error in
if let error = error {
callback(nil, OktaOidcError.errorFetchingFreshTokens(error.localizedDescription))
return
}
callback(self, nil)
}
}
@objc public func introspect(token: String?, callback: @escaping ([String : Any]?, Error?) -> Void) {
performRequest(to: .introspection, token: token, callback: callback)
}
@objc public func revoke(_ token: String?, callback: @escaping (Bool, Error?) -> Void) {
performRequest(to: .revocation, token: token) { payload, error in
if let error = error {
callback(false, error)
return
}
// Token is considered to be revoked if there is no payload.
callback(payload?.isEmpty ?? true , nil)
}
}
@objc public func removeFromSecureStorage() throws {
try OktaOidcKeychain.remove(key: self.clientId)
}
@objc public func clear() {
OktaOidcKeychain.clearAll()
}
@objc public func getUser(_ callback: @escaping ([String:Any]?, Error?) -> Void) {
guard let token = accessToken else {
DispatchQueue.main.async {
callback(nil, OktaOidcError.noBearerToken)
}
return
}
let headers = ["Authorization": "Bearer \(token)"]
performRequest(to: .userInfo, headers: headers, callback: callback)
}
}
@objc public extension OktaOidcStateManager {
@available(*, deprecated, message: "Please use readFromSecureStorage(for config: OktaOidcConfig) function")
class func readFromSecureStorage() -> OktaOidcStateManager? {
return readFromSecureStorage(forKey: "OktaAuthStateManager")
}
@objc class func readFromSecureStorage(for config: OktaOidcConfig) -> OktaOidcStateManager? {
return readFromSecureStorage(forKey: config.clientId)
}
@objc func writeToSecureStorage() {
let authStateData: Data
do {
if #available(iOS 11, OSX 10.14, *) {
authStateData = try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false)
} else {
authStateData = NSKeyedArchiver.archivedData(withRootObject: self)
}
try OktaOidcKeychain.set(
key: self.clientId,
data: authStateData,
accessibility: self.accessibility
)
} catch let error {
print("Error: \(error)")
}
}
private class func readFromSecureStorage(forKey secureStorageKey: String) -> OktaOidcStateManager? {
guard let encodedAuthState: Data = try? OktaOidcKeychain.get(key: secureStorageKey) else {
return nil
}
let state: OktaOidcStateManager?
if #available(iOS 11, OSX 10.14, *) {
state = (try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(encodedAuthState)) as? OktaOidcStateManager
} else {
state = NSKeyedUnarchiver.unarchiveObject(with: encodedAuthState) as? OktaOidcStateManager
}
return state
}
}
internal extension OktaOidcStateManager {
var discoveryDictionary: [String: Any]? {
return authState.lastAuthorizationResponse.request.configuration.discoveryDocument?.discoveryDictionary
}
}
private extension OktaOidcStateManager {
var issuer: String? {
return authState.lastAuthorizationResponse.request.configuration.issuer?.absoluteString
}
var clientId: String {
return authState.lastAuthorizationResponse.request.clientID
}
func performRequest(to endpoint: OktaOidcEndpoint,
token: String?,
callback: @escaping ([String : Any]?, OktaOidcError?) -> Void) {
guard let token = token else {
DispatchQueue.main.async {
callback(nil, OktaOidcError.noBearerToken)
}
return
}
let postString = "token=\(token)&client_id=\(clientId)"
performRequest(to: endpoint, postString: postString, callback: callback)
}
func performRequest(to endpoint: OktaOidcEndpoint,
headers: [String: String]? = nil,
postString: String? = nil,
callback: @escaping ([String : Any]?, OktaOidcError?) -> Void) {
guard let endpointURL = endpoint.getURL(discoveredMetadata: discoveryDictionary, issuer: issuer) else {
DispatchQueue.main.async {
callback(nil, endpoint.noEndpointError)
}
return
}
var requestHeaders = [
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
]
if let headers = headers {
requestHeaders.merge(headers) { (_, new) in new }
}
restAPI.post(endpointURL, headers: requestHeaders, postString: postString, onSuccess: { response in
callback(response, nil)
}, onError: { error in
callback(nil, error)
})
}
}
| 34.606618 | 120 | 0.613301 |
67222f9d717adeb794ce382fc7127b826f375cc2 | 10,124 | //
// LoginView.swift
// EasyLearn
//
// Created by Tebeen on 5/24/17.
// Copyright © 2017 Tebin. All rights reserved.
//
import UIKit
class LoginView: UIScrollView {
lazy var loginRegisterSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Sign In", "Register"])
//sc.backgroundColor = .white
sc.tintColor = .white
sc.selectedSegmentIndex = 1
sc.translatesAutoresizingMaskIntoConstraints = false
sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: UIControlEvents.valueChanged)
return sc
}()
let container: UIView = {
let container = UIView()
container.backgroundColor = .clear
container.translatesAutoresizingMaskIntoConstraints = false
return container
}()
let nameTextField: LeftPaddedTextField = {
let textField = LeftPaddedTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.layer.borderColor = UIColor.white.cgColor
textField.layer.borderWidth = 1
textField.textColor = .white
textField.placeholder = "enter name"
return textField
}()
let emailTextField: LeftPaddedTextField = {
let textField = LeftPaddedTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.layer.borderColor = UIColor.white.cgColor
textField.layer.borderWidth = 1
textField.textColor = .white
textField.placeholder = "enter email address"
textField.keyboardType = .emailAddress
return textField
}()
let passTextField: LeftPaddedTextField = {
let textField = LeftPaddedTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.placeholder = "enter password"
textField.layer.borderColor = UIColor.white.cgColor
textField.layer.borderWidth = 1
textField.textColor = .white
textField.isSecureTextEntry = true
return textField
}()
lazy var loginRegisterButton: UIButton = {
let btn = UIButton(type: .system)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Register", for: .normal)
btn.setTitleColor(UIColor.appColor, for: .normal)
btn.backgroundColor = .white
btn.layer.cornerRadius = 20
btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
btn.layer.shadowColor = UIColor.black.cgColor
btn.layer.shadowOffset = .zero
btn.layer.shadowOpacity = 0.5
btn.layer.shouldRasterize = true //cache the shadow because it's expensive
btn.addTarget(self, action: #selector(handleLoginRegister), for: .touchUpInside)
return btn
}()
lazy var forgetPasswordBtn: UIButton = {
let btn = UIButton(type: .system)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("forget password?", for: .normal)
btn.setTitleColor(UIColor.white, for: .normal)
btn.addTarget(self, action: #selector(handleForgetPassword), for: .touchUpInside)
return btn
}()
let fieldHeight: CGFloat = 40
let containerHeight: CGFloat = 40 * 3 + 30
let containerHeightWithoutName: CGFloat = 40 * 3
var containerConstraint: NSLayoutConstraint!
var nameHeightConstraint: NSLayoutConstraint!
var nameTopConstarint: NSLayoutConstraint!
func handleLoginRegisterChange(){
let title = loginRegisterSegmentedControl.titleForSegment(at: loginRegisterSegmentedControl.selectedSegmentIndex)
loginRegisterButton.setTitle(title, for: .normal)
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
nameTopConstarint.constant = 0
nameTextField.isHidden = true
forgetPasswordBtn.isHidden = false
} else {
nameTopConstarint.constant = 10
nameTextField.isHidden = false
forgetPasswordBtn.isHidden = true
}
containerConstraint.constant = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? containerHeightWithoutName : containerHeight
nameHeightConstraint.isActive = false
let nameHeight: CGFloat = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : (1/3 - 0.06)
nameHeightConstraint = nameTextField.heightAnchor.constraint(equalTo: container.heightAnchor, multiplier: nameHeight)
nameHeightConstraint.isActive = true
}
//MARK:- Initializer
override init(frame: CGRect) {
super.init(frame: frame)
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .clear
isScrollEnabled = true
alwaysBounceVertical = true
showsVerticalScrollIndicator = false
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews(){
addSubViews()
setupSegmentedControl()
setupContainer()
setupForgetPassword()
setupLoginRegisterBtn()
}
func addSubViews(){
addSubview(loginRegisterSegmentedControl)
addSubview(container)
container.addSubview(nameTextField)
container.addSubview(emailTextField)
container.addSubview(passTextField)
addSubview(forgetPasswordBtn)
addSubview(loginRegisterButton)
}
func setupSegmentedControl(){
NSLayoutConstraint.activate([
loginRegisterSegmentedControl.centerXAnchor.constraint(equalTo: centerXAnchor),
loginRegisterSegmentedControl.topAnchor.constraint(equalTo: topAnchor),
loginRegisterSegmentedControl.heightAnchor.constraint(equalToConstant: fieldHeight),
loginRegisterSegmentedControl.leadingAnchor.constraint(equalTo: leadingAnchor),
loginRegisterSegmentedControl.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
func setupContainer(){
NSLayoutConstraint.activate([
container.topAnchor.constraint(equalTo: loginRegisterSegmentedControl.bottomAnchor),
container.leadingAnchor.constraint(equalTo: leadingAnchor),
container.trailingAnchor.constraint(equalTo: trailingAnchor),
])
//height = name + email + password + spacing height
containerConstraint = container.heightAnchor.constraint(equalToConstant: fieldHeight * 3 + 30)
containerConstraint.isActive = true
setupName()
setupEmail()
setupPassword()
}
func setupName(){
NSLayoutConstraint.activate([
nameTextField.leadingAnchor.constraint(equalTo: container.leadingAnchor),
nameTextField.trailingAnchor.constraint(equalTo: container.trailingAnchor),
])
nameTopConstarint = nameTextField.topAnchor.constraint(equalTo: container.topAnchor)
nameTopConstarint.constant = 10
nameTopConstarint.isActive = true
nameHeightConstraint = nameTextField.heightAnchor.constraint(equalTo: container.heightAnchor, multiplier: 1/3 - 0.06)
nameHeightConstraint.isActive = true
}
func setupEmail(){
NSLayoutConstraint.activate([
emailTextField.topAnchor.constraint(equalTo: nameTextField.bottomAnchor, constant: 10),
emailTextField.leadingAnchor.constraint(equalTo: container.leadingAnchor),
emailTextField.trailingAnchor.constraint(equalTo: container.trailingAnchor),
emailTextField.heightAnchor.constraint(equalToConstant: fieldHeight)
])
}
func setupPassword(){
NSLayoutConstraint.activate([
passTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: 10),
passTextField.leadingAnchor.constraint(equalTo: container.leadingAnchor),
passTextField.trailingAnchor.constraint(equalTo: container.trailingAnchor),
passTextField.heightAnchor.constraint(equalToConstant: fieldHeight)
])
}
func setupForgetPassword(){
forgetPasswordBtn.topAnchor.constraint(equalTo: passTextField.bottomAnchor).isActive = true
forgetPasswordBtn.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
forgetPasswordBtn.heightAnchor.constraint(equalTo: forgetPasswordBtn.heightAnchor).isActive = true
forgetPasswordBtn.widthAnchor.constraint(equalTo: forgetPasswordBtn.widthAnchor).isActive = true
forgetPasswordBtn.isHidden = true
}
func setupLoginRegisterBtn(){
loginRegisterButton.topAnchor.constraint(equalTo: forgetPasswordBtn.bottomAnchor, constant: 10).isActive = true
loginRegisterButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
loginRegisterButton.heightAnchor.constraint(equalToConstant: fieldHeight).isActive = true
loginRegisterButton.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
loginRegisterButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -220).isActive = true
}
func keyboardResponder() {
nameTextField.resignFirstResponder()
emailTextField.resignFirstResponder()
passTextField.resignFirstResponder()
}
var loginDelegate: LoginViewDelegate!
//MARK: Button Handlers
@objc private func handleLoginRegister() {
if loginRegisterSegmentedControl.selectedSegmentIndex == 0{
handleLogin()
}else{
handleRegister()
}
//hide the keyboard
endEditing(true)
}
private func handleLogin(){
loginDelegate.loginBtn()
}
private func handleRegister(){
loginDelegate.registerBtn()
}
@objc private func handleForgetPassword(){
loginDelegate.forgetPasswordBtn()
}
}
protocol LoginViewDelegate {
func loginBtn()
func registerBtn()
func forgetPasswordBtn()
func getStartedBtn()
}
| 40.334661 | 141 | 0.686092 |
ccaa6c527f0071a84d3b66ca4e0c441967fbc810 | 356 | import SubstrateSdk
struct SubqueryEraValidatorInfo {
let address: AccountAddress
let era: EraIndex
init?(from json: JSON) {
guard
let era = json.era?.unsignedIntValue,
let address = json.address?.stringValue
else { return nil }
self.era = EraIndex(era)
self.address = address
}
}
| 20.941176 | 51 | 0.609551 |
fbb4176d0b08cab056b10c722897ca3a8088d7eb | 365 | import MicrosoftKiotaAbstractions
extension Swiftconsoleapp.Users.Item.MailFolders.Item.Messages.Item.Extensions {
public class ExtensionsResponse : AdditionalDataHolder {
public var additionalData: [String:Any] = [String:Any]()
public var nextLink: String?
public var value: [Swiftconsoleapp.Models.Microsoft.Graph.Extension]?
}
}
| 36.5 | 80 | 0.747945 |
01d2fd4bde87af7702003d8c4f610b10ab09aaad | 12,705 | //
// VersaPlayer.swift
// VersaPlayer Demo
//
// Created by Jose Quintero on 10/11/18.
// Copyright © 2018 Quasar. All rights reserved.
//
import AVFoundation
open class VersaPlayer: AVPlayer, AVAssetResourceLoaderDelegate {
/// Dispatch queue for resource loader
private let queue = DispatchQueue(label: "quasar.studio.versaplayer")
/// Notification key to extract info
public enum VPlayerNotificationInfoKey: String {
case time = "VERSA_PLAYER_TIME"
}
/// Notification name to post
public enum VPlayerNotificationName: String {
case assetLoaded = "VERSA_ASSET_ADDED"
case timeChanged = "VERSA_TIME_CHANGED"
case willPlay = "VERSA_PLAYER_STATE_WILL_PLAY"
case play = "VERSA_PLAYER_STATE_PLAY"
case pause = "VERSA_PLAYER_STATE_PAUSE"
case buffering = "VERSA_PLAYER_BUFFERING"
case endBuffering = "VERSA_PLAYER_END_BUFFERING"
case didEnd = "VERSA_PLAYER_END_PLAYING"
/// Notification name representation
public var notification: NSNotification.Name {
return NSNotification.Name(rawValue)
}
}
/// VersaPlayer instance
public weak var handler: VersaPlayerView!
/// Caption text style rules
public lazy var captionStyling: VersaPlayerCaptionStyling = {
VersaPlayerCaptionStyling(with: self)
}()
/// Whether player is buffering
public var isBuffering: Bool = false
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemTimeJumped, object: self)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self)
#if DEBUG
print("9 \(String(describing: self))")
#endif
}
/// Play content
open override func play() {
handler.playbackDelegate?.playbackWillBegin(player: self)
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.willPlay.notification, object: self, userInfo: nil)
if !(handler.playbackDelegate?.playbackShouldBegin(player: self) ?? true) {
return
}
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.play.notification, object: self, userInfo: nil)
super.play()
handler.playbackDelegate?.playbackDidBegin(player: self)
}
/// Pause content
open override func pause() {
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.pause.notification, object: self, userInfo: nil)
super.pause()
}
/// Replace current item with a new one
///
/// - Parameters:
/// - item: AVPlayer item instance to be added
open override func replaceCurrentItem(with item: AVPlayerItem?) {
if let asset = item?.asset as? AVURLAsset, let vitem = item as? VersaPlayerItem, vitem.isEncrypted {
asset.resourceLoader.setDelegate(self, queue: queue)
}
if currentItem != nil {
currentItem!.removeObserver(self, forKeyPath: "playbackBufferEmpty")
currentItem!.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp")
currentItem!.removeObserver(self, forKeyPath: "playbackBufferFull")
currentItem!.removeObserver(self, forKeyPath: "status")
}
super.replaceCurrentItem(with: item)
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.assetLoaded.notification, object: self, userInfo: nil)
if item != nil {
currentItem!.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .new, context: nil)
currentItem!.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
currentItem!.addObserver(self, forKeyPath: "playbackBufferFull", options: .new, context: nil)
currentItem!.addObserver(self, forKeyPath: "status", options: .new, context: nil)
}
}
}
extension VersaPlayer {
/// Start time
///
/// - Returns: Player's current item start time as CMTime
open func startTime() -> CMTime {
guard let item = currentItem else {
return CMTime(seconds: 0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
}
if item.reversePlaybackEndTime.isValid {
return item.reversePlaybackEndTime
} else {
return CMTime(seconds: 0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
}
}
/// End time
///
/// - Returns: Player's current item end time as CMTime
open func endTime() -> CMTime {
guard let item = currentItem else {
return CMTime(seconds: 0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
}
if item.forwardPlaybackEndTime.isValid {
return item.forwardPlaybackEndTime
} else {
if item.duration.isValid, !item.duration.isIndefinite {
return item.duration
} else {
return item.currentTime()
}
}
}
/// Prepare players playback delegate observers
open func preparePlayerPlaybackDelegate() {
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: OperationQueue.main) { [weak self] _ in
guard let self = self else { return }
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.didEnd.notification, object: self, userInfo: nil)
self.handler?.playbackDelegate?.playbackDidEnd(player: self)
}
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemTimeJumped, object: self, queue: OperationQueue.main) { [weak self] _ in
guard let self = self else { return }
self.handler?.playbackDelegate?.playbackDidJump(player: self)
}
addPeriodicTimeObserver(
forInterval: CMTime(
seconds: 1,
preferredTimescale: CMTimeScale(NSEC_PER_SEC)
),
queue: DispatchQueue.main
) { [weak self] time in
guard let self = self else { return }
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.timeChanged.notification, object: self, userInfo: [VPlayerNotificationInfoKey.time.rawValue: time])
self.handler?.playbackDelegate?.timeDidChange(player: self, to: time)
}
addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
}
/// Value observer
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) {
if let obj = object as? VersaPlayer, obj == self {
if keyPath == "status" {
switch status {
case AVPlayer.Status.readyToPlay:
handler.playbackDelegate?.playbackReady(player: self)
case AVPlayer.Status.failed:
handler.playbackDelegate?.playbackDidFailed(with: VersaPlayerPlaybackError.unknown)
default:
break
}
}
} else {
switch keyPath ?? "" {
case "status":
if let value = change?[.newKey] as? Int, let status = AVPlayerItem.Status(rawValue: value), let item = object as? AVPlayerItem {
if status == .failed, let error = item.error as NSError?, let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError {
var playbackError = VersaPlayerPlaybackError.unknown
switch underlyingError.code {
case -12937:
playbackError = .authenticationError
case -16840:
playbackError = .unauthorized
case -12660:
playbackError = .forbidden
case -12938:
playbackError = .notFound
case -12661:
playbackError = .unavailable
case -12645, -12889:
playbackError = .mediaFileError
case -12318:
playbackError = .bandwidthExceeded
case -12642:
playbackError = .playlistUnchanged
case -1004:
playbackError = .wrongHostIP
case -1003:
playbackError = .wrongHostDNS
case -1000:
playbackError = .badURL
case -1202:
playbackError = .invalidRequest
default:
playbackError = .unknown
}
handler.playbackDelegate?.playbackDidFailed(with: playbackError)
}
}
case "playbackBufferEmpty":
isBuffering = true
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.buffering.notification, object: self, userInfo: nil)
handler.playbackDelegate?.startBuffering(player: self)
case "playbackLikelyToKeepUp":
isBuffering = false
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.endBuffering.notification, object: self, userInfo: nil)
handler.playbackDelegate?.endBuffering(player: self)
case "playbackBufferFull":
isBuffering = false
NotificationCenter.default.post(name: VersaPlayer.VPlayerNotificationName.endBuffering.notification, object: self, userInfo: nil)
handler.playbackDelegate?.endBuffering(player: self)
default:
break
}
}
}
public func resourceLoader(_: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
guard let url = loadingRequest.request.url else {
print("VersaPlayerResourceLoadingError", #function, "Unable to read the url/host data.")
loadingRequest.finishLoading(with: NSError(domain: "quasar.studio.error", code: -1, userInfo: nil))
return false
}
print("VersaPlayerResourceLoading: \(url)")
guard
let certificateURL = handler.decryptionDelegate?.urlFor(player: self),
let certificateData = try? Data(contentsOf: certificateURL) else {
print("VersaPlayerResourceLoadingError", #function, "Unable to read the certificate data.")
loadingRequest.finishLoading(with: NSError(domain: "quasar.studio.error", code: -2, userInfo: nil))
return false
}
let contentId = handler.decryptionDelegate?.contentIdFor(player: self) ?? ""
guard
let contentIdData = contentId.data(using: String.Encoding.utf8),
let spcData = try? loadingRequest.streamingContentKeyRequestData(forApp: certificateData, contentIdentifier: contentIdData, options: nil),
let dataRequest = loadingRequest.dataRequest else {
loadingRequest.finishLoading(with: NSError(domain: "quasar.studio.error", code: -3, userInfo: nil))
print("VersaPlayerResourceLoadingError", #function, "Unable to read the SPC data.")
return false
}
guard let ckcURL = handler.decryptionDelegate?.contentKeyContextURLFor(player: self) else {
loadingRequest.finishLoading(with: NSError(domain: "quasar.studio.error", code: -4, userInfo: nil))
print("VersaPlayerResourceLoadingError", #function, "Unable to read the ckcURL.")
return false
}
var request = URLRequest(url: ckcURL)
request.httpMethod = "POST"
request.httpBody = spcData
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request) { data, _, _ in
if let data = data {
dataRequest.respond(with: data)
loadingRequest.finishLoading()
} else {
print("VersaPlayerResourceLoadingError", #function, "Unable to fetch the CKC.")
loadingRequest.finishLoading(with: NSError(domain: "quasar.studio.error", code: -5, userInfo: nil))
}
}
task.resume()
return true
}
}
| 45.213523 | 185 | 0.619913 |
385547da6e73c5f5b2ef602e95075c720aedba63 | 5,303 | //
// CurrencyConverterViewModel.swift
// CurrencyConverter
//
// Created by Ruffolo Antonio on 07/08/2019.
// Copyright © 2019 AR. All rights reserved.
//
import Foundation
enum ConverterError: Error {
case valueNotFormatted
case bothCurrencyNotSelected
case impossibleToConvert
}
class CurrencyConverterViewModel: CurrencyConverterViewModelProtocol
{
private weak var currencyViewController: CurrencyConverterViewProtocol?
private var currencyConverter: CurrencyConverterCalculator
private var currenciesRates: [String: Double] = [:]
private var waitingForFromCurrecyToSet: Bool
private var currencyFrom: String?
private var currencyTo: String?
var viewData: CurrencyConverterViewData
let ratesFetcher: CurrencyFetcherProtocol
init(currencyViewController: CurrencyConverterViewProtocol, ratesFetcher: CurrencyFetcherProtocol)
{
self.currencyViewController = currencyViewController
self.ratesFetcher = ratesFetcher
self.currencyConverter = CurrencyConverterCalculator()
waitingForFromCurrecyToSet = false
viewData = CurrencyConverterViewData(topAmount: "",
topCurrency: AppStrings.currency.value,
bottomAmount: "",
bottomCurrency: AppStrings.currency.value)
currencyConverter.currencies = currenciesRates
}
func viewWillAppear()
{
loadData()
}
func loadData()
{
ratesFetcher.latestCurrenciesRates(completion: { [weak self] dataModel in
self?.receiveRates(ratesResult: dataModel)
})
}
func receiveRates(ratesResult: Result<CurrencyDataModel, RatesFetchError>)
{
switch ratesResult
{
case .success(let model):
currencyConverter.currencies = model.rates
currenciesRates = model.rates
case .failure:
currencyViewController?.showErrorForDataFailure(title: AppStrings.error.value,
message: AppStrings.serviceUnavailable.value,
buttonLabel: AppStrings.retry.value)
}
}
func topAmountChanged(amount: String)
{
viewData.topAmount = amount
currencyViewController?.updateView(viewData: viewData)
}
func selectCurrencyTopButtonPressed()
{
waitingForFromCurrecyToSet = true
currencyViewController?.presentCurrencyPicker(currencies: currenciesRates.keys.sorted())
}
func selectCurrencyBottomButtonPressed()
{
waitingForFromCurrecyToSet = false
currencyViewController?.presentCurrencyPicker(currencies: currenciesRates.keys.sorted())
}
func currencyIndexSelected(index: Int)
{
let selected = currenciesRates.keys.sorted()[index]
if waitingForFromCurrecyToSet
{
currencyFrom = selected
viewData.topCurrency = selected
}
else
{
currencyTo = selected
viewData.bottomCurrency = selected
}
// I may want to reset the amount on the bottom
viewData.bottomAmount = ""
currencyViewController?.updateView(viewData: viewData)
}
func convertButtonPressed(importToConvert: String)
{
let result = convertCurrentImport(importToConvert: importToConvert)
switch result
{
case .success(let viewData):
self.viewData = viewData
currencyViewController?.updateView(viewData: viewData)
case .failure(let error):
showAlertFromError(error: error)
}
}
private func showAlertFromError(error: ConverterError)
{
switch error {
case .valueNotFormatted:
currencyViewController?.showError(title: AppStrings.error.value, message: AppStrings.valueFormatError.value,
buttonLabel: AppStrings.close.value)
case .bothCurrencyNotSelected:
currencyViewController?.showError(title: AppStrings.error.value, message: AppStrings.selectBothCurrency.value,
buttonLabel: AppStrings.close.value)
case .impossibleToConvert:
currencyViewController?.showError(title: AppStrings.error.value, message: AppStrings.notPossibleToConver.value,
buttonLabel: AppStrings.close.value)
}
}
private func convertCurrentImport(importToConvert: String) -> Result<CurrencyConverterViewData, ConverterError>
{
guard let number = NumbersUtil.convertStringToDouble(stringNumber: importToConvert) else {
return Result.failure(.valueNotFormatted)
}
guard let currencyFrom = currencyFrom, let currencyTo = currencyTo else {
return Result.failure(.bothCurrencyNotSelected)
}
let valueConverted = currencyConverter.convertCurrencyValue(fromCur: currencyFrom, toCur: currencyTo,
valueToConvert: number)
guard let stringConverted = NumbersUtil.converDoubleToFormattedString(importInserted: valueConverted) else {
return Result.failure(.impossibleToConvert)
}
let viewData = CurrencyConverterViewData(topAmount: importToConvert, topCurrency: currencyFrom,
bottomAmount: stringConverted, bottomCurrency: currencyTo)
return Result.success(viewData)
}
}
| 32.937888 | 117 | 0.687535 |
46405f433deaa130e270d228056f8f66b05cfc93 | 1,004 | import XCTest
public protocol RobotContext { }
public struct NoContext: RobotContext { }
public struct NoConfiguration { }
public class RunningRobot<Configuration, Context: RobotContext, Current: Robot, Previous: Robot>: Robot {
public typealias Element = Current.Element
public var source: XCUIElement { return current.source }
public let configuration: Configuration
public let context: Context
public let current: Current
public let previous: Previous
public required init(configuration: Configuration, context: Context, current: Current, previous: Previous) {
self.configuration = configuration
self.context = context
self.current = current
self.previous = previous
}
public required convenience init(source: XCUIElement) {
fatalError("This Robot can not be created this way")
}
}
extension RunningRobot: Assertable where Current: Assertable { }
extension RunningRobot: Actionable where Current: Actionable { }
| 30.424242 | 112 | 0.734064 |
0344e51e0e34d493a4e4f0050bcc55f5bf4d96ba | 1,125 | //
// TypeHolderExample.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
@objc public class TypeHolderExample: NSObject, Codable {
public var stringItem: String
public var numberItem: Double
public var integerItem: Int
public var integerItemNum: NSNumber? {
get {
return integerItem as NSNumber?
}
}
public var boolItem: Bool
public var boolItemNum: NSNumber? {
get {
return boolItem as NSNumber?
}
}
public var arrayItem: [Int]
public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) {
self.stringItem = stringItem
self.numberItem = numberItem
self.integerItem = integerItem
self.boolItem = boolItem
self.arrayItem = arrayItem
}
public enum CodingKeys: String, CodingKey {
case stringItem = "string_item"
case numberItem = "number_item"
case integerItem = "integer_item"
case boolItem = "bool_item"
case arrayItem = "array_item"
}
}
| 25 | 109 | 0.64 |
d716584c0742a01162578b610d59e4934b113d4f | 5,243 | import AEXML_CU
import Alamofire
import Foundation
import ReactiveSwift
public struct CheckedResponse<T> {
let request: URLRequest
let response: HTTPURLResponse
let value: T
}
extension DataRequest {
public static func xmlResponseSerializer() -> DataResponseSerializer<AEXMLDocument> {
return DataResponseSerializer { _, resp, data, error in
guard error == nil else { return .failure(AlamofireRACError.network(error: error)) }
let result = Request.serializeResponseData(response: resp, data: data, error: nil)
guard case let .success(validData) = result else {
return .failure(AlamofireRACError.dataSerialization(error: error))
}
do {
let document = try AEXMLDocument(xml: validData)
return .success(document)
} catch {
return .failure(AlamofireRACError.xmlSerialization)
}
}
}
public static func emptyAllowedStringResponseSerializer() -> DataResponseSerializer<String> {
return DataResponseSerializer { _, resp, data, error in
guard error == nil else { return .failure(AlamofireRACError.network(error: error)) }
let result = Request.serializeResponseData(response: resp, data: data, error: nil)
guard case let .success(validData) = result else {
return .failure(AlamofireRACError.dataSerialization(error: error))
}
guard let string = String(data: validData, encoding: String.Encoding.utf8) else {
return .success("")
}
return .success(string)
}
}
@discardableResult
public func responseXML(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<AEXMLDocument>) -> Void)
-> Self {
return response(
queue: queue,
responseSerializer: DataRequest.xmlResponseSerializer(),
completionHandler: completionHandler
)
}
@discardableResult
public func responseStringEmptyAllowed(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<String>) -> Void
) -> Self {
return response(
queue: queue,
responseSerializer: DataRequest.emptyAllowedStringResponseSerializer(),
completionHandler: completionHandler
)
}
public func responseXML() -> SignalProducer<CheckedResponse<AEXMLDocument>, AnyError> {
return SignalProducer { observer, _ in
self.responseXML { response in
if let error = response.result.error {
return observer.send(error: AnyError(cause: error))
}
guard let document = response.result.value else {
return observer.send(error: AlamofireRACError.xmlSerialization.asAnyError())
}
guard let request = response.request, let response = response.response else {
return observer.send(error: AlamofireRACError.incompleteResponse.asAnyError())
}
observer.send(
value: CheckedResponse<AEXMLDocument>(
request: request, response: response, value: document
)
)
observer.sendCompleted()
}
}
}
public func responseString(
errorOnNil: Bool = true
) -> SignalProducer<CheckedResponse<String>, AnyError> {
return SignalProducer { observer, _ in
self.responseStringEmptyAllowed { response in
if let error = response.result.error {
return observer.send(error: AnyError(cause: error))
}
if errorOnNil && response.result.value?.count == 0 {
return observer.send(error: AlamofireRACError.incompleteResponse.asAnyError())
}
guard let req = response.request, let resp = response.response else {
return observer.send(error: AlamofireRACError.incompleteResponse.asAnyError())
}
observer.send(
value: CheckedResponse<String>(
request: req, response: resp, value: response.result.value ?? ""
)
)
observer.sendCompleted()
}
}
}
}
public enum AlamofireRACError: Error, AnyErrorConverter {
case network(error: Error?)
case dataSerialization(error: Error?)
case xmlSerialization
case incompleteResponse
case unknownError
public var description: String {
switch self {
case .network(let error):
return "There was a network issue: \(String(describing: error))."
case .dataSerialization(let error):
return "Could not serialize data: \(String(describing: error))."
case .xmlSerialization:
return "Could not serialize XML."
case .incompleteResponse:
return "Incomplete response."
default:
return "There was an unknown error."
}
}
}
| 35.187919 | 98 | 0.591074 |
9c27340c027cadddd481c4cf353ba0de59e20dbf | 355 | //
// SearchListDelegate.swift
// EmeraldComponents
//
// Created by João Mendes | Stone on 14/06/18.
// Copyright © 2018 StoneCo. All rights reserved.
//
import UIKit
public protocol SearchListDelegate: class {
var dataList: [PickerData] { get }
func didSelectOption(_ option: PickerData)
func didDeselectOption(_ option: PickerData)
}
| 22.1875 | 50 | 0.71831 |
220ab7aeacbf6b1f306f2925b385cc991a326141 | 155 | //
// Box.swift
// YumeKit
//
// Created by 林煒峻 on 2019/9/18.
// Copyright © 2019 Yume. All rights reserved.
//
import Foundation
public enum Box {}
| 12.916667 | 47 | 0.63871 |
01062dabb7bbb77ff511b03dd483faf0695e87bb | 495 | //
// AppDelegate.swift
// Day3
//
// Created by iOSDevLog on 2020/1/5.
// Copyright © 2020 iOSDevLog. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 18.333333 | 71 | 0.709091 |
14275a383348d814cb40bf98169e687c35457c8a | 2,056 | //
// CycleTrackingProtocol.swift
// MBHealthTracker
//
// Created by matybrennan on 27/9/19.
//
import Foundation
public protocol CycleTrackingProtocol: AnyObject {
func abdominalCramps(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func acne(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func appetiteChanges(handler: @escaping (MBAsyncCallResult<AppetiteChanges>) -> Void) throws
func bladderIncontinence(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func bloating(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func breastPain(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func cervicalMucusQuality(handler: @escaping (MBAsyncCallResult<CervicalMucusQuality>) -> Void) throws
func chills(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func constipation(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func diarrhea(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func drySkin(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func fatigue(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func hairLoss(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func headache(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func hotFlashes(handler: @escaping (MBAsyncCallResult<GenericCycleTrackingModel>) -> Void) throws
func menstrualFlow(handler: @escaping (MBAsyncCallResult<MenstrualFlow>) -> Void) throws
func ovulation(handler: @escaping (MBAsyncCallResult<Ovulation>) -> Void) throws
func sexualActivity(handler: @escaping (MBAsyncCallResult<SexualActivity>) -> Void) throws
func spotting(handler: @escaping (MBAsyncCallResult<Spotting>) -> Void) throws
}
| 64.25 | 110 | 0.781615 |
33ebc180670990e0378c194cffc302706d82112e | 425 | //
// UIImage.swift
// FirebaseStarterApp
//
// Created by Florian Marcu on 2/21/19.
// Copyright © 2019 Instamobile. All rights reserved.
//
import UIKit
extension UIImage {
static func localImage(_ name: String, template: Bool = false) -> UIImage {
var image = UIImage(named: name)!
if template {
image = image.withRenderingMode(.alwaysTemplate)
}
return image
}
}
| 21.25 | 79 | 0.628235 |
0843767611924a7eecddf1da19f47a2cebe4cea8 | 1,021 | //
// UILabel+Extensions.swift
// Headlines
//
// Created by Daniel Morgz on 18/01/2016.
// Copyright © 2016 Daniel Morgan. All rights reserved.
//
import UIKit
@IBDesignable class TopAlignedLabel: UILabel {
override func drawTextInRect(rect: CGRect) {
if let stringText = text {
let stringTextAsNSString = stringText as NSString
let labelStringSize = stringTextAsNSString.boundingRectWithSize(CGSizeMake(CGRectGetWidth(self.frame), CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
super.drawTextInRect(CGRectMake(0, 0, CGRectGetWidth(self.frame), ceil(labelStringSize.height)))
} else {
super.drawTextInRect(rect)
}
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.borderWidth = 1
layer.borderColor = UIColor.blackColor().CGColor
}
}
| 34.033333 | 128 | 0.667973 |
e97cfe50a9a53fd220197ad81edd4df3b5f8a2e8 | 4,536 | //
// FolderWatcher.swift
// PHP Monitor
//
// Created by Nico Verbruggen on 30/03/2021.
// Copyright © 2021 Nico Verbruggen. All rights reserved.
//
import Foundation
class PhpConfigWatcher {
let folderMonitorQueue = DispatchQueue(label: "FolderMonitorQueue", attributes: .concurrent)
let url: URL
var didChange: ((URL) -> Void)?
var lastUpdate: TimeInterval? = nil
var watchers: [FSWatcher] = []
init(for url: URL) {
self.url = url
// Add a watcher for php.ini
self.addWatcher(for: self.url.appendingPathComponent("php.ini"), eventMask: .write)
// Add a watcher for conf.d (in case a new file is added or a file is deleted)
// This watcher, when triggered, will restart all watchers
self.addWatcher(for: self.url.appendingPathComponent("conf.d"), eventMask: .all, behaviour: .reloadsWatchers)
// Scan the conf.d folder for .ini files, and add a watcher for each file
let enumerator = FileManager.default.enumerator(atPath: self.url.appendingPathComponent("conf.d").path)
let filePaths = enumerator?.allObjects as! [String]
// Loop over the .ini files that we discovered
filePaths.filter { $0.contains(".ini") }.forEach { (file) in
// Add a watcher for each file we have discovered
self.addWatcher(for: self.url.appendingPathComponent("conf.d/\(file)"), eventMask: .write)
}
Log.info("A watcher exists for the following config paths:")
Log.info(self.watchers.map({ watcher in
return watcher.url.relativePath
}))
}
func addWatcher(for url: URL, eventMask: DispatchSource.FileSystemEvent, behaviour: FSWatcherBehaviour = .reloadsMenu) {
let watcher = FSWatcher(for: url, eventMask: eventMask, parent: self, behaviour: behaviour)
self.watchers.append(watcher)
}
func disable() {
Log.info("Turning off existing watchers...")
self.watchers.forEach { (watcher) in
watcher.stopMonitoring()
}
}
deinit {
Log.perf("A PhpConfigWatcher has been deinitialized.")
}
}
enum FSWatcherBehaviour {
case reloadsMenu
case reloadsWatchers
}
class FSWatcher {
private var parent: PhpConfigWatcher!
private var monitoredFolderFileDescriptor: CInt = -1
private var folderMonitorSource: DispatchSourceFileSystemObject?
let url: URL
init(for url: URL, eventMask: DispatchSource.FileSystemEvent, parent: PhpConfigWatcher, behaviour: FSWatcherBehaviour = .reloadsMenu) {
self.url = url
self.parent = parent
self.startMonitoring(eventMask, behaviour: behaviour)
}
func startMonitoring(_ eventMask: DispatchSource.FileSystemEvent, behaviour: FSWatcherBehaviour) {
guard folderMonitorSource == nil && monitoredFolderFileDescriptor == -1 else {
return
}
// Open the file or folder referenced by URL for monitoring only.
monitoredFolderFileDescriptor = open(url.path, O_EVTONLY)
folderMonitorSource = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: monitoredFolderFileDescriptor,
eventMask: eventMask,
queue: parent.folderMonitorQueue
)
// Define the block to call when a file change is detected.
folderMonitorSource?.setEventHandler { [weak self] in
// The default behaviour is to reload the menu
switch behaviour {
case .reloadsMenu:
// Default behaviour: reload the menu items
self?.parent.didChange?(self!.url)
case .reloadsWatchers:
// Alternative behaviour: reload all watchers
App.shared.handlePhpConfigWatcher(forceReload: true)
}
}
// Define a cancel handler to ensure the directory is closed when the source is cancelled.
folderMonitorSource?.setCancelHandler { [weak self] in
guard let self = self else { return }
close(self.monitoredFolderFileDescriptor)
self.monitoredFolderFileDescriptor = -1
self.folderMonitorSource = nil
}
// Start monitoring the directory via the source.
folderMonitorSource?.resume()
}
func stopMonitoring() {
folderMonitorSource?.cancel()
self.parent = nil
}
}
| 34.625954 | 139 | 0.633598 |
efe538e005f80a160564db51a6dd2a469a78ad04 | 2,508 | import Foundation
import UIKit
import Display
import SwiftSignalKit
import Postbox
import TelegramCore
public struct ChatListNodeAdditionalCategory {
public enum Appearance {
case option
case action
}
public var id: Int
public var icon: UIImage?
public var title: String
public var appearance: Appearance
public init(id: Int, icon: UIImage?, title: String, appearance: Appearance = .option) {
self.id = id
self.icon = icon
self.title = title
self.appearance = appearance
}
}
public struct ContactMultiselectionControllerAdditionalCategories {
public var categories: [ChatListNodeAdditionalCategory]
public var selectedCategories: Set<Int>
public init(categories: [ChatListNodeAdditionalCategory], selectedCategories: Set<Int>) {
self.categories = categories
self.selectedCategories = selectedCategories
}
}
public enum ContactMultiselectionControllerMode {
case groupCreation
case peerSelection(searchChatList: Bool, searchGroups: Bool, searchChannels: Bool)
case channelCreation
case chatSelection(title: String, selectedChats: Set<PeerId>, additionalCategories: ContactMultiselectionControllerAdditionalCategories?, chatListFilters: [ChatListFilter]?)
}
public enum ContactListFilter {
case excludeSelf
case exclude([PeerId])
case disable([PeerId])
}
public final class ContactMultiselectionControllerParams {
public let context: AccountContext
public let mode: ContactMultiselectionControllerMode
public let options: [ContactListAdditionalOption]
public let filters: [ContactListFilter]
public let alwaysEnabled: Bool
public let limit: Int32?
public init(context: AccountContext, mode: ContactMultiselectionControllerMode, options: [ContactListAdditionalOption], filters: [ContactListFilter] = [.excludeSelf], alwaysEnabled: Bool = false, limit: Int32? = nil) {
self.context = context
self.mode = mode
self.options = options
self.filters = filters
self.alwaysEnabled = alwaysEnabled
self.limit = limit
}
}
public enum ContactMultiselectionResult {
case none
case result(peerIds: [ContactListPeerId], additionalOptionIds: [Int])
}
public protocol ContactMultiselectionController: ViewController {
var result: Signal<ContactMultiselectionResult, NoError> { get }
var displayProgress: Bool { get set }
var dismissed: (() -> Void)? { get set }
}
| 32.153846 | 222 | 0.73126 |
fccf79b9db33784c500eba408eb5303d903389cc | 728 | //
// LoadableViewState.swift
// iOSToolkit
//
// Created by Matthew Quiros on 7/24/20.
// Copyright © 2020 Matthew Quiros. All rights reserved.
//
import Foundation
/// The `LoadableView`'s state, which is intended to correspond with the states of an executable task.
enum LoadableViewState {
/// The view state before a task is executed.
case initial
/// The view state while a task is executing.
case loading
/// The view state after a task finishes executing and successfully returns a result.
case success
/// The view state after a task finishes executing and returns an empty or a null result.
case empty
/// The view state after a task finishes executing and returns an error.
case failure
}
| 24.266667 | 102 | 0.730769 |
64626acbc99adde9236ec18c12154a69260e7d29 | 20,215 | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import QuartzCore
import UIKit
import third_party_objective_c_material_components_ios_components_Typography_Typography
fileprivate extension MDCTypography {
static func boldFont(withSize size: CGFloat) -> UIFont {
// This font should load unless something is wrong with Material's fonts.
return MDCTypography.fontLoader().boldFont!(ofSize: size)
}
static var fontName: String {
// Arbitrary size to get the font name.
return boldFont(withSize: 10).fontName
}
}
/// Animation view for the pitch sensor.
class PitchSensorAnimationView: SensorAnimationView {
// MARK: - Nested
private enum Metrics {
static let backgroundColorValueBlueHigh: CGFloat = 175
static let backgroundColorValueBlueLow: CGFloat = 248
static let backgroundColorValueGreenHigh: CGFloat = 97
static let backgroundColorValueGreenLow: CGFloat = 202
static let backgroundColorValueRedHigh: CGFloat = 13
static let backgroundColorValueRedLow: CGFloat = 113
static let backgroundRadiusRatio: CGFloat = 0.38
static let dotAngleTop = CGFloat(Double.pi / 2)
static let dotEllipseRadiusRatio: CGFloat = 0.44
static let dotRadiusRatio: CGFloat = 0.05
static let musicSignFlat = "\u{266D} "
static let musicSignSharp = "\u{266F} "
static let noteFontSizeRatio: CGFloat = 0.48
static let noteRatioX: CGFloat = 0.42
static let noteRatioY: CGFloat = 0.46
static let noteLeftTextColor =
UIColor(red: 238 / 255, green: 238 / 255, blue: 238 / 255, alpha: 1).cgColor
static let noteRightTextColor =
UIColor(red: 220 / 255, green: 220 / 255, blue: 220 / 255, alpha: 1).cgColor
static let numberOfPianoKeys = 88
static let octaveFontSizeRatio: CGFloat = 0.2
static let octaveRatioX: CGFloat = 0.67
static let octaveRatioY: CGFloat = 0.67
static let octaveTextColor =
UIColor(red: 220 / 255, green: 220 / 255, blue: 220 / 255, alpha: 1).cgColor
static let signFontSizeRatio: CGFloat = 0.25
static let signRatioX: CGFloat = 0.62
static let signRatioY: CGFloat = 0.43
static let signTextColor =
UIColor(red: 220 / 255, green: 220 / 255, blue: 220 / 255, alpha: 1).cgColor
static let textShadowColor = UIColor(white: 0, alpha: 0.61).cgColor
static let textShadowOffset = CGSize(width: 1, height: 2)
static let textShadowRadius: CGFloat = 4
}
private struct MusicalNote {
let letter: String
let octave: String
let sign: String
var shouldCenter: Bool {
// "-" and "+" should be centered.
return letter == "-" || letter == "+"
}
}
// MARK: - Properties
private let backgroundShapeLayer = CAShapeLayer()
private let dotShapeLayer = CAShapeLayer()
private let noteLeftTextLayer = CATextLayer()
private let noteRightTextLayer = CATextLayer()
private let signTextLayer = CATextLayer()
private let octaveTextLayer = CATextLayer()
// The angle of the dot indicating how close the detected pitch is to the nearest musical note. A
// value of 0 positions the dot at the far right. A value of PI/2 positions the dot at the top. A
// value of PI positions the dot at the far left.
private var angleOfDot = Metrics.dotAngleTop
private var level: Int?
private var musicalNote: MusicalNote? {
guard let level = level else { return nil }
return musicalNotes[level]
}
private let musicalNotes: [MusicalNote] = {
let natural = ""
var musicalNotes = [MusicalNote]()
musicalNotes.append(MusicalNote(letter: "-", octave: "", sign: ""))
for i in 1...Metrics.numberOfPianoKeys {
var letter = ""
var sign = ""
switch (i + 8) % 12 {
case 0:
letter = "C"
sign = natural
case 1:
letter = "C"
sign = Metrics.musicSignSharp
case 2:
letter = "D"
sign = natural
case 3:
letter = "E"
sign = Metrics.musicSignFlat
case 4:
letter = "E"
sign = natural
case 5:
letter = "F"
sign = natural
case 6:
letter = "F"
sign = Metrics.musicSignSharp
case 7:
letter = "G"
sign = natural
case 8:
letter = "A"
sign = Metrics.musicSignFlat
case 9:
letter = "A"
sign = natural
case 10:
letter = "B"
sign = Metrics.musicSignFlat
case 11:
letter = "B"
sign = natural
default:
break
}
let octave = (i + 8) / 12
musicalNotes.append(MusicalNote(letter: letter, octave: String(octave), sign: sign))
}
musicalNotes.append(MusicalNote(letter: "+", octave: "", sign: ""))
return musicalNotes
}()
/// The frequencies of notes of a piano at indices 1-88. Each value is a half step more than the
/// previous value.
private let noteFrequencies: [Double] = {
var noteFrequencies = [Double]()
var multiplier = 1.0
while (noteFrequencies.count < Metrics.numberOfPianoKeys) {
for note in SoundUtils.highNotes {
guard noteFrequencies.count < Metrics.numberOfPianoKeys else { break }
noteFrequencies.append(note * multiplier)
}
multiplier /= 2.0
}
noteFrequencies.reverse()
// Add first and last items to make lookup easier. Use the approximate half-step ratio to
// determine the first and last items.
noteFrequencies.insert(noteFrequencies[0] / SoundUtils.halfStepFrequencyRatio, at: 0)
noteFrequencies.append(
noteFrequencies[noteFrequencies.endIndex - 1] * SoundUtils.halfStepFrequencyRatio
)
return noteFrequencies
}()
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
override func layoutSubviews() {
super.layoutSubviews()
// Background shape layer.
let backgroundShapeRadius = bounds.width * Metrics.backgroundRadiusRatio
let backgroundShapeRect = CGRect(x: bounds.midX - backgroundShapeRadius,
y: bounds.midY - backgroundShapeRadius,
width: backgroundShapeRadius * 2,
height: backgroundShapeRadius * 2)
backgroundShapeLayer.path = UIBezierPath(ovalIn: backgroundShapeRect).cgPath
// Dot shape layer will be at a point on an invisible ellipse.
let ellipseRadius = bounds.width * Metrics.dotEllipseRadiusRatio
let dotX = bounds.midX + ellipseRadius * cos(angleOfDot)
let dotY = bounds.midY - ellipseRadius * sin(angleOfDot)
let dotRadius = bounds.width * Metrics.dotRadiusRatio
let dotShapeRect = CGRect(x: dotX - dotRadius,
y: dotY - dotRadius,
width: dotRadius * 2,
height: dotRadius * 2)
dotShapeLayer.path = UIBezierPath(ovalIn: dotShapeRect).cgPath
// Text layers.
if let musicalNote = musicalNote {
// Letter
let noteFontSize = floor(bounds.height * Metrics.noteFontSizeRatio)
noteLeftTextLayer.fontSize = noteFontSize
noteRightTextLayer.fontSize = noteFontSize
let noteSize = musicalNote.letter.boundingRect(
with: .zero,
options: [],
attributes: [NSAttributedString.Key.font: MDCTypography.boldFont(withSize: noteFontSize)],
context: nil).size
var noteX: CGFloat
var noteY: CGFloat
if musicalNote.shouldCenter {
noteX = bounds.midX - ceil(noteSize.width) / 2
noteY = bounds.midY - ceil(noteSize.height) / 2
} else {
noteX = bounds.width * Metrics.noteRatioX - ceil(noteSize.width) / 2
noteY = bounds.height * Metrics.noteRatioY - ceil(noteSize.height) / 2
}
// The note layer on the left is half width.
noteLeftTextLayer.frame = CGRect(x: floor(noteX),
y: floor(noteY),
width: ceil(noteSize.width / 2),
height: ceil(noteSize.height))
noteRightTextLayer.frame = CGRect(x: floor(noteX),
y: floor(noteY),
width: ceil(noteSize.width),
height: ceil(noteSize.height))
// Sign.
signTextLayer.fontSize = floor(bounds.height * Metrics.signFontSizeRatio)
let signFont = MDCTypography.boldFont(withSize: signTextLayer.fontSize)
let signSize = musicalNote.sign.boundingRect(
with: .zero,
options: [],
attributes: [NSAttributedString.Key.font: signFont],
context: nil).size
signTextLayer.frame =
CGRect(x: floor(bounds.width * Metrics.signRatioX - signSize.width / 2),
y: floor(bounds.height * Metrics.signRatioY - signSize.height / 2),
width: ceil(signSize.width),
height: ceil(signSize.height))
// Octave
octaveTextLayer.fontSize = floor(bounds.height * Metrics.octaveFontSizeRatio)
let octaveFont = MDCTypography.boldFont(withSize: octaveTextLayer.fontSize)
let octaveSize =
musicalNote.octave.boundingRect(with: .zero,
options: [],
attributes: [NSAttributedString.Key.font: octaveFont],
context: nil).size
octaveTextLayer.frame =
CGRect(x: floor(bounds.width * Metrics.octaveRatioX - octaveSize.width / 2),
y: floor(bounds.height * Metrics.octaveRatioY - octaveSize.height / 2),
width: ceil(octaveSize.width),
height: ceil(octaveSize.height))
}
}
override func setValue(_ value: Double, minValue: Double, maxValue: Double) {
guard let level = noteIndex(fromFrequency: value), level != self.level else { return }
// Store the level.
self.level = level
// Set the fill color of the background shape layer.
backgroundShapeLayer.fillColor = backgroundColor(forLevel: level).cgColor
// The the angle of the dot.
let difference = differenceBetween(pitch: value, andLevel: level)
angleOfDot = CGFloat((1 - 2 * difference) * (Double.pi / 2))
// Set the musical note letter, sign and octave.
let musicalNote = musicalNotes[level]
noteLeftTextLayer.string = musicalNote.letter
noteRightTextLayer.string = musicalNote.letter
signTextLayer.string = musicalNote.sign
octaveTextLayer.string = musicalNote.octave
setNeedsLayout()
setAccessibilityLabel(withMusicalNote: musicalNote,
level: level,
differenceBetweenNoteAndPitch: difference)
}
override func reset() {
setValue(0, minValue: 0, maxValue: 0)
}
/// Returns an image snapshot and an accessibility label for this view, showing a given value.
///
/// - Parameters:
/// - size: The size of the image on screen.
/// - value: The value to display the pitch at.
/// - Returns: A tuple containing an optional image snapshot and an optional accessibility label.
static func imageAttributes(atSize size: CGSize, withValue value: Double) -> (UIImage?, String?) {
let pitchSensorAnimationView =
PitchSensorAnimationView(frame: CGRect(origin: .zero, size: size))
pitchSensorAnimationView.setValue(value, minValue: 0, maxValue: 1)
return (pitchSensorAnimationView.imageSnapshot, pitchSensorAnimationView.accessibilityLabel)
}
// MARK: - Private
private func backgroundColor(forLevel level: Int) -> UIColor {
if (level == 0) {
return UIColor(red: Metrics.backgroundColorValueRedLow / 255,
green: Metrics.backgroundColorValueGreenLow / 255,
blue: Metrics.backgroundColorValueBlueLow / 255, alpha: 1)
} else if level == noteFrequencies.endIndex - 1 {
return UIColor(red: Metrics.backgroundColorValueRedHigh / 255,
green: Metrics.backgroundColorValueGreenHigh / 255,
blue: Metrics.backgroundColorValueBlueHigh / 255, alpha: 1)
} else {
let red = round(Metrics.backgroundColorValueRedLow +
(Metrics.backgroundColorValueRedHigh - Metrics.backgroundColorValueRedLow) *
CGFloat(level) / CGFloat(noteFrequencies.endIndex - 1))
let green = round(Metrics.backgroundColorValueGreenLow +
(Metrics.backgroundColorValueGreenHigh - Metrics.backgroundColorValueGreenLow) *
CGFloat(level) / CGFloat(noteFrequencies.endIndex - 1))
let blue = round(Metrics.backgroundColorValueBlueLow +
(Metrics.backgroundColorValueBlueHigh - Metrics.backgroundColorValueBlueLow) *
CGFloat(level) / CGFloat(noteFrequencies.endIndex - 1))
return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1)
}
}
private func configureView() {
isAccessibilityElement = true
// Background image view.
let imageView = UIImageView(image: UIImage(named: "sensor_sound_frequency_0"))
imageView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
imageView.frame = bounds
addSubview(imageView)
// Background shape layer.
backgroundShapeLayer.fillColor = backgroundColor(forLevel: 0).cgColor
layer.addSublayer(backgroundShapeLayer)
// Dot shape layer.
dotShapeLayer.fillColor = UIColor.red.cgColor
layer.addSublayer(dotShapeLayer)
// Text layer common configuration.
[noteRightTextLayer, noteLeftTextLayer, signTextLayer, octaveTextLayer].forEach {
$0.alignmentMode = .center
$0.contentsScale = UIScreen.main.scale
$0.font = CGFont(MDCTypography.fontName as CFString)
$0.shadowColor = Metrics.textShadowColor
$0.shadowOffset = Metrics.textShadowOffset
$0.shadowRadius = Metrics.textShadowRadius
layer.addSublayer($0)
}
// Right note.
noteRightTextLayer.foregroundColor = Metrics.noteRightTextColor
// Left note.
noteLeftTextLayer.foregroundColor = Metrics.noteLeftTextColor
noteLeftTextLayer.masksToBounds = true
// Sign.
signTextLayer.foregroundColor = Metrics.signTextColor
// Octave.
octaveTextLayer.foregroundColor = Metrics.octaveTextColor
// Set the lowest detectable value initially.
reset()
}
// The difference, in half steps, between the detected pitch and the note associated with the
// level.
func differenceBetween(pitch: Double, andLevel level: Int) -> Double {
if (level == 0 || level == noteFrequencies.endIndex - 1) {
// If the nearest musical note is more than one half step lower than the lowest musical note
// or more than one half step higher than the highest musical note, don't calculate the
// difference.
return 0
}
// If the detected pitch equals a musical note the dot is at the top, which is 90 degrees or
// Double.pi / 2 radians. If the detected pitch is half way between the nearest musical note and
// the next lower musical note, the dot is at the far left, which is 180 degrees, or Double.pi
// radians. If the detected pitch is half way between the nearest musical note and the next
// higher musical note, the dot is at the far right, which is 0 degrees, or 0 radians.
let nearestNote = noteFrequencies[level]
var difference = pitch - nearestNote
if (difference < 0) {
// The detected pitch is lower than the nearest musical note. Adjust the difference to the
// range of -1 to 0, where -1 is the next lower note. The difference should never be less than
// -0.5, since that would indicate that the pitch was actually closer to the lower note.
let lowerNote = noteFrequencies[level - 1]
difference /= nearestNote - lowerNote
} else {
// The detected pitch is higher than the nearest musical note. Adjust the difference to the
// range of 0 to 1, where 1 is the next higher note. The difference should never be greater
// than 0.5, since that would indicate that the pitch was actually closer to the higher note.
let higherNote = noteFrequencies[level + 1]
difference /= higherNote - nearestNote
}
return difference
}
/// The index of the note corresponding to the given sound frequency, where indices 1-88 represent
/// the notes of keys on a piano.
private func noteIndex(fromFrequency frequency: Double) -> Int? {
if frequency < noteFrequencies[0] {
// `frequency` is lower than the lowest note.
return 0
} else if frequency > noteFrequencies[noteFrequencies.endIndex - 1] {
// `frequency` is higher than the highest note.
return noteFrequencies.endIndex - 1
} else {
var previousNote: Double?
for (index, note) in noteFrequencies.enumerated() {
if note == frequency {
// `frequency` matched a note.
return index
}
if let previousNote = previousNote, frequency > previousNote && frequency < note {
// `frequency` is between two notes.
let midpoint = (previousNote + note) / 2
return frequency < midpoint ? index - 1 : index
}
previousNote = note
}
}
return nil
}
private func setAccessibilityLabel(withMusicalNote musicalNote: MusicalNote,
level: Int,
differenceBetweenNoteAndPitch difference: Double) {
let accessibilityLabel: String
if level == 0 {
accessibilityLabel = String.pitchLowContentDescription
} else if (level == noteFrequencies.endIndex - 1) {
accessibilityLabel = String.pitchHighContentDescription
} else {
let formatString: String
let differenceString = String.localizedStringWithFormat("%.2f", abs(difference))
if difference < 0 {
if musicalNote.sign == Metrics.musicSignFlat {
formatString = String.pitchFlatterThanFlatNoteContentDescription
} else if musicalNote.sign == Metrics.musicSignSharp {
formatString = String.pitchFlatterThanSharpNoteContentDescription
} else {
// Natural note
formatString = String.pitchFlatterThanNaturalNoteContentDescription
}
accessibilityLabel =
String(format: formatString, differenceString, musicalNote.letter, musicalNote.octave)
} else if difference > 0 {
if musicalNote.sign == Metrics.musicSignFlat {
formatString = String.pitchSharperThanFlatNoteContentDescription
} else if musicalNote.sign == Metrics.musicSignSharp {
formatString = String.pitchSharperThanSharpNoteContentDescription
} else {
// Natural note
formatString = String.pitchSharperThanNaturalNoteContentDescription
}
accessibilityLabel =
String(format: formatString, differenceString, musicalNote.letter, musicalNote.octave)
} else {
// difference == 0
if musicalNote.sign == Metrics.musicSignFlat {
formatString = String.pitchFlatNoteContentDescription
} else if musicalNote.sign == Metrics.musicSignSharp {
formatString = String.pitchSharpNoteContentDescription
} else {
// Natural note
formatString = String.pitchNaturalNoteContentDescription
}
accessibilityLabel = String(format: formatString, musicalNote.letter, musicalNote.octave)
}
}
self.accessibilityLabel = accessibilityLabel
}
}
| 39.793307 | 100 | 0.658867 |
1c420ed778998fcba3a09068e47a7705f37ee2b0 | 385 | //
// UIColor+NamedColors.swift
// MoneyChallenge
//
// Created by Juan López Bosch on 14/09/2020.
// Copyright © 2020 Juan López. All rights reserved.
//
import UIKit
extension UIColor {
static var primary = UIColor(named: "primary") ?? .black
static var secondary = UIColor(named: "secondary") ?? .black
static var tertiary = UIColor(named: "tertiary") ?? .white
}
| 24.0625 | 64 | 0.680519 |
69ebdbce37f817fd3bbdf50728b922f422f1ca38 | 2,957 | //
// WebView.swift
// LazyKeyboard
//
// Created by sunny on 2018/3/3.
// Copyright © 2018年 CepheusSun. All rights reserved.
//
import UIKit
import WebKit
import RxCocoa
import RxSwift
final class WebController: UIViewController, WKNavigationDelegate {
/// url 链接
var webURL: URL?
/// HTML 文本
var webContent: String?
var isShareAllowed: Bool = false
fileprivate lazy var wkWebView: WKWebView = {
let infoDictionary = Bundle.main.infoDictionary!
let version = infoDictionary["CFBundleShortVersionString"]!
let jsStr = "localStorage.setItem('appVersion', '\(version)')"
let script = WKUserScript(source: jsStr,
injectionTime: .atDocumentStart,
forMainFrameOnly: false)
let config = WKWebViewConfiguration()
config.userContentController.addUserScript(script)
let web = WKWebView(frame: CGRect.zero, configuration: config)
web.navigationDelegate = self
view.addSubview(web)
return web
}()
lazy var progressView: UIProgressView = {
let progress = UIProgressView(frame: .zero)
progress.tintColor = C.themeGreen
progress.trackTintColor = .white
view.addSubview(progress)
return progress
}()
var kvo: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
edgesForExtendedLayout = .bottom
wkWebView.frame = view.bounds
progressView.frame = CGRect(x: 0, y: 0, width: view.width, height: 2)
webURL.ifSome {[unowned self] (url) in
let urlRequest = URLRequest(url: url)
self.wkWebView.load(urlRequest)
}
webContent.ifSome {[unowned self] (html) in
self.wkWebView.loadHTMLString(html, baseURL: nil)
}
kvo = wkWebView.observe(\.estimatedProgress) {[weak self] (obj, changed) in
let new = obj.estimatedProgress
if new == 1 {
self?.progressView.isHidden = true
} else {
self?.progressView.isHidden = false
self?.progressView.setProgress(Float(new), animated: true)
}
}
}
}
// MARK: - WKNavigationDelegate
extension WebController {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
webView.url.ifSome {
if $0.absoluteString.hasPrefix("https://itunes.apple.com") {
UIApplication.shared.open(navigationAction.request.url!, options: [:]
, completionHandler: nil)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
}
}
| 30.484536 | 157 | 0.591816 |
dd08e562d669d6863c4b46a2a3fb5fa2b3018e89 | 302 | //
// CurrencyModel.swift
// Practice exercise
//
// Created by Itiel Luque on 14/2/22.
//
import Foundation
class CurrencyModel {
let currency: String
let amount: Float
init(currency: String, amount: Float) {
self.currency = currency
self.amount = amount
}
}
| 15.894737 | 43 | 0.629139 |
8a13fdf01d048e337a8bd12a4715620312276914 | 2,405 | //
// Endpoint.swift
// ProtocolOrientedNetworking
//
// Created by Pedro Brito on 13/12/2018.
// Copyright © 2018 pmlbrito. All rights reserved.
//
import Foundation
public protocol Endpoint {
var configuration: APIConfigurable { get set }
var base: String { get }
var urlComponents: URLComponents { get }
var path: String { get }
var httpMethod: HTTPMethod { get }
var headers: [String: String]? { get }
var body: Data? { get }
//func encode<T: Encodable>(data: T, with strategy: JSONEncoder.KeyEncodingStrategy?) -> Data?
}
public extension Endpoint {
var base: String { return configuration.baseURL }
var headers: [String: String]? {
let deviceModel = UIDevice.current.model
let osNumber = UIDevice.current.systemVersion
let userAgent = String(format: "Apple|%@|%@", deviceModel, osNumber)
return ["Content-Type": "application/json", "User-Agent": userAgent]
}
var urlComponents: URLComponents {
var components = URLComponents(string: base)!
components.path = path
components.queryItems = configuration.appQueryParams
return components
}
var request: URLRequest {
let url = urlComponents.url!
var composedURLRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: configuration.requestTimeout)
self.headers?.forEach { (key, value) in
composedURLRequest.setValue(value, forHTTPHeaderField: key)
}
composedURLRequest.httpBody = body
composedURLRequest.httpMethod = self.httpMethod.rawValue
return composedURLRequest
}
func encode<T: Encodable>(data: T, with strategy: JSONEncoder.KeyEncodingStrategy? = nil) -> Data? {
do {
let jsonEncoder = JSONEncoder()
if let jsonStrategy = strategy {
jsonEncoder.keyEncodingStrategy = jsonStrategy
}
let jsonData = try jsonEncoder.encode(data)
jsonEncoder.outputFormatting = .prettyPrinted
NSLog("jsonData: \(String(data: jsonData, encoding: .utf8)!))")
return jsonData
}
catch let error {
NSLog("Error encoding parameters - \(error.localizedDescription)")
return nil
}
}
}
| 32.5 | 153 | 0.627859 |
e08a5e7720bf36d807b66c58a01f4261036f2c27 | 224 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a {
func a<H : d
var d = B
class B<T where B : A
| 24.888889 | 87 | 0.727679 |
4b53576f676b99528fbd58e111de7c1b7fad0c3e | 1,400 | //
// SafeListCoordinator.swift
// Heimdall
//
// Created by Luis Reisewitz on 06.11.17.
// Copyright © 2017 Gnosis. All rights reserved.
//
import ReactiveKit
import UIKit
class SafeListCoordinator: TabCoordinator {
let store: DataStore
init(store: DataStore) {
self.store = store
super.init()
}
override var tabBarItem: UITabBarItem {
return UITabBarItem(tabBarSystemItem: .favorites, tag: 0)
}
override func start() -> Signal<Void, NoError> {
let safeStore = AppDataStore<Safe>(store: store)
let safeListViewModel = SafeListViewModel(store: safeStore)
let safeListViewController = SafeListViewController(viewModel: safeListViewModel)
navigationController.rootViewController = safeListViewController
safeListViewModel
.addSafe
.flatMapLatest { _ in
self.coordinate(to: AddSafeCoordinator(navigationController: self.navigationController))
}
.flatMap { (result: AddSafeCoordinator.CoordinationResult) -> Safe? in
guard case .safe(let newSafe) = result else {
return nil
}
return newSafe
}
.observeNext { safe in
_ = try? safeStore.add(safe)
}
.dispose(in: disposeBag)
return Signal.never()
}
}
| 29.166667 | 104 | 0.613571 |
ac6ddf31fe6bbfca6084605140a2576d07b22a34 | 402 | // RUN: rm -rf %t && mkdir -p %t && not %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/pre_fixit_pass.swift.result -o /dev/null
// We shouldn't be able to successfully use the pre-fix-it passes to
// fix this file before migration because there is a use of an
// unresolved identifier 'bar'.
func foo(s: String) {}
foo("Hello")
bar("Hello") // Unresolved failure
| 40.2 | 164 | 0.706468 |
f896ea46896bcaaa19ca88328cdcd43e11518576 | 3,115 | //
// RepositoryTest.swift
// Viper BadTests
//
// Created by Marcio Duarte on 2021-09-16.
//
import XCTest
@testable import Viper_Bad
class RepositoryTests: XCTestCase {
var apiClient: BreakingBadAPIClient?
var emptyApiClient: BreakingBadAPIClient?
var failureApiClient: BreakingBadAPIClient?
var apiRepository: BreakingBadRepository?
var emptyApiRepository: BreakingBadRepository?
var failureApiRepository: BreakingBadRepository?
override func setUp() {
apiClient = MockBreakingBadAPIClient()
emptyApiClient = EmptyBreakingBadAPIClient()
failureApiClient = FailureBreakingBadAPIClient()
apiRepository = BreakingBadNetworkRepository(apiClient: apiClient!)
emptyApiRepository = BreakingBadNetworkRepository(apiClient: emptyApiClient!)
failureApiRepository = BreakingBadNetworkRepository(apiClient: failureApiClient!)
}
override func tearDown() {}
func testNotEmptyApiClient() {
apiClient?.getAllCharacters { result in
guard case let .success(characters) = result else {
XCTFail("ApiClient result is failure")
return
}
XCTAssertTrue(!characters.isEmpty, "Characters result is empty")
XCTAssertEqual(characters, testCharactersList, "The returned character list is not equal")
}
}
func testEmptyApiClient() {
emptyApiClient?.getAllCharacters { result in
guard case let .success(characters) = result else {
XCTFail("ApiClient result is failure")
return
}
XCTAssertTrue(characters.isEmpty, "Characters result is not empty")
}
}
func testFailureApiClient() {
failureApiClient?.getAllCharacters { result in
guard case .failure(_) = result else {
XCTFail("ApiClient result is not failure")
return
}
}
}
func testNotEmptyRepository() {
apiRepository?.getAllCharacters { result in
guard case let .success(characters) = result else {
XCTFail("ApiRepository result is failure")
return
}
XCTAssertTrue(!characters.isEmpty, "Characters result is empty")
XCTAssertEqual(characters, testCharactersList, "The returned character list is not equal")
}
}
func testEmptyRepository() {
emptyApiRepository?.getAllCharacters { result in
guard case let .success(characters) = result else {
XCTFail("ApiRepository result is failure")
return
}
XCTAssertTrue(characters.isEmpty, "Characters result is not empty")
}
}
func testFailureRepository() {
failureApiRepository?.getAllCharacters { result in
guard case .failure(_) = result else {
XCTFail("ApiRepository result is not failure")
return
}
}
}
}
| 32.447917 | 102 | 0.613483 |
8fa65a4e023f7dfb1bd407e54edf6f57f67a54eb | 317 | //
// RequestProtocol.swift
//
//
// Created by Mathew Gacy on 5/29/21.
//
import Foundation
public protocol URLRequestConvertible {
func asURLRequest() -> URLRequest
}
public protocol RequestProtocol: URLRequestConvertible {
associatedtype Response
var decode: (Data) throws -> Response { get }
}
| 17.611111 | 56 | 0.709779 |
09438bfdbe81fc777c10fc7f494edeed92ea665e | 1,473 | // Test that there is no crash in such a case:
// - there is mixed framework A
// - swift module B depends on A and is built fine
// - there is a swift invocation that imports B but causes the ObjC part of A to fail to import
// RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/MixModA.framework/Headers)
// RUN: %empty-directory(%t/MixModA.framework/Modules/MixModA.swiftmodule)
// RUN: cp %S/Inputs/MixModA.modulemap %t/MixModA.framework/Modules/module.modulemap
// RUN: %target-swift-frontend -emit-module %S/Inputs/SwiftModA.swift -module-name MixModA -I %S/Inputs/objcfail -o %t/MixModA.framework/Modules/MixModA.swiftmodule/%target-swiftmodule-name -emit-objc-header -emit-objc-header-path %t/MixModA.framework/Headers/MixModA-Swift.h -module-cache-path %t/mcp
// RUN: %target-swift-frontend -emit-module %S/Inputs/SwiftModB.swift -module-name SwiftModB -F %t -o %t -module-cache-path %t/mcp
// RUN: %target-swift-frontend -typecheck %s -I %t -module-cache-path %t/mcp
// RUN: %target-swift-frontend -typecheck %s -Xcc -DFAIL -I %t -module-cache-path %t/mcp -show-diagnostics-after-fatal -verify -verify-ignore-unknown
import SwiftModB // expected-error {{missing required module}}
_ = TyB() // expected-error {{cannot find 'TyB' in scope}}
// -verify-ignore-unknown is for:
// <unknown>:0: error: unexpected error produced: could not build Objective-C module 'ObjCFail'
// <unknown>:0: error: unexpected error produced: missing required module 'ObjCFail'
| 61.375 | 301 | 0.742023 |
acbc475fad37af87fd9e167d3affbcb3014c74d4 | 14,699 | import UIKit
import CoreGraphics
import AVFoundation
public protocol QRCodeScannerDelegate: AnyObject {
func qrCodeScanner(_ controller: UIViewController, scanDidComplete result: String)
func qrCodeScannerDidFail(_ controller: UIViewController, error: String)
func qrCodeScannerDidCancel(_ controller: UIViewController)
}
public class QRCodeScannerController: UIViewController, AVCaptureMetadataOutputObjectsDelegate, UIImagePickerControllerDelegate, UINavigationBarDelegate {
var squareView: SquareView? = nil
public var delegate: QRCodeScannerDelegate?
private var flashButton: UIButton? = nil
//Extra images for adding extra features
public var cameraImage: UIImage? = nil
public var cancelImage: UIImage? = nil
public var flashOnImage: UIImage? = nil
public var flashOffImage: UIImage? = nil
//Default Properties
private let bottomSpace: CGFloat = 80.0
private let spaceFactor: CGFloat = 16.0
private let devicePosition: AVCaptureDevice.Position = .back
private var delCnt: Int = 0
//This is for adding delay so user will get sufficient time for align QR within frame
private let delayCount: Int = 15
//Initialise CaptureDevice
lazy var defaultDevice: AVCaptureDevice? = {
if let device = AVCaptureDevice.default(for: .video) {
return device
}
return nil
}()
//Initialise front CaptureDevice
lazy var frontDevice: AVCaptureDevice? = {
if #available(iOS 10, *) {
if let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) {
return device
}
} else {
for device in AVCaptureDevice.devices(for: .video) {
if device.position == .front { return device }
}
}
return nil
}()
//Initialise AVCaptureInput with defaultDevice
lazy var defaultCaptureInput: AVCaptureInput? = {
if let captureDevice = defaultDevice {
do {
return try AVCaptureDeviceInput(device: captureDevice)
} catch let error as NSError {
print(error)
}
}
return nil
}()
//Initialise AVCaptureInput with frontDevice
lazy var frontCaptureInput: AVCaptureInput? = {
if let captureDevice = frontDevice {
do {
return try AVCaptureDeviceInput(device: captureDevice)
} catch let error as NSError {
print(error)
}
}
return nil
}()
lazy var dataOutput = AVCaptureMetadataOutput()
//Initialise capture session
lazy var captureSession = AVCaptureSession()
//Initialise videoPreviewLayer with capture session
lazy var videoPreviewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.captureSession)
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
layer.cornerRadius = 10.0
return layer
}()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nil, bundle: nil)
}
//Convinience init for adding extra images (camera, torch, cancel)
convenience public init(cameraImage: UIImage?, cancelImage: UIImage?, flashOnImage: UIImage?, flashOffImage: UIImage?) {
self.init()
self.cameraImage = cameraImage
self.cancelImage = cancelImage
self.flashOnImage = flashOnImage
self.flashOffImage = flashOffImage
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
print("SwiftQRScanner deallocating...")
}
//MARK: Life cycle methods
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Currently only "Portraint" mode is supported
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
delCnt = 0
prepareQRScannerView(self.view)
startScanningQRCode()
}
/* This calls up methods which makes code ready for scan codes.
- parameter view: UIView in which you want to add scanner.
*/
func prepareQRScannerView(_ view: UIView) {
setupCaptureSession(devicePosition) //Default device capture position is rear
addViedoPreviewLayer(view)
createCornerFrame()
addButtons(view)
}
//Creates corner rectagle frame with green coloe(default color)
func createCornerFrame() {
let width: CGFloat = 200.0
let height: CGFloat = 200.0
let rect = CGRect.init(
origin: CGPoint.init(
x: self.view.frame.midX - width/2,
y: self.view.frame.midY - (width+bottomSpace)/2),
size: CGSize.init(width: width, height: height))
self.squareView = SquareView(frame: rect)
if let squareView = squareView {
self.view.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
squareView.autoresizingMask = UIView.AutoresizingMask(rawValue: UInt(0.0))
self.view.addSubview(squareView)
addMaskLayerToVideoPreviewLayerAndAddText(rect: rect)
}
}
func addMaskLayerToVideoPreviewLayerAndAddText(rect: CGRect) {
let maskLayer = CAShapeLayer()
maskLayer.frame = view.bounds
maskLayer.fillColor = UIColor(white: 0.0, alpha: 0.5).cgColor
let path = UIBezierPath(rect: rect)
path.append(UIBezierPath(rect: view.bounds))
maskLayer.path = path.cgPath
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
view.layer.insertSublayer(maskLayer, above: videoPreviewLayer)
let noteText = CATextLayer()
noteText.fontSize = 18.0
noteText.string = "Align QR code within frame to scan"
noteText.alignmentMode = CATextLayerAlignmentMode.center
noteText.contentsScale = UIScreen.main.scale
noteText.frame = CGRect(x: spaceFactor, y: rect.origin.y + rect.size.height + 30, width: view.frame.size.width - (2.0 * spaceFactor), height: 22)
noteText.foregroundColor = UIColor.white.cgColor
view.layer.insertSublayer(noteText, above: maskLayer)
}
// Adds buttons to view which can we used as extra fearures
private func addButtons(_ view: UIView) {
let height: CGFloat = 44.0
let width: CGFloat = 44.0
let btnWidthWhenCancelImageNil: CGFloat = 60.0
//Cancel button
let cancelButton = UIButton()
if let cancelImg = cancelImage {
cancelButton.frame = CGRect(
x: view.frame.width/2 - width/2,
y: view.frame.height - 60,
width: width,
height: height)
cancelButton.setImage(cancelImg, for: .normal)
} else {
cancelButton.frame = CGRect(
x: view.frame.width/2 - btnWidthWhenCancelImageNil/2,
y: view.frame.height - 60,
width: btnWidthWhenCancelImageNil,
height: height)
cancelButton.setTitle("Cancel", for: .normal)
}
cancelButton.contentMode = .scaleAspectFit
cancelButton.addTarget(self, action: #selector(dismissVC), for:.touchUpInside)
view.addSubview(cancelButton)
//Torch button
if let flashOffImg = flashOffImage {
let flashButtonFrame = CGRect(x: 16, y: self.view.bounds.size.height - (bottomSpace + height + 10), width: width, height: height)
let flashButton = createButtons(flashButtonFrame, height: height)
flashButton.addTarget(self, action: #selector(toggleTorch), for: .touchUpInside)
flashButton.setImage(flashOffImg, for: .normal)
view.addSubview(flashButton)
self.flashButton = flashButton
}
//Camera button
if let cameraImg = cameraImage {
let frame = CGRect(x: self.view.bounds.width - (width + 16), y: self.view.bounds.size.height - (bottomSpace + height + 10), width: width, height: height)
let cameraSwitchButton = createButtons(frame, height: height)
cameraSwitchButton.setImage(cameraImg, for: .normal)
cameraSwitchButton.addTarget(self, action: #selector(switchCamera), for: .touchUpInside)
view.addSubview(cameraSwitchButton)
}
}
func createButtons(_ frame: CGRect, height: CGFloat) -> UIButton {
let button = UIButton()
button.frame = frame
button.tintColor = UIColor.white
button.layer.cornerRadius = height/2
button.backgroundColor = UIColor.black.withAlphaComponent(0.5)
button.contentMode = .scaleAspectFit
return button
}
//Toggle torch
@objc func toggleTorch() {
//If device postion is front then no need to torch
if let currentInput = getCurrentInput() {
if currentInput.device.position == .front { return }
}
guard let defaultDevice = defaultDevice else {return}
if defaultDevice.isTorchAvailable {
do {
try defaultDevice.lockForConfiguration()
defaultDevice.torchMode = defaultDevice.torchMode == .on ? .off : .on
if defaultDevice.torchMode == .on {
if let flashOnImage = flashOnImage {
flashButton?.setImage(flashOnImage, for: .normal)
}
} else {
if let flashOffImage = flashOffImage {
flashButton?.setImage(flashOffImage, for: .normal)
}
}
defaultDevice.unlockForConfiguration()
} catch let error as NSError {
print(error)
}
}
}
//Switch camera
@objc func switchCamera() {
if let frontDeviceInput = frontCaptureInput {
captureSession.beginConfiguration()
if let currentInput = getCurrentInput() {
captureSession.removeInput(currentInput)
if let newDeviceInput = (currentInput.device.position == .front) ? defaultCaptureInput : frontDeviceInput {
captureSession.addInput(newDeviceInput)
}
}
captureSession.commitConfiguration()
}
}
private func getCurrentInput() -> AVCaptureDeviceInput? {
if let currentInput = captureSession.inputs.first as? AVCaptureDeviceInput {
return currentInput
}
return nil
}
@objc func dismissVC() {
self.dismiss(animated: true, completion: nil)
delegate?.qrCodeScannerDidCancel(self)
}
//MARK: - Setup and start capturing session
open func startScanningQRCode() {
if captureSession.isRunning { return }
captureSession.startRunning()
}
private func setupCaptureSession(_ devicePostion: AVCaptureDevice.Position) {
if captureSession.isRunning { return }
switch devicePosition {
case .front:
if let frontDeviceInput = frontCaptureInput {
if !captureSession.canAddInput(frontDeviceInput) {
delegate?.qrCodeScannerDidFail(self, error: "Failed to add Input")
self.dismiss(animated: true, completion: nil)
return
}
captureSession.addInput(frontDeviceInput)
}
break
case .back, .unspecified :
if let defaultDeviceInput = defaultCaptureInput {
if !captureSession.canAddInput(defaultDeviceInput) {
delegate?.qrCodeScannerDidFail(self, error: "Failed to add Input")
self.dismiss(animated: true, completion: nil)
return
}
captureSession.addInput(defaultDeviceInput)
}
break
default: print("Do nothing")
}
if !captureSession.canAddOutput(dataOutput) {
delegate?.qrCodeScannerDidFail(self, error: "Failed to add Output")
self.dismiss(animated: true, completion: nil)
return
}
captureSession.addOutput(dataOutput)
dataOutput.metadataObjectTypes = dataOutput.availableMetadataObjectTypes
dataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
}
//Inserts layer to view
private func addViedoPreviewLayer(_ view: UIView) {
videoPreviewLayer.frame = CGRect(x:view.bounds.origin.x, y: view.bounds.origin.y, width: view.bounds.size.width, height: view.bounds.size.height - bottomSpace)
view.layer.insertSublayer(videoPreviewLayer, at: 0)
}
// This method get called when Scanning gets complete
public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
for data in metadataObjects {
let transformed = videoPreviewLayer.transformedMetadataObject(for: data) as? AVMetadataMachineReadableCodeObject
if let unwraped = transformed {
if view.bounds.contains(unwraped.bounds) {
delCnt = delCnt + 1
if delCnt > delayCount {
if let unwrapedStringValue = unwraped.stringValue {
print(unwrapedStringValue)
print(delegate)
delegate?.qrCodeScanner(self, scanDidComplete: unwrapedStringValue)
} else {
delegate?.qrCodeScannerDidFail(self, error: "Empty string found")
}
captureSession.stopRunning()
self.dismiss(animated: true, completion: nil)
}
}
}
}
}
}
extension QRCodeScannerController {
override public var shouldAutorotate: Bool {
return false
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override public var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
}
| 38.580052 | 167 | 0.614736 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.