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
|
---|---|---|---|---|---|
9b641f0d8d884bbc049150e6bd7fce4902a9fa92 | 2,303 | //
// UITextFieldViewlet.swift
// Json inflator example
//
// Create a simple text input field
//
import UIKit
import JsonInflator
class UITextFieldViewlet: JsonInflatable {
func create() -> Any {
return UITextField()
}
func update(convUtil: InflatorConvUtil, object: Any, attributes: [String: Any], parent: Any?, binder: InflatorBinder?) -> Bool {
if let textField = object as? UITextField {
// Prefilled text and placeholder
textField.text = convUtil.asString(value: attributes["text"])
textField.placeholder = NSLocalizedString(convUtil.asString(value: attributes["placeholder"]) ?? "", comment: "")
// Set keyboard mode
textField.keyboardType = .default
textField.autocapitalizationType = .sentences
if let keyboardType = convUtil.asString(value: attributes["keyboardType"]) {
if keyboardType == "email" {
textField.keyboardType = .emailAddress
textField.autocapitalizationType = .none
} else if keyboardType == "url" {
textField.keyboardType = .URL
textField.autocapitalizationType = .none
}
}
// Text style
let fontSize = convUtil.asDimension(value: attributes["textSize"]) ?? 17
if let font = convUtil.asString(value: attributes["font"]) {
if font == "bold" {
textField.font = UIFont.boldSystemFont(ofSize: fontSize)
} else if font == "italics" {
textField.font = UIFont.italicSystemFont(ofSize: fontSize)
} else {
textField.font = UIFont(name: font, size: fontSize)
}
} else {
textField.font = UIFont.systemFont(ofSize: fontSize)
}
// Standard view attributes
UIViewViewlet.applyDefaultAttributes(convUtil: convUtil, view: textField, attributes: attributes)
return true
}
return false
}
func canRecycle(convUtil: InflatorConvUtil, object: Any, attributes: [String : Any]) -> Bool {
return object is UITextField
}
}
| 37.145161 | 132 | 0.567521 |
e56f5c08e82cc00013fb252615b0bd528a1da8e0 | 223 | //
// UILayoutGuide+Constrictable.swift
// Constrictor
//
// Created by Pedro Carrasco on 27/05/2018.
// Copyright © 2018 Pedro Carrasco. All rights reserved.
//
import UIKit
extension UILayoutGuide: Constrictable {}
| 18.583333 | 57 | 0.730942 |
3862497ac7270d89adce280a3371481c878baf49 | 1,801 | //
// SubscribeOn.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class SubscribeOnSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = SubscribeOn<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
observer?.on(event)
if event.isStopEvent {
self.dispose()
}
}
func run() -> Disposable {
let disposeEverything = SerialDisposable()
let cancelSchedule = SingleAssignmentDisposable()
disposeEverything.disposable = cancelSchedule
cancelSchedule.disposable = parent.scheduler.schedule(()) { (_) -> Disposable in
let subscription = self.parent.source.subscribeSafe(self)
disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription)
return NopDisposable.instance
}
return disposeEverything
}
}
class SubscribeOn<Element> : Producer<Element> {
let source: Observable<Element>
let scheduler: ImmediateSchedulerType
init(source: Observable<Element>, scheduler: ImmediateSchedulerType) {
self.source = source
self.scheduler = scheduler
}
override func run<O : ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | 30.016667 | 140 | 0.642976 |
4656d2120209d8e976468716bdafad45dbe179f0 | 315 | //
// Created by Tsimur Bernikovich on 2/15/19.
// Copyright © 2019 Tsimur Bernikovich. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| 19.6875 | 76 | 0.701587 |
defb8d5434084aef98e79a10b148425be8f274a7 | 32,628 | //
// SheetViewController.swift
// FittedSheetsPod
//
// Created by Gordon Tucker on 7/29/20.
// Copyright © 2020 Gordon Tucker. All rights reserved.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
public class SheetViewController: UIViewController {
public private(set) var options: SheetOptions
/// Default value for autoAdjustToKeyboard. Defaults to true.
public static var autoAdjustToKeyboard = true
/// Automatically grow/move the sheet to accomidate the keyboard. Defaults to false.
public var autoAdjustToKeyboard = SheetViewController.autoAdjustToKeyboard
/// Default value for allowPullingPastMaxHeight. Defaults to true.
public static var allowPullingPastMaxHeight = true
/// Allow pulling past the maximum height and bounce back. Defaults to true.
public var allowPullingPastMaxHeight = SheetViewController.allowPullingPastMaxHeight
/// Default value for allowPullingPastMinHeight. Defaults to true.
public static var allowPullingPastMinHeight = true
/// Allow pulling below the minimum height and bounce back. Defaults to true.
public var allowPullingPastMinHeight = SheetViewController.allowPullingPastMinHeight
/// The sizes that the sheet will attempt to pin to. Defaults to intrinsic only.
public var sizes: [SheetSize] = [.intrinsic] {
didSet {
self.updateOrderedSizes()
}
}
public var orderedSizes: [SheetSize] = []
public private(set) var currentSize: SheetSize = .intrinsic
/// Allows dismissing of the sheet by pulling down
public var dismissOnPull: Bool = true {
didSet {
self.updateAccessibility()
}
}
/// Dismisses the sheet by tapping on the background overlay
public var dismissOnOverlayTap: Bool = true {
didSet {
self.updateAccessibility()
}
}
/// If true you can pull using UIControls (so you can grab and drag a button to control the sheet)
public var shouldRecognizePanGestureWithUIControls: Bool = true
/// The view controller being presented by the sheet currently
public var childViewController: UIViewController {
return self.contentViewController.childViewController
}
public override var childForStatusBarStyle: UIViewController? {
childViewController
}
public static var hasBlurBackground = false
public var hasBlurBackground = SheetViewController.hasBlurBackground {
didSet {
blurView.isHidden = !hasBlurBackground
overlayView.backgroundColor = hasBlurBackground ? .clear : self.overlayColor
}
}
public static var minimumSpaceAbovePullBar: CGFloat = 0
public var minimumSpaceAbovePullBar: CGFloat {
didSet {
if self.isViewLoaded {
self.resize(to: self.currentSize)
}
}
}
/// The default color of the overlay background
public static var overlayColor = UIColor(white: 0, alpha: 0.25)
/// The color of the overlay background
public var overlayColor = SheetViewController.overlayColor {
didSet {
self.overlayView.backgroundColor = self.hasBlurBackground ? .clear : self.overlayColor
}
}
public static var blurEffect: UIBlurEffect = {
return UIBlurEffect(style: .prominent)
}()
public var blurEffect = SheetViewController.blurEffect {
didSet {
self.blurView.effect = blurEffect
}
}
public static var allowGestureThroughOverlay: Bool = false
public var allowGestureThroughOverlay: Bool = SheetViewController.allowGestureThroughOverlay {
didSet {
self.overlayTapView.isUserInteractionEnabled = !self.allowGestureThroughOverlay
}
}
public static var cornerRadius: CGFloat = 12
public var cornerRadius: CGFloat {
get { return self.contentViewController.cornerRadius }
set { self.contentViewController.cornerRadius = newValue }
}
public static var gripSize: CGSize = CGSize (width: 50, height: 6)
public var gripSize: CGSize {
get { return self.contentViewController.gripSize }
set { self.contentViewController.gripSize = newValue }
}
public static var gripColor: UIColor = UIColor(white: 0.868, black: 0.1)
public var gripColor: UIColor? {
get { return self.contentViewController.gripColor }
set { self.contentViewController.gripColor = newValue }
}
public static var pullBarBackgroundColor: UIColor = UIColor.clear
public var pullBarBackgroundColor: UIColor? {
get { return self.contentViewController.pullBarBackgroundColor }
set { self.contentViewController.pullBarBackgroundColor = newValue }
}
public static var treatPullBarAsClear: Bool = false
public var treatPullBarAsClear: Bool {
get { return self.contentViewController.treatPullBarAsClear }
set { self.contentViewController.treatPullBarAsClear = newValue }
}
let transition: SheetTransition
public var shouldDismiss: ((SheetViewController) -> Bool)?
public var didDismiss: ((SheetViewController) -> Void)?
public var sizeChanged: ((SheetViewController, SheetSize, CGFloat) -> Void)?
public private(set) var contentViewController: SheetContentViewController
var overlayView = UIView()
var blurView = UIVisualEffectView()
var overlayTapView = UIView()
var overflowView = UIView()
var overlayTapGesture: UITapGestureRecognizer?
private var contentViewHeightConstraint: NSLayoutConstraint!
/// The child view controller's scroll view we are watching so we can override the pull down/up to work on the sheet when needed
private weak var childScrollView: UIScrollView?
private var keyboardHeight: CGFloat = 0
private var firstPanPoint: CGPoint = CGPoint.zero
private var panOffset: CGFloat = 0
private var panGestureRecognizer: InitialTouchPanGestureRecognizer!
private var prePanHeight: CGFloat = 0
private var isPanning: Bool = false
public var contentBackgroundColor: UIColor? {
get { self.contentViewController.contentBackgroundColor }
set { self.contentViewController.contentBackgroundColor = newValue }
}
public init(controller: UIViewController, sizes: [SheetSize] = [.intrinsic], options: SheetOptions? = nil) {
let options = options ?? SheetOptions.default
self.contentViewController = SheetContentViewController(childViewController: controller, options: options)
if #available(iOS 13.0, *) {
self.contentViewController.contentBackgroundColor = UIColor.systemBackground
} else {
self.contentViewController.contentBackgroundColor = UIColor.white
}
self.sizes = sizes.count > 0 ? sizes : [.intrinsic]
self.options = options
self.transition = SheetTransition(options: options)
self.minimumSpaceAbovePullBar = SheetViewController.minimumSpaceAbovePullBar
super.init(nibName: nil, bundle: nil)
self.gripColor = SheetViewController.gripColor
self.gripSize = SheetViewController.gripSize
self.pullBarBackgroundColor = SheetViewController.pullBarBackgroundColor
self.cornerRadius = SheetViewController.cornerRadius
self.updateOrderedSizes()
self.modalPresentationStyle = .custom
self.transitioningDelegate = self
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func loadView() {
if self.options.useInlineMode {
let sheetView = SheetView()
sheetView.delegate = self
self.view = sheetView
} else {
super.loadView()
}
}
public override func viewDidLoad() {
super.viewDidLoad()
self.additionalSafeAreaInsets = UIEdgeInsets(top: -self.options.pullBarHeight, left: 0, bottom: 0, right: 0)
self.view.backgroundColor = UIColor.clear
self.addPanGestureRecognizer()
self.addOverlay()
self.addBlurBackground()
self.addContentView()
self.addOverlayTapView()
self.registerKeyboardObservers()
self.resize(to: self.sizes.first ?? .intrinsic, animated: false)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.updateOrderedSizes()
self.contentViewController.updatePreferredHeight()
self.resize(to: self.currentSize, animated: false)
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let presenter = self.transition.presenter, self.options.shrinkPresentingViewController {
self.transition.restorePresentor(presenter, completion: { _ in
self.didDismiss?(self)
})
} else if !self.options.useInlineMode {
self.didDismiss?(self)
}
}
/// Handle a scroll view in the child view controller by watching for the offset for the scrollview and taking priority when at the top (so pulling up/down can grow/shrink the sheet instead of bouncing the child's scroll view)
public func handleScrollView(_ scrollView: UIScrollView) {
scrollView.panGestureRecognizer.require(toFail: panGestureRecognizer)
self.childScrollView = scrollView
}
/// Change the sizes the sheet should try to pin to
public func setSizes(_ sizes: [SheetSize], animated: Bool = true) {
guard sizes.count > 0 else {
return
}
self.sizes = sizes
self.resize(to: sizes[0], animated: animated)
}
func updateOrderedSizes() {
var concreteSizes: [(SheetSize, CGFloat)] = self.sizes.map {
return ($0, self.height(for: $0))
}
concreteSizes.sort { $0.1 < $1.1 }
self.orderedSizes = concreteSizes.map({ size, _ in size })
self.updateAccessibility()
}
private func updateAccessibility() {
let isOverlayAccessable = !self.allowGestureThroughOverlay && (self.dismissOnOverlayTap || self.dismissOnPull)
self.overlayTapView.isAccessibilityElement = isOverlayAccessable
var pullBarLabel = ""
if !isOverlayAccessable && (self.dismissOnOverlayTap || self.dismissOnPull) {
pullBarLabel = Localize.dismissPresentation.localized
} else if self.orderedSizes.count > 1 {
pullBarLabel = Localize.changeSizeOfPresentation.localized
}
self.contentViewController.pullBarView.isAccessibilityElement = !pullBarLabel.isEmpty
self.contentViewController.pullBarView.accessibilityLabel = pullBarLabel
}
private func addOverlay() {
self.view.addSubview(self.overlayView)
Constraints(for: self.overlayView) {
$0.edges(.top, .left, .right, .bottom).pinToSuperview()
}
self.overlayView.isUserInteractionEnabled = false
self.overlayView.backgroundColor = self.hasBlurBackground ? .clear : self.overlayColor
}
private func addBlurBackground() {
self.overlayView.addSubview(self.blurView)
blurView.effect = blurEffect
Constraints(for: self.blurView) {
$0.edges(.top, .left, .right, .bottom).pinToSuperview()
}
self.blurView.isUserInteractionEnabled = false
self.blurView.isHidden = !self.hasBlurBackground
}
private func addOverlayTapView() {
let overlayTapView = self.overlayTapView
overlayTapView.backgroundColor = .clear
overlayTapView.isUserInteractionEnabled = !self.allowGestureThroughOverlay
self.view.addSubview(overlayTapView)
self.overlayTapView.accessibilityLabel = Localize.dismissPresentation.localized
Constraints(for: overlayTapView, self.contentViewController.view) {
$0.top.pinToSuperview()
$0.left.pinToSuperview()
$0.right.pinToSuperview()
$0.bottom.align(with: $1.top)
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(overlayTapped))
self.overlayTapGesture = tapGestureRecognizer
overlayTapView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func overlayTapped(_ gesture: UITapGestureRecognizer) {
guard self.dismissOnOverlayTap else { return }
self.attemptDismiss(animated: true)
}
private func addContentView() {
self.contentViewController.willMove(toParent: self)
self.addChild(self.contentViewController)
self.view.addSubview(self.contentViewController.view)
self.contentViewController.didMove(toParent: self)
self.contentViewController.delegate = self
Constraints(for: self.contentViewController.view) {
$0.left.pinToSuperview().priority = UILayoutPriority(999)
$0.left.pinToSuperview(inset: self.options.horizontalPadding, relation: .greaterThanOrEqual)
if let maxWidth = self.options.maxWidth {
$0.width.set(maxWidth, relation: .lessThanOrEqual)
}
$0.centerX.alignWithSuperview()
self.contentViewHeightConstraint = $0.height.set(self.height(for: self.currentSize))
let top: CGFloat
if (self.options.useFullScreenMode) {
top = 0
} else {
top = max(12, UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.safeAreaInsets.top ?? 12)
}
$0.bottom.pinToSuperview()
$0.top.pinToSuperview(inset: top, relation: .greaterThanOrEqual).priority = UILayoutPriority(999)
}
}
private func addPanGestureRecognizer() {
let panGestureRecognizer = InitialTouchPanGestureRecognizer(target: self, action: #selector(panned(_:)))
self.view.addGestureRecognizer(panGestureRecognizer)
panGestureRecognizer.delegate = self
self.panGestureRecognizer = panGestureRecognizer
}
@objc func panned(_ gesture: UIPanGestureRecognizer) {
let point = gesture.translation(in: gesture.view?.superview)
if gesture.state == .began {
self.firstPanPoint = point
self.prePanHeight = self.contentViewController.view.bounds.height
self.isPanning = true
}
let minHeight: CGFloat = self.height(for: self.orderedSizes.first)
let maxHeight: CGFloat
if self.allowPullingPastMaxHeight {
maxHeight = self.height(for: .fullscreen) // self.view.bounds.height
} else {
maxHeight = max(self.height(for: self.orderedSizes.last), self.prePanHeight)
}
var newHeight = max(0, self.prePanHeight + (self.firstPanPoint.y - point.y))
var offset: CGFloat = 0
if newHeight < minHeight {
if self.allowPullingPastMinHeight {
offset = minHeight - newHeight
}
newHeight = minHeight
}
if newHeight > maxHeight {
newHeight = maxHeight
}
switch gesture.state {
case .cancelled, .failed:
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseOut], animations: {
self.contentViewController.view.transform = CGAffineTransform.identity
self.contentViewHeightConstraint.constant = self.height(for: self.currentSize)
self.transition.setPresentor(percentComplete: 0)
self.overlayView.alpha = 1
}, completion: { _ in
self.isPanning = false
})
case .began, .changed:
self.contentViewHeightConstraint.constant = newHeight
if offset > 0 {
let percent = max(0, min(1, offset / max(1, newHeight)))
self.transition.setPresentor(percentComplete: percent)
self.overlayView.alpha = 1 - percent
self.contentViewController.view.transform = CGAffineTransform(translationX: 0, y: offset)
} else {
self.contentViewController.view.transform = CGAffineTransform.identity
}
case .ended:
let velocity = (0.2 * gesture.velocity(in: self.view).y)
var finalHeight = newHeight - offset - velocity
if velocity > 400 || finalHeight < minHeight / 2 {
// They swiped hard, always just close the sheet when they do
finalHeight = -1
}
let animationDuration = TimeInterval(abs(velocity*0.0002) + 0.2)
guard finalHeight > 0 || !self.dismissOnPull else {
// Dismiss
self.attemptDismiss(animated: true)
// UIView.animate(
// withDuration: animationDuration,
// delay: 0,
// usingSpringWithDamping: self.options.transitionDampening,
// initialSpringVelocity: self.options.transitionVelocity,
// options: self.options.transitionAnimationOptions,
// animations: {
// self.contentViewController.view.transform = CGAffineTransform(translationX: 0, y: self.contentViewController.view.bounds.height)
// self.view.backgroundColor = UIColor.clear
// self.transition.setPresentor(percentComplete: 1)
// self.overlayView.alpha = 0
// }, completion: { complete in
// self.attemptDismiss(animated: false)
// })
return
}
var newSize = self.currentSize
if point.y < 0 {
// We need to move to the next larger one
newSize = self.orderedSizes.last ?? self.currentSize
for size in self.orderedSizes.reversed() {
if finalHeight < self.height(for: size) {
newSize = size
} else {
break
}
}
} else {
// We need to move to the next smaller one
newSize = self.orderedSizes.first ?? self.currentSize
for size in self.orderedSizes {
if finalHeight > self.height(for: size) {
newSize = size
} else {
break
}
}
}
let previousSize = self.currentSize
self.currentSize = newSize
let newContentHeight = self.height(for: newSize)
UIView.animate(
withDuration: animationDuration,
delay: 0,
usingSpringWithDamping: self.options.transitionDampening,
initialSpringVelocity: self.options.transitionVelocity,
options: self.options.transitionAnimationOptions,
animations: {
self.contentViewController.view.transform = CGAffineTransform.identity
self.contentViewHeightConstraint.constant = newContentHeight
self.transition.setPresentor(percentComplete: 0)
self.overlayView.alpha = 1
self.view.layoutIfNeeded()
}, completion: { complete in
self.isPanning = false
if previousSize != newSize {
self.sizeChanged?(self, newSize, newContentHeight)
}
})
case .possible:
break
@unknown default:
break // Do nothing
}
}
private func registerKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShown(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDismissed(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardShown(_ notification: Notification) {
guard let info:[AnyHashable: Any] = notification.userInfo, let keyboardRect:CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
let windowRect = self.view.convert(self.view.bounds, to: nil)
let actualHeight = windowRect.maxY - keyboardRect.origin.y
self.adjustForKeyboard(height: actualHeight, from: notification)
}
@objc func keyboardDismissed(_ notification: Notification) {
self.adjustForKeyboard(height: 0, from: notification)
}
private func adjustForKeyboard(height: CGFloat, from notification: Notification) {
guard self.autoAdjustToKeyboard, let info:[AnyHashable: Any] = notification.userInfo else { return }
self.keyboardHeight = height
let duration:TimeInterval = (info[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
self.contentViewController.adjustForKeyboard(height: self.keyboardHeight)
self.resize(to: self.currentSize, duration: duration, options: animationCurve, animated: true, complete: {
self.resize(to: self.currentSize)
})
}
private func height(for size: SheetSize?) -> CGFloat {
guard let size = size else { return 0 }
let contentHeight: CGFloat
let fullscreenHeight: CGFloat
if self.options.useFullScreenMode {
fullscreenHeight = self.view.bounds.height - self.minimumSpaceAbovePullBar
} else {
fullscreenHeight = self.view.bounds.height - self.view.safeAreaInsets.top - self.minimumSpaceAbovePullBar
}
switch (size) {
case .fixed(let height):
contentHeight = height + self.keyboardHeight
case .fullscreen:
contentHeight = fullscreenHeight
case .intrinsic:
contentHeight = self.contentViewController.preferredHeight + self.keyboardHeight
case .percent(let percent):
contentHeight = (self.view.bounds.height) * CGFloat(percent) + self.keyboardHeight
case .marginFromTop(let margin):
contentHeight = (self.view.bounds.height) - margin + self.keyboardHeight
}
return min(fullscreenHeight, contentHeight)
}
public func resize(to size: SheetSize,
duration: TimeInterval = 0.2,
options: UIView.AnimationOptions = [.curveEaseOut],
animated: Bool = true,
complete: (() -> Void)? = nil) {
let previousSize = self.currentSize
self.currentSize = size
let oldConstraintHeight = self.contentViewHeightConstraint.constant
let newHeight = self.height(for: size)
guard oldConstraintHeight != newHeight else {
return
}
if animated {
UIView.animate(withDuration: duration, delay: 0, options: options, animations: { [weak self] in
guard let self = self, let constraint = self.contentViewHeightConstraint else { return }
constraint.constant = newHeight
self.view.layoutIfNeeded()
}, completion: { _ in
if previousSize != size {
self.sizeChanged?(self, size, newHeight)
}
self.contentViewController.updateAfterLayout()
complete?()
})
} else {
UIView.performWithoutAnimation {
self.contentViewHeightConstraint?.constant = self.height(for: size)
self.contentViewController.view.layoutIfNeeded()
}
complete?()
}
}
public func attemptDismiss(animated: Bool) {
if self.shouldDismiss?(self) != false {
if self.options.useInlineMode {
if animated {
self.animateOut {
self.didDismiss?(self)
}
} else {
self.view.removeFromSuperview()
self.removeFromParent()
self.didDismiss?(self)
}
} else {
self.dismiss(animated: animated, completion: nil)
}
}
}
/// Recalculates the intrinsic height of the sheet based on the content, and updates the sheet height to match.
///
/// **Note:** Only meant for use with `.intrinsic` sheet size
public func updateIntrinsicHeight() {
contentViewController.updatePreferredHeight()
}
/// Animates the sheet in, but only if presenting using the inline mode
public func animateIn(to view: UIView, in parent: UIViewController, size: SheetSize? = nil, duration: TimeInterval = 0.3, completion: (() -> Void)? = nil) {
self.willMove(toParent: parent)
parent.addChild(self)
view.addSubview(self.view)
self.didMove(toParent: parent)
self.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.view.topAnchor.constraint(equalTo: view.topAnchor),
self.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
self.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
self.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
self.animateIn(size: size, duration: duration, completion: completion)
}
public func animateIn(size: SheetSize? = nil, duration: TimeInterval = 0.3, completion: (() -> Void)? = nil) {
guard self.options.useInlineMode else { return }
guard self.view.superview != nil else {
print("It appears your sheet is not set as a subview of another view. Make sure to add this view as a subview before trying to animate it in.")
return
}
self.view.superview?.layoutIfNeeded()
self.contentViewController.updatePreferredHeight()
self.resize(to: size ?? self.sizes.first ?? self.currentSize, animated: false)
let contentView = self.contentViewController.view!
contentView.transform = CGAffineTransform(translationX: 0, y: contentView.bounds.height)
self.overlayView.alpha = 0
self.updateOrderedSizes()
UIView.animate(
withDuration: duration,
animations: {
contentView.transform = .identity
self.overlayView.alpha = 1
},
completion: { _ in
completion?()
}
)
}
/// Animates the sheet out, but only if presenting using the inline mode
public func animateOut(duration: TimeInterval = 0.3, completion: (() -> Void)? = nil) {
guard self.options.useInlineMode else { return }
let contentView = self.contentViewController.view!
UIView.animate(
withDuration: duration,
delay: 0,
usingSpringWithDamping: self.options.transitionDampening,
initialSpringVelocity: self.options.transitionVelocity,
options: self.options.transitionAnimationOptions,
animations: {
contentView.transform = CGAffineTransform(translationX: 0, y: contentView.bounds.height)
self.overlayView.alpha = 0
},
completion: { _ in
self.view.removeFromSuperview()
self.removeFromParent()
completion?()
}
)
}
}
extension SheetViewController: SheetViewDelegate {
func sheetPoint(inside point: CGPoint, with event: UIEvent?) -> Bool {
let isInOverlay = self.overlayTapView.bounds.contains(point)
if self.allowGestureThroughOverlay, isInOverlay {
return false
} else {
return true
}
}
}
extension SheetViewController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Allowing gesture recognition on a UIControl seems to prevent its events from firing properly sometimes
if !shouldRecognizePanGestureWithUIControls {
if let view = touch.view {
return !(view is UIControl)
}
}
return true
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let panGestureRecognizer = gestureRecognizer as? InitialTouchPanGestureRecognizer, let childScrollView = self.childScrollView, let point = panGestureRecognizer.initialTouchLocation else { return true }
let pointInChildScrollView = self.view.convert(point, to: childScrollView).y - childScrollView.contentOffset.y
let velocity = panGestureRecognizer.velocity(in: panGestureRecognizer.view?.superview)
guard pointInChildScrollView > 0, pointInChildScrollView < childScrollView.bounds.height else {
if keyboardHeight > 0 {
childScrollView.endEditing(true)
}
return true
}
let topInset = childScrollView.contentInset.top
guard abs(velocity.y) > abs(velocity.x), childScrollView.contentOffset.y <= -topInset else { return false }
if velocity.y < 0 {
let containerHeight = height(for: self.currentSize)
return height(for: self.orderedSizes.last) > containerHeight && containerHeight < height(for: SheetSize.fullscreen)
} else {
return true
}
}
}
extension SheetViewController: SheetContentViewDelegate {
func pullBarTapped() {
// Tapping the pull bar is just for accessibility
guard UIAccessibility.isVoiceOverRunning else { return }
let shouldDismiss = self.allowGestureThroughOverlay && (self.dismissOnOverlayTap || self.dismissOnPull)
guard !shouldDismiss else {
self.attemptDismiss(animated: true)
return
}
if self.sizes.count > 1 {
let index = (self.sizes.firstIndex(of: self.currentSize) ?? 0) + 1
if index >= self.sizes.count {
self.resize(to: self.sizes[0])
} else {
self.resize(to: self.sizes[index])
}
}
}
func preferredHeightChanged(oldHeight: CGFloat, newSize: CGFloat) {
if self.sizes.contains(.intrinsic) {
self.updateOrderedSizes()
}
// If our intrinsic size changed and that is what we are sized to currently, use that
if self.currentSize == .intrinsic, !self.isPanning {
self.resize(to: .intrinsic)
}
}
}
extension SheetViewController: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.presenting = true
return transition
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.presenting = false
return transition
}
}
#endif // os(iOS) || os(tvOS) || os(watchOS)
| 42.875164 | 230 | 0.625843 |
ed5d880b5ba45258a2b294935b424f553b9ed571 | 275 | //
// Message.swift
// Messages
//
// Created by Văn Tiến Tú on 8/23/19.
// Copyright © 2019 Văn Tiến Tú. All rights reserved.
//
import UIKit
class Message: NSObject {
var content: String?
init(_ content: String?) {
self.content = content
}
}
| 15.277778 | 54 | 0.607273 |
f784a0f0e36680fa1fffc2b372ad081c7d3121d6 | 1,766 | // Copyright 2022 Pera Wallet, LDA
// 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.
//
// AccountNameSetupViewTheme.swift
import Foundation
import MacaroonUIKit
import UIKit
struct AccountNameSetupViewTheme: StyleSheet, LayoutSheet {
let title: TextStyle
let description: TextStyle
let mainButtonTheme: ButtonTheme
let textInputVerticalInset: LayoutMetric
let horizontalInset: LayoutMetric
let bottomInset: LayoutMetric
let topInset: LayoutMetric
init(_ family: LayoutFamily) {
self.title = [
.textAlignment(.left),
.textOverflow(FittingText()),
.textColor(AppColors.Components.Text.main),
.font(Fonts.DMSans.medium.make(32)),
.text("account-details-title".localized)
]
self.description = [
.textColor(AppColors.Components.Text.gray),
.font(Fonts.DMSans.regular.make(15)),
.textAlignment(.left),
.textOverflow(FittingText()),
.text("account-name-setup-description".localized)
]
self.mainButtonTheme = ButtonPrimaryTheme()
self.textInputVerticalInset = 40
self.horizontalInset = 24
self.bottomInset = 16
self.topInset = 2
}
}
| 30.448276 | 75 | 0.677803 |
1a7f2df081870467cb7a51097055f4ba295df0fc | 1,826 | /// Copyright (c) 2018 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import UIKit
extension UIColor {
class func rwGreen() -> UIColor {
return UIColor(red: 43.0/255.0, green: 138.0/255.0, blue: 100.0/255.0, alpha: 1.0)
}
}
| 49.351351 | 86 | 0.747536 |
d67c0338984e76239c0d011727501b7ea47ac023 | 8,673 | import UIKit
// MARK: - 尾随闭包
func comparison(closure: () -> Void) {
}
let strList = ["1","2","3","4","5"]
let numList: [Int] = strList.map { (num) in
return Int(num) ?? 0
}
// MARK: - 逃逸闭包
func requestServer(with URL: String,parameter: @escaping(AnyObject?, Error?) -> Void) {
}
// 尾随闭包
func requestServerTrailing(losure: () -> Void) {
}
class EscapingTest {
var x = 10
func request() {
// 尾随闭包
requestServerTrailing {
x = x + 1
}
// 逃逸闭包
requestServer(with: "") { [weak self] (obj, error) in
guard let self = `self` else {
return
}
self.x = self.x + 1
}
}
}
// MARK: - 图片下载管理类
struct DownLoadImageManager {
// 单例方法
static let sharedInstance = DownLoadImageManager()
let queue = DispatchQueue(label: "com.tsn.demo.escapingClosure", attributes: .concurrent)
// 逃逸闭包
// path: 图片的URL
func downLoadImageWithEscapingClosure(path: String, completionHandler: @escaping(UIImage?, Error?) -> Void) {
queue.async {
URLSession.shared.dataTask(with: URL(string: path)!) { (data, response, error) in
if let error = error {
print("error===============\(error)")
DispatchQueue.main.async {
completionHandler(nil, error)
}
} else {
guard let responseData = data, let image = UIImage(data: responseData) else {
return
}
DispatchQueue.main.async {
completionHandler(image, nil)
}
}
}.resume()
}
}
// 保证init方法在外部不会被调用
private init() {
}
}
let path = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F12056372662%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1618456758&t=3df7a5cf69ad424954badda9bc7fc55f"
DownLoadImageManager.sharedInstance.downLoadImageWithEscapingClosure(path: path) { (image: UIImage?, error: Error?) in
if let error = error {
print("error===============\(error)")
} else {
guard let image = image else { return }
print("图片下载完成,显示图片: \(image)")
let imageView = UIImageView(image: image)
imageView.layer.cornerRadius = 5
}
}
enum Course {
case spacePhysics // 空间物理
case nuclearPhysics // 原子核物理
case calculus // 微积分
case quantumMechanics // 量子力学
case geology // 地质学
}
struct StudentModel {
var name: String = String()
var course: Course!
init(name: String, course: Course) {
self.name = name
self.course = course
}
}
// MARK: - 自动闭包
class StudentManager {
var studentInfoArray: [StudentModel] = [StudentModel]()
func autoAddWith(_ student: @autoclosure @escaping() -> StudentModel) {
studentInfoArray.append(student())
}
func autoDeleteWith(_ index: @autoclosure() -> Int) {
studentInfoArray.remove(at: index())
}
}
class HomeWork: NSObject {
let studentManager: StudentManager = StudentManager()
override init() {
super.init()
// John Appleseed 交了作业
studentManager.autoAddWith(StudentModel(name: "John Appleseed", course: .spacePhysics))
print("====================\(studentManager.studentInfoArray.count)")
// Kate Bell 交了作业
studentManager.autoAddWith(StudentModel(name: "Kate Bell", course: .nuclearPhysics))
print("====================\(studentManager.studentInfoArray.count)")
// Anna Haro 交了作业
studentManager.autoAddWith(StudentModel(name: "Anna Haro", course: .calculus))
print("====================\(studentManager.studentInfoArray.count)")
// Daniel Higgins Jr. 交了作业
studentManager.autoAddWith(StudentModel(name: "Daniel Higgins Jr.", course: .quantumMechanics))
print("====================\(studentManager.studentInfoArray.count)")
// David taylor 交了作业
studentManager.autoAddWith(StudentModel(name: "David taylor", course: .geology))
print("====================\(studentManager.studentInfoArray.count)")
// Hand M. Zakroff 交了作业
studentManager.autoAddWith(StudentModel(name: "Hand M. Zakroff", course: .spacePhysics))
print("====================\(studentManager.studentInfoArray.count)")
studentManager.autoDeleteWith(0)
print("====================\(studentManager.studentInfoArray.count)")
}
}
StudentManager()
// MARK: - 自动闭包 + 逃逸闭包
func autoAndEscaping(_ name: @autoclosure @escaping() -> String) {
}
autoAndEscaping("")
// MARK: - inout
func configStudent(_ fraction: inout Int) -> Int {
return fraction + 30
}
var num = 53
configStudent(&num)
var testArray = [1,2,3,4,5,6]
testArray[1] = configStudent(&testArray[1])
print("\(testArray)")
struct Location {
var lat: Double
var lon: Double
var fraction: Int {
return 30
}
}
func configLocation(_ num: inout Double) -> String {
return "\(num + 1)"
}
func configFraction(_ fraction: inout Int) -> Int {
return fraction + 30
}
var location = Location(lat: 37.33020, lon: -122.024348)
configLocation(&location.lat)
configLocation(&location.lon)
// MARK: - closures捕获值
class Demo: NSObject {
var test = String()
}
// 常量
var index = 10086
// 变量
var number = 1008611
// 引用类型
let demo = Demo()
var capturel = {
index = 10086 + 998525
number = 1008611 - 998525
demo.test = "block test"
print("index==========\(index)")
print("number==========\(number)")
print("demo.test==========\(demo.test)")
}
number = number + 1
demo.test = "test"
capturel()
func makeIncrementer(_ amount: Int) -> () -> Int {
var total = 0
// 闭包
func incrementer() -> Int {
total = total + amount
return total
}
return incrementer
}
let incrementerTen = makeIncrementer(10)
incrementerTen()
incrementerTen()
incrementerTen()
let incrementerSix = makeIncrementer(6)
incrementerSix()
incrementerSix()
incrementerTen()
let alsoIncrementerTen = incrementerTen
alsoIncrementerTen()
// MARK: - Closure循环引用
enum Answer {
case A
case B
case C
case D
}
extension Optional {
func withExtendedLifetime(_ body: (Wrapped) -> Void) {
guard let value = self else { return }
body(value)
}
}
class Student: CustomStringConvertible {
var name: String = String()
lazy var replyClosure: (Answer) -> Void = { [weak self] _ in
guard let value = self else { return }
print("replyClosure self=============\(self)")
}
init(name: String) {
self.name = name
print("==========Student init==========\(name)")
replyClosure(.B)
}
func doHomeWork() {
// 全局队列
let queue = DispatchQueue.global()
queue.async { [weak self] in
self.withExtendedLifetime { _ in
print("\(self?.name):开始写作业")
sleep(2)
print("\(self?.name):完成作业")
}
}
}
deinit {
print("==========Student deinit==========\(self.name)")
}
}
extension Student {
var description: String {
return "<Student: \(name)>"
}
}
class Teacher {
var isRight: Bool = false
init() {
print("==========Teacher init==========")
var student = Student(name: "Kate Bell")
let judgeClosure = { [unowned student] (answer: Answer) in
print("student===========\(student)")
}
student.replyClosure = judgeClosure
student = Student(name: "Tom")
student.replyClosure(.C)
}
deinit {
print("==========Teacher deinit==========")
}
}
Teacher()
//Student(name: "Kate Bell").replyClosure(.B)
Student(name: "Kate Bell").doHomeWork()
//class Role {
// var name: String
// lazy var action: () -> Void = {
// print("\(self) takes action.")
// }
//
// init(_ name: String = "Foo") {
// self.name = name
// print("\(self) init")
// }
//
// deinit {
// print("\(self) deinit")
// }
//}
//
//extension Role: CustomStringConvertible {
// var description: String {
// return "<Role: \(name)>"
// }
//}
//if true {
// var boss = Role("boss")
// let fn = { [unowned boss] in
// print("\(boss) takes action.")
// }
// boss.action = fn
//
// boss = Role("hidden boss")
// boss.action()
//}
| 24.709402 | 259 | 0.564395 |
673a832a0e909e774bd6f2532f8b269ecd246674 | 1,013 | //
// FlowGridBlock.swift
// SwiftUIHub
//
// Created by Yu Fan on 2019/6/28.
// Copyright © 2019 Yu Fan. All rights reserved.
//
import SwiftUI
struct FlowGridBlock : View {
var body: some View {
FlowStack(direction: .vertical, numPerRow: 2, numOfItems: 59, alignment: .leading, showIndicator: false) { (index, width) in
FlowBlockItem()
.padding()
.frame(width: width, height: width)
}
}
}
struct FlowBlockItem : View {
var body: some View {
HStack {
Rectangle()
.frame(width: 50)
.foregroundColor(.blue)
VStack {
Rectangle()
.foregroundColor(Color.pink)
Rectangle()
.foregroundColor(Color.orange)
}
}
}
}
#if DEBUG
struct FlowGridBlock_Previews : PreviewProvider {
static var previews: some View {
FlowGridBlock()
}
}
#endif
| 22.021739 | 132 | 0.521224 |
e5d8b1cf7339e0da42b098bc3b8b920c4a20b759 | 7,855 | //
// DataSourceSelectionHandler.swift
// GenericDataSource
//
// Created by Mohamed Afifi on 2/14/16.
// Copyright © 2016 mohamede1945. All rights reserved.
//
import Foundation
/**
Represents the selection handler when a selection changes it handle it.
It's mainly used with `BasicDataSource`. It also can work with `BasicDataSource` nested inside multiple `CompositeDataSource`. You can have one handler for each data source.
*/
public protocol DataSourceSelectionHandler {
/**
Represents the item type
*/
associatedtype ItemType
/**
Represents the cell type
*/
associatedtype CellType: ReusableCell
/**
Called when the items of the data source are modified inserted/delete/updated.
*/
func dataSourceItemsModified(_ dataSource: BasicDataSource<ItemType, CellType>)
/**
Called when the cell needs to be configured.
- parameter dataSource: The data source that handle the event.
- parameter collectionView: The collection view that is used for the dequeuing operation.
- parameter cell: The cell under configuration.
- parameter item: The item that will be binded to the cell.
- parameter indexPath: The local index path of the cell that will be configured.
*/
func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
configure cell: CellType,
with item: ItemType,
at indexPath: IndexPath)
// MARK: - Highlighting
/**
Called to see if the cell can be highlighted.
- parameter dataSource: The data source that handle the event.
- parameter collectionView: The collection view that is used for the dequeuing operation.
- parameter indexPath: The local index path of the cell that will be configured.
- returns: `true`, if can be highlighted.
*/
func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
shouldHighlightItemAt indexPath: IndexPath) -> Bool
/**
Called when the cell is already highlighted.
- parameter dataSource: The data source that handle the event.
- parameter collectionView: The collection view that is used for the dequeuing operation.
- parameter indexPath: The local index path of the cell that will be configured.
*/
func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
didHighlightItemAt indexPath: IndexPath)
/**
Called after the cell is unhighlighted.
- parameter dataSource: The data source that handle the event.
- parameter collectionView: The collection view that is used for the dequeuing operation.
- parameter indexPath: The local index path of the cell that will be configured.
*/
func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
didUnhighlightItemAt indexPath: IndexPath)
// MARK: - Selecting
/**
Whether or not to select a cell.
- parameter dataSource: The data source that handle the event.
- parameter collectionView: The collection view that is used for the dequeuing operation.
- parameter indexPath: The local index path of the cell that will be configured.
- returns: `true`, if should select the item.
*/
func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
shouldSelectItemAt indexPath: IndexPath) -> Bool
/**
Called when the select is selected.
- parameter dataSource: The data source that handle the event.
- parameter collectionView: The collection view that is used for the dequeuing operation.
- parameter indexPath: The local index path of the cell that will be configured.
*/
func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
didSelectItemAt indexPath: IndexPath)
// MARK: - Deselecting
/**
Should the cell be delselected or not.
- parameter dataSource: The data source that handle the event.
- parameter collectionView: The collection view that is used for the dequeuing operation.
- parameter indexPath: The local index path of the cell that will be configured.
- returns: `true`, if the cell should be deleselected.
*/
func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
shouldDeselectItemAt indexPath: IndexPath) -> Bool
/**
The cell is already deselected.
- parameter dataSource: The data source that handle the event.
- parameter collectionView: The collection view that is used for the dequeuing operation.
- parameter indexPath: The local index path of the cell that will be configured.
*/
func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
didDeselectItemAt indexPath: IndexPath)
}
// MARK: - Default implementation
extension DataSourceSelectionHandler {
/**
Default implementation. Does nothing.
*/
public func dataSourceItemsModified(_ dataSource: BasicDataSource<ItemType, CellType>) {
}
/**
Default implementation. Does nothing.
*/
public func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
configure cell: CellType,
with item: ItemType,
at indexPath: IndexPath) {
}
// MARK: - Highlighting
/**
Default implementation. Returns `true`.
*/
public func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
/**
Default implementation. Does nothing.
*/
public func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
didHighlightItemAt indexPath: IndexPath) {
// does nothing
}
/**
Default implementation. Does nothing.
*/
public func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
didUnhighlightItemAt indexPath: IndexPath) {
// does nothing
}
// MARK: - Selecting
/**
Default implementation. Returns `true`.
*/
public func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
/**
Default implementation. Does nothing.
*/
public func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
didSelectItemAt indexPath: IndexPath) {
// does nothing
}
// MARK: - Deselecting
/**
Default implementation. Returns `true`.
*/
public func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
shouldDeselectItemAt indexPath: IndexPath) -> Bool {
return true
}
/**
Default implementation. Does nothing.
*/
public func dataSource(
_ dataSource: BasicDataSource<ItemType, CellType>,
collectionView: GeneralCollectionView,
didDeselectItemAt indexPath: IndexPath) {
// does nothing
}
}
| 32.593361 | 174 | 0.672693 |
3aa367a5ef58c233bd6e32908d1cef3a50d23c12 | 1,369 | //
// Created by Dani Postigo on 9/30/16.
//
import Foundation
import UIKit
public class CustomNavigationBar: UINavigationBar {
public var customHeight: CGFloat = 44 {
didSet {
self.invalidateIntrinsicContentSize()
Swift.print("self.customHeight = \(self.customHeight)")
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func intrinsicContentSize() -> CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: self.customHeight)
}
// override class func requiresConstraintBasedLayout() -> Bool {
// return super.requiresConstraintBasedLayout()
// }
override public func sizeThatFits(size: CGSize) -> CGSize {
return CGSize(width: super.sizeThatFits(size).width, height: self.intrinsicContentSize().height)
}
}
extension UINavigationController {
public convenience init(rootViewController: UIViewController, navigationBarClass: AnyClass?) {
self.init(navigationBarClass: navigationBarClass, toolbarClass: nil)
self.setViewControllers([rootViewController], animated: false)
}
public var customNavigationBar: CustomNavigationBar? { return self.navigationBar as? CustomNavigationBar }
}
| 27.38 | 110 | 0.697589 |
e6bfd49386849d26934220c2b7f44dba02318cd5 | 30,731 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== TaskGroup --------------------------------------------------------------
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension Task {
@available(*, deprecated, message: "`Task.Group` was replaced by `ThrowingTaskGroup` and `TaskGroup` and will be removed shortly.")
public typealias Group<TaskResult: Sendable> = ThrowingTaskGroup<TaskResult, Error>
@available(*, deprecated, message: "`Task.withGroup` was replaced by `withThrowingTaskGroup` and `withTaskGroup` and will be removed shortly.")
public static func withGroup<TaskResult, BodyResult>(
resultType: TaskResult.Type,
returning returnType: BodyResult.Type = BodyResult.self,
body: (inout Task.Group<TaskResult>) async throws -> BodyResult
) async rethrows -> BodyResult {
try await withThrowingTaskGroup(of: resultType) { group in
try await body(&group)
}
}
}
/// Starts a new task group which provides a scope in which a dynamic number of
/// tasks may be spawned.
///
/// Tasks added to the group by `group.spawn()` will automatically be awaited on
/// when the scope exits. If the group exits by throwing, all added tasks will
/// be cancelled and their results discarded.
///
/// ### Implicit awaiting
/// When the group returns it will implicitly await for all spawned tasks to
/// complete. The tasks are only cancelled if `cancelAll()` was invoked before
/// returning, the groups' task was cancelled, or the group body has thrown.
///
/// When results of tasks added to the group need to be collected, one can
/// gather their results using the following pattern:
///
/// while let result = await group.next() {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// It is also possible to collect results from the group by using its
/// `AsyncSequence` conformance, which enables its use in an asynchronous for-loop,
/// like this:
///
/// for await result in group {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// ### Cancellation
/// If the task that the group is running in is cancelled, the group becomes
/// cancelled and all child tasks spawned in the group are cancelled as well.
///
/// Since the `withTaskGroup` provided group is specifically non-throwing,
/// child tasks (or the group) cannot react to cancellation by throwing a
/// `CancellationError`, however they may interrupt their work and e.g. return
/// some best-effort approximation of their work.
///
/// If throwing is a good option for the kinds of tasks spawned by the group,
/// consider using the `withThrowingTaskGroup` function instead.
///
/// Postcondition:
/// Once `withTaskGroup` returns it is guaranteed that the `group` is *empty*.
///
/// This is achieved in the following way:
/// - if the body returns normally:
/// - the group will await any not yet complete tasks,
/// - once the `withTaskGroup` returns the group is guaranteed to be empty.
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@inlinable
public func withTaskGroup<ChildTaskResult: Sendable, GroupResult>(
of childTaskResultType: ChildTaskResult.Type,
returning returnType: GroupResult.Type = GroupResult.self,
body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult
) async -> GroupResult {
#if compiler(>=5.5) && $BuiltinTaskGroup
let _group = Builtin.createTaskGroup()
var group = TaskGroup<ChildTaskResult>(group: _group)
// Run the withTaskGroup body.
let result = await body(&group)
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
return result
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
}
/// Starts a new throwing task group which provides a scope in which a dynamic
/// number of tasks may be spawned.
///
/// Tasks added to the group by `group.spawn()` will automatically be awaited on
/// when the scope exits. If the group exits by throwing, all added tasks will
/// be cancelled and their results discarded.
///
/// ### Implicit awaiting
/// When the group returns it will implicitly await for all spawned tasks to
/// complete. The tasks are only cancelled if `cancelAll()` was invoked before
/// returning, the groups' task was cancelled, or the group body has thrown.
///
/// When results of tasks added to the group need to be collected, one can
/// gather their results using the following pattern:
///
/// while let result = await try group.next() {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// It is also possible to collect results from the group by using its
/// `AsyncSequence` conformance, which enables its use in an asynchronous for-loop,
/// like this:
///
/// for try await result in group {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// ### Thrown errors
/// When tasks are added to the group using the `group.spawn` function, they may
/// immediately begin executing. Even if their results are not collected explicitly
/// and such task throws, and was not yet cancelled, it may result in the `withTaskGroup`
/// throwing.
///
/// ### Cancellation
/// If the task that the group is running in is cancelled, the group becomes
/// cancelled and all child tasks spawned in the group are cancelled as well.
///
/// If an error is thrown out of the task group, all of its remaining tasks
/// will be cancelled and the `withTaskGroup` call will rethrow that error.
///
/// Individual tasks throwing results in their corresponding `try group.next()`
/// call throwing, giving a chance to handle individual errors or letting the
/// error be rethrown by the group.
///
/// Postcondition:
/// Once `withThrowingTaskGroup` returns it is guaranteed that the `group` is *empty*.
///
/// This is achieved in the following way:
/// - if the body returns normally:
/// - the group will await any not yet complete tasks,
/// - if any of those tasks throws, the remaining tasks will be cancelled,
/// - once the `withTaskGroup` returns the group is guaranteed to be empty.
/// - if the body throws:
/// - all tasks remaining in the group will be automatically cancelled.
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@inlinable
public func withThrowingTaskGroup<ChildTaskResult: Sendable, GroupResult>(
of childTaskResultType: ChildTaskResult.Type,
returning returnType: GroupResult.Type = GroupResult.self,
body: (inout ThrowingTaskGroup<ChildTaskResult, Error>) async throws -> GroupResult
) async rethrows -> GroupResult {
#if compiler(>=5.5) && $BuiltinTaskGroup
let _group = Builtin.createTaskGroup()
var group = ThrowingTaskGroup<ChildTaskResult, Error>(group: _group)
do {
// Run the withTaskGroup body.
let result = try await body(&group)
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
return result
} catch {
group.cancelAll()
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
throw error
}
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
}
/// A task group serves as storage for dynamically spawned tasks.
///
/// It is created by the `withTaskGroup` function.
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@frozen
public struct TaskGroup<ChildTaskResult: Sendable> {
/// Group task into which child tasks offer their results,
/// and the `next()` function polls those results from.
@usableFromInline
internal let _group: Builtin.RawPointer
/// No public initializers
@inlinable
init(group: Builtin.RawPointer) {
self._group = group
}
@available(*, deprecated, message: "`Task.Group.add` has been replaced by `TaskGroup.spawn` or `TaskGroup.spawnUnlessCancelled` and will be removed shortly.")
public mutating func add(
priority: Task.Priority = .unspecified,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) async -> Bool {
return try self.spawnUnlessCancelled(priority: priority) {
await operation()
}
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
public mutating func spawn(
priority: Task.Priority = .unspecified,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) {
_ = _taskGroupAddPendingTask(group: _group, unconditionally: true)
// Set up the job flags for a new task.
var flags = Task.JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
flags.isChildTask = true
flags.isGroupChildTask = true
// Create the asynchronous task future.
let (childTask, _) = Builtin.createAsyncTaskGroupFuture(
flags.bits, _group, operation)
// Attach it to the group's task record in the current task.
_ = _taskGroupAttachChild(group: _group, child: childTask)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(childTask))
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
public mutating func spawnUnlessCancelled(
priority: Task.Priority = .unspecified,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) -> Bool {
let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)
guard canAdd else {
// the group is cancelled and is not accepting any new work
return false
}
// Set up the job flags for a new task.
var flags = Task.JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
flags.isChildTask = true
flags.isGroupChildTask = true
// Create the asynchronous task future.
let (childTask, _) = Builtin.createAsyncTaskGroupFuture(
flags.bits, _group, operation)
// Attach it to the group's task record in the current task.
_ = _taskGroupAttachChild(group: _group, child: childTask)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(childTask))
return true
}
/// Wait for the a child task that was added to the group to complete,
/// and return (or rethrow) the value it completed with. If no tasks are
/// pending in the task group this function returns `nil`, allowing the
/// following convenient expressions to be written for awaiting for one
/// or all tasks to complete:
///
/// Await on a single completion:
///
/// if let first = try await group.next() {
/// return first
/// }
///
/// Wait and collect all group child task completions:
///
/// while let first = try await group.next() {
/// collected += value
/// }
/// return collected
///
/// Awaiting on an empty group results in the immediate return of a `nil`
/// value, without the group task having to suspend.
///
/// It is also possible to use `for await` to collect results of a task groups:
///
/// for await try value in group {
/// collected += value
/// }
///
/// ### Thread-safety
/// Please note that the `group` object MUST NOT escape into another task.
/// The `group.next()` MUST be awaited from the task that had originally
/// created the group. It is not allowed to escape the group reference.
///
/// Note also that this is generally prevented by Swift's type-system,
/// as the `add` operation is `mutating`, and those may not be performed
/// from concurrent execution contexts, such as child tasks.
///
/// ### Ordering
/// Order of values returned by next() is *completion order*, and not
/// submission order. I.e. if tasks are added to the group one after another:
///
/// group.spawn { 1 }
/// group.spawn { 2 }
///
/// print(await group.next())
/// /// Prints "1" OR "2"
///
/// ### Errors
/// If an operation added to the group throws, that error will be rethrown
/// by the next() call corresponding to that operation's completion.
///
/// It is possible to directly rethrow such error out of a `withTaskGroup` body
/// function's body, causing all remaining tasks to be implicitly cancelled.
public mutating func next() async -> ChildTaskResult? {
// try!-safe because this function only exists for Failure == Never,
// and as such, it is impossible to spawn a throwing child task.
return try! await _taskGroupWaitNext(group: _group)
}
/// Await all the remaining tasks on this group.
@usableFromInline
internal mutating func awaitAllRemainingTasks() async {
while let _ = await next() {}
}
/// Query whether the group has any remaining tasks.
///
/// Task groups are always empty upon entry to the `withTaskGroup` body, and
/// become empty again when `withTaskGroup` returns (either by awaiting on all
/// pending tasks or cancelling them).
///
/// - Returns: `true` if the group has no pending tasks, `false` otherwise.
public var isEmpty: Bool {
_taskGroupIsEmpty(_group)
}
/// Cancel all the remaining tasks in the group.
///
/// A cancelled group will not will NOT accept new tasks being added into it.
///
/// Any results, including errors thrown by tasks affected by this
/// cancellation, are silently discarded.
///
/// This function may be called even from within child (or any other) tasks,
/// and will reliably cause the group to become cancelled.
///
/// - SeeAlso: `Task.isCancelled`
/// - SeeAlso: `TaskGroup.isCancelled`
public func cancelAll() {
_taskGroupCancelAll(group: _group)
}
/// Returns `true` if the group was cancelled, e.g. by `cancelAll`.
///
/// If the task currently running this group was cancelled, the group will
/// also be implicitly cancelled, which will be reflected in the return
/// value of this function as well.
///
/// - Returns: `true` if the group (or its parent task) was cancelled,
/// `false` otherwise.
public var isCancelled: Bool {
return _taskGroupIsCancelled(group: _group)
}
}
// Implementation note:
// We are unable to just™ abstract over Failure == Error / Never because of the
// complicated relationship between `group.spawn` which dictates if `group.next`
// AND the AsyncSequence conformances would be throwing or not.
//
// We would be able to abstract over TaskGroup<..., Failure> equal to Never
// or Error, and specifically only add the `spawn` and `next` functions for
// those two cases. However, we are not able to conform to AsyncSequence "twice"
// depending on if the Failure is Error or Never, as we'll hit:
// conflicting conformance of 'TaskGroup<ChildTaskResult, Failure>' to protocol
// 'AsyncSequence'; there cannot be more than one conformance, even with
// different conditional bounds
// So, sadly we're forced to duplicate the entire implementation of TaskGroup
// to TaskGroup and ThrowingTaskGroup.
//
// The throwing task group is parameterized with failure only because of future
// proofing, in case we'd ever have typed errors, however unlikely this may be.
// Today the throwing task group failure is simply automatically bound to `Error`.
/// A task group serves as storage for dynamically spawned, potentially throwing,
/// child tasks.
///
/// It is created by the `withTaskGroup` function.
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@frozen
public struct ThrowingTaskGroup<ChildTaskResult: Sendable, Failure: Error> {
/// Group task into which child tasks offer their results,
/// and the `next()` function polls those results from.
@usableFromInline
internal let _group: Builtin.RawPointer
/// No public initializers
@inlinable
init(group: Builtin.RawPointer) {
self._group = group
}
/// Await all the remaining tasks on this group.
@usableFromInline
internal mutating func awaitAllRemainingTasks() async {
while true {
do {
guard let _ = try await next() else {
return
}
} catch {}
}
}
@available(*, deprecated, message: "`Task.Group.add` has been replaced by `(Throwing)TaskGroup.spawn` or `(Throwing)TaskGroup.spawnUnlessCancelled` and will be removed shortly.")
public mutating func add(
priority: Task.Priority = .unspecified,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) async -> Bool {
return try self.spawnUnlessCancelled(priority: priority) {
try await operation()
}
}
/// Spawn, unconditionally, a child task in the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
public mutating func spawn(
priority: Task.Priority = .unspecified,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) {
// we always add, so no need to check if group was cancelled
_ = _taskGroupAddPendingTask(group: _group, unconditionally: true)
// Set up the job flags for a new task.
var flags = Task.JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
flags.isChildTask = true
flags.isGroupChildTask = true
// Create the asynchronous task future.
let (childTask, _) = Builtin.createAsyncTaskGroupFuture(
flags.bits, _group, operation)
// Attach it to the group's task record in the current task.
_ = _taskGroupAttachChild(group: _group, child: childTask)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(childTask))
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
public mutating func spawnUnlessCancelled(
priority: Task.Priority = .unspecified,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) -> Bool {
let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)
guard canAdd else {
// the group is cancelled and is not accepting any new work
return false
}
// Set up the job flags for a new task.
var flags = Task.JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
flags.isChildTask = true
flags.isGroupChildTask = true
// Create the asynchronous task future.
let (childTask, _) = Builtin.createAsyncTaskGroupFuture(
flags.bits, _group, operation)
// Attach it to the group's task record in the current task.
_ = _taskGroupAttachChild(group: _group, child: childTask)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(childTask))
return true
}
/// Wait for the a child task that was added to the group to complete,
/// and return (or rethrow) the value it completed with. If no tasks are
/// pending in the task group this function returns `nil`, allowing the
/// following convenient expressions to be written for awaiting for one
/// or all tasks to complete:
///
/// Await on a single completion:
///
/// if let first = try await group.next() {
/// return first
/// }
///
/// Wait and collect all group child task completions:
///
/// while let first = try await group.next() {
/// collected += value
/// }
/// return collected
///
/// Awaiting on an empty group results in the immediate return of a `nil`
/// value, without the group task having to suspend.
///
/// It is also possible to use `for await` to collect results of a task groups:
///
/// for await try value in group {
/// collected += value
/// }
///
/// ### Thread-safety
/// Please note that the `group` object MUST NOT escape into another task.
/// The `group.next()` MUST be awaited from the task that had originally
/// created the group. It is not allowed to escape the group reference.
///
/// Note also that this is generally prevented by Swift's type-system,
/// as the `add` operation is `mutating`, and those may not be performed
/// from concurrent execution contexts, such as child tasks.
///
/// ### Ordering
/// Order of values returned by next() is *completion order*, and not
/// submission order. I.e. if tasks are added to the group one after another:
///
/// group.spawn { 1 }
/// group.spawn { 2 }
///
/// print(await group.next())
/// /// Prints "1" OR "2"
///
/// ### Errors
/// If an operation added to the group throws, that error will be rethrown
/// by the next() call corresponding to that operation's completion.
///
/// It is possible to directly rethrow such error out of a `withTaskGroup` body
/// function's body, causing all remaining tasks to be implicitly cancelled.
public mutating func next() async throws -> ChildTaskResult? {
return try await _taskGroupWaitNext(group: _group)
}
/// - SeeAlso: `next()`
public mutating func nextResult() async throws -> Result<ChildTaskResult, Failure>? {
do {
guard let success: ChildTaskResult = try await _taskGroupWaitNext(group: _group) else {
return nil
}
return .success(success)
} catch {
return .failure(error as! Failure) // as!-safe, because we are only allowed to throw Failure (Error)
}
}
/// Query whether the group has any remaining tasks.
///
/// Task groups are always empty upon entry to the `withTaskGroup` body, and
/// become empty again when `withTaskGroup` returns (either by awaiting on all
/// pending tasks or cancelling them).
///
/// - Returns: `true` if the group has no pending tasks, `false` otherwise.
public var isEmpty: Bool {
_taskGroupIsEmpty(_group)
}
/// Cancel all the remaining tasks in the group.
///
/// A cancelled group will not will NOT accept new tasks being added into it.
///
/// Any results, including errors thrown by tasks affected by this
/// cancellation, are silently discarded.
///
/// This function may be called even from within child (or any other) tasks,
/// and will reliably cause the group to become cancelled.
///
/// - SeeAlso: `Task.isCancelled`
/// - SeeAlso: `TaskGroup.isCancelled`
public func cancelAll() {
_taskGroupCancelAll(group: _group)
}
/// Returns `true` if the group was cancelled, e.g. by `cancelAll`.
///
/// If the task currently running this group was cancelled, the group will
/// also be implicitly cancelled, which will be reflected in the return
/// value of this function as well.
///
/// - Returns: `true` if the group (or its parent task) was cancelled,
/// `false` otherwise.
public var isCancelled: Bool {
return _taskGroupIsCancelled(group: _group)
}
}
/// ==== TaskGroup: AsyncSequence ----------------------------------------------
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension TaskGroup: AsyncSequence {
public typealias AsyncIterator = Iterator
public typealias Element = ChildTaskResult
public func makeAsyncIterator() -> Iterator {
return Iterator(group: self)
}
/// Allows iterating over results of tasks added to the group.
///
/// The order of elements returned by this iterator is the same as manually
/// invoking the `group.next()` function in a loop, meaning that results
/// are returned in *completion order*.
///
/// This iterator terminates after all tasks have completed successfully, or
/// after any task completes by throwing an error.
///
/// - SeeAlso: `TaskGroup.next()`
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct Iterator: AsyncIteratorProtocol {
public typealias Element = ChildTaskResult
@usableFromInline
var group: TaskGroup<ChildTaskResult>
@usableFromInline
var finished: Bool = false
// no public constructors
init(group: TaskGroup<ChildTaskResult>) {
self.group = group
}
/// Once this function returns `nil` this specific iterator is guaranteed to
/// never produce more values.
/// - SeeAlso: `TaskGroup.next()` for a detailed discussion its semantics.
public mutating func next() async -> Element? {
guard !finished else { return nil }
guard let element = await group.next() else {
finished = true
return nil
}
return element
}
public mutating func cancel() {
finished = true
group.cancelAll()
}
}
}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension ThrowingTaskGroup: AsyncSequence {
public typealias AsyncIterator = Iterator
public typealias Element = ChildTaskResult
public func makeAsyncIterator() -> Iterator {
return Iterator(group: self)
}
/// Allows iterating over results of tasks added to the group.
///
/// The order of elements returned by this iterator is the same as manually
/// invoking the `group.next()` function in a loop, meaning that results
/// are returned in *completion order*.
///
/// This iterator terminates after all tasks have completed successfully, or
/// after any task completes by throwing an error. If a task completes by
/// throwing an error, no further task results are returned.
///
/// - SeeAlso: `ThrowingTaskGroup.next()`
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct Iterator: AsyncIteratorProtocol {
public typealias Element = ChildTaskResult
@usableFromInline
var group: ThrowingTaskGroup<ChildTaskResult, Failure>
@usableFromInline
var finished: Bool = false
// no public constructors
init(group: ThrowingTaskGroup<ChildTaskResult, Failure>) {
self.group = group
}
/// - SeeAlso: `ThrowingTaskGroup.next()` for a detailed discussion its semantics.
public mutating func next() async throws -> Element? {
guard !finished else { return nil }
do {
guard let element = try await group.next() else {
finished = true
return nil
}
return element
} catch {
finished = true
throw error
}
}
public mutating func cancel() {
finished = true
group.cancelAll()
}
}
}
/// ==== -----------------------------------------------------------------------
/// Attach task group child to the group group to the task.
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@_silgen_name("swift_taskGroup_attachChild")
func _taskGroupAttachChild(
group: Builtin.RawPointer,
child: Builtin.NativeObject
) -> UnsafeRawPointer /*ChildTaskStatusRecord*/
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@_silgen_name("swift_taskGroup_destroy")
func _taskGroupDestroy(group: __owned Builtin.RawPointer)
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@_silgen_name("swift_taskGroup_addPending")
func _taskGroupAddPendingTask(
group: Builtin.RawPointer,
unconditionally: Bool
) -> Bool
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@_silgen_name("swift_taskGroup_cancelAll")
func _taskGroupCancelAll(group: Builtin.RawPointer)
/// Checks ONLY if the group was specifically cancelled.
/// The task itself being cancelled must be checked separately.
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@_silgen_name("swift_taskGroup_isCancelled")
func _taskGroupIsCancelled(group: Builtin.RawPointer) -> Bool
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@_silgen_name("swift_taskGroup_wait_next_throwing")
func _taskGroupWaitNext<T>(group: Builtin.RawPointer) async throws -> T?
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
enum PollStatus: Int {
case empty = 0
case waiting = 1
case success = 2
case error = 3
}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@_silgen_name("swift_taskGroup_isEmpty")
func _taskGroupIsEmpty(
_ group: Builtin.RawPointer
) -> Bool
| 36.891957 | 180 | 0.68208 |
ab784847f41b35d117b5acad8227b6f5a870daa4 | 1,484 | // The MIT License (MIT)
// Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, [email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
extension SafeSFSymbol {
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public static var clear: Clear { .init(name: "clear") }
open class Clear: SafeSFSymbol {
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var fill: SafeSFSymbol { ext(.start.fill) }
}
} | 46.375 | 83 | 0.744609 |
3a2434704b1b1d782ddbe45a846e6318617e44f7 | 278 | //
// Item.swift
// FurnitureAppUI
//
// Created by recherst on 2021/9/19.
//
import SwiftUI
struct Item: Identifiable {
var id = UUID().uuidString
var title: String
var price: String
var subTitle: String
var image: String
var offset: CGFloat = 0
}
| 15.444444 | 37 | 0.643885 |
67074382f851fc0d6958a9deb69316d6be276f39 | 314 | //
// Test2ViewController.swift
// Navigator
//
// Created by 工作 on 2019/8/15.
// Copyright © 2019 aksskas. All rights reserved.
//
import UIKit
class Test2ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
}
}
| 14.952381 | 50 | 0.652866 |
086455da022982d3c29b733a3f8751abcb1d3b9d | 2,569 | //
// ParcelTableViewCell.swift
// DeliverySystem
//
// Created by Arvin Quiliza on 10/22/18.
// Copyright © 2018 arvnq. All rights reserved.
//
import UIKit
/// protocol providing method that is called when button inside cell is tapped
protocol ParcelTableViewCellDelegate: class {
func ParcelTableViewCell(didTappedbuttonOn cell: ParcelTableViewCell)
}
/// Parcel's own table view cell class
class ParcelTableViewCell: UITableViewCell {
@IBOutlet weak var recipientNameLabel: UILabel!
@IBOutlet weak var recipientAddressLabel: UILabel!
@IBOutlet weak var statusChangeDateLabel: UILabel!
@IBOutlet weak var statusButton: StatusButton!
weak var delegate: ParcelTableViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
configureCellView()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
/// Initializing default cell display
func configureCellView () {
recipientNameLabel.font = UIFont.boldSystemFont(ofSize: 14.0)
recipientAddressLabel.font = UIFont.systemFont(ofSize: 12.0)
statusChangeDateLabel.font = .systemFont(ofSize: 12.0)
recipientAddressLabel.textColor = .lightGray
statusChangeDateLabel.textColor = .lightGray
}
/**
Updating cell's properties with parcel information.
- Parameter parcel: containing the properties to be displayed
*/
func configureCell (usingParcel parcel: Parcel) {
let image: UIImage?
recipientNameLabel.text = parcel.recipientName
recipientAddressLabel.text = parcel.deliveryAddress
statusChangeDateLabel.text = Parcel.listDateFormatter.string(from: parcel.statusChangedDate)
/// image on status button will be determined based on parcel's status
switch parcel.status {
case .new: image = UIImage(named: "new.png")
case .dispatched: image = UIImage(named: "dispatch.png")
case .forPickup: image = UIImage(named: "pickup.png")
case .delivered: image = UIImage(named: "delivered.jpg")
}
statusButton.setImage(image, for: .normal)
}
/// call the delegate when status button is tapped
@IBAction func statusButtonTapped(_ sender: Any) {
delegate?.ParcelTableViewCell(didTappedbuttonOn: self)
}
}
| 31.329268 | 100 | 0.673803 |
3a9ef701f930fcc2b534a38afe048258da3fc226 | 524 | //
// CircleImage.swift
// CreatingAndCombiningViews
//
// Created by Said Ozcan on 22/05/2020.
// Copyright © 2020 Said Ozcan. All rights reserved.
//
import SwiftUI
struct CircleImage: View {
var body: some View {
Image("turtlerock")
.clipShape(Circle())
.overlay(
Circle().stroke(Color.white, lineWidth: 4))
.shadow(radius: 10)
}
}
struct CircleImage_Previews: PreviewProvider {
static var previews: some View {
CircleImage()
}
}
| 20.153846 | 59 | 0.604962 |
7a009b1d48437708fbade53a6f749ff1ccd69652 | 380 | /**
Registers passed stylesheets by calling `define` function where
all styling closures should be added.
- Parameter stylesheets: Array of stylesheets to be registered.
*/
public func register(stylesheets: [Stylesheet]) {
stylesheets.forEach {
$0.define()
}
}
/**
Must be set to `true` to get shared styles working automatically.
*/
public var runtimeStyles = true
| 22.352941 | 65 | 0.734211 |
d5b44b0a5c0fb22c7e8913e2d26ac7a58ee5e11e | 2,043 | //
// MovieProvider.swift
// iOSMovieDB
//
// Created by Sebastian Diaz Avila on 23-04-20.
//
import Foundation
public class MovieProvider: ProviderProtocol {
var service: ServiceProtocol
public init(service: ServiceProtocol) {
self.service = service
}
public func getMovie(id: Int, completion: @escaping movieResult) {
service.fetchMovie(id: id) { response in
completion(self.responseHandler(response))
}
}
public func getUpcoming(page: Int, completion: @escaping listMoviesResult) {
service.fetchUpcoming(page: page) { response in
completion(self.responseHandler(response))
}
}
public func getTopRated(page: Int, completion: @escaping listMoviesResult) {
service.fetchTopRated(page: page) { response in
completion(self.responseHandler(response))
}
}
public func getPopular(page: Int, completion: @escaping listMoviesResult) {
service.fetchPopular(page: page) { response in
completion(self.responseHandler(response))
}
}
public func getNowPlaying(page: Int, completion: @escaping listMoviesResult) {
service.fetchNowPlaying(page: page) { response in
completion(self.responseHandler(response))
}
}
public func getLatest(completion: @escaping listMoviesResult) {
service.fetchLatest { response in
completion(self.responseHandler(response))
}
}
private func responseHandler<Model: Codable>(_ response: Result<Data>) -> Result<Model> {
switch response {
case .success(let data):
do {
let decoder = JSONDecoder()
let model = try decoder.decode(Model.self, from: data)
return .success(model)
} catch let error {
return .failure(.ErrorMapperModel(error))
}
case.failure(let error):
return .failure(error)
}
}
}
| 29.608696 | 93 | 0.610866 |
5bf46ea5b2446d0cfc898772702fc83f8edf1ccd | 243 | // Copyright © Fleuronic LLC. All rights reserved.
import Emissary
public extension JSONBin.V2.API.SchemaDoc {
struct CreateParameters {
let name: String
}
}
// MARK: -
extension JSONBin.V2.API.SchemaDoc.CreateParameters: Parameters {}
| 18.692308 | 66 | 0.753086 |
9bbadf46936181cbb993a60d40a52256077d9b22 | 2,374 | //
// SceneDelegate.swift
// CombineVsRXSwift
//
// Created by Alberto Penas Amor on 25/09/2020.
// Copyright © 2020 com.github.albertopeam. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.962963 | 147 | 0.71567 |
e51a7ca36851228327973fb013313a0967d46d07 | 589 | //
// Tools.swift
// CircleButton
//
// Created by 周奇天 on 2019/2/17.
// Copyright © 2019 周奇天. All rights reserved.
//
import UIKit
extension UIImage{
class func imageFromBundle(named name: String!) -> UIImage? {
var bundle = Bundle.init(for: DirectionButton.self)
if let resourcePath = bundle.path(forResource: "DirectionButton", ofType: "bundle") {
if let resourcesBundle = Bundle(path: resourcePath) {
bundle = resourcesBundle
}
}
return UIImage.init(named: name, in: bundle, compatibleWith: nil)
}
}
| 26.772727 | 93 | 0.626486 |
3818cf1f9d6e54e69e8360fdd86ae0ab9080a3d2 | 2,271 | #if os(iOS) || os(macOS) // Added by Auth0toSPM
import Auth0ObjC // Added by Auth0toSPM
// A0SimpleKeychain+RSAPublicKey.swift
//
// Copyright (c) 2020 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(macOS) // Added by Auth0toSPM(original value '#if WEB_AUTH_PLATFORM')
import Foundation
import SimpleKeychain
extension A0SimpleKeychain {
func setRSAPublicKey(data: Data, forKey tag: String) -> Bool {
let sizeInBits = data.count * MemoryLayout<UInt8>.size
let query: [CFString: Any] = [kSecClass: kSecClassKey,
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
kSecAttrAccessible: kSecAttrAccessibleAlways,
kSecAttrKeySizeInBits: NSNumber(value: sizeInBits),
kSecAttrApplicationTag: tag,
kSecValueData: data]
if hasRSAKey(withTag: tag) { deleteRSAKey(withTag: tag) }
let result = SecItemAdd(query as CFDictionary, nil)
return result == errSecSuccess
}
}
#endif
#endif // Added by Auth0toSPM
| 48.319149 | 89 | 0.678556 |
11ec9c9699014528716f59e0ab6befee260b01d2 | 697 | //
// MockLoader.swift
// RMImageLoader
//
// Created by Robert D. Mogos.
// Copyright © 2017 Robert D. Mogos. All rights reserved.
//
import Foundation
class MockRetriever: Retriever {
public var fakeDelay: TimeInterval = 0
override public func loadRequest(url: URL, for subscriber: AnyObject, completion: @escaping RetrieverCompletion) {
let superLoad = super.loadRequest
let mockCompletion: RetrieverCompletion = { [weak self] res in
guard let this = self else {
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + this.fakeDelay, execute: {
completion(res)
})
}
return superLoad(url, subscriber, mockCompletion)
}
}
| 25.814815 | 116 | 0.681492 |
08513927e63b89d71f157e06c9dddaf7b9e7bb4c | 80 | import PackageDescription
let package = Package(
name: "OpalImagePicker"
)
| 13.333333 | 27 | 0.75 |
09480d764060c8128567933a11912e4505c89576 | 1,081 | //
// ControlFlow.swift
// Depends
//
// Created by Nikita Leonov on 10/14/17.
// Copyright © 2017 Nikita Leonov. All rights reserved.
//
func `if`<TR, ER>(_ true: Type<Bool, True>, then: () -> (TR), else: () -> (ER)) -> TR {
return then()
}
func `if`<TR, ER>(_ true: Type<Bool, False>, then: () -> (TR), else: () -> (ER)) -> ER {
return `else`()
}
func `do`<S>(count: Type<UInt, Number<() -> () -> () -> ()>>, state: S, process: (S) -> (S) ) -> S {
let one = Type<UInt, One>()
return `do`(count: count - one, state: process(state), process: process)
}
func `do`<S>(count: Type<UInt, Number<() -> () -> ()>>, state: S, process: (S) -> (S) ) -> S {
let one = Type<UInt, One>()
return `do`(count: count - one, state: process(state), process: process)
}
func `do`<S>(count: Type<UInt, Number<() -> ()>>, state: S, process: (S) -> (S) ) -> S {
let one = Type<UInt, One>()
return `do`(count: count - one, state: process(state), process: process)
}
func `do`<S>(count: Type<UInt, Zero>, state: S, process: (S) -> (S) ) -> S {
return state
}
| 30.885714 | 100 | 0.537465 |
e0db67be9e34c95de8bcb59f07c48de971ae3016 | 5,522 | //
// sessionPinningHandler.swift
// MAG Native App
//
// Created by Sean O'Connell on 05/11/2021.
//
import Foundation
class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if (MagClientData().getKeyChainFieldValue(fieldName: "magSSLPinningEnabled") == "true") {
let serverCredential = getServerUrlCredential(protectionSpace: challenge.protectionSpace)
guard serverCredential != nil else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
completionHandler(URLSession.AuthChallengeDisposition.useCredential, serverCredential)
} else {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
return
}
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
if (MagClientData().getKeyChainFieldValue(fieldName: "magSSLPinningEnabled") == "false") {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
return
}
NSLog("NSURLAuthenticationMethodClientCertificate Authentication Method")
let getCertQuery: [String: Any] = [
kSecClass as String : kSecClassCertificate,
kSecReturnRef as String : kCFBooleanTrue,
kSecAttrPublicKeyHash as String: privKeyAttrApplicationLabel,
]
var certItem: CFTypeRef?
let certStatus = SecItemCopyMatching(getCertQuery as CFDictionary, &certItem)
guard certStatus == errSecSuccess else { return }
let certificate = certItem as! SecCertificate
let getIdentityQuery: [String: Any] = [kSecClass as String: kSecClassIdentity,
kSecReturnRef as String : kCFBooleanTrue]
var identityItem: CFTypeRef?
let certificateStatus = SecItemCopyMatching(getIdentityQuery as CFDictionary, &identityItem)
if (certificateStatus == errSecSuccess) {
let identity = identityItem as! SecIdentity
let magClientCredential = URLCredential(identity: identity, certificates: [certificate], persistence: .forSession)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, magClientCredential)
} else {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
}
}
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
// We've got an error
if let err = error {
print("Error: \(err.localizedDescription)")
} else {
print("Error. Giving up")
}
}
func getServerUrlCredential(protectionSpace:URLProtectionSpace)->URLCredential?{
if let serverTrust = protectionSpace.serverTrust {
//
// Check if the server presented certificate is actually valid
//
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(serverTrust, &result)
print("SecTrustEvaluate res = \(result.rawValue)")
if (status == errSecSuccess),
let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
//Get Server Certificate Data
let serverCertificateData = SecCertificateCopyData(serverCertificate)
//
// Get the registered MAG Server certificate and compare them
//
let getquery: [String: Any] = [kSecClass as String: kSecClassCertificate,
kSecAttrLabel as String: magServerDeviceCertificateTag,
kSecReturnData as String: kCFBooleanTrue]
var item: CFTypeRef?
let certificateStatus = SecItemCopyMatching(getquery as CFDictionary, &item)
var validCertificateFound:Bool = false
if (certificateStatus == errSecSuccess) {
//
// Check if certificates are equal, otherwhise pinning failed and return nil
//
guard [serverCertificateData as? Data] == [item as? Data] else {
print("Pinned Certificate and the one received do not match.")
return nil
}
}
return URLCredential(trust: serverTrust)
}
}
return nil
}
}
| 40.903704 | 186 | 0.561029 |
eb72fa1477b7011542e42b3500fac83185e7c18b | 1,603 | /*
* Copyright 2017 WalmartLabs
* 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
/**
* This class is a generated place holder for your Movies implementations.!
* Feel free to modify this class contents as needed. `ern regen-api-impl` command WILL NOT modify the content of this class.
* Don't modify the class name as this naming convention is used for container generation.
*/
@objc public class MoviesApiRequestHandlerProvider : RequestHandlerProvider, MoviesApiRequestHandlerDelegate
{
/**
* - Parameter config : Optional config object that can be passed to an api impl provider.
*/
init(handlerConfig: MoviesApiConfig? = nil)
{
super.init(config: handlerConfig)
}
public func registerGetTopRatedMoviesRequestHandler()
{
// TODO: Needs to be implemented.
}
public func registerGetMovieDetailRequestHandler()
{
// TODO: Needs to be implemented.
}
}
// DO NOT rename this class as this naming convention is used when a container is generated.
public class MoviesApiConfig : RequestHandlerConfig
{
}
| 34.106383 | 125 | 0.734872 |
014d021730d10aa5c6d8491e3c72fb562ff2a39c | 2,035 | //
// HistoryInteractor.swift
// DoorConcept
//
// Created by Jorge Raul Ovalle Zuleta on 3/22/16.
// Copyright © 2016 jorgeovalle. All rights reserved.
//
import UIKit
import CoreData
class HistoryInteractor {
private let managedObjectContext:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
init(){}
/**
Method to retrieve History for a User, check wether the current user owns the Building or not.
- parameter completion: completion description (data = [History], error = error description)
*/
func getHistory(completion:FetchCompletionHandler){
let fetchRequest = NSFetchRequest(entityName: "History")
fetchRequest.predicate = NSPredicate(format: "user == %@ OR door.building IN %@", UserService.sharedInstance.currentUser!, UserService.sharedInstance.currentUser!.buildings!)
do{
let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult
let fetchBuilding = fetchResults.finalResult as! [History]
completion!(data:fetchBuilding, error: nil)
}catch{
completion!(data:nil,error: "CoreData error!")
}
}
/**
Method to save History on CoreData, from user/door. An user attempt to open a door
- parameter door: Door datatype to be added to the History
- parameter user: User datatype to be added to the History
- parameter state: Transaction's state, passible (authorized/denied)
*/
func saveHistory(door:Door, user:User, state:String){
let history = NSEntityDescription.insertNewObjectForEntityForName("History", inManagedObjectContext: managedObjectContext) as! History
history.door = door
history.user = user
history.state = state
history.date = NSDate()
do{
try managedObjectContext.save()
}catch{
print("Some error inserting Door")
}
}
}
| 37 | 182 | 0.676658 |
2823b6dbb415f9e083ac094bd30b1c7a35cbece8 | 14,751 | import Errors
import Foundation
import HighwayDispatch
import Result
import SignPost
import SourceryAutoProtocols
import SourceryWorker
import Terminal
import ZFile
// Generated using Sourcery 0.15.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
// MARK: - ImportProtocolMock
open class ImportProtocolMock: ImportProtocol
{
public init() {}
public var name: String
{
get { return underlyingName }
set(value) { underlyingName = value }
}
public var underlyingName: String = "AutoMockable filled value"
public var testable: Bool
{
get { return underlyingTestable }
set(value) { underlyingTestable = value }
}
public var underlyingTestable: Bool = false
}
// MARK: - SourceryBuilderProtocolMock
open class SourceryBuilderProtocolMock: SourceryBuilderProtocol
{
public init() {}
public static var executalbeFolderPath: String
{
get { return underlyingExecutalbeFolderPath }
set(value) { underlyingExecutalbeFolderPath = value }
}
public static var underlyingExecutalbeFolderPath: String = "AutoMockable filled value"
// MARK: - <templateFolder> - parameters
public var templateFolderThrowableError: Error?
public var templateFolderCallsCount = 0
public var templateFolderCalled: Bool
{
return templateFolderCallsCount > 0
}
public var templateFolderReturnValue: FolderProtocol?
// MARK: - <templateFolder> - closure mocks
public var templateFolderClosure: (() throws -> FolderProtocol)?
// MARK: - <templateFolder> - method mocked
open func templateFolder() throws -> FolderProtocol
{
// <templateFolder> - Throwable method implementation
if let error = templateFolderThrowableError
{
throw error
}
templateFolderCallsCount += 1
// <templateFolder> - Return Value mock implementation
guard let closureReturn = templateFolderClosure else
{
guard let returnValue = templateFolderReturnValue else
{
let message = "No returnValue implemented for templateFolderClosure"
let error = SourceryMockError.implementErrorCaseFor(message)
// You should implement FolderProtocol
throw error
}
return returnValue
}
return try closureReturn()
}
// MARK: - <sourceryAutoProtocolFile> - parameters
public var sourceryAutoProtocolFileThrowableError: Error?
public var sourceryAutoProtocolFileCallsCount = 0
public var sourceryAutoProtocolFileCalled: Bool
{
return sourceryAutoProtocolFileCallsCount > 0
}
public var sourceryAutoProtocolFileReturnValue: FileProtocol?
// MARK: - <sourceryAutoProtocolFile> - closure mocks
public var sourceryAutoProtocolFileClosure: (() throws -> FileProtocol)?
// MARK: - <sourceryAutoProtocolFile> - method mocked
open func sourceryAutoProtocolFile() throws -> FileProtocol
{
// <sourceryAutoProtocolFile> - Throwable method implementation
if let error = sourceryAutoProtocolFileThrowableError
{
throw error
}
sourceryAutoProtocolFileCallsCount += 1
// <sourceryAutoProtocolFile> - Return Value mock implementation
guard let closureReturn = sourceryAutoProtocolFileClosure else
{
guard let returnValue = sourceryAutoProtocolFileReturnValue else
{
let message = "No returnValue implemented for sourceryAutoProtocolFileClosure"
let error = SourceryMockError.implementErrorCaseFor(message)
// You should implement FileProtocol
throw error
}
return returnValue
}
return try closureReturn()
}
// MARK: - <dependencies> - parameters
public var dependenciesThrowableError: Error?
public var dependenciesCallsCount = 0
public var dependenciesCalled: Bool
{
return dependenciesCallsCount > 0
}
public var dependenciesReturnValue: DependencyProtocol?
// MARK: - <dependencies> - closure mocks
public var dependenciesClosure: (() throws -> DependencyProtocol)?
// MARK: - <dependencies> - method mocked
open func dependencies() throws -> DependencyProtocol
{
// <dependencies> - Throwable method implementation
if let error = dependenciesThrowableError
{
throw error
}
dependenciesCallsCount += 1
// <dependencies> - Return Value mock implementation
guard let closureReturn = dependenciesClosure else
{
guard let returnValue = dependenciesReturnValue else
{
let message = "No returnValue implemented for dependenciesClosure"
let error = SourceryMockError.implementErrorCaseFor(message)
// You should implement DependencyProtocol
throw error
}
return returnValue
}
return try closureReturn()
}
// MARK: - <attemptToBuildSourceryIfNeeded> - parameters
public var attemptToBuildSourceryIfNeededThrowableError: Error?
public var attemptToBuildSourceryIfNeededCallsCount = 0
public var attemptToBuildSourceryIfNeededCalled: Bool
{
return attemptToBuildSourceryIfNeededCallsCount > 0
}
public var attemptToBuildSourceryIfNeededReturnValue: FileProtocol?
// MARK: - <attemptToBuildSourceryIfNeeded> - closure mocks
public var attemptToBuildSourceryIfNeededClosure: (() throws -> FileProtocol)?
// MARK: - <attemptToBuildSourceryIfNeeded> - method mocked
open func attemptToBuildSourceryIfNeeded() throws -> FileProtocol
{
// <attemptToBuildSourceryIfNeeded> - Throwable method implementation
if let error = attemptToBuildSourceryIfNeededThrowableError
{
throw error
}
attemptToBuildSourceryIfNeededCallsCount += 1
// <attemptToBuildSourceryIfNeeded> - Return Value mock implementation
guard let closureReturn = attemptToBuildSourceryIfNeededClosure else
{
guard let returnValue = attemptToBuildSourceryIfNeededReturnValue else
{
let message = "No returnValue implemented for attemptToBuildSourceryIfNeededClosure"
let error = SourceryMockError.implementErrorCaseFor(message)
// You should implement FileProtocol
throw error
}
return returnValue
}
return try closureReturn()
}
}
// MARK: - SourceryProtocolMock
open class SourceryProtocolMock: SourceryProtocol
{
public init() {}
public var uuid: String
{
get { return underlyingUuid }
set(value) { underlyingUuid = value }
}
public var underlyingUuid: String = "AutoMockable filled value"
public var name: String
{
get { return underlyingName }
set(value) { underlyingName = value }
}
public var underlyingName: String = "AutoMockable filled value"
public var templateFolder: FolderProtocol
{
get { return underlyingTemplateFolder }
set(value) { underlyingTemplateFolder = value }
}
public var underlyingTemplateFolder: FolderProtocol!
public var outputFolder: FolderProtocol
{
get { return underlyingOutputFolder }
set(value) { underlyingOutputFolder = value }
}
public var underlyingOutputFolder: FolderProtocol!
public var sourcesFolders: [FolderProtocol] = []
public var individualSourceFiles: [File]?
public var sourceryAutoProtocolsFile: FileProtocol
{
get { return underlyingSourceryAutoProtocolsFile }
set(value) { underlyingSourceryAutoProtocolsFile = value }
}
public var underlyingSourceryAutoProtocolsFile: FileProtocol!
public var sourceryYMLFile: FileProtocol
{
get { return underlyingSourceryYMLFile }
set(value) { underlyingSourceryYMLFile = value }
}
public var underlyingSourceryYMLFile: FileProtocol!
public var sourceryBuilder: SourceryBuilderProtocol
{
get { return underlyingSourceryBuilder }
set(value) { underlyingSourceryBuilder = value }
}
public var underlyingSourceryBuilder: SourceryBuilderProtocol!
public var imports: Set<TemplatePrepend>
{
get { return underlyingImports }
set(value) { underlyingImports = value }
}
public var underlyingImports: Set<TemplatePrepend>!
// MARK: - <init> - parameters
public var initProductNameSwiftPackageDependenciesSwiftPackageDumpSourceryBuilderSignPostThrowableError: Error?
public var initProductNameSwiftPackageDependenciesSwiftPackageDumpSourceryBuilderSignPostReceivedArguments: (productName: String, swiftPackageDependencies: DependencyProtocol, swiftPackageDump: DumpProtocol, sourceryBuilder: SourceryBuilderProtocol, signPost: SignPostProtocol)?
// MARK: - <init> - closure mocks
public var initProductNameSwiftPackageDependenciesSwiftPackageDumpSourceryBuilderSignPostClosure: ((String, DependencyProtocol, DumpProtocol, SourceryBuilderProtocol, SignPostProtocol) throws -> Void)?
// MARK: - <init> - initializer mocked
public required init(productName: String, swiftPackageDependencies: DependencyProtocol, swiftPackageDump: DumpProtocol, sourceryBuilder: SourceryBuilderProtocol, signPost: SignPostProtocol) throws
{
initProductNameSwiftPackageDependenciesSwiftPackageDumpSourceryBuilderSignPostReceivedArguments = (productName: productName, swiftPackageDependencies: swiftPackageDependencies, swiftPackageDump: swiftPackageDump, sourceryBuilder: sourceryBuilder, signPost: signPost)
try? initProductNameSwiftPackageDependenciesSwiftPackageDumpSourceryBuilderSignPostClosure?(productName, swiftPackageDependencies, swiftPackageDump, sourceryBuilder, signPost)
}
// MARK: - <executableFile> - parameters
public var executableFileThrowableError: Error?
public var executableFileCallsCount = 0
public var executableFileCalled: Bool
{
return executableFileCallsCount > 0
}
public var executableFileReturnValue: FileProtocol?
// MARK: - <executableFile> - closure mocks
public var executableFileClosure: (() throws -> FileProtocol)?
// MARK: - <executableFile> - method mocked
open func executableFile() throws -> FileProtocol
{
// <executableFile> - Throwable method implementation
if let error = executableFileThrowableError
{
throw error
}
executableFileCallsCount += 1
// <executableFile> - Return Value mock implementation
guard let closureReturn = executableFileClosure else
{
guard let returnValue = executableFileReturnValue else
{
let message = "No returnValue implemented for executableFileClosure"
let error = SourceryMockError.implementErrorCaseFor(message)
// You should implement FileProtocol
throw error
}
return returnValue
}
return try closureReturn()
}
}
// MARK: - SourceryWorkerProtocolMock
open class SourceryWorkerProtocolMock: SourceryWorkerProtocol
{
public init() {}
public var name: String
{
get { return underlyingName }
set(value) { underlyingName = value }
}
public var underlyingName: String = "AutoMockable filled value"
public var sourceryYMLFile: FileProtocol
{
get { return underlyingSourceryYMLFile }
set(value) { underlyingSourceryYMLFile = value }
}
public var underlyingSourceryYMLFile: FileProtocol!
// MARK: - <init> - parameters
public var initSourceryTerminalSignPostQueueReceivedArguments: (sourcery: SourceryProtocol, terminal: TerminalProtocol, signPost: SignPostProtocol, queue: HighwayDispatchProtocol)?
// MARK: - <init> - closure mocks
public var initSourceryTerminalSignPostQueueClosure: ((SourceryProtocol, TerminalProtocol, SignPostProtocol, HighwayDispatchProtocol) -> Void)?
// MARK: - <init> - initializer mocked
public required init(sourcery: SourceryProtocol, terminal: TerminalProtocol, signPost: SignPostProtocol, queue: HighwayDispatchProtocol)
{
initSourceryTerminalSignPostQueueReceivedArguments = (sourcery: sourcery, terminal: terminal, signPost: signPost, queue: queue)
initSourceryTerminalSignPostQueueClosure?(sourcery, terminal, signPost, queue)
}
// MARK: - <attempt> - parameters
public var attemptInCallsCount = 0
public var attemptInCalled: Bool
{
return attemptInCallsCount > 0
}
public var attemptInReceivedArguments: (folder: FolderProtocol, async: (@escaping SourceryWorker.SyncOutput) -> Void)?
// MARK: - <attempt> - closure mocks
public var attemptInClosure: ((FolderProtocol, @escaping (@escaping SourceryWorker.SyncOutput) -> Void) -> Void)?
// MARK: - <attempt> - method mocked
open func attempt(in folder: FolderProtocol, _ async: @escaping (@escaping SourceryWorker.SyncOutput) -> Void)
{
attemptInCallsCount += 1
attemptInReceivedArguments = (folder: folder, async: async)
// <attempt> - Void return mock implementation
attemptInClosure?(folder, async)
}
}
// MARK: - TemplatePrependProtocolMock
open class TemplatePrependProtocolMock: TemplatePrependProtocol
{
public init() {}
public var names: Set<TemplatePrepend.Import>
{
get { return underlyingNames }
set(value) { underlyingNames = value }
}
public var underlyingNames: Set<TemplatePrepend.Import>!
public var template: String
{
get { return underlyingTemplate }
set(value) { underlyingTemplate = value }
}
public var underlyingTemplate: String = "AutoMockable filled value"
}
// MARK: - OBJECTIVE-C
// MARK: - Sourcery Errors
public enum SourceryMockError: Swift.Error, Hashable
{
case implementErrorCaseFor(String)
case subclassMockBeforeUsing(String)
public var debugDescription: String
{
switch self
{
case let .implementErrorCaseFor(message):
return """
🧙♂️ SourceryMockError.implementErrorCaseFor:
message: \(message)
"""
case let .subclassMockBeforeUsing(message):
return """
\n
🧙♂️ SourceryMockError.subclassMockBeforeUsing:
message: \(message)
"""
}
}
}
| 30.603734 | 282 | 0.686869 |
e92ab0cf3f21621adb130a4d10cfa124c31b087d | 794 | //
// preworkUITestsLaunchTests.swift
// preworkUITests
//
// Created by DarlingPan on 1/19/22.
//
import XCTest
class preworkUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 24.060606 | 88 | 0.672544 |
082e6a5351f35a4c7f4e1b9d74eb49aa6337faaa | 1,441 | //
// PingBuddyUITests.swift
// PingBuddyUITests
//
// Created by Stefan Horner on 08/07/2020.
// Copyright © 2020 Stefan Horner. All rights reserved.
//
import XCTest
class PingBuddyUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 32.75 | 182 | 0.655101 |
ef44a19cd6372a70dc6458e4388bbde9ba37cf71 | 1,238 | //
// TumblrUITests.swift
// TumblrUITests
//
// Created by Jesus perez on 1/31/18.
// Copyright © 2018 Jesus perez. All rights reserved.
//
import XCTest
class TumblrUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.459459 | 182 | 0.660743 |
f44a193da41dd0cce57efd6597f4138654c8d0f5 | 19,827 | //
// OAuth2Swift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/22/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
open class OAuth2Swift: OAuthSwift {
/// If your oauth provider need to use basic authentification
/// set value to true (default: false)
open var accessTokenBasicAuthentification = false
/// Set to true to deactivate state check. Be careful of CSRF
open var allowMissingStateCheck: Bool = false
/// Encode callback url, some services require it to be encoded.
open var encodeCallbackURL: Bool = false
/// Encode callback url inside the query, this is second encoding phase when the entire query string gets assembled. In rare
/// cases, like with Imgur, the url needs to be encoded only once and this value needs to be set to `false`.
open var encodeCallbackURLQuery: Bool = true
var consumerKey: String
var consumerSecret: String
var authorizeUrl: String
var accessTokenUrl: String?
var responseType: String
var contentType: String?
// RFC7636 PKCE
var codeVerifier: String?
// MARK: init
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: URLConvertible, accessTokenUrl: URLConvertible, responseType: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.accessTokenUrl = accessTokenUrl.string
}
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: URLConvertible, accessTokenUrl: URLConvertible, responseType: String, contentType: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.accessTokenUrl = accessTokenUrl.string
self.contentType = contentType
}
public init(consumerKey: String, consumerSecret: String, authorizeUrl: URLConvertible, responseType: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.authorizeUrl = authorizeUrl.string
self.responseType = responseType
super.init(consumerKey: consumerKey, consumerSecret: consumerSecret)
self.client.credential.version = .oauth2
}
public convenience init?(parameters: ConfigParameters) {
guard let consumerKey = parameters["consumerKey"], let consumerSecret = parameters["consumerSecret"],
let responseType = parameters["responseType"], let authorizeUrl = parameters["authorizeUrl"] else {
return nil
}
if let accessTokenUrl = parameters["accessTokenUrl"] {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret,
authorizeUrl: authorizeUrl, accessTokenUrl: accessTokenUrl, responseType: responseType)
} else {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret,
authorizeUrl: authorizeUrl, responseType: responseType)
}
}
open var parameters: ConfigParameters {
return [
"consumerKey": consumerKey,
"consumerSecret": consumerSecret,
"authorizeUrl": authorizeUrl,
"accessTokenUrl": accessTokenUrl ?? "",
"responseType": responseType
]
}
// MARK: functions
@discardableResult
open func authorize(withCallbackURL callbackURL: URLConvertible?, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) -> OAuthSwiftRequestHandle? {
if let url = callbackURL, url.url == nil {
completion(.failure(.encodingError(urlString: url.string)))
return nil
}
self.observeCallback { [weak self] url in
guard let this = self else {
OAuthSwift.retainError(completion)
return
}
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString
}
if let fragment = url.fragment, !fragment.isEmpty {
responseParameters += fragment.parametersFromQueryString
}
if let accessToken = responseParameters["access_token"] {
this.client.credential.oauthToken = accessToken.safeStringByRemovingPercentEncoding
if let expiresIn: String = responseParameters["expires_in"], let offset = Double(expiresIn) {
this.client.credential.oauthTokenExpiresAt = Date(timeInterval: offset, since: Date())
}
completion(.success((this.client.credential, nil, responseParameters)))
} else if let code = responseParameters["code"] {
if !this.allowMissingStateCheck {
guard let responseState = responseParameters["state"] else {
completion(.failure(.missingState))
return
}
if responseState != state {
completion(.failure(.stateNotEqual(state: state, responseState: responseState)))
return
}
}
let callbackURLEncoded: URL?
if let callbackURL = callbackURL {
callbackURLEncoded = callbackURL.encodedURL // XXX do not known why to re-encode, maybe if string only?
} else {
callbackURLEncoded = nil
}
if let handle = this.postOAuthAccessTokenWithRequestToken(
byCode: code.safeStringByRemovingPercentEncoding,
callbackURL: callbackURLEncoded, headers: headers, completionHandler: completion) {
this.putHandle(handle, withKey: UUID().uuidString)
}
} else if let error = responseParameters["error"] {
let description = responseParameters["error_description"] ?? ""
let message = NSLocalizedString(error, comment: description)
completion(.failure(.serverError(message: message)))
} else {
let message = "No access_token, no code and no error provided by server"
completion(.failure(.serverError(message: message)))
}
}
var queryErrorString = ""
let encodeError: (String, String) -> Void = { name, value in
if let newQuery = queryErrorString.urlQueryByAppending(parameter: name, value: value, encode: false) {
queryErrorString = newQuery
}
}
var queryString: String? = ""
queryString = queryString?.urlQueryByAppending(parameter: "client_id", value: self.consumerKey, encodeError)
if let callbackURL = callbackURL {
let value = self.encodeCallbackURL ? callbackURL.string.urlEncoded : callbackURL.string
queryString = queryString?.urlQueryByAppending(parameter: "redirect_uri", value: value, encode: self.encodeCallbackURLQuery, encodeError)
}
queryString = queryString?.urlQueryByAppending(parameter: "response_type", value: self.responseType, encodeError)
queryString = queryString?.urlQueryByAppending(parameter: "scope", value: scope, encodeError)
queryString = queryString?.urlQueryByAppending(parameter: "state", value: state, encodeError)
for (name, value) in parameters {
queryString = queryString?.urlQueryByAppending(parameter: name, value: "\(value)", encodeError)
}
if let queryString = queryString {
let urlString = self.authorizeUrl.urlByAppending(query: queryString)
if let url: URL = URL(string: urlString) {
self.authorizeURLHandler.handle(url)
return self
} else {
completion(.failure(.encodingError(urlString: urlString)))
}
} else {
let urlString = self.authorizeUrl.urlByAppending(query: queryErrorString)
completion(.failure(.encodingError(urlString: urlString)))
}
self.cancel() // ie. remove the observer.
return nil
}
open func postOAuthAccessTokenWithRequestToken(byCode code: String, callbackURL: URL?, headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) -> OAuthSwiftRequestHandle? {
var parameters = OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["code"] = code
parameters["grant_type"] = "authorization_code"
// PKCE - extra parameter
if let codeVerifier = self.codeVerifier {
parameters["code_verifier"] = codeVerifier
// Don't send client secret when using PKCE, some services complain
} else {
parameters["client_secret"] = self.consumerSecret
}
if let callbackURL = callbackURL {
parameters["redirect_uri"] = callbackURL.absoluteString.safeStringByRemovingPercentEncoding
}
return requestOAuthAccessToken(withParameters: parameters, headers: headers, completionHandler: completion)
}
@discardableResult
open func renewAccessToken(withRefreshToken refreshToken: String, parameters: OAuthSwift.Parameters? = nil, headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) -> OAuthSwiftRequestHandle? {
var parameters = parameters ?? OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["refresh_token"] = refreshToken
parameters["grant_type"] = "refresh_token"
return requestOAuthAccessToken(withParameters: parameters, headers: headers, completionHandler: completion)
}
fileprivate func requestOAuthAccessToken(withParameters parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) -> OAuthSwiftRequestHandle? {
let completionHandler: OAuthSwiftHTTPRequest.CompletionHandler = { [weak self] result in
guard let this = self else {
OAuthSwift.retainError(completion)
return
}
switch result {
case .success(let response):
let responseJSON: Any? = try? response.jsonObject(options: .mutableContainers)
let responseParameters: OAuthSwift.Parameters
if let jsonDico = responseJSON as? [String: Any] {
responseParameters = jsonDico
} else {
responseParameters = response.string?.parametersFromQueryString ?? [:]
}
guard let accessToken = responseParameters["access_token"] as? String else {
let message = NSLocalizedString("Could not get Access Token", comment: "Due to an error in the OAuth2 process, we couldn't get a valid token.")
completion(.failure(.serverError(message: message)))
return
}
if let refreshToken = responseParameters["refresh_token"] as? String {
this.client.credential.oauthRefreshToken = refreshToken.safeStringByRemovingPercentEncoding
}
if let expiresIn = responseParameters["expires_in"] as? String, let offset = Double(expiresIn) {
this.client.credential.oauthTokenExpiresAt = Date(timeInterval: offset, since: Date())
} else if let expiresIn = responseParameters["expires_in"] as? Double {
this.client.credential.oauthTokenExpiresAt = Date(timeInterval: expiresIn, since: Date())
}
this.client.credential.oauthToken = accessToken.safeStringByRemovingPercentEncoding
completion(.success((this.client.credential, response, responseParameters)))
case .failure(let error):
completion(.failure(error))
}
}
guard let accessTokenUrl = accessTokenUrl else {
let message = NSLocalizedString("access token url not defined", comment: "access token url not defined with code type auth")
completion(.failure(.configurationError(message: message)))
return nil
}
if self.contentType == "multipart/form-data" {
// Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token.
return self.client.postMultiPartRequest(accessTokenUrl, method: .POST, parameters: parameters, headers: headers, checkTokenExpiration: false, completionHandler: completionHandler)
} else {
// special headers
var finalHeaders: OAuthSwift.Headers? = headers
if accessTokenBasicAuthentification {
let authentification = "\(self.consumerKey):\(self.consumerSecret)".data(using: String.Encoding.utf8)
if let base64Encoded = authentification?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) {
finalHeaders += ["Authorization": "Basic \(base64Encoded)"] as OAuthSwift.Headers
}
}
// Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token.
return self.client.request(accessTokenUrl, method: .POST, parameters: parameters, headers: finalHeaders, checkTokenExpiration: false, completionHandler: completionHandler)
}
}
/**
Convenience method to start a request that must be authorized with the previously retrieved access token.
Since OAuth 2 requires support for the access token refresh mechanism, this method will take care to automatically
refresh the token if needed such that the developer only has to be concerned about the outcome of the request.
- parameter url: The url for the request.
- parameter method: The HTTP method to use.
- parameter parameters: The request's parameters.
- parameter headers: The request's headers.
- parameter renewHeaders: The request's headers if renewing. If nil, the `headers`` are used when renewing.
- parameter body: The request's HTTP body.
- parameter onTokenRenewal: Optional callback triggered in case the access token renewal was required in order to properly authorize the request.
- parameter success: The success block. Takes the successfull response and data as parameter.
- parameter failure: The failure block. Takes the error as parameter.
*/
@discardableResult
open func startAuthorizedRequest(_ url: URLConvertible, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, renewHeaders: OAuthSwift.Headers? = nil, body: Data? = nil, onTokenRenewal: TokenRenewedHandler? = nil, completionHandler completion: @escaping OAuthSwiftHTTPRequest.CompletionHandler) -> OAuthSwiftRequestHandle? {
let completionHandler: OAuthSwiftHTTPRequest.CompletionHandler = { result in
switch result {
case .success:
completion(result)
case .failure(let error): // map/recovery error
switch error {
case OAuthSwiftError.tokenExpired:
let renewCompletionHandler: TokenCompletionHandler = { result in
switch result {
case .success(let credential, _, _):
// Ommit response parameters so they don't override the original ones
// We have successfully renewed the access token.
// If provided, fire the onRenewal closure
if let renewalCallBack = onTokenRenewal {
renewalCallBack(.success(credential))
}
// Reauthorize the request again, this time with a brand new access token ready to be used.
_ = self.startAuthorizedRequest(url, method: method, parameters: parameters, headers: headers, body: body, onTokenRenewal: onTokenRenewal, completionHandler: completion)
case .failure(let error):
completion(.failure(error))
}
}
_ = self.renewAccessToken(withRefreshToken: self.client.credential.oauthRefreshToken, headers: renewHeaders ?? headers, completionHandler: renewCompletionHandler)
default:
completion(.failure(error))
}
}
}
// build request
return self.client.request(url, method: method, parameters: parameters, headers: headers, body: body, completionHandler: completionHandler)
}
// OAuth 2.0 Specification: https://tools.ietf.org/html/draft-ietf-oauth-v2-13#section-4.3
@discardableResult
open func authorize(username: String, password: String, scope: String?, headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) -> OAuthSwiftRequestHandle? {
var parameters = OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["username"] = username
parameters["password"] = password
parameters["grant_type"] = "password"
if let scope = scope {
parameters["scope"] = scope
}
return requestOAuthAccessToken(
withParameters: parameters,
headers: headers,
completionHandler: completion
)
}
@discardableResult
open func authorize(deviceToken deviceCode: String, grantType: String = "http://oauth.net/grant_type/device/1.0", completionHandler completion: @escaping TokenCompletionHandler) -> OAuthSwiftRequestHandle? {
var parameters = OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["code"] = deviceCode
parameters["grant_type"] = grantType
return requestOAuthAccessToken(
withParameters: parameters,
completionHandler: completion
)
}
/// use RFC7636 PKCE credentials - convenience method
@discardableResult
open func authorize(withCallbackURL url: URLConvertible, scope: String, state: String, codeChallenge: String, codeChallengeMethod: String = "S256", codeVerifier: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) -> OAuthSwiftRequestHandle? {
guard let callbackURL = url.url else {
completion(.failure(.encodingError(urlString: url.string)))
return nil
}
// remember code_verifier
self.codeVerifier = codeVerifier
// PKCE - extra parameter
var pkceParameters = Parameters()
pkceParameters["code_challenge"] = codeChallenge
pkceParameters["code_challenge_method"] = codeChallengeMethod
return authorize(withCallbackURL: callbackURL, scope: scope, state: state, parameters: parameters + pkceParameters, headers: headers, completionHandler: completion)
}
}
| 52.176316 | 383 | 0.650628 |
0a47d481fd3e423450df34d7fabcaf6da3392743 | 1,495 | import Foundation
import MapKit
import RxSwift
import RxCocoa
extension MKMapView: HasDelegate {}
class RxMKMapViewDelegateProxy: DelegateProxy<MKMapView, MKMapViewDelegate>, DelegateProxyType, MKMapViewDelegate {
weak public private(set) var mapView: MKMapView?
public init(mapView: ParentObject) {
self.mapView = mapView
super.init(parentObject: mapView, delegateProxy: RxMKMapViewDelegateProxy.self)
}
static func registerKnownImplementations() {
register { RxMKMapViewDelegateProxy(mapView: $0) }
}
}
public extension Reactive where Base: MKMapView {
var delegate: DelegateProxy<MKMapView, MKMapViewDelegate> {
RxMKMapViewDelegateProxy.proxy(for: base)
}
func setDelegate(_ delegate: MKMapViewDelegate) -> Disposable {
RxMKMapViewDelegateProxy.installForwardDelegate(
delegate,
retainDelegate: false,
onProxyForObject: self.base
)
}
var overlay: Binder<MKOverlay> {
Binder(base) { mapView, overlay in
mapView.removeOverlays(mapView.overlays)
mapView.addOverlay(overlay)
}
}
var regionDidChangeAnimated: ControlEvent<Bool> {
let source = delegate
.methodInvoked(#selector(MKMapViewDelegate.mapView(_:regionDidChangeAnimated:)))
.map { parameters in
return (parameters[1] as? Bool) ?? false
}
return ControlEvent(events: source)
}
}
| 27.685185 | 115 | 0.672241 |
297015e885d2f31311e5fe2798864dc105f762a1 | 857 | import UIKit
import QuartzCore
import SceneKit
class InputViewController: UIViewController {
@IBOutlet weak var inputField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated:Bool) {
super.viewWillAppear(animated)
inputField.becomeFirstResponder()
}
@IBAction func endInput(_ sender: Any) {
if let txt = inputField.text {
player.name = txt
player.needUpdateName = true
self.dismiss(animated: true)
lockAllInteraction = false
write()
}
}
@IBAction func inputChanged(_ sender: Any) {
if var txt = inputField.text {
while(txt.count > 15){
txt = String(txt.dropLast())
inputField.text = txt
}
}
}
}
| 27.645161 | 51 | 0.583431 |
f52197b6a7fe3f994fa99fed82c5a4ac307d6a8d | 797 | //
// DecimalFormatter.swift
// mandayFaktura
//
// Created by Wojciech Kicior on 14.02.2018.
// Copyright © 2018 Wojciech Kicior. All rights reserved.
//
import Foundation
extension Decimal {
func formatAmount() -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = ""
return formatter.string(from: self as NSDecimalNumber)!.trimmingCharacters(in: .whitespaces)
}
func formatDecimal() -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.currencyDecimalSeparator = ","
formatter.currencyGroupingSeparator = " "
return formatter.string(from: self as NSDecimalNumber)!.trimmingCharacters(in: .whitespaces)
}
}
| 29.518519 | 100 | 0.678795 |
16e274bf3a79797cbc439be5603bfa8b20bcc766 | 844 | //
// LoginServicesRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 04/04/18.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
// DOCS: https://rocket.chat/docs/developer-guides/rest-api/miscellaneous/info
import SwiftyJSON
import RealmSwift
class LoginServicesRequest: APIRequest {
typealias APIResourceType = LoginServicesResource
let requiredVersion: Version = Version(0, 64, 0)
let path = "/api/v1/settings.oauth"
}
class LoginServicesResource: APIResource {
var loginServices: [LoginService] {
return raw?["services"].arrayValue.compactMap {
let service = LoginService()
service.map($0, realm: nil)
guard service.isValid, service.service != nil else {
return nil
}
return service
} ?? []
}
}
| 24.823529 | 79 | 0.646919 |
f5598cbf0c08f12e225766a49804b921d507b3f5 | 2,202 | //
// AppDelegate.swift
// PoseEstimation-CoreML
//
// Created by Fazle Rabbi Linkon on 22/11/2020.
// Copyright © 2020 Fazle Rabbi Linkon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.851064 | 285 | 0.756585 |
e97b5bc24576cce7cceddba5d0dcefb1b278634c | 3,390 | /*
Erica Sadun, http://ericasadun.com
Cross Platform Defines: Image Renderer
Apple Platforms Only
*/
#if canImport(Cocoa)
import Cocoa
#elseif canImport(UIKit)
import UIKit
#endif
#if canImport(Cocoa)
typealias CocoaImage = NSImage
typealias CocoaColor = NSColor
#elseif canImport(UIKit)
typealias CocoaImage = UIImage
typealias CocoaColor = UIColor
#endif
#if canImport(Cocoa)
final class CocoaGraphicsImageRendererFormat: NSObject {
public var opaque: Bool = false
public var prefersExtendedRange: Bool = false
public var scale: CGFloat = 2.0
public var bounds: CGRect = .zero
}
#elseif canImport(UIKit)
typealias CocoaGraphicsImageRendererFormat = UIGraphicsImageRendererFormat
#endif
#if canImport(Cocoa)
final class CocoaGraphicsImageRendererContext: NSObject {
var format: CocoaGraphicsImageRendererFormat
var cgContext: CGContext {
guard let context = NSGraphicsContext.current?.cgContext else {
fatalError("Unavailable cgContext while drawing")
}
return context
}
func clip(to rect: CGRect) {
cgContext.clip(to: rect)
}
func fill(_ rect: CGRect) {
cgContext.fill(rect)
}
func fill(_ rect: CGRect, blendMode: CGBlendMode) {
NSGraphicsContext.saveGraphicsState()
cgContext.setBlendMode(blendMode)
cgContext.fill(rect)
NSGraphicsContext.restoreGraphicsState()
}
func stroke(_ rect: CGRect) {
cgContext.stroke(rect)
}
func stroke(_ rect: CGRect, blendMode: CGBlendMode) {
NSGraphicsContext.saveGraphicsState()
cgContext.setBlendMode(blendMode)
cgContext.stroke(rect)
NSGraphicsContext.restoreGraphicsState()
}
override init() {
self.format = CocoaGraphicsImageRendererFormat()
super.init()
}
var currentImage: NSImage {
guard let cgImage = cgContext.makeImage() else {
fatalError("Cannot retrieve cgImage from current context")
}
return NSImage(cgImage: cgImage, size: format.bounds.size)
}
}
#elseif canImport(UIKit)
typealias CocoaGraphicsImageRendererContext = UIGraphicsImageRendererContext
#endif
#if canImport(Cocoa)
final class CocoaGraphicsImageRenderer: NSObject {
var allowsImageOutput: Bool = true
let format: CocoaGraphicsImageRendererFormat
let bounds: CGRect
init(bounds: CGRect, format: CocoaGraphicsImageRendererFormat) {
self.bounds = bounds
self.format = format
self.format.bounds = self.bounds
super.init()
}
convenience init(size: CGSize, format: CocoaGraphicsImageRendererFormat) {
self.init(bounds: CGRect(origin: .zero, size: size), format: format)
}
convenience init(size: CGSize) {
self.init(bounds: CGRect(origin: .zero, size: size), format: CocoaGraphicsImageRendererFormat())
}
public func image(actions: @escaping (CocoaGraphicsImageRendererContext) -> Void) -> NSImage {
let image = NSImage(size: format.bounds.size, flipped: false) { (drawRect: NSRect) -> Bool in
let imageContext = CocoaGraphicsImageRendererContext()
imageContext.format = self.format
actions(imageContext)
return true
}
return image
}
}
#elseif canImport(UIKit)
typealias CocoaGraphicsImageRenderer = UIGraphicsImageRenderer
#endif
| 26.484375 | 104 | 0.696165 |
bb9836a7476d199dcd7d34e61f058a8ea02769bd | 4,149 | // Copyright 2022 Pera Wallet, LDA
// 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.
// CollectibleDetailOptedInActionViewTheme.swift
import MacaroonUIKit
struct CollectibleDetailOptedInActionViewTheme:
StyleSheet,
LayoutSheet {
let title: TextStyle
let subtitle: TextStyle
let optOut: ButtonStyle
let optedInTitle: TextStyle
let separator: ViewStyle
let topInset: LayoutMetric
let subtitleTopOffset: LayoutMetric
let buttonTopInset: LayoutMetric
let buttonBottomInset: LayoutMetric
let accountShareTopInset: LayoutMetric
let optedInTitleHeight: LayoutMetric
let accountShareHeight: LayoutMetric
let accountShareBottomInset: LayoutMetric
let separatorHorizontalInset: LayoutMetric
let actionContentEdgeInsets: LayoutPaddings
let actionCorner: Corner
let buttonHeight: LayoutMetric
let separatorHeight: LayoutMetric
init(
_ family: LayoutFamily
) {
title = [
.textOverflow(FittingText()),
.textAlignment(.left),
.textColor(AppColors.Components.Text.gray)
]
subtitle = [
.textOverflow(FittingText()),
.textAlignment(.left),
.textColor(AppColors.Components.Text.main)
]
optedInTitle = [
.textOverflow(FittingText()),
.textAlignment(.left),
.textColor(AppColors.Components.Text.main),
.text(Self.getOptedInTitle("collectible-detail-opted-in"))
]
actionContentEdgeInsets = (14, 0, 14, 0)
actionCorner = Corner(radius: 4)
optOut = [
.title(Self.getActionTitle("collectible-detail-opt-out")),
.titleColor(
[ .normal(AppColors.Components.Button.Secondary.text)]
),
.backgroundColor(AppColors.Components.Button.Secondary.background),
.icon([.normal("icon-trash-24")])
]
separator = [
.backgroundColor(AppColors.Shared.Layer.grayLighter)
]
topInset = 24
subtitleTopOffset = 4
buttonTopInset = 28
buttonBottomInset = 40
optedInTitleHeight = 28
accountShareHeight = 64
accountShareTopInset = 16
accountShareBottomInset = 28
separatorHorizontalInset = -24
buttonHeight = 52
separatorHeight = 1
}
}
extension CollectibleDetailOptedInActionViewTheme {
private static func getOptedInTitle(
_ aTitle: String
) -> EditText {
let font = Fonts.DMSans.medium.make(19)
let lineHeightMultiplier = 1.13
return .attributedString(
aTitle
.localized
.attributed([
.font(font),
.lineHeightMultiplier(lineHeightMultiplier, font),
.paragraph([
.lineBreakMode(.byWordWrapping),
.lineHeightMultiple(lineHeightMultiplier)
])
])
)
}
private static func getActionTitle(
_ aTitle: String
) -> EditText {
let font = Fonts.DMSans.medium.make(15)
let lineHeightMultiplier = 1.23
return .attributedString(
aTitle
.localized
.attributed([
.font(font),
.lineHeightMultiplier(lineHeightMultiplier, font),
.paragraph([
.lineBreakMode(.byWordWrapping),
.lineHeightMultiple(lineHeightMultiplier)
])
])
)
}
}
| 31.431818 | 79 | 0.607375 |
69dea776a62e73717e909ae6b2dcbe4c6f301808 | 2,775 | // RUN: %target-parse-verify-swift
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | %FileCheck %s
struct S<T> {}
// Specialize freestanding functions with the correct number of concrete types.
// ----------------------------------------------------------------------------
// CHECK: @_specialize(Int)
@_specialize(Int)
// CHECK: @_specialize(S<Int>)
@_specialize(S<Int>)
@_specialize(Int, Int) // expected-error{{generic type 'oneGenericParam' specialized with too many type parameters (got 2, but expected 1)}},
@_specialize(T) // expected-error{{use of undeclared type 'T'}}
public func oneGenericParam<T>(_ t: T) -> T {
return t
}
// CHECK: @_specialize(Int, Int)
@_specialize(Int, Int)
@_specialize(Int) // expected-error{{generic type 'twoGenericParams' specialized with too few type parameters (got 1, but expected 2)}},
public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) {
return (t, u)
}
// Specialize contextual types.
// ----------------------------
class G<T> {
// CHECK: @_specialize(Int)
@_specialize(Int)
@_specialize(T) // expected-error{{cannot partially specialize a generic function}}
@_specialize(S<T>) // expected-error{{cannot partially specialize a generic function}}
@_specialize(Int, Int) // expected-error{{generic type 'noGenericParams' specialized with too many type parameters (got 2, but expected 1)}}
func noGenericParams() {}
// CHECK: @_specialize(Int, Float)
@_specialize(Int, Float)
// CHECK: @_specialize(Int, S<Int>)
@_specialize(Int, S<Int>)
@_specialize(Int) // expected-error{{generic type 'oneGenericParam' specialized with too few type parameters (got 1, but expected 2)}},
func oneGenericParam<U>(_ t: T, u: U) -> (U, T) {
return (u, t)
}
}
// Specialize with requirements.
// -----------------------------
protocol Thing {}
struct AThing : Thing {}
// CHECK: @_specialize(AThing)
@_specialize(AThing)
@_specialize(Int) // expected-error{{argument type 'Int' does not conform to expected type 'Thing'}}
func oneRequirement<T : Thing>(_ t: T) {}
protocol HasElt {
associatedtype Element
}
struct IntElement : HasElt {
typealias Element = Int
}
struct FloatElement : HasElt {
typealias Element = Float
}
@_specialize(FloatElement)
@_specialize(IntElement) // expected-error{{'<T : HasElt where T.Element == Float> (T) -> ()' requires the types 'IntElement.Element' (aka 'Int') and 'Float' be equivalent}}
func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {}
class Base {}
class Sub : Base {}
class NonSub {}
@_specialize(Sub)
@_specialize(NonSub) // expected-error{{'<T : Base> (T) -> ()' requires that 'NonSub' inherit from 'Base'}}
func superTypeRequirement<T : Base>(_ t: T) {}
| 35.576923 | 173 | 0.668108 |
6a75ef0b6c9d9766e905005bf5d7268644a7fe19 | 1,571 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
extension SFSymbol {
public static var l1: L1 { .init(name: "l1") }
open class L1: SFSymbol {
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var rectangleRoundedbottom: SFSymbol { ext(.start.rectangle + ".roundedbottom") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var rectangleRoundedbottomFill: SFSymbol { ext(.start.rectangle + ".roundedbottom".fill) }
}
} | 47.606061 | 97 | 0.744112 |
6aab75e266e1b4ca8d71b2405543519d0209f046 | 2,529 | //
// Created by Andrew Podkovyrin
// Copyright © 2020 Andrew Podkovyrin. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
protocol DeepLAPI {
func fetchLanguages(completion: @escaping (Result<[Language], NetworkError>) -> Void) -> CancellationToken
func translate(text: String,
source: Language?,
target: Language,
completion: @escaping (Result<TranslationResponse, NetworkError>) -> Void) -> CancellationToken
}
enum APIRouter {
case languages
case translate
static var baseURL: URL {
URL(string: "https://api.deepl.com/v2")!
}
var url: URL {
switch self {
case .languages:
return Self.baseURL.appendingPathComponent("languages")
case .translate:
return Self.baseURL.appendingPathComponent("translate")
}
}
}
final class APIClient<T: Transport>: DeepLAPI {
private let session: Session<T>
init(authKey: String, transport: T) {
session = Session(transport: transport, authenticateRequest: { request in
request.parameters["auth_key"] = authKey
})
}
func fetchLanguages(completion: @escaping (Result<[Language], NetworkError>) -> Void) -> CancellationToken {
let request = PostRequest(url: APIRouter.languages.url)
return session.post(request: request, completion: completion)
}
func translate(text: String,
source: Language?,
target: Language,
completion: @escaping (Result<TranslationResponse, NetworkError>) -> Void) -> CancellationToken {
var parameters = [
"text": text,
"target_lang": target.code,
]
if let source = source {
parameters["source_lang"] = source.code
}
let request = PostRequest(url: APIRouter.translate.url, parameters: parameters)
return session.post(request: request, completion: completion)
}
}
| 33.276316 | 116 | 0.645314 |
6998e8d018ed13e6d2780d0921e2928045ce19e2 | 2,085 | //
// AppDelegate.swift
// ObjectAR
//
// Created by Jake Oddi on 3/9/22.
//
import UIKit
import SwiftUI
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
}
| 41.7 | 285 | 0.741487 |
1699960a11372ededaff02964f88c22cf5fa8d82 | 770 | //
// DateExtensions.swift
// CoinDeskApp
//
// Created by Vladimir Abramichev on 29/07/2018.
// Copyright © 2018 Vladimir Abramichev. All rights reserved.
//
import Foundation
extension Date {
func formar(_ format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.string(from: self)
}
init?(format: String, value: String) {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = Locale(identifier: "en_US_POSIX")
if let date = formatter.date(from: value) {
self = date
} else {
return nil
}
}
}
| 24.0625 | 62 | 0.603896 |
d623163af134cbcd7fbb16799c5c3a146bc2eb8e | 1,407 | import XCTest
@testable import SimpleRx
final class PublishRelayTests: XCTestCase {
func test_basic() {
var c = 0
let p = PublishRelay<Int>()
let o = p.asObservable()
o.subscribe { (v) in
c += 1
print("sub1: \(v)")
}
p.accept(0)
XCTAssertEqual(c, 1)
o.subscribe { (v) in
c += 1
print("sub2: \(v)")
}
p.accept(10)
XCTAssertEqual(c, 3)
}
func test_deinit() {
var c = 0
var p: PublishRelay<Int>? = PublishRelay<Int>()
p?.subscribe(onNext: { (v) in
c += 1
print("sub1: \(v)")
})
p?.accept(2)
XCTAssertEqual(c, 1)
p = nil
p?.accept(3)
XCTAssertEqual(c, 1)
}
func test_thread() {
let exp = XCTestExpectation()
XCTAssertTrue(Thread.isMainThread)
var c = 0
let p = PublishRelay<Int>()
p.subscribe { (v) in
c += 1
XCTAssertFalse(Thread.isMainThread)
exp.fulfill()
}
DispatchQueue.global(qos: .userInteractive).async {
p.accept(0)
}
wait(for: [exp], timeout: 1)
XCTAssertEqual(c, 1)
}
static var allTests = [
("testBasic", test_basic),
("testDeinit", test_deinit),
("testThread", test_thread),
]
}
| 23.847458 | 59 | 0.479033 |
908b18d36beff59e3f2630f83e6b364ff8e9a36c | 13,250 | //
// CombineTests.swift
//
import XCTest
import Chaining
class CombineTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testEachFetchable() {
// メインとサブが両方Fetchableの場合
let main = ValueHolder<Int>(1)
let sub = ValueHolder<String>("2")
var received: [(Int, String)] = []
let observer =
main.chain().combine(sub.chain())
.do { received.append($0) }
.sync()
// syncだけで両方送られてdoが呼ばれる
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 1)
XCTAssertEqual(received[0].1, "2")
observer.invalidate()
}
func testMainFetchable() {
// メインのみFetchableの場合
let main = ValueHolder<Int>(1)
let sub = Notifier<String>()
var received: [(Int, String)] = []
let observer =
main.chain().combine(sub.chain())
.do { received.append($0) }
.sync()
// syncではメインからのみ送信
XCTAssertEqual(received.count, 0)
sub.notify(value: "2")
// サブからも送られてdoが呼ばれる
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 1)
XCTAssertEqual(received[0].1, "2")
observer.invalidate()
}
func testSubFetchable() {
// サブのみFetchableの場合
let main = Notifier<Int>()
let sub = ValueHolder<String>("1")
var received: [(Int, String)] = []
let observer =
main.chain().combine(sub.chain())
.do { received.append($0) }
.sync()
// syncではサブからのみ送信
XCTAssertEqual(received.count, 0)
main.notify(value: 2)
// メインからも送られてdoが呼ばれる
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 2)
XCTAssertEqual(received[0].1, "1")
observer.invalidate()
}
func testNoFetchable() {
// 両方Fetchableでない場合
let main = Notifier<Int>()
let sub = Notifier<String>()
var received: [(Int, String)] = []
let observer =
main.chain().combine(sub.chain())
.do { received.append($0) }
.end()
// まだどちらからも送信されていない
XCTAssertEqual(received.count, 0)
main.notify(value: 1)
// メインからのみ送信されているので止まっている
XCTAssertEqual(received.count, 0)
sub.notify(value: "2")
// サブからも送信されたのでdoが呼ばれる
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 1)
XCTAssertEqual(received[0].1, "2")
observer.invalidate()
}
func testTuple2() {
let holder0 = ValueHolder(0)
let holder1 = ValueHolder(1)
let holder2 = ValueHolder(2)
let notifier0 = Notifier<Int>()
let notifier1 = Notifier<Int>()
let notifier2 = Notifier<Int>()
do {
var received: [(Int, Int, Int)] = []
let observer =
holder0.chain()
.combine(holder1.chain())
.combine(holder2.chain())
.do { received.append($0) }
.sync()
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
observer.invalidate()
}
do {
var received: [(Int, Int, Int)] = []
let observer =
holder0.chain()
.combine(holder1.chain())
.combine(notifier2.chain())
.do { received.append($0) }
.sync()
XCTAssertEqual(received.count, 0)
notifier2.notify(value: 2)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
observer.invalidate()
}
do {
var received: [(Int, Int, Int)] = []
let observer =
notifier0.chain()
.combine(notifier1.chain())
.combine(holder2.chain())
.do { received.append($0) }
.sync()
notifier0.notify(value: 0)
XCTAssertEqual(received.count, 0)
notifier1.notify(value: 1)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
observer.invalidate()
}
do {
var received: [(Int, Int, Int)] = []
let observer =
notifier0.chain()
.combine(notifier1.chain())
.combine(notifier2.chain())
.do { received.append($0) }
.end()
notifier0.notify(value: 0)
notifier1.notify(value: 1)
XCTAssertEqual(received.count, 0)
notifier2.notify(value: 2)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
observer.invalidate()
}
}
func testTuple3() {
let holder0 = ValueHolder(0)
let holder1 = ValueHolder(1)
let holder2 = ValueHolder(2)
let holder3 = ValueHolder(3)
let notifier0 = Notifier<Int>()
let notifier1 = Notifier<Int>()
let notifier2 = Notifier<Int>()
let notifier3 = Notifier<Int>()
do {
var received: [(Int, Int, Int, Int)] = []
let observer = holder0.chain()
.combine(holder1.chain())
.combine(holder2.chain())
.combine(holder3.chain())
.do { received.append($0) }
.sync()
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
XCTAssertEqual(received[0].3, 3)
observer.invalidate()
}
do {
var received: [(Int, Int, Int, Int)] = []
let observer = holder0.chain()
.combine(holder1.chain())
.combine(holder2.chain())
.combine(notifier3.chain())
.do { received.append($0) }
.sync()
XCTAssertEqual(received.count, 0)
notifier3.notify(value: 3)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
XCTAssertEqual(received[0].3, 3)
observer.invalidate()
}
do {
var received: [(Int, Int, Int, Int)] = []
let observer = notifier0.chain()
.combine(notifier1.chain())
.combine(notifier2.chain())
.combine(holder3.chain())
.do { received.append($0) }
.sync()
notifier0.notify(value: 0)
notifier1.notify(value: 1)
XCTAssertEqual(received.count, 0)
notifier2.notify(value: 2)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
XCTAssertEqual(received[0].3, 3)
observer.invalidate()
}
do {
var received: [(Int, Int, Int, Int)] = []
let observer = notifier0.chain()
.combine(notifier1.chain())
.combine(notifier2.chain())
.combine(notifier3.chain())
.do { received.append($0) }
.end()
notifier0.notify(value: 0)
notifier1.notify(value: 1)
notifier2.notify(value: 2)
XCTAssertEqual(received.count, 0)
notifier3.notify(value: 3)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
XCTAssertEqual(received[0].3, 3)
observer.invalidate()
}
}
func testTuple4() {
let holder0 = ValueHolder(0)
let holder1 = ValueHolder(1)
let holder2 = ValueHolder(2)
let holder3 = ValueHolder(3)
let holder4 = ValueHolder(4)
let notifier0 = Notifier<Int>()
let notifier1 = Notifier<Int>()
let notifier2 = Notifier<Int>()
let notifier3 = Notifier<Int>()
let notifier4 = Notifier<Int>()
do {
var received: [(Int, Int, Int, Int, Int)] = []
let observer = holder0.chain()
.combine(holder1.chain())
.combine(holder2.chain())
.combine(holder3.chain())
.combine(holder4.chain())
.do { received.append($0) }
.sync()
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
XCTAssertEqual(received[0].3, 3)
XCTAssertEqual(received[0].4, 4)
observer.invalidate()
}
do {
var received: [(Int, Int, Int, Int, Int)] = []
let observer = holder0.chain()
.combine(holder1.chain())
.combine(holder2.chain())
.combine(holder3.chain())
.combine(notifier4.chain())
.do { received.append($0) }
.sync()
XCTAssertEqual(received.count, 0)
notifier4.notify(value: 4)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
XCTAssertEqual(received[0].3, 3)
XCTAssertEqual(received[0].4, 4)
observer.invalidate()
}
do {
var received: [(Int, Int, Int, Int, Int)] = []
let observer = notifier0.chain()
.combine(notifier1.chain())
.combine(notifier2.chain())
.combine(notifier3.chain())
.combine(holder4.chain())
.do { received.append($0) }
.sync()
notifier0.notify(value: 0)
notifier1.notify(value: 1)
notifier2.notify(value: 2)
XCTAssertEqual(received.count, 0)
notifier3.notify(value: 3)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
XCTAssertEqual(received[0].3, 3)
XCTAssertEqual(received[0].4, 4)
observer.invalidate()
}
do {
var received: [(Int, Int, Int, Int, Int)] = []
let observer = notifier0.chain()
.combine(notifier1.chain())
.combine(notifier2.chain())
.combine(notifier3.chain())
.combine(notifier4.chain())
.do { received.append($0) }
.end()
notifier0.notify(value: 0)
notifier1.notify(value: 1)
notifier2.notify(value: 2)
notifier3.notify(value: 3)
XCTAssertEqual(received.count, 0)
notifier4.notify(value: 4)
XCTAssertEqual(received.count, 1)
XCTAssertEqual(received[0].0, 0)
XCTAssertEqual(received[0].1, 1)
XCTAssertEqual(received[0].2, 2)
XCTAssertEqual(received[0].3, 3)
XCTAssertEqual(received[0].4, 4)
observer.invalidate()
}
}
}
| 29.909707 | 58 | 0.460075 |
f9cc49a74a85ce7b9051f1bba35a1ee076e01aae | 1,600 | //----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
/**
* specDomain: S19089 (C-0-T11555-S13940-A10429-S10430-S19089-cpt)
*/
public enum EPA_FdV_AUTHZ_RoleClassInactiveIngredient:Int,CustomStringConvertible
{
case IACT
case COLR
case FLVR
case PRSV
case STBL
static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_RoleClassInactiveIngredient?
{
return createWithString(value: node.stringValue!)
}
static func createWithString(value:String) -> EPA_FdV_AUTHZ_RoleClassInactiveIngredient?
{
var i = 0
while let item = EPA_FdV_AUTHZ_RoleClassInactiveIngredient(rawValue: i)
{
if String(describing: item) == value
{
return item
}
i += 1
}
return nil
}
public var stringValue : String
{
return description
}
public var description : String
{
switch self
{
case .IACT: return "IACT"
case .COLR: return "COLR"
case .FLVR: return "FLVR"
case .PRSV: return "PRSV"
case .STBL: return "STBL"
}
}
public func getValue() -> Int
{
return rawValue
}
func serialize(__parent:DDXMLNode)
{
__parent.stringValue = stringValue
}
}
| 21.621622 | 93 | 0.51375 |
f5231c8ae9fce02eead7fe79064512454ef515a7 | 3,574 | //===------------------------------------------------------------------------------------===//
//
// This source file is part of the SwiftTencentSCFRuntime open source project
//
// Copyright (c) 2020-2021 stevapple and the SwiftTencentSCFRuntime project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftTencentSCFRuntime project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===------------------------------------------------------------------------------------===//
//
// This source file was part of the SwiftAWSLambdaRuntime open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftAWSLambdaRuntime project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See http://github.com/swift-server/swift-aws-lambda-runtime/blob/main/CONTRIBUTORS.txt
// for the list of SwiftAWSLambdaRuntime project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===------------------------------------------------------------------------------------===//
import Logging
import NIOCore
import NIOPosix
@testable import TencentSCFRuntimeCore
import XCTest
func runSCF(behavior: SCFServerBehavior, handler: SCF.Handler) throws {
try runSCF(behavior: behavior, factory: { $0.eventLoop.makeSucceededFuture(handler) })
}
func runSCF(behavior: SCFServerBehavior, factory: @escaping SCF.HandlerFactory) throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer { XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully()) }
let logger = Logger(label: "TestLogger")
let configuration = SCF.Configuration(runtimeEngine: .init(requestTimeout: .milliseconds(100)))
let runner = SCF.Runner(eventLoop: eventLoopGroup.next(), configuration: configuration)
let server = try MockSCFServer(behavior: behavior).start().wait()
defer { XCTAssertNoThrow(try server.stop().wait()) }
try runner.initialize(logger: logger, factory: factory).flatMap { handler in
runner.run(logger: logger, handler: handler)
}.wait()
}
func assertSCFLifecycleResult(_ result: Result<Int, Error>, shoudHaveRun: Int = 0, shouldFailWithError: Error? = nil, file: StaticString = #file, line: UInt = #line) {
switch result {
case .success where shouldFailWithError != nil:
XCTFail("should fail with \(shouldFailWithError!)", file: file, line: line)
case .success(let count) where shouldFailWithError == nil:
XCTAssertEqual(shoudHaveRun, count, "should have run \(shoudHaveRun) times", file: file, line: line)
case .failure(let error) where shouldFailWithError == nil:
XCTFail("should succeed, but failed with \(error)", file: file, line: line)
case .failure(let error) where shouldFailWithError != nil:
XCTAssertEqual(String(describing: shouldFailWithError!), String(describing: error), "expected error to mactch", file: file, line: line)
default:
XCTFail("invalid state")
}
}
struct TestError: Error, Equatable, CustomStringConvertible {
let description: String
init(_ description: String) {
self.description = description
}
}
extension Date {
internal var millisSinceEpoch: Int64 {
Int64(self.timeIntervalSince1970 * 1000)
}
}
extension SCF.RuntimeError: Equatable {
public static func == (lhs: SCF.RuntimeError, rhs: SCF.RuntimeError) -> Bool {
// technically incorrect, but good enough for our tests
String(describing: lhs) == String(describing: rhs)
}
}
| 41.55814 | 167 | 0.673475 |
f5617db4e170995edab286fcb1e303d3b16cd945 | 7,728 | // Copyright 2020, OpenTelemetry Authors
//
// 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
/// A struct that represents a trace identifier. A valid trace identifier is a 16-byte array with at
/// least one non-zero byte.
public struct TraceId: Comparable, Hashable, CustomStringConvertible, Equatable {
private static let size = 16
public static let invalidId: UInt64 = 0
public static let invalid = TraceId()
// The internal representation of the TraceId.
var idHi: UInt64 = invalidId
var idLo: UInt64 = invalidId
/// Constructs a TraceId whose representation is specified by two long values representing
/// the lower and higher parts.
/// There is no restriction on the specified values, other than the already established validity
/// rules applying to TraceId. Specifying 0 for both values will effectively make the new
/// TraceId invalid.
/// This is equivalent to calling fromBytes() with the specified values
/// stored as big-endian.
/// - Parameters:
/// - idHi: the higher part of the TraceId
/// - idLo: the lower part of the TraceId
public init(idHi: UInt64, idLo: UInt64) {
self.idHi = idHi
self.idLo = idLo
}
/// Returns an invalid TraceId. All bytes are '\0'.
public init() {
}
/// Generates a new random TraceId.
public static func random() -> TraceId {
var idHi: UInt64
var idLo: UInt64
repeat {
idHi = UInt64.random(in: .min ... .max)
idLo = UInt64.random(in: .min ... .max)
} while idHi == TraceId.invalidId && idLo == TraceId.invalidId
return TraceId(idHi: idHi, idLo: idLo)
}
/// Returns a TraceId whose representation is copied from the src beginning at the offset.
/// - Parameter data: the data where the representation of the TraceId is copied.
public init(fromData data: Data) {
var idHi: UInt64 = 0
var idLo: UInt64 = 0
data.withUnsafeBytes { rawPointer -> Void in
idHi = rawPointer.load(fromByteOffset: data.startIndex, as: UInt64.self).bigEndian
idLo = rawPointer.load(fromByteOffset: data.startIndex + MemoryLayout<UInt64>.size, as: UInt64.self).bigEndian
}
self.init(idHi: idHi, idLo: idLo)
}
/// Returns a TraceId whose representation is copied from the src beginning at the offset.
/// - Parameter data: the byte array from where the representation of the TraceId is copied.
public init(fromBytes bytes: Array<UInt8>) {
self.init(fromData: Data(bytes))
}
/// Returns a TraceId whose representation is copied from the src beginning at the offset.
/// - Parameter data: the byte array slice from where the representation of the TraceId is copied.
public init(fromBytes bytes: ArraySlice<UInt8>) {
self.init(fromData: Data(bytes))
}
/// Returns a TraceId whose representation is copied from the src beginning at the offset.
/// - Parameter data: the char array from where the representation of the TraceId is copied.
public init(fromBytes bytes: ArraySlice<Character>) {
self.init(fromData: Data(String(bytes).utf8.map { UInt8($0) }))
}
/// Copies the byte array representations of the TraceId into the dest beginning at
/// the offset.
/// - Parameters:
/// - dest: the destination buffer.
/// - destOffset: the starting offset in the destination buffer.
public func copyBytesTo(dest: inout Data, destOffset: Int) {
dest.replaceSubrange(destOffset ..< destOffset + MemoryLayout<UInt64>.size,
with: withUnsafeBytes(of: idHi.bigEndian) { Array($0) })
dest.replaceSubrange(destOffset + MemoryLayout<UInt64>.size ..< destOffset + MemoryLayout<UInt64>.size * 2,
with: withUnsafeBytes(of: idLo.bigEndian) { Array($0) })
}
/// Copies the byte array representations of the TraceId into the dest beginning at
/// the offset.
/// - Parameters:
/// - dest: the destination buffer.
/// - destOffset: the starting offset in the destination buffer.
public func copyBytesTo(dest: inout Array<UInt8>, destOffset: Int) {
dest.replaceSubrange(destOffset ..< destOffset + MemoryLayout<UInt64>.size,
with: withUnsafeBytes(of: idHi.bigEndian) { Array($0) })
dest.replaceSubrange(destOffset + MemoryLayout<UInt64>.size ..< destOffset + MemoryLayout<UInt64>.size * 2,
with: withUnsafeBytes(of: idLo.bigEndian) { Array($0) })
}
/// Copies the byte array representations of the TraceId into the dest beginning at
/// the offset.
/// - Parameters:
/// - dest: the destination buffer.
/// - destOffset: the starting offset in the destination buffer.
public func copyBytesTo(dest: inout ArraySlice<UInt8>, destOffset: Int) {
dest.replaceSubrange(destOffset ..< destOffset + MemoryLayout<UInt64>.size,
with: withUnsafeBytes(of: idHi.bigEndian) { Array($0) })
dest.replaceSubrange(destOffset + MemoryLayout<UInt64>.size ..< destOffset + MemoryLayout<UInt64>.size * 2,
with: withUnsafeBytes(of: idLo.bigEndian) { Array($0) })
}
/// Returns a TraceId built from a lowercase base16 representation.
/// - Parameters:
/// - hex: the lowercase base16 representation.
/// - offset: the offset in the buffer where the representation of the TraceId begins.
public init(fromHexString hex: String, withOffset offset: Int = 0) {
let firstIndex = hex.index(hex.startIndex, offsetBy: offset)
let secondIndex = hex.index(firstIndex, offsetBy: 16)
let thirdIndex = hex.index(secondIndex, offsetBy: 16)
guard hex.count >= 32 + offset,
let idHi = UInt64(hex[firstIndex ..< secondIndex], radix: 16),
let idLo = UInt64(hex[secondIndex ..< thirdIndex], radix: 16) else {
self.init()
return
}
self.init(idHi: idHi, idLo: idLo)
}
/// Returns whether the TraceId is valid. A valid trace identifier is a 16-byte array with
/// at least one non-zero byte.
public var isValid: Bool {
return idHi != TraceId.invalidId || idLo != TraceId.invalidId
}
/// Returns the lowercase base16 encoding of this TraceId.
public var hexString: String {
return String(format: "%016llx%016llx", idHi, idLo)
}
/// Returns the lower 8 bytes of the trace-id as a long value, assuming little-endian order. This
/// is used in ProbabilitySampler.
public var lowerLong: UInt64 {
return idHi
}
public var description: String {
return "TraceId{traceId=\(hexString)}"
}
public static func < (lhs: TraceId, rhs: TraceId) -> Bool {
if lhs.idHi < rhs.idHi {
return true
} else if lhs.idHi == rhs.idHi && lhs.idLo < rhs.idLo {
return true
} else {
return false
}
}
public static func == (lhs: TraceId, rhs: TraceId) -> Bool {
return lhs.idHi == rhs.idHi && lhs.idLo == rhs.idLo
}
}
| 43.41573 | 122 | 0.648551 |
9b2cade6ae5ea64a2061ff6f0db003e229e0bb84 | 892 | //
// JXLookTests.swift
// JXLookTests
//
// Created by Yung-Luen Lan on 2021/1/18.
//
import XCTest
@testable import JXLook
class JXLookTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.235294 | 111 | 0.660314 |
715eee05756285557030c6d31e4d90b8ecc32daa | 1,186 | //
// UIViewController.swift
// Evento
//
// Created by Олег on 24.12.2020.
// Copyright © 2020 Oleg Ben. All rights reserved.
//
import UIKit
enum StoryboardsEnum: String {
case EventsListVC = "EventsListVC"
}
extension NSObject {
class var nameOfClass: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
extension UIViewController {
private class func instantiateControllerInStoryboard<T: UIViewController>(_ storyboard: UIStoryboard, identifier: String) -> T {
return storyboard.instantiateViewController(withIdentifier: identifier) as! T
}
class func controllerInStoryboard(_ storyboard: UIStoryboard, identifier: String) -> Self {
return instantiateControllerInStoryboard(storyboard, identifier: identifier)
}
class func controllerInStoryboard(_ storyboard: UIStoryboard) -> Self {
return controllerInStoryboard(storyboard, identifier: nameOfClass)
}
class func controllerFromStoryboard(_ storyboard: StoryboardsEnum) -> Self {
return controllerInStoryboard(UIStoryboard(name: storyboard.rawValue, bundle: nil), identifier: nameOfClass)
}
}
| 30.410256 | 132 | 0.724283 |
22a07dab0bcc74a9ff32559554294582d5839596 | 402 | import Foundation
@available(iOS 15.4, macOS 12.3, tvOS 15.4, watchOS 8.5, *)
public extension SFSymbol {
static var allSymbols15P4: [SFSymbol] {
return [
.cameraMacro,
.cameraMacroCircle,
.cameraMacroCircleFill,
.dotsAndLineVerticalAndCursorarrowRectangle,
.keyViewfinder,
.personBadgeKey,
.personBadgeKeyFill
]
}
} | 23.647059 | 59 | 0.624378 |
20885012f954c5d6a76479d3ccbae5c2f13c4351 | 273 | import XCTest
@testable import SwiftCLITests
XCTMain([
testCase(CommandArgumentsTests.allTests),
testCase(CommandMessageGeneratorTests.allTests),
testCase(OptionsTests.allTests),
testCase(RouterTests.allTests),
testCase(SwiftCLITests.allTests)
])
| 24.818182 | 53 | 0.772894 |
64145b5d1b4d0e3b74e66aeb80437d64a97ab518 | 747 | //
// WatchInsectDetailView.swift
// watchOS-Cross-Platform Extension
//
// Created by Edgar Nzokwe on 6/16/20.
// Copyright © 2020 Edgar Nzokwe. All rights reserved.
//
import SwiftUI
struct WatchInsectDetailView: View {
var insect:Insect
var body: some View {
VStack{
Text(insect.name)
Image(insect.imageName)
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(Circle())
HStack {
Text("Habitat")
Text(insect.habitat)
}
}
}
}
struct WatchInsectDetailView_Previews: PreviewProvider {
static var previews: some View {
WatchInsectDetailView(insect: testInsect)
}
}
| 22.636364 | 56 | 0.579652 |
56c3fd19b38658162fbabc2d836c791a3a1cec4d | 6,348 | //
// CommentOperator.swift
// FilePlay
//
// Created by 4work on 2019/5/9.
//
import Foundation
class CommentOperator: DataBaseOperator {
// MARK: - 发布评论
///
/// - Parameters:
/// - params: 参数内容 dynamicId(动态id) content(评论内容) replyId(回复对象) authorId(评论人)
/// - Returns: 返回JSON数据
func postCommentHandle(params: [String: Any]) -> String {
let authorId: String = params["authorId"] as! String
let content: String = params["content"] as! String
let replyId: String = params["replyId"] as! String
let dynamicId: String = params["dynamicId"] as! String
let current = Date()
let postDate = Utils.dateToString(date: current, format: "yyyy-MM-dd HH:mm:ss")
let values = "('\(dynamicId)', '\(Utils.fixSingleQuotes(content))', '\(replyId)', '\(authorId)', '\(postDate)')"
let statement = "INSERT INTO \(commenttable) (dynamicId, content, replyId, authorId, postDate) VALUES \(values)"
if mysql.query(statement: statement) == false {
Utils.logError("发布评论", mysql.errorMessage())
responseJson = Utils.failureResponseJson("发布评论失败")
} else {
responseJson = Utils.successResponseJson(["isSuccessful": true])
}
return responseJson
}
// MARK: - 动态评论列表
///
/// - Parameters:
/// - params: 参数内容 loginId(用户id) dynamicId(动态id) currentPage pageSize
/// - Returns: 返回JSON数据
func dynamicCommentList(params: [String: Any]) -> String {
let loginId: String = params["loginId"] as! String
let currentPage: Int = Int(params["currentPage"] as! String)!
let pageSize: Int = Int(params["pageSize"] as! String)!
let dynamicId: String = params["dynamicId"] as! String
let originalKeys: [String] = [
"objectId",
"dynamicId",
"content",
"postDate",
"praiseCount",
"reportCount",
"isPraise"]
// 评论人
let authorValueOfKeys: [String] = [
"userId",
"nickname",
"portrait",
"gender"];
// 回复对象
let replyValueOfKeys: [String] = [
"userId",
"nickname",
"portrait",
"gender"];
let keys: [String] = [
"\(commenttable).objectId",
"\(commenttable).dynamicId",
"\(commenttable).content",
"\(commenttable).postDate",
"COUNT(DISTINCT \(reportcommenttable).commentId) reportCount",
"COUNT(DISTINCT \(praisecommenttable).commentId) praiseCount",
"COUNT(DISTINCT praisecommenttable.commentId) isPraise",
"\(accounttable).userId",
"\(accounttable).nickname",
"\(accounttable).portrait",
"\(accounttable).gender",
"replyaccounttable.userId",
"replyaccounttable.nickname",
"replyaccounttable.portrait",
"replyaccounttable.gender"]
let statements: [String] = [
"LEFT JOIN \(reportcommenttable) ON (\(reportcommenttable).commentId = \(commenttable).objectId)",
"LEFT JOIN \(praisecommenttable) ON (\(praisecommenttable).commentId = \(commenttable).objectId)",
"LEFT JOIN \(praisecommenttable) praisecommenttable ON (praisecommenttable.authorId = '\(loginId)' AND praisecommenttable.commentId = \(commenttable).objectId)",
"LEFT JOIN \(accounttable) ON (\(accounttable).userId = \(commenttable).authorId)",
"LEFT JOIN \(accounttable) replyaccounttable ON (replyaccounttable.userId = \(commenttable).replyId)"]
let statement = "SELECT \(keys.joined(separator: ", ")) FROM \(commenttable) \(statements.joined(separator: " ")) WHERE \(commenttable).dynamicId = '\(dynamicId)' GROUP BY \(commenttable).objectId DESC LIMIT \(currentPage*pageSize), \(pageSize)"
if mysql.query(statement: statement) == false {
Utils.logError("动态评论列表", mysql.errorMessage())
responseJson = Utils.failureResponseJson("动态评论列表查询失败")
} else {
var commentList = [[String: Any]]()
let results = mysql.storeResults()
if results != nil && results!.numRows() > 0 {
results!.forEachRow { (row) in
var dict: [String: Any] = [:]
var author: [String: Any] = [:]
var reply: [String: Any] = [:]
for idx in 0...row.count-1 {
if idx < originalKeys.count {
let key = originalKeys[idx]
let value = row[idx]
dict[key] = value
if dict["isPraise"] != nil {
if Int(dict["isPraise"] as! String) != 0 {
dict["isPraise"] = true
} else {
dict["isPraise"] = false
}
}
} else if idx < originalKeys.count+authorValueOfKeys.count {
let authorIdx: Int = idx-originalKeys.count
let key = authorValueOfKeys[authorIdx]
let value = row[idx]
author[key] = value
} else {
let replyIdx: Int = idx-(originalKeys.count+replyValueOfKeys.count)
let key = replyValueOfKeys[replyIdx]
let value = row[idx]
reply[key] = value
}
}
if author.count > 0 {
dict["author"] = author
}
if reply.count > 0 {
dict["reply"] = reply
}
commentList.append(dict)
}
}
responseJson = Utils.successResponseJson(commentList)
}
return responseJson
}
}
| 41.763158 | 253 | 0.49748 |
91a80ee0b237cd24da0081dd45e260794b80512a | 394 | import Foundation
struct StockResults: Codable {
let result: [AppleStock]
}
struct AppleStock: Codable {
let date: String
let open: Double
let high: Double
let low: Double
let close: Double
let volume: Int
let unadjustedVolume: Int
let change: Double
let changePercent: Double
let vwap: Double
let label: String
let changeOverTime: Double
}
| 19.7 | 30 | 0.682741 |
7976d1f03afc03f124793b970f0783f4864a26a1 | 224 | //
// AdapterTests.swift
// Arcade
//
// Created by Aaron Wright on 2/5/18.
// Copyright © 2018 A.C. Wright Design. All rights reserved.
//
import XCTest
@testable import Arcade
class AdapterTests: XCTestCase {
}
| 14.933333 | 61 | 0.678571 |
28618598dc355320116ccb386178601378fbdd06 | 5,598 | //
// Subscription.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/9/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
enum SubscriptionType: String, Equatable {
case directMessage = "d"
case channel = "c"
case group = "p"
}
enum SubscriptionNotificationsStatus: String, CaseIterable {
case `default`
case nothing
case all
case mentions
}
enum SubscriptionNotificationsAudioValue: String, CaseIterable {
case none
case `default`
case beep
case chelle
case ding
case droplet
case highbell
case seasons
}
typealias RoomType = SubscriptionType
final class Subscription: BaseModel {
@objc dynamic var auth: Auth?
@objc internal dynamic var privateType = SubscriptionType.channel.rawValue
var type: SubscriptionType {
get { return SubscriptionType(rawValue: privateType) ?? SubscriptionType.group }
set { privateType = newValue.rawValue }
}
@objc dynamic var rid = ""
// Name of the subscription
@objc dynamic var name = ""
// Full name of the user, in the case of
// using the full user name setting
// Setting: UI_Use_Real_Name
@objc dynamic var fname = ""
@objc dynamic var unread = 0
@objc dynamic var userMentions = 0
@objc dynamic var groupMentions = 0
@objc dynamic var open = false
@objc dynamic var alert = false
@objc dynamic var favorite = false
@objc dynamic var createdAt: Date?
@objc dynamic var lastSeen: Date?
@objc dynamic var roomTopic: String?
@objc dynamic var roomDescription: String?
@objc dynamic var roomReadOnly = false
@objc dynamic var roomUpdatedAt: Date?
@objc dynamic var roomLastMessage: Message?
@objc dynamic var roomLastMessageText: String?
@objc dynamic var roomLastMessageDate: Date?
@objc dynamic var roomBroadcast = false
let roomMuted = List<String>()
@objc dynamic var roomOwnerId: String?
@objc dynamic var otherUserId: String?
@objc dynamic var disableNotifications = false
@objc dynamic var hideUnreadStatus = false
@objc dynamic var desktopNotificationDuration = 0
@objc internal dynamic var privateDesktopNotifications = SubscriptionNotificationsStatus.default.rawValue
@objc internal dynamic var privateEmailNotifications = SubscriptionNotificationsStatus.default.rawValue
@objc internal dynamic var privateMobilePushNotifications = SubscriptionNotificationsStatus.default.rawValue
@objc internal dynamic var privateAudioNotifications = SubscriptionNotificationsStatus.default.rawValue
@objc internal dynamic var privateAudioNotificationsValue = SubscriptionNotificationsAudioValue.default.rawValue
var desktopNotifications: SubscriptionNotificationsStatus {
get { return SubscriptionNotificationsStatus(rawValue: privateDesktopNotifications) ?? .default }
set { privateDesktopNotifications = newValue.rawValue }
}
var emailNotifications: SubscriptionNotificationsStatus {
get { return SubscriptionNotificationsStatus(rawValue: privateEmailNotifications) ?? .default }
set { privateEmailNotifications = newValue.rawValue }
}
var mobilePushNotifications: SubscriptionNotificationsStatus {
get { return SubscriptionNotificationsStatus(rawValue: privateMobilePushNotifications) ?? .default }
set { privateMobilePushNotifications = newValue.rawValue }
}
var audioNotifications: SubscriptionNotificationsStatus {
get { return SubscriptionNotificationsStatus(rawValue: privateAudioNotifications) ?? .default }
set { privateAudioNotifications = newValue.rawValue }
}
var audioNotificationValue: SubscriptionNotificationsAudioValue {
get { return SubscriptionNotificationsAudioValue(rawValue: privateAudioNotificationsValue) ?? .default }
set { privateAudioNotificationsValue = newValue.rawValue }
}
let messages = LinkingObjects(fromType: Message.self, property: "subscription")
let usersRoles = List<RoomRoles>()
// MARK: Internal
@objc dynamic var privateOtherUserStatus: String?
var otherUserStatus: UserStatus? {
if let privateOtherUserStatus = privateOtherUserStatus {
return UserStatus(rawValue: privateOtherUserStatus)
} else {
return nil
}
}
}
final class RoomRoles: Object {
@objc dynamic var user: User?
var roles = List<String>()
}
// MARK: Failed Messages
extension Subscription {
func setTemporaryMessagesFailed(user: User? = AuthManager.currentUser()) {
guard let user = user else {
return
}
try? realm?.write {
messages.filter("temporary = true").filter({
$0.user == user
}).forEach {
$0.temporary = false
$0.failed = true
}
}
}
}
// MARK: Avatar
extension Subscription {
func avatarURL(auth: Auth? = nil) -> URL? {
guard
let auth = auth ?? AuthManager.isAuthenticated(),
let baseURL = auth.baseURL(),
let encodedName = name.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
else {
return nil
}
return URL(string: "\(baseURL)/avatar/%22\(encodedName)?format=jpeg")
}
}
extension Subscription: UnmanagedConvertible {
typealias UnmanagedType = UnmanagedSubscription
var unmanaged: UnmanagedSubscription {
return UnmanagedSubscription(self)
}
}
| 32.172414 | 116 | 0.700965 |
875cb2bd31bd20f1eb240a28fd612c7b424208cc | 462 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
c< let a{
class A
class A
let a{
enum b
<c{{}class B
{
func a:A
| 27.176471 | 79 | 0.735931 |
18a234a88a0e248f68a8e1397cd5457628c9eb1f | 1,290 | import UIKit
/// Spruce adds `UIView` extensions so that you can easily access a Spruce animation anywere. To make things
/// simple all Spruce functions are under the computed variable `spruce` or use our spruce tree emoji!
extension UIView: PXPropertyStoring {
/// Access to all of the Spruce library animations. Use this to call functions such as `.animate` or `.prepare`
internal var pxSpruce: PXSpruce {
return PXSpruce(view: self)
}
private struct PXCustomProperties {
static var animationEnabled: Bool = true
static var onetapRowAnimatedEnabled: Bool = false
}
typealias CustomT = Bool
var pxShouldAnimated: Bool {
get {
return getAssociatedObject(&PXCustomProperties.animationEnabled, defaultValue: true)
}
set {
return objc_setAssociatedObject(self, &PXCustomProperties.animationEnabled, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
var pxShouldAnimatedOneTapRow: Bool {
get {
return getAssociatedObject(&PXCustomProperties.onetapRowAnimatedEnabled, defaultValue: false)
}
set {
return objc_setAssociatedObject(self, &PXCustomProperties.onetapRowAnimatedEnabled, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
| 35.833333 | 131 | 0.696124 |
111a76d4d79b7cbda01fb3586a226dbb3dc03663 | 8,748 | //
// Copyright 2016 Lionheart Software LLC
//
// 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
public enum VariableNamingFormat {
case camelCase
case underscores
case pascalCase
}
extension CharacterSet: ExpressibleByStringLiteral {
public typealias StringLiteralType = String
public typealias UnicodeScalarLiteralType = StringLiteralType
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public init(stringLiteral value: StringLiteralType) {
self.init(charactersIn: value)
}
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(stringLiteral: value)
}
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(stringLiteral: value)
}
}
public protocol LHSStringType {
/**
Conforming types must provide a getter for the length of the string.
- Returns: An `Int` representing the "length" of the string (understood that this can differ based on encoding).
- Date: February 17, 2016
*/
var length: Int { get }
/**
Conforming types must provide a method to get the full range of the string.
- Returns: An `NSRange` representing the entire string.
- Date: February 17, 2016
*/
var range: NSRange { get }
var stringByLowercasingFirstLetter: String { get }
var stringByUppercasingFirstLetter: String { get }
var stringByReplacingSpacesWithDashes: String { get }
func stringByConverting(toNamingFormat naming: VariableNamingFormat) -> String
}
public protocol LHSURLStringType {
var URLEncodedString: String? { get }
}
extension String: LHSStringType, LHSURLStringType {}
extension NSString: LHSStringType {}
extension NSAttributedString: LHSStringType {}
public extension String {
/**
A string identifical to `self` if not an empty string, `nil` otherwise.
- SeeAlso: `Optional.nilIfEmpty`
*/
var nilIfEmpty: String? {
guard self != "" else {
return nil
}
return self
}
/// The length of the current string.
var length: Int {
return NSString(string: self).length
}
/// An `NSRange` encompassing all of `self`.
var range: NSRange {
return NSMakeRange(0, length)
}
/// Returns a `Range<String.Index>` equivalent to the provided `NSRange` for `self`.
@available(*, deprecated, message: "Now in the Swift Standard Library. Use `Range(_:in:)` instead.")
func toRange(_ range: NSRange) -> Range<String.Index> {
return Range(range, in: self)!
}
/// Trims all characters from the string in the specified `CharacterSet`.
mutating func trim(_ characterSet: CharacterSet) {
self = self.trimmingCharacters(in: characterSet)
}
/// URL encode the current string.
mutating func URLEncode() {
guard let string = URLEncodedString else {
return
}
self = string
}
mutating func replaceSpacesWithDashes() {
self = stringByReplacingSpacesWithDashes
}
mutating func replaceCapitalsWithUnderscores() {
self = stringByConverting(toNamingFormat: .underscores)
}
/// A copy of `self` with the first letter lowercased.
var stringByLowercasingFirstLetter: String {
let start = index(after: startIndex)
return self[..<start].lowercased() + self[start..<endIndex]
}
/// A copy of `self` with the first letter uppercased.
var stringByUppercasingFirstLetter: String {
let start = index(after: startIndex)
return self[..<start].uppercased() + self[start..<endIndex]
}
/**
A URL encoded copy of the current `String`.
*/
var URLEncodedString: String? {
guard let string = addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return nil
}
return string
}
/**
A copy of the current `String` with all spaces replaced with dashes.
*/
var stringByReplacingSpacesWithDashes: String {
let options: NSRegularExpression.Options = []
let regex = try! NSRegularExpression(pattern: "[ ]", options: options)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "-").lowercased()
}
func stringByConverting(toNamingFormat naming: VariableNamingFormat) -> String {
switch naming {
case .underscores:
let regex = try! NSRegularExpression(pattern: "([A-Z]+)", options: NSRegularExpression.Options())
let string = NSMutableString(string: self)
regex.replaceMatches(in: string, options: [], range: range, withTemplate: "_$0")
let newString = string.trimmingCharacters(in: "_").lowercased()
if hasPrefix("_") {
return "_" + newString
} else {
return newString
}
case .camelCase:
// MARK: TODO
fatalError()
case .pascalCase:
var uppercaseNextCharacter = false
var result = ""
for character in self {
if character == "_" {
uppercaseNextCharacter = true
} else {
if uppercaseNextCharacter {
result += String(character).uppercased()
uppercaseNextCharacter = false
} else {
character.write(to: &result)
}
}
}
return result
}
}
mutating func convert(toNamingFormat naming: VariableNamingFormat) {
self = stringByConverting(toNamingFormat: naming)
}
func isComposedOf(charactersInSet characterSet: CharacterSet) -> Bool {
for scalar in unicodeScalars where !characterSet.contains(UnicodeScalar(scalar.value)!) {
return false
}
return true
}
}
public extension NSString {
/**
An `NSRange` indicating the length of the `NSString`.
- Returns: An `NSRange`
*/
var range: NSRange {
return String(self).range
}
var stringByLowercasingFirstLetter: String {
return String(self).stringByLowercasingFirstLetter
}
var stringByUppercasingFirstLetter: String {
return String(self).stringByLowercasingFirstLetter
}
var stringByReplacingSpacesWithDashes: String {
return String(self).stringByReplacingSpacesWithDashes
}
func stringByConverting(toNamingFormat naming: VariableNamingFormat) -> String {
return String(self).stringByConverting(toNamingFormat: naming)
}
}
public extension NSAttributedString {
/**
Returns an `NSRange` indicating the length of the `NSAttributedString`.
- Returns: An `NSRange`
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
var range: NSRange {
return string.range
}
var stringByLowercasingFirstLetter: String {
return string.stringByLowercasingFirstLetter
}
var stringByUppercasingFirstLetter: String {
return string.stringByLowercasingFirstLetter
}
var stringByReplacingSpacesWithDashes: String {
return string.stringByReplacingSpacesWithDashes
}
func stringByConverting(toNamingFormat naming: VariableNamingFormat) -> String {
return string.stringByConverting(toNamingFormat: .underscores)
}
}
public extension NSMutableAttributedString {
func addString(_ string: String, attributes: [NSAttributedString.Key: Any]) {
let attributedString = NSAttributedString(string: string, attributes: attributes)
append(attributedString)
}
func addAttribute(_ name: NSAttributedString.Key, value: Any) {
addAttribute(name, value: value, range: range)
}
func addAttributes(_ attributes: [NSAttributedString.Key: Any]) {
addAttributes(attributes, range: range)
}
func removeAttribute(_ name: String) {
removeAttribute(NSAttributedString.Key(rawValue: name), range: range)
}
}
| 30.802817 | 117 | 0.652606 |
e66ac0823fe45f672880b15168286f3cd81b4a64 | 7,398 | //===--- AugmentedArithmeticTests.swift -----------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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
//
//===----------------------------------------------------------------------===//
import RealModule
import XCTest
import _TestSupport
final class AugmentedArithmeticTests: XCTestCase {
func testTwoSumSpecials<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// Must be exact and not overflow on outer bounds
var x = T.greatestFiniteMagnitude
var y = -T.greatestFiniteMagnitude
XCTAssertEqual(Augmented.sum(x, y).head, .zero)
XCTAssertEqual(Augmented.sum(x, y).tail, .zero)
XCTAssert(Augmented.sum(x, y).head.isFinite)
XCTAssert(Augmented.sum(x, y).tail.isFinite)
// Must be exact on lower subnormal bounds
x = T.leastNonzeroMagnitude
y = -T.leastNonzeroMagnitude
XCTAssertEqual(Augmented.sum(x, y).head, .zero)
XCTAssertEqual(Augmented.sum(x, y).tail, .zero)
// Must preserve floating point signs for:
// (1) (+0) + (-0) == +0
// (2) (-0) + (+0) == +0
// (3) (-0) + (-0) == -0
x = T(sign: .plus, exponent: 1, significand: 0)
y = T(sign: .minus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .plus) // (1)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
x = T(sign: .minus, exponent: 1, significand: 0)
y = T(sign: .plus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .plus) // (2)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
x = T(sign: .minus, exponent: 1, significand: 0)
y = T(sign: .minus, exponent: 1, significand: 0)
XCTAssertEqual(Augmented.sum(x, y).head.sign, .minus) // (3)
XCTAssertEqual(Augmented.sum(x, y).tail.sign, .plus)
// Infinity and NaN are propagated correctly
XCTAssertEqual(Augmented.sum( 0, T.infinity).head, T.infinity)
XCTAssertEqual(Augmented.sum( T.infinity, 0 ).head, T.infinity)
XCTAssertEqual(Augmented.sum( T.infinity, T.infinity).head, T.infinity)
XCTAssertEqual(Augmented.sum( 0, -T.infinity).head, -T.infinity)
XCTAssertEqual(Augmented.sum(-T.infinity, 0 ).head, -T.infinity)
XCTAssertEqual(Augmented.sum(-T.infinity, -T.infinity).head, -T.infinity)
XCTAssert(Augmented.sum( T.infinity, -T.infinity).head.isNaN)
XCTAssert(Augmented.sum(-T.infinity, T.infinity).head.isNaN)
XCTAssert(Augmented.sum( T.infinity, T.nan).head.isNaN)
XCTAssert(Augmented.sum( T.nan, T.infinity).head.isNaN)
XCTAssert(Augmented.sum(-T.infinity, T.nan).head.isNaN)
XCTAssert(Augmented.sum( T.nan, -T.infinity).head.isNaN)
XCTAssert(Augmented.sum( 0, T.nan).head.isNaN)
XCTAssert(Augmented.sum(T.nan, 0).head.isNaN)
XCTAssert(Augmented.sum(T.nan, T.nan).head.isNaN)
}
func testTwoSumRandomValues<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// For randomly-chosen well-scaled finite values, we expect:
// (1) `head` to be exactly the IEEE 754 sum of `a + b`
// (2) `tail` to be less than or equal `head.ulp/2`
// (3) the result of `twoSum` for unordered input to be exactly equal to
// the result of `fastTwoSum` for ordered input.
var g = SystemRandomNumberGenerator()
let values: [T] = (0 ..< 100).map { _ in
T.random(
in: T.ulpOfOne ..< 1,
using: &g)
}
for a in values {
for b in values {
let twoSum = Augmented.sum(a, b)
XCTAssertEqual(twoSum.head, a + b) // (1)
XCTAssert(twoSum.tail.magnitude <= twoSum.head.ulp/2) // (2)
let x: T = a.magnitude < b.magnitude ? b : a
let y: T = a.magnitude < b.magnitude ? a : b
let fastTwoSum = Augmented.sum(large: x, small: y)
XCTAssertEqual(twoSum.head, fastTwoSum.head) // (3)
XCTAssertEqual(twoSum.tail, fastTwoSum.tail) // (3)
}
}
}
func testTwoSumCancellation<T: Real & FixedWidthFloatingPoint>(_: T.Type) {
// Must be exact for exactly representable values
XCTAssertEqual(Augmented.sum( 0.984375, 1.375).head, 2.359375)
XCTAssertEqual(Augmented.sum( 0.984375, 1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-0.984375, 1.375).head, 0.390625)
XCTAssertEqual(Augmented.sum(-0.984375, 1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 0.984375,-1.375).head,-0.390625)
XCTAssertEqual(Augmented.sum( 0.984375,-1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-0.984375,-1.375).head,-2.359375)
XCTAssertEqual(Augmented.sum(-0.984375,-1.375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 1.375, 0.984375).head, 2.359375)
XCTAssertEqual(Augmented.sum( 1.375, 0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum( 1.375,-0.984375).head, 0.390625)
XCTAssertEqual(Augmented.sum( 1.375,-0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-1.375, 0.984375).head,-0.390625)
XCTAssertEqual(Augmented.sum(-1.375, 0.984375).tail, 0.0)
XCTAssertEqual(Augmented.sum(-1.375,-0.984375).head,-2.359375)
XCTAssertEqual(Augmented.sum(-1.375,-0.984375).tail, 0.0)
// Must handle cancellation when `b` is not representable in `a` and
// we expect `b` to be lost entirely in the calculation of `a + b`.
var a: T = 1.0
var b: T = .ulpOfOne * .ulpOfOne
var twoSum = Augmented.sum(a, b)
XCTAssertEqual(twoSum.head, a) // a + b = a
XCTAssertEqual(twoSum.tail, b) // Error: b
twoSum = Augmented.sum( a, -b)
XCTAssertEqual(twoSum.head, a)
XCTAssertEqual(twoSum.tail,-b)
twoSum = Augmented.sum(-a, b)
XCTAssertEqual(twoSum.head,-a)
XCTAssertEqual(twoSum.tail, b)
twoSum = Augmented.sum(-a, -b)
XCTAssertEqual(twoSum.head,-a)
XCTAssertEqual(twoSum.tail,-b)
// Must handle cancellation when `b` is only partially representable in `a`.
// We expect the fractional digits of `b` to be cancelled in the following
// example but the fractional digits to be preserved in `tail`.
let exponent = T.Exponent(T.significandBitCount + 1)
a = T(sign: .plus, exponent: exponent, significand: 1.0)
b = 256 + 0.5
twoSum = Augmented.sum( a, b)
XCTAssertEqual(twoSum.head, a + 256)
XCTAssertEqual(twoSum.tail, 0.5)
twoSum = Augmented.sum( a, -b)
XCTAssertEqual(twoSum.head, a - 256)
XCTAssertEqual(twoSum.tail, -0.5)
twoSum = Augmented.sum(-a, b)
XCTAssertEqual(twoSum.head, -a + 256)
XCTAssertEqual(twoSum.tail, 0.5)
twoSum = Augmented.sum(-a, -b)
XCTAssertEqual(twoSum.head, -a - 256)
XCTAssertEqual(twoSum.tail, -0.5)
}
func testTwoSum() {
testTwoSumSpecials(Float32.self)
testTwoSumRandomValues(Float32.self)
testTwoSumCancellation(Float32.self)
testTwoSumSpecials(Float64.self)
testTwoSumRandomValues(Float64.self)
testTwoSumCancellation(Float64.self)
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
testTwoSumSpecials(Float80.self)
testTwoSumRandomValues(Float80.self)
testTwoSumCancellation(Float80.self)
#endif
}
}
| 45.950311 | 80 | 0.646661 |
d671cc2b4d9169ddedc915accfabc8bac07eff8b | 1,813 | //
// HTKLocationUtils.swift
//
// Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai)
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import Foundation
import CoreLocation
let htkDidUpdateLocationNotification = "htkDidUpdateLocationNotification"
class HTKLocationUtils: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
var mostRecentLocation: CLLocation?
class var sharedInstance : HTKLocationUtils {
struct Static {
static var token : dispatch_once_t = 0
static var instance : HTKLocationUtils? = nil
}
dispatch_once(&Static.token) {
Static.instance = HTKLocationUtils()
}
return Static.instance!
}
override init() {
locationManager = CLLocationManager()
}
func startMonitoringLocation() {
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
//locationManager.stopUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var location = locations[0] as CLLocation
mostRecentLocation = location
NSNotificationCenter.defaultCenter().postNotificationName(
htkDidUpdateLocationNotification,
object: nil,
userInfo: ["location" : location]
)
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if ((error) != nil) {
println("Error : \(error)")
}
}
}
| 31.258621 | 99 | 0.681191 |
ddbab1c3ed29a61f111d9133350d326d02b8d50c | 3,947 | //
// PopoverHost.swift
// SwiftUITest
//
// Created by Thomas Visser on 29/08/2019.
// Copyright © 2019 Thomas Visser. All rights reserved.
//
import Foundation
import SwiftUI
extension View {
func popover(_ content: Binding<Popover?>) -> some View {
self.background(PopoverPresenter(
content: Binding(
get: { content.wrappedValue?.makeBody() },
set: { _ in content.wrappedValue = nil }
)).opacity(0))
}
func popover<Content>(_ content: Binding<Content?>) -> some View where Content: View {
self.background(PopoverPresenter(content: content).opacity(0))
}
}
// Inspired by https://www.objc.io/blog/2020/04/21/swiftui-alert-with-textfield/
struct PopoverPresenter<Popover>: UIViewControllerRepresentable where Popover: View {
@Binding var content: Popover?
@State var present = false
func makeUIViewController(context: UIViewControllerRepresentableContext<PopoverPresenter>) -> UIHostingController<EmptyView> {
UIHostingController(rootView: EmptyView())
}
final class Coordinator {
var popoverVC: UIHostingController<PopoverWrapper>?
init(_ controller: UIHostingController<PopoverWrapper>? = nil) {
self.popoverVC = controller
}
}
func makeCoordinator() -> Coordinator {
return Coordinator()
}
func updateUIViewController(_ uiViewController: UIHostingController<EmptyView>, context: Context) {
let popoverVC = uiViewController.presentedViewController as? UIHostingController<PopoverWrapper>
if content != nil {
popoverVC?.rootView = PopoverWrapper(popover: $content, present: $present)
if popoverVC == nil {
let newPopoverVC = UIHostingController(rootView: PopoverWrapper(popover: $content, present: $present))
newPopoverVC.view.backgroundColor = .clear
newPopoverVC.modalPresentationStyle = .overFullScreen
context.coordinator.popoverVC = newPopoverVC
uiViewController.present(newPopoverVC, animated: false)
DispatchQueue.main.async {
withAnimation {
present = true
}
}
}
}
if content == nil && popoverVC != nil && popoverVC == context.coordinator.popoverVC {
DispatchQueue.main.async {
present = false
}
context.coordinator.popoverVC = nil
uiViewController.dismiss(animated: false)
}
}
struct PopoverWrapper: View {
@Binding var popover: Popover?
@Binding var present: Bool
var body: some View {
ZStack {
if let popover = popover, present {
Color(UIColor.systemGray3).opacity(0.45).edgesIgnoringSafeArea(.all)
.onTapGesture {
$popover.wrappedValue = nil
}
.transition(.opacity)
popover
.padding(15)
.clipped()
.background(
Color(UIColor.systemBackground)
.cornerRadius(8)
.shadow(radius: 5)
)
.padding(20)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.transition(
AnyTransition.offset(y: 50)
.combined(with: .scale(scale: 0.9))
.combined(with: AnyTransition.opacity.animation(.easeOut(duration: 0.1)))
)
}
}
.animation(.spring())
}
}
}
| 35.881818 | 130 | 0.538637 |
014da0a74dfc7ed39e8be471a5b86a92369d56a6 | 1,117 | //
// PostDetailView.swift
// RedditMate
//
// Created by Samuel Sainz on 9/8/20.
// Copyright © 2020 Samuel Sainz. All rights reserved.
//
import UIKit
protocol PostDetailView: class {
/// Show time since was published
func setDate(text: String)
/// Show the Post's title
func setTitle(text: String)
/// Show author username
func setAuthor(text: String)
/// Show subreddit tag
func setSubreddit(text: String)
/// Show how many upvotes has the post
func setUpvotes(text: String)
/// Show how many comments has the post
func setComments(text: String)
/// Show the post's image
func setImage(_ image: UIImage)
/// Set size for the image
func setImageSize(ratio: Float)
/// Show an activity indicator while downloading the image
func showImageLoading()
/// Returns the image shown by the image view
func getImage() -> UIImage?
/// Show the image full screen
func showFullScreenImage(url: URL)
/// Show an alert with given message
func showAlert(message: String)
}
| 23.270833 | 62 | 0.642793 |
b9688c0f28e2e9d09079aad09ebf400ccfaac0a4 | 9,686 | //
// Example
// man.li
//
// Created by man.li on 11/11/2018.
// Copyright © 2020 man.li. All rights reserved.
//
import UIKit
class AppInfoViewController: UITableViewController {
@IBOutlet weak var labelVersionNumber: UILabel!
@IBOutlet weak var labelBuildNumber: UILabel!
@IBOutlet weak var labelBundleName: UILabel!
@IBOutlet weak var labelScreenResolution: UILabel!
@IBOutlet weak var labelDeviceModel: UILabel!
@IBOutlet weak var labelCrashCount: UILabel!
@IBOutlet weak var labelBundleID: UILabel!
@IBOutlet weak var labelserverURL: UILabel!
@IBOutlet weak var labelIOSVersion: UILabel!
@IBOutlet weak var labelHtml: UILabel!
@IBOutlet weak var crashSwitch: UISwitch!
@IBOutlet weak var logSwitch: UISwitch!
@IBOutlet weak var networkSwitch: UISwitch!
@IBOutlet weak var webViewSwitch: UISwitch!
@IBOutlet weak var slowAnimationsSwitch: UISwitch!
@IBOutlet weak var naviItem: UINavigationItem!
@IBOutlet weak var rnSwitch: UISwitch!
@IBOutlet weak var fpsSwitch: UISwitch!
var naviItemTitleLabel: UILabel?
//MARK: - init
override func viewDidLoad() {
super.viewDidLoad()
naviItemTitleLabel = UILabel.init(frame: CGRect(x: 0, y: 0, width: 80, height: 40))
naviItemTitleLabel?.textAlignment = .center
naviItemTitleLabel?.textColor = Color.mainGreen
naviItemTitleLabel?.font = .boldSystemFont(ofSize: 20)
naviItemTitleLabel?.text = "App"
naviItem.titleView = naviItemTitleLabel
labelCrashCount.frame.size = CGSize(width: 30, height: 20)
labelVersionNumber.text = CocoaDebugDeviceInfo.sharedInstance().appVersion
labelBuildNumber.text = CocoaDebugDeviceInfo.sharedInstance().appBuiltVersion
labelBundleName.text = CocoaDebugDeviceInfo.sharedInstance().appBundleName
labelScreenResolution.text = "\(Int(CocoaDebugDeviceInfo.sharedInstance().resolution.width))" + "*" + "\(Int(CocoaDebugDeviceInfo.sharedInstance().resolution.height))"
labelDeviceModel.text = "\(CocoaDebugDeviceInfo.sharedInstance().getPlatformString)"
labelBundleID.text = CocoaDebugDeviceInfo.sharedInstance().appBundleID
labelserverURL.text = CocoaDebugSettings.shared.serverURL
labelIOSVersion.text = UIDevice.current.systemVersion
if UIScreen.main.bounds.size.width == 320 {
labelHtml.font = UIFont.systemFont(ofSize: 15)
}
logSwitch.isOn = CocoaDebugSettings.shared.enableLogMonitoring
networkSwitch.isOn = !CocoaDebugSettings.shared.disableNetworkMonitoring
rnSwitch.isOn = CocoaDebugSettings.shared.enableRNMonitoring
webViewSwitch.isOn = CocoaDebugSettings.shared.enableWKWebViewMonitoring
slowAnimationsSwitch.isOn = CocoaDebugSettings.shared.slowAnimations
crashSwitch.isOn = CocoaDebugSettings.shared.enableCrashRecording
fpsSwitch.isOn = CocoaDebugSettings.shared.enableFpsMonitoring
logSwitch.addTarget(self, action: #selector(logSwitchChanged), for: UIControl.Event.valueChanged)
networkSwitch.addTarget(self, action: #selector(networkSwitchChanged), for: UIControl.Event.valueChanged)
rnSwitch.addTarget(self, action: #selector(rnSwitchChanged), for: UIControl.Event.valueChanged)
webViewSwitch.addTarget(self, action: #selector(webViewSwitchChanged), for: UIControl.Event.valueChanged)
slowAnimationsSwitch.addTarget(self, action: #selector(slowAnimationsSwitchChanged), for: UIControl.Event.valueChanged)
crashSwitch.addTarget(self, action: #selector(crashSwitchChanged), for: UIControl.Event.valueChanged)
fpsSwitch.addTarget(self, action: #selector(fpsSwitchChanged), for: UIControl.Event.valueChanged)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let count = UserDefaults.standard.integer(forKey: "crashCount_CocoaDebug")
labelCrashCount.text = "\(count)"
labelCrashCount.textColor = count > 0 ? .red : .white
}
//MARK: - alert
func showAlert() {
let alert = UIAlertController.init(title: nil, message: "You must restart APP to ensure the changes take effect", preferredStyle: .alert)
let cancelAction = UIAlertAction.init(title: "Restart later", style: .cancel, handler: nil)
let okAction = UIAlertAction.init(title: "Restart now", style: .destructive) { _ in
exit(0)
}
alert.addAction(cancelAction)
alert.addAction(okAction)
alert.popoverPresentationController?.permittedArrowDirections = .init(rawValue: 0)
alert.popoverPresentationController?.sourceView = self.view
alert.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
self.present(alert, animated: true, completion: nil)
}
//MARK: - target action
@objc func slowAnimationsSwitchChanged(sender: UISwitch) {
CocoaDebugSettings.shared.slowAnimations = slowAnimationsSwitch.isOn
// self.showAlert()
}
@objc func fpsSwitchChanged(sender: UISwitch) {
CocoaDebugSettings.shared.enableFpsMonitoring = fpsSwitch.isOn
if fpsSwitch.isOn == true {
WindowHelper.shared.startFpsMonitoring()
} else {
WindowHelper.shared.stopFpsMonitoring()
}
}
@objc func crashSwitchChanged(sender: UISwitch) {
CocoaDebugSettings.shared.enableCrashRecording = crashSwitch.isOn
self.showAlert()
}
@objc func networkSwitchChanged(sender: UISwitch) {
CocoaDebugSettings.shared.disableNetworkMonitoring = !networkSwitch.isOn
self.showAlert()
}
@objc func logSwitchChanged(sender: UISwitch) {
CocoaDebugSettings.shared.enableLogMonitoring = logSwitch.isOn
self.showAlert()
}
@objc func rnSwitchChanged(sender: UISwitch) {
CocoaDebugSettings.shared.enableRNMonitoring = rnSwitch.isOn
self.showAlert()
}
@objc func webViewSwitchChanged(sender: UISwitch) {
CocoaDebugSettings.shared.enableWKWebViewMonitoring = webViewSwitch.isOn
self.showAlert()
}
}
//MARK: - UITableViewDelegate
extension AppInfoViewController {
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
if section == 0 {
return 56
}
return 38
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
if indexPath.section == 1 && indexPath.row == 4 {
if labelserverURL.text == nil || labelserverURL.text == "" {
return 0
}
}
return 44
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 1 && indexPath.row == 2 {
UIPasteboard.general.string = CocoaDebugDeviceInfo.sharedInstance().appBundleName
let alert = UIAlertController.init(title: "copied bundle name to clipboard", message: nil, preferredStyle: .alert)
let action = UIAlertAction.init(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
alert.popoverPresentationController?.permittedArrowDirections = .init(rawValue: 0)
alert.popoverPresentationController?.sourceView = self.view
alert.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
self.present(alert, animated: true, completion: nil)
}
if indexPath.section == 1 && indexPath.row == 3 {
UIPasteboard.general.string = CocoaDebugDeviceInfo.sharedInstance().appBundleID
let alert = UIAlertController.init(title: "copied bundle id to clipboard", message: nil, preferredStyle: .alert)
let action = UIAlertAction.init(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
alert.popoverPresentationController?.permittedArrowDirections = .init(rawValue: 0)
alert.popoverPresentationController?.sourceView = self.view
alert.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
self.present(alert, animated: true, completion: nil)
}
if indexPath.section == 1 && indexPath.row == 4 {
if labelserverURL.text == nil || labelserverURL.text == "" {return}
UIPasteboard.general.string = CocoaDebugSettings.shared.serverURL
let alert = UIAlertController.init(title: "copied server to clipboard", message: nil, preferredStyle: .alert)
let action = UIAlertAction.init(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
alert.popoverPresentationController?.permittedArrowDirections = .init(rawValue: 0)
alert.popoverPresentationController?.sourceView = self.view
alert.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
self.present(alert, animated: true, completion: nil)
}
}
}
| 44.431193 | 175 | 0.674685 |
f5224ada9ce8dd83ad40082bbd5907c830b2bcaa | 2,116 | import Quick
import Nimble
import AVFoundation
@testable import SwiftAudio
class AVPlayerObserverTests: QuickSpec, AVPlayerObserverDelegate {
var status: AVPlayerStatus?
var timeControlStatus: AVPlayerTimeControlStatus?
override func spec() {
describe("A player observer") {
var player: AVPlayer!
var observer: AVPlayerObserver!
beforeEach {
player = AVPlayer()
observer = AVPlayerObserver(player: player)
observer.delegate = self
}
context("when observing has started", {
beforeEach {
observer.startObserving()
}
it("should be observing", closure: {
expect(observer.isObserving).toEventually(beTrue())
})
context("when player has started", {
beforeEach {
player.replaceCurrentItem(with: AVPlayerItem(url: URL(fileURLWithPath: Source.path)))
player.play()
}
it("it should update the delegate", closure: {
expect(self.status).toEventuallyNot(beNil())
expect(self.timeControlStatus).toEventuallyNot(beNil())
})
})
context("when observing again", {
beforeEach {
observer.startObserving()
}
it("should be observing", closure: {
expect(observer.isObserving).toEventually(beTrue())
})
})
})
}
}
func player(statusDidChange status: AVPlayerStatus) {
self.status = status
}
func player(didChangeTimeControlStatus status: AVPlayerTimeControlStatus) {
self.timeControlStatus = status
}
}
| 30.228571 | 109 | 0.473535 |
699b8df082209d07c9cd35cfe658a15a696ac578 | 452 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
// REQUIRES: asserts
private class B
class d<T where B<T>:w
| 37.666667 | 78 | 0.747788 |
3344e3ff82dadbd6496fe47a4604489c9172d8eb | 344 | //
// LoginPageFormatter.swift
// Movee
//
// Created by Oguz Tandogan on 6.12.2020.
// Copyright (c) 2020 Oguz Tandogan. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
final class LoginPageFormatter {
}
// MARK: - Extensions -
extension LoginPageFormatter: LoginPageFormatterInterface {
}
| 17.2 | 59 | 0.718023 |
89071f15531a63200a4fa88ec29d27bcd54b13be | 1,416 | //
// Tests_macOS.swift
// Tests macOS
//
// Created by Heru Handika on 12/17/21.
//
import XCTest
class Tests_macOS: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.930233 | 182 | 0.652542 |
9b0888a76ec1c1315fb74bed4c39477d1535bf49 | 739 | //
// ScrollViewCalculator.swift
// MVP-Sample
//
// Created by Nixon.Shih on 2019/4/15.
// Copyright © 2019 NixonShih. All rights reserved.
//
import UIKit
class ScrollViewCalculator {
enum Direction {
case up
case down
}
init(scrollView: UIScrollView, originOffset: CGFloat = 0) {
self.scrollView = scrollView
previousScrollOffset = originOffset
}
var scrollDifference: CGFloat {
return scrollView.contentOffset.y - previousScrollOffset
}
var moveDirection: Direction {
return scrollDifference > 0 ? .up : .down
}
var previousScrollOffset: CGFloat
// MARK: private
private let scrollView: UIScrollView
}
| 19.972973 | 64 | 0.633288 |
1c9fddd81d476024e6cbec0e5b9167deef7137c2 | 2,111 | //
// PulseAPI.swift
// TestCombine
//
// Created by Martin Mitrevski on 2/4/20.
// Copyright © 2020 Netcetera. All rights reserved.
//
import GirdersSwift
import Combine
let sensorPath = "sensor"
enum PulseEndpoint {
case sensors
case sensor(String)
}
extension PulseEndpoint: ServiceEndpoint {
var path: String {
switch self {
case .sensors:
return sensorPath
case .sensor(let sensorId):
return "\(sensorPath)/\(sensorId)"
}
}
}
class PulseAPI {
let httpClient: HTTP
init(with httpClient: HTTP = HTTPClient()) {
self.httpClient = httpClient
}
func loadSensors() -> AnyPublisher<[Sensor], Error> {
let request = Request(endpoint: PulseEndpoint.sensors)
let publisher: AnyPublisher<[SensorResponse], Error> = httpClient.executeRequest(request: request)
return publisher.map { (response) -> [Sensor] in
self.convert(sensorsResponse: response)
}
.eraseToAnyPublisher()
}
func loadSensor(with id: String) -> AnyPublisher<Sensor, Error> {
let request = Request(endpoint: PulseEndpoint.sensor(id))
let future: Future<SensorResponse, Error> = httpClient.executeRequest(request: request)
return future.map { (response) -> Sensor in
self.convert(sensorResponse: response)
}
.eraseToAnyPublisher()
}
private func convert(sensorsResponse: [SensorResponse]) -> [Sensor] {
let sensors = sensorsResponse.map { (sensorResponse) -> Sensor in
return convert(sensorResponse: sensorResponse)
}
return sensors
}
private func convert(sensorResponse: SensorResponse) -> Sensor {
return Sensor(id: sensorResponse.sensorId,
position: sensorResponse.position,
comments: sensorResponse.comments,
type: sensorResponse.type,
description: sensorResponse.description,
status: sensorResponse.status)
}
}
| 27.776316 | 106 | 0.613453 |
5be3dcbec0b1d1088ed911f2493fe7c9a55b7941 | 3,111 | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
extension Int32 {
/**
* Encode as a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that
* can be efficiently encoded with varint. (Otherwise, negative values must be sign-extended to
* 64 bits to be varint encoded, thus always taking 10 bytes on the wire.)
*
* - returns: An unsigned 32-bit integer
*/
func zigZagEncoded() -> UInt32 {
// Note: the right-shift must be arithmetic
return UInt32(bitPattern: (self << 1) ^ (self >> 31))
}
}
extension UInt32 {
/**
* Compute the number of bytes that would be needed to encode a varint.
*/
var varintSize: UInt32 {
if self & (~0 << 7) == 0 { return 1 }
if self & (~0 << 14) == 0 { return 2 }
if self & (~0 << 21) == 0 { return 3 }
if self & (~0 << 28) == 0 { return 4 }
return 5
}
/**
* Decodes a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be
* efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits
* to be varint encoded, thus always taking 10 bytes on the wire.)
*
* - returns: A signed 32-bit integer.
*/
func zigZagDecoded() -> Int32 {
return Int32(bitPattern: (self >> 1)) ^ -(Int32(bitPattern: self) & 1)
}
}
// MARK: -
extension Int64 {
/**
* Encode as a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that
* can be efficiently encoded with varint. (Otherwise, negative values must be sign-extended to
* 64 bits to be varint encoded, thus always taking 10 bytes on the wire.)
*
* - returns: An unsigned 64-bit integer
*/
func zigZagEncoded() -> UInt64 {
// Note: the right-shift must be arithmetic
return UInt64(bitPattern: (self << 1) ^ (self >> 63))
}
}
// MARK: -
extension UInt64 {
/**
* Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be
* efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits
* to be varint encoded, thus always taking 10 bytes on the wire.)
*
* - returns: An unsigned 64-bit integer, stored in a signed int because Java has no explicit
* unsigned support.
*/
func zigZagDecoded() -> Int64 {
// Note: the right-shift must be arithmetic
return Int64(bitPattern: (self >> 1)) ^ -(Int64(bitPattern: self) & 1)
}
}
| 32.072165 | 100 | 0.642237 |
723e1b0b1ac98c86559209de64822a5be46b37a6 | 16,512 | //
// AuthorPagerVC.swift
// shishi
//
// Created by andymao on 2017/5/8.
// Copyright © 2017年 andymao. All rights reserved.
//
import Foundation
import UIKit
import iCarousel
import FTPopOverMenu_Swift
import SnapKit
import RxSwift
private let poetryCellReuseIdentifier = "poetryCellReuseIdentifier"
private let authorCellReuseIdentifier = "authorCellReuseIdentifier"
private let UserDefaultsKeyLoadTimes = "UserDefaultsKeyLoadTimes"
private let bootimBarHeight = convertWidth(pix: 100)
//字体变化每次步径
private let increaseFontStep: CGFloat = AppConfig.Constants.increaseFontStep
//第一页是退出动画页,第二页是诗人页
class AuthorPagerVC: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var poetrys = [Poetry]()
var pageController: UIPageViewController!
var controllers = [UIViewController]()
var author : Author!
var color : UIColor!
//初始定位的诗
var firstPoetry: Poetry?
fileprivate lazy var tipView:UIView = {
let tipView = UIView()
return tipView
}()
fileprivate lazy var tipTitleView:UILabel = {
let titleView = UILabel()
titleView.text = SSStr.Tips.AUTHOR_SLIDE
titleView.textColor = UIColor.white
return titleView
}()
fileprivate lazy var tipImageView:UIImageView = {
let imageView = UIImageView()
var images = [UIImage]()
let formatName = "left_slip_guide_%03d"
for index in 0...24 {
let imageName = String(format: formatName, index)
images.append(UIImage(named: imageName)!)
}
imageView.animationImages = images
return imageView
}()
internal var editBtn: UIButton!
internal lazy var bottomBar: UIView = {
let bottomBar = UIView()
return bottomBar
}()
//滑动到最左边退出当前页面
var canSwapExit = true
var bottomBarConstraint: Constraint!
var isBottomBarHidden = true
deinit {
}
init(author : Author,color : UIColor) {
self.author = author
self.color = color
poetrys = PoetryDB.getAll(author: author.name!)
NSLog("poetry size %d %@", poetrys.count,author.name!)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
pageController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
pageController.dataSource = self
pageController.delegate = self
addChildViewController(pageController)
view.addSubview(pageController.view)
let views = ["pageController": pageController.view] as [String: AnyObject]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[pageController]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[pageController]|", options: [], metrics: nil, views: views))
if self.canSwapExit {
let imageViewController = ImageViewContoller()
let parentImage = SSImageUtil.image(with: self.parent!.view)
imageViewController.image = parentImage
controllers.append(imageViewController)
}
controllers.append(AuthorCellVC(author:self.author))
for (index,poetry) in poetrys.enumerated() {
let vc = PoetryCellVC(poetry:poetry,color:color,pager:String(index+1).appending("/").appending(String(poetrys.count)))
controllers.append(vc)
}
//pageController.setViewControllers([controllers[0]], direction: .forward, animated: false)
self.setupBottomView()
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
if let firstPoetry = self.firstPoetry {
let index = self.poetrys.index(where: { (poetry) -> Bool in
return poetry.dNum == firstPoetry.dNum
})
let firstPoetryIndex = 2
pageController.setViewControllers([controllers[index! + firstPoetryIndex]], direction: .forward, animated: false)
}
else if self.canSwapExit {
pageController.setViewControllers([controllers[1]], direction: .forward, animated: false)
}
if UserDefaults.standard.value(forKey: UserDefaultsKeyLoadTimes) == nil {
UserDefaults.standard.setValue(true, forKey: UserDefaultsKeyLoadTimes)
self.showTip()
}
// //更新上次保存的字体大小
// let fontOffset = DataContainer.default.fontOffset
// if fontOffset != 0 {
// self.updateFont(pointSizeStep: fontOffset)
// }
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
SpeechUtil.default.stop()
}
internal func setupBottomView() {
self.view.addSubview(self.bottomBar)
self.bottomBar.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
//self.bottomBarConstraint = make.bottom.equalToSuperview().offset(bootimBarHeight).constraint
self.bottomBarConstraint = make.bottom.equalToSuperview().constraint
make.height.equalTo(convertWidth(pix: 100))
}
// let cancleBtn = UIButton()
// self.bottomBar.addSubview(cancleBtn)
// cancleBtn.setImage(UIImage(named:"cancel"), for: .normal)
// cancleBtn.snp.makeConstraints { (make) in
// make.left.equalToSuperview().offset(convertWidth(pix: 20))
// make.bottom.equalToSuperview().offset(convertWidth(pix: -20))
// make.height.width.equalTo(convertWidth(pix: 90))
// }
// cancleBtn.addTapHandler { [unowned self] in
// self.navigationController?.popViewController(animated: true)
// }
self.editBtn = UIButton()
self.bottomBar.addSubview(editBtn)
editBtn.setImage(UIImage(named:"setting"), for: .normal)
editBtn.snp.makeConstraints { (make) in
make.right.equalToSuperview().offset(convertWidth(pix: -20))
make.bottom.equalToSuperview().offset(convertWidth(pix: -20))
make.height.width.equalTo(convertWidth(pix: 90))
}
editBtn.addTapHandler { [unowned self] in
self.showMenu()
}
// let tapGestrue = UITapGestureRecognizer()
// self.view.addGestureRecognizer(tapGestrue)
// tapGestrue.rx.event
// .subscribe(onNext: { [weak self] x in
// self?.toggleBottomView()
// })
// .addDisposableTo(self.rx_disposeBag)
}
// internal func toggleBottomView() {
// let targetOffset = self.isBottomBarHidden ? 0 : bootimBarHeight
//
// UIView.animate(withDuration: 0.5) {
// self.bottomBarConstraint.update(offset: targetOffset)
// self.bottomBar.superview?.layoutIfNeeded()
// }
//
// self.isBottomBarHidden = !self.isBottomBarHidden
// }
fileprivate func showTip() {
if self.tipView.superview == nil {
self.view.addSubview(self.tipView)
self.tipView.snp.makeConstraints({ (make) in
make.right.centerY.equalToSuperview()
})
self.tipView.addSubview(self.tipImageView)
self.tipImageView.snp.makeConstraints({ (make) in
make.centerX.top.equalToSuperview()
make.width.height.equalTo(120)
})
self.tipImageView.startAnimating()
self.tipView.addSubview(self.tipTitleView)
self.tipTitleView.snp.makeConstraints({ (make) in
make.left.greaterThanOrEqualToSuperview()
make.right.lessThanOrEqualToSuperview()
make.bottom.equalToSuperview()
make.top.equalTo(self.tipImageView.snp.bottom)
})
let tapGuesture = UITapGestureRecognizer()
self.tipView.addGestureRecognizer(tapGuesture)
tapGuesture.rx.event
.subscribe(onNext: { [unowned self] _ in
self.hideTip()
})
.addDisposableTo(self.rx_disposeBag)
}
}
fileprivate func hideTip() {
if self.tipView.superview != nil {
self.tipView.removeFromSuperview()
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let index = controllers.index(of: viewController) {
if index > 0 {
return controllers[index - 1]
} else {
return nil
}
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let index = controllers.index(of: viewController) {
if index < controllers.count - 1 {
return controllers[index + 1]
} else {
return nil
}
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
self.hideTip()
if self.canSwapExit && pageViewController.viewControllers!.first is ImageViewContoller {
self.navigationController?.popViewController(animated: false)
}
}
}
}
//menu
extension AuthorPagerVC {
public func currentPoetry() -> Poetry? {
let pageContentViewController = self.pageController.viewControllers![0]
let index = self.controllers.index(of: pageContentViewController)!
let offset = self.canSwapExit ? 2 : 1
if index < offset {
return nil
}
let poetry = self.poetrys[index - offset]
return poetry
}
fileprivate func showMenu() {
FTPopOverMenu.showForSender(sender: self.editBtn,
with: [SSStr.Share.INCREASE_FONTSIZE, SSStr.Share.REDUCE_FONTSIZE, SSStr.All.FAVORITE, SSStr.All.DIRECTORY, SSStr.All.COPY_CONTENT, SSStr.All.SPEAK_CONTENT, SSStr.All.AUTHOR_PEDIA, SSStr.All.CONTENT_PEDIA, SSStr.All.MENU_EXIT],
done: { [unowned self] (selectedIndex) -> () in
switch selectedIndex {
case 0:
_ = DataContainer.default.increaseFontOffset()
//self.updateFont(pointSizeStep: increaseFontStep)
case 1:
_ = DataContainer.default.reduceFontOffset()
//self.updateFont(pointSizeStep: -increaseFontStep)
case 2:
guard let poetry = self.currentPoetry() else {
return
}
self.toggleCollection(poetry: poetry)
case 3:
guard let poetry = self.currentPoetry() else {
return
}
// let searchController = SearchPoetryVC()
// searchController.author = poetry.author
// self.navigationController?.pushViewController(searchController, animated: true)
SSControllerHelper.showDirectoryContoller(controller: self, author: poetry.author)
case 4:
guard let poetry = self.currentPoetry() else {
return
}
UIPasteboard.general.string = StringUtils.contentTextFilter(poerityTitle: poetry.poetry)
self.showToast(message: SSStr.Toast.COPY_SUCCESS)
case 5:
if let poetry = self.currentPoetry() {
self.speech(poetry: poetry)
}
else {
self.speech(author: self.author)
}
case 6:
// let poetry = self.currentPoetry()
// SSControllerHelper.showBaikeContoller(controller: self, word: poetry.author)
SSControllerHelper.showBaikeContoller(controller: self, word: self.author.name)
case 7:
guard let poetry = self.currentPoetry() else {
return
}
SSControllerHelper.showBaikeContoller(controller: self, word: poetry.title)
case 8:
self.navigationController?.popViewController(animated: true)
default:
break
}
}) {
}
}
// fileprivate func updateFont(pointSizeStep: CGFloat) {
// self.controllers.forEach { (controller) in
// if let poetryCellVC = controller as? PoetryCellVC {
// poetryCellVC.updateFont(pointSizeStep: pointSizeStep)
// }
// else if let authorCellVC = controller as? AuthorCellVC {
// authorCellVC.updateFont(pointSizeStep: pointSizeStep)
// }
// }
// }
fileprivate func speech(poetry: Poetry) {
let title = StringUtils.titleTextFilter(poerityTitle: poetry.title)
let content = StringUtils.contentTextFilter(poerityTitle: poetry.poetry)
SpeechUtil.default.speech(texts: [title, content])
}
fileprivate func speech(author: Author) {
SpeechUtil.default.speech(texts: [author.name, author.intro])
}
fileprivate func toggleCollection(poetry: Poetry) {
let collectionArray = UserCollection.allInstances() as! [UserCollection]
let itemIndex = collectionArray.index { (userCollection) -> Bool in
return Int(userCollection.poetryId) == poetry.dNum && userCollection.poetryName == poetry.title
}
if let item = itemIndex {
collectionArray[item].delete()
self.showToast(message: SSStr.Toast.CANCEL_COLLECTION_SUCCESS)
}
else {
let userCollection = UserCollection()
userCollection.poetryId = Int64(poetry.dNum)
userCollection.poetryName = poetry.title
userCollection.userId = ""
userCollection.save({
})
self.showToast(message: SSStr.Toast.COLLECTION_SUCCESS)
}
}
}
class ImageViewContoller: UIViewController {
var image: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(image: self.image)
self.view.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
}
| 38.669789 | 263 | 0.548086 |
5ded9cec2edcab820bf4487a8d83ebe80aa39b42 | 447 |
//
// JQEmotionKeyboardView.swift
// SinaSwiftPractice
//
// Created by maoge on 16/11/22.
// Copyright © 2016年 maoge. All rights reserved.
//
import UIKit
class JQEmotionKeyboardView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.red
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 18.625 | 59 | 0.642058 |
61ba3631c0bacb371e4837f2e8e54c57568c81fa | 562 | //
// AboutCell.swift
// UserProfile
//
// Created by Antonio Escudero on 6/3/17.
// Copyright © 2017 Antonio Escudero. All rights reserved.
//
import UIKit
class AboutCell: UITableViewCell {
@IBOutlet fileprivate weak var label: UILabel!
override func awakeFromNib() {
self.label.textColor = .text
self.label.font = .regular
self.selectionStyle = .none
}
}
extension AboutCell: GenericCell {
internal func configure(value: AboutViewModel) {
self.label.text = value.about
}
}
| 17.5625 | 59 | 0.637011 |
91b16110381c1350ccff4df414cf3e12779663c1 | 2,451 | //
// AlertGetPointView..swift
// SmartLife-App
//
// Created by thanhlt on 8/3/17.
// Copyright © 2017 thanhlt. All rights reserved.
//
import UIKit
protocol AlertGetPointViewDelegate: class {
func closeAlert()
}
class AlertGetPointView: UIView {
@IBOutlet weak var mLabelTitle: UILabel!
@IBOutlet weak var mLabelDescription: UILabel!
@IBOutlet weak var mButtonClosePink: UIButton!
@IBOutlet weak var point: UILabel!
@IBOutlet weak var mButtonClose: UIButton!
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
@IBOutlet weak var mPoint: UILabel!
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
weak var delegate:AlertGetPointViewDelegate? = nil
private var scale:CGFloat = DISPLAY_SCALE
override func awakeFromNib() {
super.awakeFromNib()
scale = IS_IPAD ? DISPLAY_SCALE_IPAD : DISPLAY_SCALE
self.mButtonClosePink.layer.cornerRadius = 5.0*scale
self.mButtonClosePink.clipsToBounds = true
self.setLanguageForView()
self.setConstraintForView()
}
@IBAction func clickButtonCloseBrown(_ sender: Any) {
self.removeFromSuperview()
self.delegate?.closeAlert()
}
private func setLanguageForView(){
self.mLabelTitle.text = NSLocalizedString("alert_getpointview_label_title", comment: "")
self.mLabelDescription.text = NSLocalizedString("alert_getpointview_label_description", comment: "")
self.mButtonClosePink.setTitle(NSLocalizedString("alert_getpointview_button_gotogetpoint", comment: ""), for: .normal)
}
private func setConstraintForView() {
// self.mBottomButtonAcceptConstraint.constant = -34 * scale
// self.mHeightImageNoticeConstraint.constant = 350 * scale
}
func changeImageNoticeInView() {
// self.status = 1
// self.mHeightImageNoticeConstraint.constant = 270 * scale
// self.layoutIfNeeded()
// self.mImageNotice.image = #imageLiteral(resourceName: "img_tutorial_pickSkill_2nd")
}
func changeToSuccessView() {
// self.status = 2
// self.mButtonClose.isHidden = true
// self.mHeightImageNoticeConstraint.constant = 167 * scale
// self.layoutIfNeeded()
// self.mImageNotice.image = #imageLiteral(resourceName: "img_tutorial_pickSkill_3rd")
}
}
| 33.575342 | 126 | 0.689922 |
ab5dd25fa9483234197eec8d3dc99c8b7eb8c604 | 5,389 | //
// SwiftyMarkdown+macOS.swift
// SwiftyMarkdown
//
// Created by Anthony Keller on 09/15/2020.
// Copyright © 2020 Voyage Travel Apps. All rights reserved.
//
import Foundation
#if os(macOS)
import AppKit
extension SwiftyMarkdown {
func font( for line : SwiftyLine, characterOverride : CharacterStyle? = nil ) -> NSFont {
var fontName : String?
var fontSize : CGFloat?
var globalBold = false
var globalItalic = false
let style : FontProperties
// What type are we and is there a font name set?
switch line.lineStyle as! MarkdownLineStyle {
case .h1:
style = self.h1
case .h2:
style = self.h2
case .h3:
style = self.h3
case .h4:
style = self.h4
case .h5:
style = self.h5
case .h6:
style = self.h6
case .codeblock:
style = self.code
case .blockquote:
style = self.blockquotes
default:
style = self.body
}
fontName = style.fontName
fontSize = style.fontSize
switch style.fontStyle {
case .bold:
globalBold = true
case .italic:
globalItalic = true
case .boldItalic:
globalItalic = true
globalBold = true
case .normal:
break
}
if fontName == nil {
fontName = body.fontName
}
if let characterOverride = characterOverride {
switch characterOverride {
case .code:
fontName = code.fontName ?? fontName
fontSize = code.fontSize
case .link:
fontName = link.fontName ?? fontName
fontSize = link.fontSize
case .bold:
fontName = bold.fontName ?? fontName
fontSize = bold.fontSize
globalBold = true
case .italic:
fontName = italic.fontName ?? fontName
fontSize = italic.fontSize
globalItalic = true
case .mention:
fontName = mention.fontName ?? fontName
fontSize = mention.fontSize
case .baton:
fontName = baton.fontName ?? fontName
fontSize = baton.fontSize
case .mentionAll:
fontName = mentionAll.fontName ?? fontName
fontSize = mentionAll.fontSize
default:
break
}
}
fontSize = fontSize == 0.0 ? nil : fontSize
let finalSize : CGFloat
if let existentFontSize = fontSize {
finalSize = existentFontSize
} else {
finalSize = NSFont.systemFontSize
}
var font : NSFont
if let existentFontName = fontName {
if let customFont = NSFont(name: existentFontName, size: finalSize) {
font = customFont
} else {
font = NSFont.systemFont(ofSize: finalSize)
}
} else {
font = NSFont.systemFont(ofSize: finalSize)
}
if globalItalic {
let italicDescriptor = font.fontDescriptor.withSymbolicTraits(.italic)
font = NSFont(descriptor: italicDescriptor, size: 0) ?? font
}
if globalBold {
let boldDescriptor = font.fontDescriptor.withSymbolicTraits(.bold)
font = NSFont(descriptor: boldDescriptor, size: 0) ?? font
}
return font
}
func color( for line : SwiftyLine ) -> NSColor {
// What type are we and is there a font name set?
switch line.lineStyle as! MarkdownLineStyle {
case .h1, .previousH1:
return h1.color
case .h2, .previousH2:
return h2.color
case .h3:
return h3.color
case .h4:
return h4.color
case .h5:
return h5.color
case .h6:
return h6.color
case .body:
return body.color
case .codeblock:
return code.color
case .blockquote:
return blockquotes.color
case .unorderedList, .unorderedListIndentFirstOrder, .unorderedListIndentSecondOrder, .orderedList, .orderedListIndentFirstOrder, .orderedListIndentSecondOrder:
return body.color
case .yaml:
return body.color
case .referencedLink:
return body.color
}
}
func backgroundColor( for line : SwiftyLine ) -> NSColor? {
switch line.lineStyle as! MarkdownLineStyle {
case .codeblock:
return NSColor(red: 245 / 255.0, green: 245 / 255.0, blue: 245 / 255.0, alpha: 1)
default:
return nil
}
}
func backgroundColor( for characterOverride: CharacterStyle ) -> UIColor? {
switch characterOverride {
case .code:
return NSColor(red: 224 / 255.0, green: 224 / 255.0, blue: 224 / 255.0, alpha: 1)
case .mention:
return NSColor(red: 222 / 255.0, green: 238 / 255.0, blue: 246 / 255.0, alpha: 1)
case .baton:
return NSColor(red: 222 / 255.0, green: 238 / 255.0, blue: 246 / 255.0, alpha: 1)
case .mentionAll:
return UIColor(red: 214 / 255.0, green: 237 / 255.0, blue: 217 / 255.0, alpha: 1)
default:
return nil
}
}
func underlineStyle( for line: SwiftyLine) -> AnyObject? {
switch line.lineStyle as! MarkdownLineStyle {
case .h1, .previousH1:
return NSUnderlineStyle.thick.rawValue as AnyObject
case .h2, .previousH2:
return NSUnderlineStyle.single.rawValue as AnyObject
default:
return nil
}
}
func underlineColor( for line: SwiftyLine) -> NSColor? {
switch line.lineStyle as! MarkdownLineStyle {
case .h1, .previousH1:
return NSColor(red: 224 / 255.0, green: 224 / 255.0, blue: 224 / 255.0, alpha: 1)
case .h2, .previousH2:
return NSColor(red: 224 / 255.0, green: 224 / 255.0, blue: 224 / 255.0, alpha: 1)
default:
return nil
}
}
}
#endif
| 26.810945 | 162 | 0.6311 |
db560855eea06f4e30127dca768bc0b3f0b7b44e | 2,969 | //
// Copyright (c) 2018 Adyen B.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import Foundation
public final class Coder {
public static func decode<T: Decodable>(_ data: Data) throws -> T {
return try decoder.decode(T.self, from: data)
}
public static func decode<T: Decodable>(_ string: String) throws -> T {
return try decode(Data(string.utf8))
}
public static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
if #available(iOS 10.0, *) {
decoder.dateDecodingStrategy = .iso8601
} else {
decoder.dateDecodingStrategy = .customISO8601
}
return decoder
}()
public static func encode<T: Encodable>(_ value: T) throws -> Data {
return try encoder.encode(value)
}
public static func encode<T: Encodable>(_ value: T) throws -> String {
let data: Data = try encode(value)
guard let string = String(data: data, encoding: .utf8) else {
fatalError("Failed to convert data to UTF-8 string.")
}
return string
}
public static let encoder: JSONEncoder = {
let encoder = JSONEncoder()
if #available(iOS 10.0, *) {
encoder.dateEncodingStrategy = .iso8601
} else {
encoder.dateEncodingStrategy = .customISO8601
}
return encoder
}()
}
extension Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
static let iso8601noFS: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
return formatter
}()
}
extension JSONDecoder.DateDecodingStrategy {
static let customISO8601 = custom { decoder throws -> Date in
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
if let date = Formatter.iso8601.date(from: string) ?? Formatter.iso8601noFS.date(from: string) {
return date
}
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: \(string)")
}
}
extension JSONEncoder.DateEncodingStrategy {
static let customISO8601 = custom { date, encoder throws in
var container = encoder.singleValueContainer()
try container.encode(Formatter.iso8601.string(from: date))
}
}
| 31.924731 | 106 | 0.628158 |
9c1746651a7f49ba203a101205792848ee54c0cb | 364 | //
// MINewsTableRowController.swift
// WPNews2 WatchKit Extension
//
// Created by Istvan Szabo on 2015. 06. 15..
// Copyright (c) 2015. Istvan Szabo. All rights reserved.
//
import WatchKit
class MINewsTableRowController: NSObject {
@IBOutlet weak var interfaceImage: WKInterfaceImage!
@IBOutlet weak var interfaceLabel: WKInterfaceLabel!
}
| 20.222222 | 58 | 0.730769 |
d92457a410a32a89dd09fca1be2557ce8dfd7eec | 2,447 | //
// NetworkTools.swift
// Weibo
//
// Created by tianyao on 17/9/10.
// Copyright © 2017年 tianyao. All rights reserved.
//
import UIKit
import AFNetworking
class NetworkTools: AFHTTPSessionManager {
static let tools:NetworkTools = {
// 注意: baseURL一定要以/结尾
let url = NSURL(string: "https://api.weibo.com/")
let t = NetworkTools(baseURL: url)
// 设置AFN能够接收得数据类型
t.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as! Set<String>
return t
}()
/// 获取单粒的方法
class func shareNetworkTools() -> NetworkTools {
return tools
}
/**
发送微博
:param: text 需要发送的正文
:param: image 需要发送的图片
:param: successCallback 成功的回调
:param: errorCallback 失败的回调
*/
func sendStatus(text: String, image: UIImage?, successCallback: (status: Status)->(), errorCallback: (error: NSError)->())
{
var path = "2/statuses/"
let params = ["access_token":UserAccount.loadAccount()!.access_token! , "status": text]
if image != nil
{
// 发送图片微博
path += "upload.json"
POST(path, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
// 1.将数据转换为二进制
let data = UIImagePNGRepresentation(image!)!
// 2.上传数据
/*
第一个参数: 需要上传的二进制数据
第二个参数: 服务端对应哪个的字段名称
第三个参数: 文件的名称(在大部分服务器上可以随便写)
第四个参数: 数据类型, 通用类型application/octet-stream
*/
formData.appendPartWithFileData(data
, name:"pic", fileName:"abc.png", mimeType:"application/octet-stream");
}, success: { (_, JSON) -> Void in
successCallback(status: Status(dict: JSON as! [String : AnyObject]))
}, failure: { (_, error) -> Void in
errorCallback(error: error)
})
}else
{
// 发送文字微博
path += "update.json"
POST(path, parameters: params, success: { (_, JSON) -> Void in
successCallback(status: Status(dict: JSON as! [String : AnyObject]))
}) { (_, error) -> Void in
errorCallback(error: error)
}
}
}
}
| 31.779221 | 150 | 0.520638 |
5d1d46c5b78d707bab60a0424d0f737b2c7475a1 | 2,078 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public
struct Condition<Input>: CustomStringConvertible
{
public
typealias Body = (_ input: Input) -> Bool
//---
public
let description: String
private
let body: Body
// MARK: - Initializers
public
init(
_ description: String,
_ body: @escaping Body
)
{
self.description = description
self.body = body
}
public
init()
{
self.init("Any value") { _ in true }
}
}
//---
public
extension Condition
{
func isValid(value: Input) -> Bool
{
return body(value)
}
func validate(value: Input) throws
{
guard
body(value)
else
{
throw ConditionUnsatisfied(
input: value,
condition: description
)
}
}
}
//---
public
typealias Check<Value> = Condition<Value>
public
typealias Conditions<Value> = [Condition<Value>]
| 22.835165 | 79 | 0.668431 |
29307962a5699994a66684ea80e11f3bd88d6816 | 661 | //
// MediaPlayController.swift
// AssemblyManager_Example
//
// Created by apple on 2021/12/18.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import UIKit
import AssemblyManager
class MediaPlayController: LandScapeController {
@IBOutlet weak var vPreview: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
MediaManager.shared.mediaPlayHalfOrFullScreen(view: self.vPreview, screenType: .full) {
}
}
@IBAction func back() {
self.dismiss(animated: true, completion: nil)
}
}
| 22.793103 | 95 | 0.67171 |
f9399f2d6584e312ba95d2ac1a65d81dac58ac7c | 11,484 | import UIKit
import PinLayout
final class AllClothesViewController: UIViewController {
private let headerView = UIView()
private let moreButton = UIButton()
private let pageTitle = UILabel()
private let emptyLabel = UILabel()
private let categoriesTableView = UITableView.customTableView()
private let dropMenuView = DropDownView()
private let screenBounds = UIScreen.main.bounds
private var tapOnMainViewGestureRecognizer: UITapGestureRecognizer!
private var tapOnHeaderViewGestureRecognizer: UITapGestureRecognizer!
private var menuIsDropped: Bool?
var editMode: Bool = false
var state: EditButtonState?
var output: AllClothesViewOutput?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.setNeedsLayout()
view.layoutIfNeeded()
if let state = state {
changeEditButton(state: state)
}
output?.didLoadView()
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
output?.didLoadView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
output?.forceHideDropView()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layoutUI()
}
@objc private func didTapMoreButton() {
output?.didTapMoreMenuButton()
}
@objc private func didTapEditButton() {
output?.didTapEditButton()
}
@objc private func didRefreshRequested() {
output?.didRefreshRequested()
}
}
extension AllClothesViewController {
private func setupUI() {
setupBackground()
setupHeaderView()
setupPageTitle()
setupEditButton()
setupCategoriesTableView()
setupDropMenuView()
setupEmptyTextLabel()
setupGestureRecognizers()
}
private func layoutUI() {
layoutHeaderView()
layoutPageTitle()
layoutEditButton()
layoutCategoriesTableView()
layoutEmptyTextLabel()
layoutDropMenuView()
}
private func setupBackground() {
self.view.backgroundColor = GlobalColors.backgroundColor
}
// MARK: HeaderView
private func setupHeaderView() {
self.view.addSubview(headerView)
}
private func layoutHeaderView() {
headerView.backgroundColor = GlobalColors.mainBlueScreen
self.headerView.pin
.top()
.left()
.right()
.height(16%)
}
// MARK: Page Title
private func setupPageTitle() {
pageTitle.numberOfLines = 2
pageTitle.textAlignment = .center
pageTitle.text = "Мои предметы"
pageTitle.font = UIFont(name: "DMSans-Bold", size: 25)
headerView.addSubview(pageTitle)
}
private func layoutPageTitle() {
pageTitle.textColor = GlobalColors.backgroundColor
pageTitle.pin
.hCenter()
.vCenter().marginTop(10%)
.sizeToFit()
}
// MARK: edit Button
private func setupEditButton() {
moreButton.addTarget(self, action: #selector(didTapMoreButton), for: .touchUpInside)
headerView.addSubview(moreButton)
}
private func layoutEditButton() {
moreButton.setImage(
UIImage(systemName: "square.and.pencil"),
for: .normal
)
moreButton.tintColor = GlobalColors.backgroundColor
moreButton.contentVerticalAlignment = .fill
moreButton.contentHorizontalAlignment = .fill
moreButton.pin
.height(25)
.width(25)
.top(pageTitle.frame.midY - moreButton.bounds.height / 2)
.right(5%)
}
// MARK: edit Button
private func setupEmptyTextLabel() {
emptyLabel.text = "Создайте категории одежды с помощью меню в верхнем правом углу экрана и добавьте в них предметы гардероба."
emptyLabel.textAlignment = .center
emptyLabel.font = UIFont(name: "DMSans-Bold", size: 20)
emptyLabel.textColor = GlobalColors.darkColor
emptyLabel.adjustsFontSizeToFitWidth = true
emptyLabel.minimumScaleFactor = 0.1
emptyLabel.numberOfLines = 0
emptyLabel.sizeToFit()
emptyLabel.isHidden = true
view.addSubview(emptyLabel)
}
private func layoutEmptyTextLabel() {
emptyLabel.pin
.center()
.height(20%)
.width(90%)
}
// MARK: categories table view
private func setupCategoriesTableView() {
let refreshControl = UIRefreshControl()
categoriesTableView.delegate = self
categoriesTableView.dataSource = self
categoriesTableView.separatorStyle = .none
categoriesTableView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(didRefreshRequested), for: .valueChanged)
categoriesTableView.register(
ItemCollectionCell.self,
forCellReuseIdentifier: ItemCollectionCell.identifier
)
categoriesTableView.contentInset = UIEdgeInsets(
top: 10,
left: 0,
bottom: 0,
right: 0
)
categoriesTableView.setContentOffset(CGPoint(x: .zero, y: -10), animated: true)
view.addSubview(categoriesTableView)
}
private func layoutCategoriesTableView() {
if let tabbar = tabBarController?.tabBar {
categoriesTableView.pin
.below(of: headerView)// .marginTop(8)
.left()
.right()
.above(of: tabbar)
} else {
categoriesTableView.pin
.below(of: headerView)
.left()
.right()
.bottom()
}
}
// MARK: Drop Menu
private func layoutDropMenuView() {
guard let isDropping = menuIsDropped else {
return
}
if isDropping {
showDropDownMenu()
} else {
hideDropDownMenu()
}
}
private func setupDropMenuView() {
view.addSubview(dropMenuView)
dropMenuView.delegate = self
dropMenuView.dropShadow()
dropMenuView.isUserInteractionEnabled = true
}
private func showDropDownMenu() {
dropMenuView.pin
.below(of: moreButton)
.marginTop(20)
.right(10)
.height(0)
.width(0)
UIView.animate(withDuration: 0.3) {
self.dropMenuView.pin
.below(of: self.moreButton)
.marginTop(20)
.right(10)
.height(13%)
.width(43%)
self.view.layoutIfNeeded()
}
}
private func hideDropDownMenu() {
dropMenuView.pin
.below(of: moreButton)
.marginTop(20)
.right(10)
.height(13%)
.width(43%)
UIView.animate(withDuration: 0.3) {
self.dropMenuView.pin
.below(of: self.moreButton)
.marginTop(20)
.right(10)
.height(0)
.width(0)
self.view.layoutIfNeeded()
}
}
// MARK: Gesture Recognizers
private func setupGestureRecognizers() {
tapOnMainViewGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapMoreButton))
self.categoriesTableView.isUserInteractionEnabled = true
tapOnMainViewGestureRecognizer.isEnabled = false
tapOnMainViewGestureRecognizer.numberOfTapsRequired = 1
categoriesTableView.addGestureRecognizer(tapOnMainViewGestureRecognizer)
tapOnHeaderViewGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapMoreButton))
tapOnHeaderViewGestureRecognizer.numberOfTapsRequired = 1
tapOnHeaderViewGestureRecognizer.isEnabled = false
headerView.addGestureRecognizer(tapOnHeaderViewGestureRecognizer)
}
private func enableGesture() {
tapOnMainViewGestureRecognizer.isEnabled = true
tapOnHeaderViewGestureRecognizer.isEnabled = true
}
private func disableGesture() {
tapOnMainViewGestureRecognizer.isEnabled = false
tapOnHeaderViewGestureRecognizer.isEnabled = false
}
}
extension AllClothesViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return output?.getCategoriesCount() ?? 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return GlobalConstants.cellSize.height * 1.3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = categoriesTableView.dequeueReusableCell(
withIdentifier: ItemCollectionCell.identifier, for: indexPath
) as? ItemCollectionCell else {
return UITableViewCell()
}
guard let presenter = self.output else { return UITableViewCell() }
cell.setData(output: presenter, index: indexPath.row, editMode: editMode)
return cell
}
}
extension AllClothesViewController: AllClothesViewInput {
func hideEmptyLabel() {
emptyLabel.isHidden = true
}
func showEmptyLable() {
emptyLabel.isHidden = false
}
func tableViewScrollTo(row: Int) {
categoriesTableView.scrollToRow(at: IndexPath(row: row, section: 0), at: .middle, animated: true)
}
func getEditMode() -> Bool {
return self.editMode
}
func showDropMenu() {
enableGesture()
menuIsDropped = true
view.setNeedsLayout()
view.layoutIfNeeded()
}
func hideDropMenu() {
disableGesture()
menuIsDropped = false
view.setNeedsLayout()
view.layoutIfNeeded()
}
func toggleEditMode() {
editMode.toggle()
}
func reloadData() {
self.categoriesTableView.refreshControl?.endRefreshing()
self.categoriesTableView.reloadData()
}
func changeEditButton(state: EditButtonState) {
self.state = state
switch state {
case .edit:
moreButton.setImage(
UIImage(systemName: "square.and.pencil"),
for: .normal
)
moreButton.removeTarget(self, action: #selector(didTapEditButton), for: .touchUpInside)
moreButton.addTarget(self, action: #selector(didTapMoreButton), for: .touchUpInside)
case .accept:
moreButton.setImage(UIImage(systemName: "checkmark"), for: .normal)
moreButton.removeTarget(self, action: #selector(didTapMoreButton), for: .touchUpInside)
moreButton.addTarget(self, action: #selector(didTapEditButton), for: .touchUpInside)
}
}
}
extension AllClothesViewController: DropDownViewDelegate {
var topTitle: String {
"Создать категорию"
}
var topImage: UIImage {
UIImage(systemName: "plus.circle") ?? UIImage()
}
var bottomTitle: String {
"Редактировать"
}
var bottomImage: UIImage {
UIImage(systemName: "square.and.pencil") ?? UIImage()
}
func didFirstTap() {
output?.didTapNewCategoryButton()
}
func didSecondTap() {
output?.didTapEditButton()
}
}
| 29.147208 | 134 | 0.624782 |
188aeb240aa25f6ad0bc442e5974bf9d1eef4675 | 2,638 | import Foundation
import HTTP
public final class FileMiddleware: Middleware {
private var publicDir: String
private let loader = DataFile()
@available(*, deprecated: 1.2, message: "This has been renamed to publicDir: and now represents the absolute path. Use `workDir.finished(\"/\") + \"Public/\"` to reproduce existing behavior.")
public init(workDir: String) {
self.publicDir = workDir.finished(with: "/") + "Public/"
}
public init(publicDir: String) {
// Remove last "/" from the publicDir if present, so we can directly append uri path from the request.
self.publicDir = publicDir.finished(with: "/")
}
public func respond(to request: Request, chainingTo next: Responder) throws -> Response {
do {
return try next.respond(to: request)
} catch Abort.notFound {
// Check in file system
var path = request.uri.path
if path.hasPrefix("/") {
path = String(path.characters.dropFirst())
}
let filePath = publicDir + path
guard
let attributes = try? Foundation.FileManager.default.attributesOfItem(atPath: filePath),
let modifiedAt = attributes[.modificationDate] as? Date,
let fileSize = attributes[.size] as? NSNumber
else {
throw Abort.notFound
}
var headers: [HeaderKey: String] = [:]
// Set Content-Type header based on the media type
if
let fileExtension = filePath.components(separatedBy: ".").last,
let type = mediaTypes[fileExtension]
{
headers["Content-Type"] = type
}
// Generate ETag value, "HEX value of last modified date" + "-" + "file size"
let fileETag = "\(modifiedAt.timeIntervalSince1970)-\(fileSize.intValue)"
headers["ETag"] = fileETag
// Check if file has been cached already and return NotModified response if the etags match
if fileETag == request.headers["If-None-Match"] {
return Response(status: .notModified, headers: headers, body: .data([]))
}
// File exists and was not cached, returning content of file.
if let fileBody = try? loader.load(path:filePath) {
return Response(status: .ok, headers: headers, body: .data(fileBody))
} else {
print("unable to load path")
throw Abort.notFound
}
}
}
}
| 39.373134 | 196 | 0.567854 |
69e3b7b0d28d82b80d73f9519c2b456d2cb80cea | 1,842 | //
// StatusDetailService.swift
// SCWeibo
//
// Created by 王书超 on 2021/5/14.
//
import Alamofire
import Foundation
class StatusDetailService {
}
// MARK: - Like
extension StatusDetailService {
func sendLikeAction(liked: Bool, statusId: Int, completion: @escaping (_ success: Bool) -> Void) {
ApiConfigService.getApiConfig { _, st, _ in
self.postLike(liked: liked, statusId: statusId, st: st, completion: completion)
}
}
private func postLike(liked: Bool, statusId: Int, st: String, completion: @escaping (_ success: Bool) -> Void) {
let URLString = liked ? URLSettings.attitudesCreate : URLSettings.attitudesDestroy
var params = [String: Any]()
params["attitude"] = "heart"
params["id"] = statusId
params["st"] = st
var headers = HTTPHeaders()
headers.add(HTTPHeader(name: "referer", value: "https://m.weibo.cn/beta"))
AF.request(URLString, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
var jsonResult: Dictionary<AnyHashable, Any>?
switch response.result {
case let .success(json):
if let dict = json as? Dictionary<AnyHashable, Any> {
jsonResult = dict
}
case .failure:
jsonResult = nil
}
if jsonResult?["data"] == nil {
completion(false)
}
completion(true)
}
}
}
// MARK: - Favorite
extension StatusDetailService {
func sendFavoriteAction(favorited: Bool, statusId: Int, completion: @escaping (_ success: Bool) -> Void) {
StatusCommonActionManager.sendFavoriteAction(statusId: statusId, favorited: favorited, completion: completion)
}
}
| 30.196721 | 141 | 0.609663 |
e238c86a8cadb6c8d90007f1db39e4a51548be90 | 2,535 | //
// SSUIPageSlide.swift
// Okee
//
// Created by Son Nguyen on 1/14/21.
//
import Foundation
import SwiftUI
@available(iOS 14.0, *)
public struct SSUIPageSlide: View {
@State private var selection = 0
let pages: [AnyView]
let config: SSUIPageSlideConfig
var controls: (Binding<Int>) -> AnyView
public init(config: SSUIPageSlideConfig, @ViewBuilder pages: () -> [AnyView], controls: @escaping (Binding<Int>) -> AnyView) {
self.pages = pages()
self.config = config
self.controls = controls
}
public var body: some View {
switch config.indicator.style {
case .system, .none:
return ZStack {
TabView(selection: $selection) {
ForEach(0..<pages.count, id: \.self) { index in
pages[index].tag(index)
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: config.indicator.style == .system ? .automatic : .never))
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: config.indicator.style == .system ? .automatic : .never))
.animation(.linear)
.applySSUIConfig(config.config)
controls(selectionBinding)
}
.anyView
case .slidingBar:
return ZStack {
TabView(selection: $selection) {
ForEach(0..<pages.count, id: \.self) { index in
pages[index].tag(index)
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.animation(.linear)
VStack {
Spacer()
SSUIPageIndicator(selection: $selection, style: config.indicator.style,
count: pages.count, config: config.indicator.config)
.padding(.bottom, SSUI.safeAreaBottomInset != 0 ? SSUI.safeAreaBottomInset : nil)
}
controls(selectionBinding)
}
.applySSUIConfig(config.config)
.anyView
}
}
private var selectionBinding: Binding<Int> {
Binding<Int>(get: {
selection
}, set: { (value) in
guard value < pages.count && value >= 0 else {
return
}
selection = value
})
}
}
| 32.088608 | 131 | 0.501381 |
d7b111e7ffec54c1a9dc7106bc5562b768540363 | 5,434 | import Combine
import ComposableArchitecture
import NewGameCore
import UIKit
class NewGameViewController: UIViewController {
struct ViewState: Equatable {
let isGameActive: Bool
let isLetsPlayButtonEnabled: Bool
let oPlayerName: String?
let xPlayerName: String?
}
enum ViewAction {
case gameDismissed
case letsPlayButtonTapped
case logoutButtonTapped
case oPlayerNameChanged(String?)
case xPlayerNameChanged(String?)
}
let store: Store<NewGameState, NewGameAction>
let viewStore: ViewStore<ViewState, ViewAction>
init(store: Store<NewGameState, NewGameAction>) {
self.store = store
self.viewStore = ViewStore(store.scope(state: { $0.view }, action: NewGameAction.view))
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "New Game"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Logout",
style: .done,
target: self,
action: #selector(logoutButtonTapped)
)
let playerXLabel = UILabel()
playerXLabel.text = "Player X"
playerXLabel.setContentHuggingPriority(.required, for: .horizontal)
let playerXTextField = UITextField()
playerXTextField.borderStyle = .roundedRect
playerXTextField.placeholder = "Blob Sr."
playerXTextField.setContentCompressionResistancePriority(.required, for: .horizontal)
playerXTextField.addTarget(
self, action: #selector(playerXTextChanged(sender:)), for: .editingChanged)
let playerXRow = UIStackView(arrangedSubviews: [
playerXLabel,
playerXTextField,
])
playerXRow.spacing = 24
let playerOLabel = UILabel()
playerOLabel.text = "Player O"
playerOLabel.setContentHuggingPriority(.required, for: .horizontal)
let playerOTextField = UITextField()
playerOTextField.borderStyle = .roundedRect
playerOTextField.placeholder = "Blob Jr."
playerOTextField.setContentCompressionResistancePriority(.required, for: .horizontal)
playerOTextField.addTarget(
self, action: #selector(playerOTextChanged(sender:)), for: .editingChanged)
let playerORow = UIStackView(arrangedSubviews: [
playerOLabel,
playerOTextField,
])
playerORow.spacing = 24
let letsPlayButton = UIButton(type: .system)
letsPlayButton.setTitle("Let’s Play!", for: .normal)
letsPlayButton.addTarget(self, action: #selector(letsPlayTapped), for: .touchUpInside)
let rootStackView = UIStackView(arrangedSubviews: [
playerXRow,
playerORow,
letsPlayButton,
])
rootStackView.isLayoutMarginsRelativeArrangement = true
rootStackView.layoutMargins = .init(top: 0, left: 32, bottom: 0, right: 32)
rootStackView.translatesAutoresizingMaskIntoConstraints = false
rootStackView.axis = .vertical
rootStackView.spacing = 24
self.view.addSubview(rootStackView)
NSLayoutConstraint.activate([
rootStackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
rootStackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
rootStackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
])
self.viewStore.produced.isLetsPlayButtonEnabled
.assign(to: \.isEnabled, on: letsPlayButton)
self.viewStore.produced.oPlayerName
.assign(to: \.text, on: playerOTextField)
self.viewStore.produced.xPlayerName
.assign(to: \.text, on: playerXTextField)
self.store
.scope(state: { $0.game }, action: NewGameAction.game)
.ifLet(
then: { [weak self] gameStore in
self?.navigationController?.pushViewController(
GameViewController(store: gameStore),
animated: true
)
},
else: { [weak self] in
guard let self = self else { return }
self.navigationController?.popToViewController(self, animated: true)
}
)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
if !self.isMovingToParent {
self.viewStore.send(.gameDismissed)
}
}
@objc private func logoutButtonTapped() {
self.viewStore.send(.logoutButtonTapped)
}
@objc private func playerXTextChanged(sender: UITextField) {
self.viewStore.send(.xPlayerNameChanged(sender.text))
}
@objc private func playerOTextChanged(sender: UITextField) {
self.viewStore.send(.oPlayerNameChanged(sender.text))
}
@objc private func letsPlayTapped() {
self.viewStore.send(.letsPlayButtonTapped)
}
}
extension NewGameState {
var view: NewGameViewController.ViewState {
.init(
isGameActive: self.game != nil,
isLetsPlayButtonEnabled: !self.oPlayerName.isEmpty && !self.xPlayerName.isEmpty,
oPlayerName: self.oPlayerName,
xPlayerName: self.xPlayerName
)
}
}
extension NewGameAction {
static func view(_ action: NewGameViewController.ViewAction) -> Self {
switch action {
case .gameDismissed:
return .gameDismissed
case .letsPlayButtonTapped:
return .letsPlayButtonTapped
case .logoutButtonTapped:
return .logoutButtonTapped
case let .oPlayerNameChanged(name):
return .oPlayerNameChanged(name ?? "")
case let .xPlayerNameChanged(name):
return .xPlayerNameChanged(name ?? "")
}
}
}
| 30.022099 | 91 | 0.708502 |
e9f98701c0e1bf56686d3ddc77fd8401722f1eb6 | 238 | // 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 a{
class a{
struct B{
struct B{
let h{
deinit{
class
case,
| 18.307692 | 87 | 0.752101 |
dda7b74de32e8f45e99a429bf1d9e969cd1f6475 | 1,332 | //
// Env.swift
// Hyakuninisshu
//
// Created by Rei Matsushita on 2021/02/06.
//
import Foundation
class Env {
static let shared = Env()
enum EnvKey: String {
case adUnitId = "AD_UNIT_ID"
case gADApplicationIdentifier = "GAD_APPLICATION_IDENTIFIER"
case testDeviceIdentifier = "TEST_DEVICE_IDENTIFIER"
}
func configure() {
var resource = ".env"
#if DEBUG
resource = ".debug.env"
#endif
guard let path = Bundle.main.path(forResource: resource, ofType: nil) else {
fatalError("Not found: '.env'.\nPlease create .env file.")
}
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let str = String(data: data, encoding: .utf8) ?? "Empty File"
let clean = str.replacingOccurrences(of: "\"", with: "").replacingOccurrences(
of: "'", with: "")
let envVars = clean.components(separatedBy: "\n")
for envVar in envVars {
/// TODO: キーのチェックまでしたほうがいいかな
let keyVal = envVar.components(separatedBy: "=")
if keyVal.count == 2 {
setenv(keyVal[0], keyVal[1], 1)
}
}
} catch {
fatalError(error.localizedDescription)
}
}
func value(_ key: EnvKey) -> String? {
return ProcessInfo.processInfo.environment[key.rawValue]
}
private init() {
}
}
| 24.666667 | 84 | 0.617117 |
39a5a0bd02cee30bf5ee18abe4a70b210c19bd7c | 785 | //
// MainCollectionCellView.swift
// myTunes
//
// Created by Hüsnü Taş on 29.10.2021.
//
import Foundation
class MainCollectionViewCell: BaseCollectionViewCell {
private lazy var mainContentView: MainCollectionContentView = {
let temp = MainCollectionContentView()
temp.translatesAutoresizingMaskIntoConstraints = false
return temp
}()
override func addMajorViewComponents() {
super.addMajorViewComponents()
addContentView()
}
func setData(with cellData: MainCollectionContentViewData) {
mainContentView.setData(by: cellData)
}
private func addContentView() {
contentView.addSubview(mainContentView)
mainContentView.expandView(to: contentView)
}
}
| 23.088235 | 67 | 0.675159 |
1c7a76fa25e673f6963ac336d7bf52c0ebfa1ce1 | 375 | //
// WKWebViewExtensions.swift
// DDMvvm
//
// Created by Dao Duy Duong on 9/26/18.
//
import RxCocoa
import RxSwift
import UIKit
import WebKit
public extension Reactive where Base: WKWebView {
var url: Binder<URL?> {
Binder(base) { view, url in
guard let url = url else { return }
view.stopLoading()
view.load(URLRequest(url: url))
}
}
}
| 17.045455 | 49 | 0.650667 |
4a3ffdbc5127c2be867af285e503454c3fad75ca | 705 | //
// ItemSlideMenuTableViewCell.swift
// smoothies
//
// Created by zhen xin tan ruan on 4/26/19.
// Copyright © 2019 zhen xin tan ruan. All rights reserved.
//
import UIKit
class ItemSlideMenuTableViewCell: UITableViewCell, ReusableView, NibloadableView {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func loadData(item: ItemSlideMenu) {
iconImageView.image = item.icon
titleLabel.text = item.name
}
}
| 23.5 | 82 | 0.699291 |
9ca4b40f16ec68295d5a5663b019c9ebae772806 | 2,560 | //
// StartupShutdownTestCase.swift
// AutoTester
//
// Created by Steve Gifford on 10/29/19.
// Copyright © 2019 mousebird consulting. All rights reserved.
//
import UIKit
class StartupShutdownTestCase: MaplyTestCase {
override init() {
super.init()
self.name = "Repeated Startup/Shutdown"
self.captureDelay = 4
self.implementations = [.globe,.map]
}
var testCase = VectorMBTilesTestCase()
func startGlobe() {
globeViewController = WhirlyGlobeViewController()
baseViewController = globeViewController
testView?.addSubview(globeViewController!.view)
globeViewController!.view.frame = testView!.bounds
globeViewController!.delegate = self
// Note: Should also be adding as a child of the view controller
testCase.setUpWithGlobe(globeViewController!)
// Shut it down in a bit
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.stopGlobe()
}
}
func stopGlobe() {
// globeViewController?.teardown()
globeViewController?.view.removeFromSuperview()
// Start it back up again in a bit
// Note: Check to see if we're still valid here
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.startGlobe()
}
}
func startMap() {
mapViewController = MaplyViewController()
baseViewController = mapViewController
testView?.addSubview(mapViewController!.view)
mapViewController!.view.frame = testView!.bounds
mapViewController!.delegate = self
// Note: Should also be adding as a child of the view controller
testCase.setUpWithMap(mapViewController!)
// Shut it down in a bit
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.stopMap()
}
}
func stopMap() {
// globeViewController?.teardown()
mapViewController?.view.removeFromSuperview()
// Start it back up again in a bit
// Note: Check to see if we're still valid here
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.startMap()
}
}
// We need to create the globe controller ourselves so we can shut it down
override func runGlobeTest(withLock lock: DispatchGroup) {
startGlobe()
}
// Likewise for the map
override func runMapTest(withLock lock: DispatchGroup) {
startMap()
}
}
| 29.090909 | 78 | 0.616797 |
4a9b6e902c04fa23dcf038bcd537135e8b31fbe0 | 2,686 | //
// HomeInteractor.swift
// MarvelList
//
// Created by MacDev on 06/10/20.
// Copyright © 2020 Alexandre Abreu. All rights reserved.
//
import UIKit
protocol HomeBusinessLogic {
func getHeroes()
}
protocol HomeDataStoreProtocol {
var currentOffset: Int { get set }
var total: Int { get set }
var homeViewModel: HomeModels.HomeViewModel? { get set }
func setImage(_ image:UIImage, forIndex: Int, at: HomeModels.HomePersistance)
func saveDataToLocalStorage()
}
class HomeInteractor: HomeBusinessLogic, HomeDataStoreProtocol {
//MARK: - Properties
private var presenter: HomePresentationLogic
private var worker: HomeWorkerProtocol
var dataStorage = MarvelListDataStorage()
//MARK: - DataStore
var currentOffset: Int = 0
var total: Int = 0
var homeViewModel: HomeModels.HomeViewModel?
//MARK: - Init
init(presenter: HomePresentationLogic, worker: HomeWorkerProtocol) {
self.presenter = presenter
self.worker = worker
}
//MARK: - Functions
func getHeroes() {
if homeViewModel == nil {
presenter.presentLoader()
//MARK: - Core Data
if let heroesList = dataStorage.retreiveHeroes() {
if heroesList.count > 0 {
currentOffset = heroesList.count
presenter.presentLocalStorage(heroes: heroesList, hasMore: MarvelListDataStorage().hasMore())
return
}
}
}
let request = HomeRequest(offset: currentOffset)
worker.getHeroes(request: request, onSuccess: { result in
self.currentOffset = result.data.offset + result.data.count
self.total = result.data.total
self.presenter.presentSuccess(result, viewModel: self.homeViewModel)
}, onFailure: { error in
self.presenter.presentError(error)
})
}
func setImage(_ image:UIImage, forIndex: Int, at: HomeModels.HomePersistance) {
switch at {
case .carroussel:
homeViewModel?.carroussel[forIndex].image = image
case .tableView:
homeViewModel?.tableView[forIndex].image = image
}
}
func saveDataToLocalStorage() {
guard let model = homeViewModel, total > 0 else {
return
}
var heroesArray: [HomeModels.HomeViewModel.Hero] = []
heroesArray.append(contentsOf: model.carroussel)
heroesArray.append(contentsOf: model.tableView)
let hasMore: Bool = self.currentOffset < self.total
dataStorage.save(heroes: heroesArray, hasMore: hasMore)
}
}
| 31.6 | 113 | 0.628071 |
75e7fcab7ceba4e1efa7cb123a570dc2b6e3fa58 | 949 | //
// String+Name.swift
// dikitgen
//
// Created by Yosuke Ishikawa on 2017/09/16.
//
import Foundation
extension String {
var firstWordLowercased: String {
var firstlowercaseIndex: String.Index?
for (offset, character) in enumerated() where offset > 0 {
if let scalar = character.unicodeScalars.first,
character.unicodeScalars.count == 1 &&
CharacterSet.lowercaseLetters.contains(scalar) {
if offset == 1 {
firstlowercaseIndex = index(startIndex, offsetBy: offset)
} else {
firstlowercaseIndex = index(startIndex, offsetBy: offset - 1)
}
break
}
}
let wordRange = ..<(firstlowercaseIndex ?? endIndex)
var newString = self
newString.replaceSubrange(wordRange, with: self[wordRange].lowercased())
return newString
}
}
| 28.757576 | 81 | 0.574289 |
1da96b6979cc2b6bec2ddf90de4fe95ff483f5ad | 1,662 | //
// idmeTHETests.swift
// idmeTHETests
//
// Created by Mohamed Farook, Irshad on 1/18/22.
//
import XCTest
@testable import idmeTHE
class idmeTHETests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testHistoryData() throws {
guard let path = Bundle(for: type(of: self)).path(forResource: "purchaseHistory", ofType: "json")
else { fatalError("Can't find purchaseHistory.json file") }
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601Full)
if let decodedResponse = try? decoder.decode(Purchases.self, from: data), let purchase = decodedResponse.first {
XCTAssertEqual(purchase.purchaseDate.debugDescription, "2020-12-30 00:00:00 +0000")
XCTAssertEqual(purchase.purchaseDescription, "I'll input the neural ADP panel, that should card the JBOD application!")
} else {
XCTAssertFalse(true)
}
}
func testPhoneNumberFormater() throws {
XCTAssertEqual("17025555555".toPhoneNumber,"+1 (702) 555-5555")
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 33.918367 | 131 | 0.659446 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.