label
int64 0
1
| text
stringlengths 0
2.8M
|
---|---|
0 | //
// PhotosViewerTransitioningDelegate.swift
// JNPhotosViewer
//
// Created by JN Disrupter on 8/29/18.
// Copyright © 2018 JN Disrupter. All rights reserved.
//
import UIKit
/// Photos Viewer Transitioning Delegate
public class PhotosViewerTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
/// Presentation Transition
private var presentationTransition: PhotosViewerPresentationAnimatedTransitioning?
/// Dismissal Transition
private var dismissalTransition: PhotosViewerDismissalAnimatedTransitioning?
/// Dismissal Interactor
private var dismissalInteractor: PhotosViewerDismissalInteractorTransitioning?
/// Dismiss Interactively
public var forcesNonInteractiveDismissal = false
/**
Setup
- Parameter startingImageView: Starting image view to start animation from it
- Parameter endingImageView: Ending image view to end animating to it.
*/
public func setupPresentation(startingImageView: UIImageView? = nil) {
if let startingImageView = startingImageView {
self.presentationTransition = PhotosViewerPresentationAnimatedTransitioning(startingImageView: startingImageView)
}
}
/**
Setup
- Parameter startingImageView: Starting image view to start animation from it
- Parameter endingImageView: Ending image view to end animating to it.
*/
public func setupDismissal(startingImageView: UIImageView? = nil, endingImageView: UIImageView? = nil) {
// Cancel presentation transition
self.presentationTransition?.cancel()
// Hide new ending view
if let endingImageView = endingImageView, endingImageView.superview != nil {
endingImageView.isHidden = true
self.presentationTransition?.setStartingImageView(startingImageView: endingImageView)
}
if let startingImageView = startingImageView , startingImageView.superview != nil , endingImageView != nil {
if self.dismissalTransition == nil {
self.dismissalTransition = PhotosViewerDismissalAnimatedTransitioning(startingImageView: startingImageView, endingImageView: endingImageView)
self.dismissalInteractor = PhotosViewerDismissalInteractorTransitioning(transition: self.dismissalTransition!)
} else {
self.dismissalTransition?.setupDismissal(startingImageView: startingImageView, endingImageView: endingImageView)
}
}
}
/**
Did pan with gesture recognizer
- Parameter panGestureRecognizer: Pan gesture recognizer
- Parameter viewToPan: View to pan
*/
public func didPanWithPanGestureRecognizer(panGestureRecognizer: UIPanGestureRecognizer, viewToPan: UIView) {
let translation = panGestureRecognizer.translation(in: viewToPan)
let velocity = panGestureRecognizer.velocity(in: viewToPan)
switch panGestureRecognizer.state {
case .changed:
let percentage = abs(translation.y) / viewToPan.bounds.height
var rationPercentage = abs(1 - percentage)
if rationPercentage < 0.4 {
rationPercentage = 0.4
}
self.dismissalInteractor?.update(transform: CGAffineTransform(translationX: translation.x * rationPercentage, y: translation.y * rationPercentage), percentage: percentage)
case .ended, .cancelled:
self.forcesNonInteractiveDismissal = false
let percentage = abs(translation.y + velocity.y) / viewToPan.bounds.height
if percentage > 0.35 {
self.dismissalInteractor?.finish()
} else {
self.dismissalInteractor?.cancel()
}
default: break
}
}
/// MARK: - UIViewControllerTransitioningDelegate
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.presentationTransition
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.dismissalTransition
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return self.forcesNonInteractiveDismissal ? self.dismissalInteractor : nil
}
}
|
0 | //
// UIControl+TSExtension.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/9/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
fileprivate class TSClosureWrapper : NSObject {
let _callback : () -> Void
init(callback : @escaping () -> Void) {
_callback = callback
}
@objc func invoke() {
_callback()
}
}
fileprivate var AssociatedClosure: UInt8 = 0
public extension UIControl {
/**
UIControl with closure callback
- parameter events: UIControlEvents
- parameter callback: callback
*/
func ts_addEventHandler(forControlEvent controlEvent: UIControl.Event, handler callback: @escaping () -> Void) {
let wrapper = TSClosureWrapper(callback: callback)
addTarget(wrapper, action:#selector(TSClosureWrapper.invoke), for: controlEvent)
objc_setAssociatedObject(self, &AssociatedClosure, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
|
0 | import Combine
import SwiftUI
/// A property wrapper that works like `ObservedObject`, but takes an optional object instead.
///
/// The `@ObservedObject` wrapper requires, that the observed object actually exists. In some cases
/// it's convenient to be able to observe an object which might be nil. This is where
/// `@ObservedOptionalObject` can be used.
///
/// ```swift
/// struct SomeView: View {
/// // Instead of
/// @ObservedObject var anObject: Model? // Won't work
///
/// // use
/// @ObservedOptionalObject var anObject: Model?
///
/// var body: some View {
/// HStack {
/// Text("Name")
/// if let name = anObject?.name {
/// Text(name)
/// }
/// }
/// }
/// }
/// ```
@propertyWrapper public struct ObservedOptionalObject<T: ObservableObject>: DynamicProperty {
private(set) public var wrappedValue: T?
public init(wrappedValue: T?) {
self.wrappedValue = wrappedValue
let proxy = Proxy()
self.proxy = proxy
self.proxyObject = proxy
}
public mutating func update() {
let proxy = self.proxy
self.proxyMonitor = self.wrappedValue?.objectWillChange.sink { [weak proxy] _ in
proxy?.objectWillChange.send()
}
}
// - Private
@State private var proxy: Proxy
@ObservedObject private var proxyObject: Proxy
private var proxyMonitor: AnyCancellable?
private class Proxy: ObservableObject {
}
// - Projection
public var projectedValue: Wrapper {
Wrapper( wrappedObject: wrappedValue )
}
@dynamicMemberLookup public struct Wrapper {
let wrappedObject: T?
/// Returns an optional binding to the resulting value of a given key path.
///
/// - Parameter keyPath : A key path to a specific resulting value.
///
/// - Returns: A new binding.
public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<T, Subject>) -> Binding<Subject>? {
guard let wrappedObject = self.wrappedObject
else { return nil }
return Binding {
wrappedObject[keyPath: keyPath]
} set: { value in
wrappedObject[keyPath: keyPath] = value
}
}
}
}
|
0 | import Foundation
import NIO
extension EventLoopFuture {
public func completeQuietly() {
whenComplete { _ in }
}
public func void() -> EventLoopFuture<Void> {
return map { _ in Void() }
}
}
extension EventLoopFuture where Value == String {
func trimMap() -> EventLoopFuture<String> {
return map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
}
}
|
0 | //
// ChatInputView.swift
// Antidote
//
// Created by Dmytro Vorobiov on 13.01.16.
// Copyright © 2016 dvor. All rights reserved.
//
import UIKit
import SnapKit
private struct Constants {
static let TopBorderHeight = 0.5
static let Offset: CGFloat = 5.0
static let CameraHorizontalOffset: CGFloat = 10.0
static let CameraBottomOffset: CGFloat = -10.0
static let TextViewMinHeight: CGFloat = 35.0
}
protocol ChatInputViewDelegate: class {
func chatInputViewCameraButtonPressed(view: ChatInputView, cameraView: UIView)
func chatInputViewSendButtonPressed(view: ChatInputView)
func chatInputViewTextDidChange(view: ChatInputView)
}
class ChatInputView: UIView {
weak var delegate: ChatInputViewDelegate?
var text: String {
get {
return textView.text
}
set {
textView.text = newValue
updateViews()
}
}
var maxHeight: CGFloat {
didSet {
updateViews()
}
}
var buttonsEnabled: Bool = true{
didSet {
updateViews()
}
}
private var topBorder: UIView!
private var cameraButton: UIButton!
private var textView: UITextView!
private var sendButton: UIButton!
init(theme: Theme) {
self.maxHeight = 0.0
super.init(frame: CGRectZero)
backgroundColor = theme.colorForType(.ChatInputBackground)
createViews(theme)
installConstraints()
updateViews()
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func becomeFirstResponder() -> Bool {
return textView.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
return textView.resignFirstResponder()
}
}
// MARK: Actions
extension ChatInputView {
func cameraButtonPressed() {
delegate?.chatInputViewCameraButtonPressed(self, cameraView: cameraButton)
}
func sendButtonPressed() {
delegate?.chatInputViewSendButtonPressed(self)
}
}
extension ChatInputView: UITextViewDelegate {
func textViewDidChange(textView: UITextView) {
updateViews()
delegate?.chatInputViewTextDidChange(self)
}
}
private extension ChatInputView {
func createViews(theme: Theme) {
topBorder = UIView()
topBorder.backgroundColor = theme.colorForType(.SeparatorsAndBorders)
addSubview(topBorder)
let cameraImage = UIImage.templateNamed("chat-camera")
cameraButton = UIButton()
cameraButton.setImage(cameraImage, forState: .Normal)
cameraButton.tintColor = theme.colorForType(.LinkText)
cameraButton.addTarget(self, action: "cameraButtonPressed", forControlEvents: .TouchUpInside)
cameraButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
addSubview(cameraButton)
textView = UITextView()
textView.delegate = self
textView.font = UIFont.systemFontOfSize(16.0)
textView.backgroundColor = theme.colorForType(.NormalBackground)
textView.layer.cornerRadius = 5.0
textView.layer.borderWidth = 0.5
textView.layer.borderColor = theme.colorForType(.SeparatorsAndBorders).CGColor
textView.layer.masksToBounds = true
textView.setContentHuggingPriority(0.0, forAxis: .Horizontal)
addSubview(textView)
sendButton = UIButton(type: .System)
sendButton.setTitle(String(localized: "chat_send_button"), forState: .Normal)
sendButton.titleLabel?.font = UIFont.systemFontOfSize(16.0, weight: UIFontWeightBold)
sendButton.addTarget(self, action: "sendButtonPressed", forControlEvents: .TouchUpInside)
sendButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
addSubview(sendButton)
}
func installConstraints() {
topBorder.snp_makeConstraints {
$0.top.left.right.equalTo(self)
$0.height.equalTo(Constants.TopBorderHeight)
}
cameraButton.snp_makeConstraints {
$0.left.equalTo(self).offset(Constants.CameraHorizontalOffset)
$0.bottom.equalTo(self).offset(Constants.CameraBottomOffset)
}
textView.snp_makeConstraints {
$0.left.equalTo(cameraButton.snp_right).offset(Constants.CameraHorizontalOffset)
$0.top.equalTo(self).offset(Constants.Offset)
$0.bottom.equalTo(self).offset(-Constants.Offset)
$0.height.greaterThanOrEqualTo(Constants.TextViewMinHeight)
}
sendButton.snp_makeConstraints {
$0.left.equalTo(textView.snp_right).offset(Constants.Offset)
$0.right.equalTo(self).offset(-Constants.Offset)
$0.bottom.equalTo(self).offset(-Constants.Offset)
}
}
func updateViews() {
let size = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.max))
if maxHeight > 0.0 {
textView.scrollEnabled = (size.height + 2 * Constants.Offset) > maxHeight
}
else {
textView.scrollEnabled = false
}
cameraButton.enabled = buttonsEnabled
sendButton.enabled = buttonsEnabled && !textView.text.isEmpty
}
}
|
0 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Hummingbird
/// Structure holding an array of cookies
///
/// Cookies can be accessed from request via `HBRequest.cookies`.
public struct HBCookies {
/// Construct cookies accessor from `HBRequest`
/// - Parameter request: request to get cookies from
init(from request: HBRequest) {
self.cookieStrings = request.headers["cookie"].flatMap {
return $0.split(separator: ";").map { $0.drop { $0.isWhitespace } }
}
}
/// access cookies via dictionary subscript
public subscript(_ key: String) -> HBCookie? {
guard let cookieString = cookieStrings.first(where: {
guard let cookieName = HBCookie.getName(from: $0) else { return false }
return cookieName == key
}) else {
return nil
}
return HBCookie(from: cookieString)
}
var cookieStrings: [Substring]
}
|
0 | //
// ViewController.swift
// Specs
//
// Created by Quentin Jin on 2019/8/4.
// Copyright © 2019 Quentin Jin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
0 | //
// RouterProtocol.swift
// Switips
//
// Created by Vitaliy Kuzmenko on 21.03.2019.
// Copyright © 2019 Kuzmenko.info. All rights reserved.
//
import UIKit
public protocol RouterProtocol: Scene {
var window: UIWindow? { get }
func present(_ scene: Scene?)
func present(_ scene: Scene?, animated: Bool)
func dismiss()
func dismiss(animated: Bool, completion: (() -> Void)?)
func makeKeyIfNeeded()
}
extension RouterProtocol {
public func present(_ scene: Scene?) {
present(scene, animated: true)
}
public func dismiss() {
dismiss(animated: true, completion: nil)
}
}
|
0 | //
// BIP32.swift
// BIP32
//
// Created by Sjors on 29/05/2019.
// Copyright © 2019 Blockchain. Distributed under the MIT software
// license, see the accompanying file LICENSE.md
import Foundation
public struct BIP32Path : Equatable {
public enum DerivationStep : Equatable {
// max 2^^31 - 1: enforced by the BIP32Path initializer
case normal(UInt32)
case hardened(UInt32)
public var isHardened: Bool {
switch self {
case .normal(_):
return false
case .hardened(_):
return true
}
}
}
public let components: [DerivationStep]
public let rawPath: [UInt32]
public let isRelative: Bool
public init(rawPath: [UInt32], isRelative: Bool) throws {
var components: [DerivationStep] = []
for index in rawPath {
if index < BIP32_INITIAL_HARDENED_CHILD {
components.append(DerivationStep.normal(index))
} else {
components.append(DerivationStep.hardened(index - BIP32_INITIAL_HARDENED_CHILD))
}
}
try self.init(components: components, isRelative:isRelative)
}
public init(components: [DerivationStep], isRelative: Bool) throws {
var rawPath: [UInt32] = []
self.isRelative = isRelative
for component in components {
switch component {
case .normal(let index):
if index >= BIP32_INITIAL_HARDENED_CHILD {
throw LibWallyError("Invalid index in path.")
}
rawPath.append(index)
case .hardened(let index):
if index >= BIP32_INITIAL_HARDENED_CHILD {
throw LibWallyError("Invalid index in path.")
}
rawPath.append(BIP32_INITIAL_HARDENED_CHILD + index)
}
}
self.components = components
self.rawPath = rawPath
}
public init(component: DerivationStep, isRelative: Bool = true) throws {
try self.init(components: [component], isRelative: isRelative)
}
public init(index: Int, isRelative: Bool = true) throws {
try self.init(components: [.normal(UInt32(index))], isRelative: isRelative)
}
public init(string: String) throws {
guard string.count > 0 else {
throw LibWallyError("Invalid path.")
}
let isRelative = string.prefix(2) != "m/"
var tmpComponents: [DerivationStep] = []
for component in string.split(separator: "/") {
if component == "m" { continue }
let index: UInt32? = UInt32(component)
if let i = index {
tmpComponents.append(.normal(i))
} else if component.suffix(1) == "h" || component.suffix(1) == "'" {
let indexHardened: UInt32? = UInt32(component.dropLast(1))
if let i = indexHardened {
tmpComponents.append(.hardened(i))
} else {
throw LibWallyError("Invalid path.")
}
} else {
throw LibWallyError("Invalid path.")
}
}
guard tmpComponents.count > 0 else {
throw LibWallyError("Invalid path.")
}
do {
try self.init(components: tmpComponents, isRelative: isRelative)
} catch {
throw LibWallyError("Invalid path.")
}
}
public var description: String {
var pathString = self.isRelative ? "" : "m/"
for (index, item) in components.enumerated() {
switch item {
case .normal(let index):
pathString += String(index)
case .hardened(let index):
pathString += String(index) + "h"
}
if index < components.endIndex - 1 {
pathString += "/"
}
}
return pathString
}
public func chop(depth: Int) throws -> BIP32Path {
if depth > components.count {
throw LibWallyError("Invalid depth.")
}
var newComponents = self.components
newComponents.removeFirst(Int(depth))
return try BIP32Path(components: newComponents, isRelative: true)
}
}
|
0 | /*
Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import SwiftUI
import AEPCore
struct ContentView: View {
var body: some View {
Button(action: {
MobileCore.track(state: "sampleState", data: ["sk1": "sv1"])
}) {
Text("Track State")
}
Button(action: {
MobileCore.track(action: "sampleAction", data: ["ak1": "av1", "&&products": "Category;Product;Quantity;Price;eventN=X|eventN2=X2;eVarN=merch_category|eVarN2=merch_category2"])
}) {
Text("Track Action")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
0 | import UIKit
protocol SettingsViewControllerDelegate: AnyObject {
func settingsViewController(
_ settingsViewController: SettingsViewController,
didChangeSettings settings: Settings
)
}
final class SettingsViewController: UIViewController {
public static func makeModule(
settings: Settings,
delegate: SettingsViewControllerDelegate? = nil
) -> UIViewController {
let controller = SettingsViewController(settings: settings)
controller.delegate = delegate
return controller
}
weak var delegate: SettingsViewControllerDelegate?
// MARK: - UI properties
private lazy var tableViewController = TableViewController(style: .grouped)
private lazy var closeBarItem = UIBarButtonItem(
image: #imageLiteral(resourceName: "Settings.Close"),
style: .plain,
target: self,
action: #selector(closeBarButtonItemDidPress)
)
// MARK: - Private properties
private var settings: Settings {
didSet {
delegate?.settingsViewController(self, didChangeSettings: settings)
}
}
// MARK: - Managing the View
override func loadView() {
view = UIView()
view.setStyles(UIView.Styles.grayBackground)
let tableView: UITableView = tableViewController.tableView
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
let constraints: [NSLayoutConstraint]
if #available(iOS 11.0, *) {
constraints = [
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
]
} else {
constraints = [
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
view.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
]
}
NSLayoutConstraint.activate(constraints)
tableViewController.didMove(toParent: self)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = closeBarItem
navigationItem.title = Localized.title
navigationItem.backBarButtonItem = UIBarButtonItem(
title: "",
style: .plain,
target: nil,
action: nil
)
tableViewController.sections = sectionDescriptors
tableViewController.reload()
}
// MARK: - Initialization/Deinitialization
init(settings: Settings) {
self.settings = settings
super.init(nibName: nil, bundle: nil)
addChild(tableViewController)
}
@available(*, unavailable, message: "Use init(settings:) instead")
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
fatalError("Use init(settings:) instead of init(nibName:, bundle:)")
}
@available(*, unavailable, message: "Use init(settings:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("Use init(settings:) instead of init?(coder:)")
}
// MARK: - Action handlers
@objc
private func closeBarButtonItemDidPress() {
navigationController?.presentingViewController?.dismiss(
animated: true,
completion: nil
)
}
}
// MARK: - TableView data
extension SettingsViewController {
private var sectionDescriptors: [SectionDescriptor] {
return [
paymentMethodsSection,
uiCustomizationSection,
testModeSection,
]
}
private var paymentMethodsSection: SectionDescriptor {
let yooMoneyCell = switchCellWith(
title: Localized.yooMoney,
initialValue: { $0.isYooMoneyEnabled },
settingHandler: { $0.isYooMoneyEnabled = $1 }
)
let sberbankCell = switchCellWith(
title: Localized.sberbank,
initialValue: { $0.isSberbankEnabled },
settingHandler: { $0.isSberbankEnabled = $1 }
)
let bankCardCell = switchCellWith(
title: Localized.bankCard,
initialValue: { $0.isBankCardEnabled },
settingHandler: { $0.isBankCardEnabled = $1 }
)
let applePayCell = switchCellWith(
title: Localized.applePay,
initialValue: { $0.isApplePayEnabled },
settingHandler: { $0.isApplePayEnabled = $1 }
)
return SectionDescriptor(
headerText: Localized.paymentMethods,
rows: [
yooMoneyCell,
sberbankCell,
bankCardCell,
applePayCell,
]
)
}
private var uiCustomizationSection: SectionDescriptor {
let yooMoneyLogoCell = switchCellWith(
title: Localized.yooMoneyLogo,
initialValue: { $0.isShowingYooMoneyLogoEnabled },
settingHandler: { $0.isShowingYooMoneyLogoEnabled = $1 }
)
let bankCardScanCell = switchCellWith(
title: Localized.bankCardScan,
initialValue: { $0.isBankCardScanEnabled },
settingHandler: { $0.isBankCardScanEnabled = $1 }
)
return SectionDescriptor(
rows: [
yooMoneyLogoCell,
bankCardScanCell,
]
)
}
private var testModeSection: SectionDescriptor {
let testMode = CellDescriptor(configuration: { [unowned self] (cell: ContainerTableViewCell<TextValueView>) in
cell.containedView.title = Localized.test_mode
cell.containedView.value = self.settings.testModeSettings.isTestModeEnadled
? translate(CommonLocalized.on)
: translate(CommonLocalized.off)
cell.accessoryType = .disclosureIndicator
}, selection: { [unowned self] (indexPath) in
self.tableViewController.tableView.deselectRow(at: indexPath, animated: true)
let controller = TestSettingsViewController.makeModule(
settings: self.settings.testModeSettings,
delegate: self
)
let navigation = UINavigationController(rootViewController: controller)
if #available(iOS 11.0, *) {
navigation.navigationBar.prefersLargeTitles = true
}
navigation.modalPresentationStyle = .formSheet
self.present(navigation, animated: true, completion: nil)
})
return SectionDescriptor(rows: [testMode])
}
private func switchCellWith(
title: String,
initialValue: @escaping (Settings) -> Bool,
settingHandler: @escaping (inout Settings, Bool) -> Void
) -> CellDescriptor {
return CellDescriptor(configuration: { [unowned self] (cell: ContainerTableViewCell<TitledSwitchView>) in
cell.containedView.title = title
cell.containedView.isOn = initialValue(self.settings)
cell.containedView.valueChangeHandler = {
settingHandler(&self.settings, $0)
}
})
}
}
// MARK: - TestSettingsViewControllerDelegate
extension SettingsViewController: TestSettingsViewControllerDelegate {
func testSettingsViewController(
_ testSettingsViewController: TestSettingsViewController,
didChangeSettings settings: TestSettings
) {
self.settings.testModeSettings = settings
tableViewController.reloadTable()
}
}
// MARK: - Localization
extension SettingsViewController {
private enum Localized {
static let title = NSLocalizedString("settings.title", comment: "")
static let paymentMethods = NSLocalizedString("settings.payment_methods.title", comment: "")
static let yooMoney = NSLocalizedString("settings.payment_methods.yoo_money", comment: "")
static let bankCard = NSLocalizedString("settings.payment_methods.bank_card", comment: "")
static let sberbank = NSLocalizedString("settings.payment_methods.sberbank", comment: "")
static let applePay = NSLocalizedString("settings.payment_methods.apple_pay", comment: "")
static let yooMoneyLogo = NSLocalizedString("settings.ui_customization.yoo_money_logo", comment: "")
static let bankCardScan = NSLocalizedString("settings.ui_customization.bank_card_scan_enabled", comment: "")
static let test_mode = NSLocalizedString("settings.test_mode.title", comment: "")
}
}
|
0 | //
// ViewController.swift
// KeyboardView-Demo
//
// Created by 方林威 on 2020/11/5.
//
import UIKit
import KeyboardView
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textField: UITextField!
lazy var keyboard = AlphabeticKeyboardView()
override func viewDidLoad() {
super.viewDidLoad()
textView.inputView = keyboard
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
keyboard.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 212.0 + view.safeAreaInsets.bottom)
UIResponder.keyboardDidShowNotification
}
}
class AlphabeticKeyboardView: UIView {
let keyboard = KeyboardViewController()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
addSubview(keyboard.view)
keyboard.view.translatesAutoresizingMaskIntoConstraints = false
keyboard.view.topAnchor.constraint(equalTo: topAnchor, constant: 5.0).isActive = true
keyboard.view.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
keyboard.view.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
}
}
extension Double {
func auto() -> Double {
guard UIDevice.current.userInterfaceIdiom == .phone else {
return self
}
let base = 375.0
let screenWidth = Double(UIScreen.main.bounds.width)
let screenHeight = Double(UIScreen.main.bounds.height)
let width = min(screenWidth, screenHeight)
let result = self * (width / base)
let scale = Double(UIScreen.main.scale)
return (result * scale).rounded(.up) / scale
}
}
//
//extension BinaryInteger {
//
// func auto() -> Double {
// let temp = Double("\(self)") ?? 0
// return temp.auto()
// }
// func auto<T>() -> T where T : BinaryInteger {
// let temp = Double("\(self)") ?? 0
// return temp.auto()
// }
// func auto<T>() -> T where T : BinaryFloatingPoint {
// let temp = Double("\(self)") ?? 0
// return temp.auto()
// }
//}
extension BinaryFloatingPoint {
func auto() -> Double {
let temp = Double("\(self)") ?? 0
return temp.auto()
}
func auto<T>() -> T where T : BinaryInteger {
let temp = Double("\(self)") ?? 0
return T(temp.auto())
}
func auto<T>() -> T where T : BinaryFloatingPoint {
let temp = Double("\(self)") ?? 0
return T(temp.auto())
}
}
|
0 | //
// CaptiveNetwork.swift
// SwiftConfig
//
// Created by Jacob on 5/25/18.
// Copyright © 2018 Jacob Greenfield. All rights reserved.
//
import Foundation
import SystemConfiguration.CaptiveNetwork
open class CaptiveNetworkManager: Hashable, Equatable, CustomStringConvertible {
public enum InterfaceError: Error {
case unsupported
case gotNil
}
private static func supportedNames() throws -> [CFString] {
guard let names = CNCopySupportedInterfaces() as? [CFString] else { throw InterfaceError.gotNil }
return names
}
open class func supportedInterfaces() throws -> [NetworkInterface] {
let all = try NetworkInterface.all()
return try CaptiveNetworkManager.supportedNames().lazy.compactMap { name in
all.first { $0.bsdName() == name }
}
}
open class func setSupportedSSIDs(_ newValue: [String]) -> Bool {
return CNSetSupportedSSIDs(newValue as CFArray)
}
public let interface: NetworkInterface
private let interfaceName: CFString
public init(interface: NetworkInterface) throws {
guard let name = interface.bsdName(),
try CaptiveNetworkManager.supportedNames().contains(name) else { throw InterfaceError.unsupported }
self.interface = interface
self.interfaceName = name
}
open func setPortal(online: Bool) -> Bool {
if online {
return CNMarkPortalOnline(self.interfaceName)
} else {
return CNMarkPortalOffline(self.interfaceName)
}
}
open var hashValue: Int {
return self.interface.hashValue
}
public static func == (lhs: CaptiveNetworkManager, rhs: CaptiveNetworkManager) -> Bool {
return lhs.interface == rhs.interface
}
open var description: String {
if let interfaceDescription = CFCopyDescription(self.interface) as String? {
return "CaptiveNetwork(interface: \(interfaceDescription))"
}
return String(describing: self.interface)
}
}
|
1 |
// RUN: %target-swift-frontend -emit-module %t/Lib.swift -I %t \
// RUN: -module-name Lib -emit-module-path %t/Lib.swiftmodule \
// RUN: -swift-version 5
// RUN: %target-swift-frontend -emit-module %t/APILib.swift -I %t \
// RUN: -swift-version 5 -verify \
// RUN: -experimental-spi-only-imports \
// RUN: -library-level api \
// RUN: -require-explicit-availability=ignore
// RUN: %target-swift-frontend -emit-module %t/SPILib.swift -I %t \
// RUN: -swift-version 5 -verify \
// RUN: -experimental-spi-only-imports \
// RUN: -library-level spi
// RUN: %target-swift-frontend -emit-module %t/OtherLib.swift -I %t \
// RUN: -swift-version 5 -verify \
// RUN: -experimental-spi-only-imports
//--- Lib.swift
public struct LibStruct {}
//--- APILib.swift
@_spiOnly import Lib
public func publicClient() -> LibStruct { fatalError() } // expected-error {{cannot use struct 'LibStruct' here; 'Lib' was imported for SPI only}}
@_spi(X) public func spiClient() -> LibStruct { fatalError() }
//--- SPILib.swift
@_spiOnly import Lib
public func publicClient() -> LibStruct { fatalError() }
@_spi(X) public func spiClient() -> LibStruct { fatalError() }
//--- OtherLib.swift
@_spiOnly import Lib
public func publicClient() -> LibStruct { fatalError() } // expected-error {{cannot use struct 'LibStruct' here; 'Lib' was imported for SPI only}}
@_spi(X) public func spiClient() -> LibStruct { fatalError() } |
0 | public struct GeoJson {
internal static let parser = GeoJsonParser()
internal static func coordinates(geoJson: GeoJsonDictionary) -> [Any]? { geoJson["coordinates"] as? [Any] }
/**
Parses a GeoJsonDictionary into a GeoJsonObject.
- geoJson: An JSON dictionary conforming to the GeoJson current spcification.
- returns: A successfully parsed GeoJsonObject or nil if the specification was not correct
*/
public func parseObject(fromGeoJson geoJson: GeoJsonDictionary) -> Result<GeoJsonObject, InvalidGeoJson> { GeoJson.parser.geoJsonObject(fromGeoJson: geoJson) }
public func parseCoordinatesGeometry(fromGeoJson geoJson: GeoJsonDictionary) -> Result<GeoJsonCoordinatesGeometry, InvalidGeoJson> { GeoJson.parser.geoJsonCoordinatesGeometry(fromGeoJson: geoJson) }
/**
Parses a validated GeoJsonDictionary into a GeoJsonObject.
Assumes validated GeoJson for performance and will crash if invalid!
- geoJson: An JSON dictionary conforming to the GeoJson current spcification.
- returns: A GeoJsonObject or nil if the specification was not correct
*/
public func parseObject(fromValidatedGeoJson geoJson: GeoJsonDictionary) -> GeoJsonObject { GeoJson.parser.geoJsonObject(fromValidatedGeoJson: geoJson) }
public func parseCoordinatesGeometry(fromValidatedGeoJson geoJson: GeoJsonDictionary) -> GeoJsonCoordinatesGeometry { GeoJson.parser.geoJsonCoordinatesGeometry(fromValidatedGeoJson: geoJson) }
}
|
0 | import UIKit
import SwiftUI
import Combine
import OwnIDGigyaSDK
import GigyaAndScreensetsShared
final class ViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
let ownIDViewModel = OwnID.GigyaSDK.registrationViewModel(instance: GigyaShared.instance)
private var userEmail = ""
var bag = Set<AnyCancellable>()
private lazy var ownIdButton = makeOwnIDButton()
override func viewDidLoad() {
super.viewDidLoad()
subscribe(to: ownIDViewModel.eventPublisher)
activityIndicator.isHidden = true
emailTextField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)
addChild(ownIdButton)
view.addSubview(ownIdButton.view)
ownIdButton.didMove(toParent: self)
NSLayoutConstraint.activate([
ownIdButton.view.topAnchor.constraint(equalTo: passwordTextField.topAnchor),
ownIdButton.view.leadingAnchor.constraint(equalTo: passwordTextField.trailingAnchor, constant: 10),
ownIdButton.view.heightAnchor.constraint(equalToConstant: 44)
])
}
func makeOwnIDButton() -> UIHostingController<OwnID.FlowsSDK.RegisterView> {
let headerView = OwnID.GigyaSDK.createRegisterView(viewModel: ownIDViewModel, email: emailBinding)
let headerVC = UIHostingController(rootView: headerView)
headerVC.view.translatesAutoresizingMaskIntoConstraints = false
return headerVC
}
var emailBinding: Binding<String> {
Binding(
get: { self.userEmail },
set: { _ in }
)
}
@objc func textFieldDidChange(_ textField: UITextField) {
userEmail = textField.text ?? ""
}
@IBAction func registerTapped(_ sender: UIButton) {
ownIDViewModel.register(with: userEmail)
}
func subscribe(to eventsPublisher: OwnID.RegistrationPublisher) {
eventsPublisher
.sink { [unowned self] event in
switch event {
case .success(let event):
switch event {
// Event when user successfully
// finishes Skip Password
// in OwnID Web App
case .readyToRegister:
activityIndicator.isHidden = true
activityIndicator.stopAnimating()
// Event when OwnID creates Firebase
// account and logs in user
case .userRegisteredAndLoggedIn:
break
case .loading:
activityIndicator.isHidden = false
activityIndicator.startAnimating()
case .resetTapped:
print(OwnID.FlowsSDK.RegistrationEvent.resetTapped)
}
case .failure(let error):
activityIndicator.isHidden = true
activityIndicator.stopAnimating()
print(error.localizedDescription)
}
}
.store(in: &bag)
}
}
|
0 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2017 Jean-David Gadina - www.xs-labs.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.
******************************************************************************/
import Foundation
/**
* Protocol for `AtomicKit` thread-safe wrapper objects around a value/type.
*/
public protocol ThreadSafeValueWrapper
{
associatedtype ValueType
/**
* Required initializer.
* Initializes a thread-safe wrapper object with a default value.
*
* - parameter value: The default value for the wrapped type.
*/
init( value: ValueType )
/**
* Atomically gets the value of the wrapped type.
*
* - returns: The actual value of the wrapped type.
*/
func get() -> ValueType
/**
* Atomically sets the value of the wrapped type.
*
* - parameter value: The value to set for the wrapped type.
*/
func set( _ value: ValueType )
/**
* Atomically executes a custom closure, receiving the value of the wrapped
* type.
*
* The passed closure is guaranteed to be executed atomically, in respect
* of the current value of the wrapped type.
*
* - parameter closure: The close to execute.
*/
func execute( closure: ( ValueType ) -> Swift.Void )
/**
* Atomically executes a custom closure, receiving the value of the wrapped
* type.
*
* The passed closure is guaranteed to be executed atomically, in respect
* of the current value of the wrapped type.
*
* - parameter closure: The close to execute.
* - returns: The closure's return value.
*/
func execute< R >( closure: ( ValueType ) -> R ) -> R
}
|
0 | //
// Created by Ladislav Lisy on 28.06.2021.
//
import Foundation
protocol IProviderTaxing: IPropsProvider {
func allowancePayer(_ period: IPeriod) -> Int32
func allowanceDisab1st(_ period: IPeriod) -> Int32
func allowanceDisab2nd(_ period: IPeriod) -> Int32
func allowanceDisab3rd(_ period: IPeriod) -> Int32
func allowanceStudy(_ period: IPeriod) -> Int32
func allowanceChild1st(_ period: IPeriod) -> Int32
func allowanceChild2nd(_ period: IPeriod) -> Int32
func allowanceChild3rd(_ period: IPeriod) -> Int32
func factorAdvances(_ period: IPeriod) -> Decimal
func factorWithhold(_ period: IPeriod) -> Decimal
func factorSolidary(_ period: IPeriod) -> Decimal
func minAmountOfTaxBonus(_ period: IPeriod) -> Int32
func maxAmountOfTaxBonus(_ period: IPeriod) -> Int32
func marginIncomeOfTaxBonus(_ period: IPeriod) -> Int32
func marginIncomeOfRounding(_ period: IPeriod) -> Int32
func marginIncomeOfWithhold(_ period: IPeriod) -> Int32
func marginIncomeOfSolidary(_ period: IPeriod) -> Int32
func marginIncomeOfWthEmp(_ period: IPeriod) -> Int32
func marginIncomeOfWthAgr(_ period: IPeriod) -> Int32
}
|
0 | //
// Package.swift
// Perfect-ZooKeeper
//
// Created by Rockford Wei on 2017-02-22.
// Copyright © 2017 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2017 - 2018 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PackageDescription
let package = Package(
name: "PerfectZooKeeper",
dependencies: [
.Package(url: "https://github.com/PerfectlySoft/Perfect-libZooKeeper.git", majorVersion: 1)
]
)
|
0 | //
// RadarChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// Implementation of the RadarChart, a "spidernet"-like chart. It works best
/// when displaying 5-10 entries per DataSet.
open class RadarChartView: PieRadarChartViewBase
{
/// width of the web lines that come from the center.
@objc open var webLineWidth = CGFloat(1.5)
/// width of the web lines that are in between the lines coming from the center
@objc open var innerWebLineWidth = CGFloat(0.75)
/// color for the web lines that come from the center
@objc open var webColor = NSUIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0)
/// color for the web lines in between the lines that come from the center.
@objc open var innerWebColor = NSUIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0)
/// transparency the grid is drawn with (0.0 - 1.0)
@objc open var webAlpha: CGFloat = 150.0 / 255.0
/// flag indicating if the web lines should be drawn or not
@objc open var drawWeb = true
/// modulus that determines how many labels and web-lines are skipped before the next is drawn
fileprivate var _skipWebLineCount = 0
/// the object reprsenting the y-axis labels
fileprivate var _yAxis: YAxis!
@objc internal var _yAxisRenderer: YAxisRendererRadarChart!
@objc internal var _xAxisRenderer: XAxisRendererRadarChart!
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
_yAxis = YAxis(position: .left)
renderer = RadarChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
_yAxisRenderer = YAxisRendererRadarChart(viewPortHandler: _viewPortHandler, yAxis: _yAxis, chart: self)
_xAxisRenderer = XAxisRendererRadarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, chart: self)
self.highlighter = RadarHighlighter(chart: self)
}
internal override func calcMinMax()
{
super.calcMinMax()
guard let data = _data else { return }
_yAxis.calculate(min: data.getYMin(axis: .left), max: data.getYMax(axis: .left))
_xAxis.calculate(min: 0.0, max: Double(data.maxEntryCountSet?.countOfEntries ?? 0))
}
open override func notifyDataSetChanged()
{
calcMinMax()
_yAxisRenderer?.computeAxis(min: _yAxis._axisMinimum, max: _yAxis._axisMaximum, inverted: _yAxis.isInverted)
_xAxisRenderer?.computeAxis(min: _xAxis._axisMinimum, max: _xAxis._axisMaximum, inverted: false)
if let data = _data,
let aLegend = _aLegend,
!aLegend.isLegendCustom
{
_legendRenderer?.computeLegend(data: data)
}
calculateOffsets()
setNeedsDisplay()
}
open override func draw(_ rect: CGRect)
{
super.draw(rect)
if _data === nil
{
return
}
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
if _xAxis.isEnabled
{
_xAxisRenderer.computeAxis(min: _xAxis._axisMinimum, max: _xAxis._axisMaximum, inverted: false)
}
_xAxisRenderer?.renderAxisLabels(context: context)
if drawWeb
{
renderer!.drawExtras(context: context)
}
if _yAxis.isEnabled && _yAxis.isDrawLimitLinesBehindDataEnabled
{
_yAxisRenderer.renderLimitLines(context: context)
}
renderer!.drawData(context: context)
if valuesToHighlight()
{
renderer!.drawHighlighted(context: context, indices: _indicesToHighlight)
}
if _yAxis.isEnabled && !_yAxis.isDrawLimitLinesBehindDataEnabled
{
_yAxisRenderer.renderLimitLines(context: context)
}
_yAxisRenderer.renderAxisLabels(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
/// - returns: The factor that is needed to transform values into pixels.
@objc open var factor: CGFloat
{
let content = _viewPortHandler.contentRect
return min(content.width / 2.0, content.height / 2.0)
/ CGFloat(_yAxis.axisRange)
}
/// - returns: The angle that each slice in the radar chart occupies.
@objc open var sliceAngle: CGFloat
{
return 360.0 / CGFloat(_data?.maxEntryCountSet?.countOfEntries ?? 0)
}
open override func indexForAngle(_ angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.angleOfRotation)
let sliceAngle = self.sliceAngle
let max = _data?.maxEntryCountSet?.countOfEntries ?? 0
var index = 0
for i in 0..<max
{
let referenceAngle = sliceAngle * CGFloat(i + 1) - sliceAngle / 2.0
if referenceAngle > a
{
index = i
break
}
}
return index
}
/// - returns: The object that represents all y-labels of the RadarChart.
@objc open var yAxis: YAxis
{
return _yAxis
}
/// Sets the number of web-lines that should be skipped on chart web before the next one is drawn. This targets the lines that come from the center of the RadarChart.
/// if count = 1 -> 1 line is skipped in between
@objc open var skipWebLineCount: Int
{
get
{
return _skipWebLineCount
}
set
{
_skipWebLineCount = max(0, newValue)
}
}
internal override var requiredLegendOffset: CGFloat
{
return _aLegend.font.pointSize * 4.0
}
internal override var requiredBaseOffset: CGFloat
{
return _xAxis.isEnabled && _xAxis.isDrawLabelsEnabled ? _xAxis.labelRotatedWidth : 10.0
}
open override var radius: CGFloat
{
let content = _viewPortHandler.contentRect
return min(content.width / 2.0, content.height / 2.0)
}
/// - returns: The maximum value this chart can display on it's y-axis.
open override var chartYMax: Double { return _yAxis._axisMaximum }
/// - returns: The minimum value this chart can display on it's y-axis.
open override var chartYMin: Double { return _yAxis._axisMinimum }
/// - returns: The range of y-values this chart can display.
@objc open var yRange: Double { return _yAxis.axisRange }
}
|
0 | //
// Worry.swift
// Worrybook
//
// Created by cognophile
//
import Foundation
import SQLite
class Worry: ModelProtocol {
var table: Table?
var record: Row?
var id = Expression<Int>("id")
let title = Expression<String>("title")
let description = Expression<String>("description")
let solution = Expression<String?>("solution")
let archived = Expression<Bool?>("archived")
let created = Expression<Date?>("created")
let modified = Expression<Date?>("modified")
let worryTypeId = Expression<Int>("worry_type_id")
let categoryId = Expression<Int?>("category_id")
let refocusId = Expression<Int?>("refocus_id")
init() {
self.table = Table("worry")
}
public func instantiateTable() -> String {
return (self.table?.create(ifNotExists: true) {
t in
t.column(self.id, primaryKey: true)
t.column(self.title)
t.column(self.description)
t.column(self.solution)
t.column(self.archived)
t.column(self.created)
t.column(self.modified)
t.column(self.worryTypeId)
t.column(self.categoryId)
t.column(self.refocusId)
})!
}
}
|
0 | //
// UIViewController+Swizzling.swift
// EachNavigationBar
//
// Created by Pircate([email protected]) on 2018/11/22
// Copyright © 2018年 Pircate. All rights reserved.
//
infix operator <=>
extension UIViewController {
static let methodSwizzling: Void = {
#selector(viewDidLoad) <=> #selector(navigation_viewDidLoad)
#selector(viewWillAppear(_:)) <=> #selector(navigation_viewWillAppear(_:))
#selector(setNeedsStatusBarAppearanceUpdate) <=> #selector(navigation_setNeedsStatusBarAppearanceUpdate)
#selector(viewDidLayoutSubviews) <=> #selector(navigation_viewDidLayoutSubviews)
}()
private var isNavigationBarEnabled: Bool {
guard let navigationController = navigationController,
navigationController.navigation.configuration.isEnabled,
navigationController.viewControllers.contains(self) else { return false }
return true
}
@objc private func navigation_viewDidLoad() {
navigation_viewDidLoad()
guard isNavigationBarEnabled else { return }
setupNavigationBarWhenViewDidLoad()
if let tableViewController = self as? UITableViewController {
tableViewController.observeContentOffset()
}
}
@objc private func navigation_viewWillAppear(_ animated: Bool) {
navigation_viewWillAppear(animated)
guard isNavigationBarEnabled else { return }
updateNavigationBarWhenViewWillAppear()
}
@objc private func navigation_setNeedsStatusBarAppearanceUpdate() {
navigation_setNeedsStatusBarAppearanceUpdate()
adjustsNavigationBarLayout()
}
@objc private func navigation_viewDidLayoutSubviews() {
navigation_viewDidLayoutSubviews()
view.bringSubviewToFront(_navigationBar)
}
}
private extension Selector {
static func <=> (left: Selector, right: Selector) {
if let originalMethod = class_getInstanceMethod(UIViewController.self, left),
let swizzledMethod = class_getInstanceMethod(UIViewController.self, right) {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
|
0 | //
// CallbackURLKit.swift
// CallbackURLKit
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
// action ie. url path
public typealias Action = String
// block which handle action and optionally respond to callback
public typealias ActionHandler = (Parameters, SuccessCallback, FailureCallback, CancelCallback) -> Void
// Simple dictionary for parameters
public typealias Parameters = [String: String]
// Callback for response
public typealias SuccessCallback = (Parameters?) -> Void
public typealias FailureCallback = (FailureCallbackErrorType) -> Void
public typealias CancelCallback = () -> Void
// MARK: global functions
// Perform an action on client application
// - Parameter action: The action to perform.
// - Parameter URLScheme: The URLScheme for application to apply action.
// - Parameter parameters: Optional parameters for the action.
// - Parameter onSuccess: callback for success.
// - Parameter onFailure: callback for failure.
// - Parameter onCancel: callback for cancel.
//
// Throws: CallbackURLKitError
public func performAction(action: Action, URLScheme: String, parameters: Parameters = [:],
onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws {
try Manager.performAction(action, URLScheme: URLScheme, parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel)
}
public func registerAction(action: Action, actionHandler: ActionHandler) {
Manager.sharedInstance[action] = actionHandler
}
// MARK: - ErrorType
// Implement this protocol to custom the error into Client
public protocol FailureCallbackErrorType: ErrorType {
var code: Int {get}
var message: String {get}
}
extension FailureCallbackErrorType {
public var XCUErrorParameters: Parameters {
return [kXCUErrorCode: "\(self.code)", kXCUErrorMessage: self.message]
}
public var XCUErrorQuery: String {
return XCUErrorParameters.query
}
}
public struct Error {
public static let Domain = "CallbackURLKit.error"
/// The custom error codes generated by Alamofire.
public enum Code: Int {
case NotSupportedAction = 1 // "(action) not supported by (appName)"
case MissingParameter = 2 // when handling an action, could return an error to show that parameters are missing
case MissingErrorCode = 3
}
public static func errorWithCode(code: Code, failureReason: String) -> NSError {
return errorWithCode(code.rawValue, failureReason: failureReason)
}
public static func errorWithCode(code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Domain, code: code, userInfo: userInfo)
}
}
extension NSError: FailureCallbackErrorType {
public var message: String { return localizedDescription }
}
// Framework errors
public enum CallbackURLKitError : ErrorType {
// It's seems that application with specified scheme has not installed
case AppWithSchemeNotInstalled(scheme: String)
// Failed to create NSURL for request
case FailedToCreateRequestURL(components: NSURLComponents)
// You specify a callback but no manager.callbackURLScheme defined
case CallbackURLSchemeNotDefined
}
// MARK: - x-callback-url
let kXCUPrefix = "x-"
let kXCUHost = "x-callback-url"
// Parameters
// The friendly name of the source app calling the action. If the action in the target app requires user interface elements, it may be necessary to identify to the user the app requesting the action.
let kXCUSource = "x-source"
// If the action in the target method is intended to return a result to the source app, the x-callback parameter should be included and provide a URL to open to return to the source app. On completion of the action, the target app will open this URL, possibly with additional parameters tacked on to return a result to the source app. If x-success is not provided, it is assumed that the user will stay in the target app on successful completion of the action.
let kXCUSuccess = "x-success"
// URL to open if the requested action generates an error in the target app. This URL will be open with at least the parameters “errorCode=code&errorMessage=message”. If x-error is not present, and a error occurs, it is assumed the target app will report the failure to the user and remain in the target app.
let kXCUError = "x-error"
let kXCUErrorCode = "error-Code"
let kXCUErrorMessage = "errorMessage"
// URL to open if the requested action is cancelled by the user. In the case where the target app offer the user the option to “cancel” the requested action, without a success or error result, this the the URL that should be opened to return the user to the source app.
let kXCUCancel = "x-cancel"
// MARK: - framework strings
let kResponse = "response"
let kResponseType = "responseType";
let kRequestID = "requestID"
let protocolKeys = [kResponse, kResponseType, kRequestID]
|
0 | import XCTest
class WhisperTests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
XCUIApplication().launch()
XCUIDevice.sharedDevice().orientation = .Portrait
}
override func tearDown() {
super.tearDown()
}
func testBasicSetup() {
let app = XCUIApplication()
XCTAssert(app.navigationBars["Whisper".uppercaseString].exists)
XCTAssert(app.staticTexts["Welcome to the magic of a tiny Whisper... 🍃"].exists)
XCTAssertEqual(app.buttons.count, 8)
}
func testWhisper() {
let app = XCUIApplication()
app.buttons["Present and silent"].tap()
XCTAssert(app.staticTexts["This message will silent in 3 seconds."].exists)
let expectation = expectationWithDescription("Test bottom whisper")
app.buttons["Present at the bottom and silent"].tap()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
XCTAssert(app.staticTexts["Bottom message that will silent in 3 seconds."].exists)
expectation.fulfill()
}
waitForExpectationsWithTimeout(0.5) { (error) -> Void in
if nil != error {
XCTFail("Expectation failed with error - \(error)")
}
}
app.buttons["Show"].tap()
sleep(1)
XCTAssert(app.staticTexts["Showing all the things."].exists)
app.buttons["Present permanent Whisper"].tap()
sleep(1)
XCTAssert(app.staticTexts["This is a permanent Whisper."].exists)
}
func testNotifications() {
let app = XCUIApplication()
app.buttons["Notification"].tap()
sleep(1)
XCTAssert(app.staticTexts["Ramon Gilabert"].exists)
}
func testStatusBar() {
let app = XCUIApplication()
app.buttons["Status bar"].tap()
sleep(1)
XCTAssert(app.staticTexts["This is a small whistle..."].exists)
}
}
|
0 | import Foundation
public class SeatingChart {
let seatsioWebView: SeatsioWebView
public init(_ seatsioWebView: SeatsioWebView) {
self.seatsioWebView = seatsioWebView
}
public func selectObjects(_ objects: [String]) {
seatsioWebView.bridge.call("selectObjects", data: objects)
}
public func deselectObjects(_ objects: [String]) {
seatsioWebView.bridge.call("deselectObjects", data: objects)
}
public func getHoldtoken(_ callback: @escaping (String?) -> ()) {
seatsioWebView.bridge.call(
"getHoldToken",
data: nil,
callback: { (response) in callback(nullToNil(value: response) as? String) }
)
}
public func zoomToSelectedObjects() {
seatsioWebView.bridge.call("zoomToSelectedObjects", data: nil)
}
public func rerender() {
seatsioWebView.bridge.call("rerender", data: nil)
}
public func resetView() {
seatsioWebView.bridge.call("resetView", data: nil)
}
public func startNewSession() {
seatsioWebView.bridge.call("startNewSession", data: nil)
}
public func selectCategories(_ categories: [String]) {
seatsioWebView.bridge.call("selectCategories", data: categories)
}
public func deselectCategories(_ categories: [String]) {
seatsioWebView.bridge.call("deselectCategories", data: categories)
}
public func selectBestAvailable(_ bestAvailable: BestAvailable) {
seatsioWebView.bridge.call("selectBestAvailable", data: toJsonString(AnyEncodable(value: bestAvailable)))
}
public func changeConfig(_ configChange: ConfigChange) {
seatsioWebView.bridge.call("changeConfig", data: toJsonString(AnyEncodable(value: configChange)))
}
public func clearSelection(_ callback: @escaping () -> ()) {
seatsioWebView.bridge.call(
"clearSelection",
data: nil,
callback: { (response) in callback() }
)
}
public func listCategories(_ callback: @escaping ([Category]) -> ()) {
seatsioWebView.bridge.call(
"listCategories",
data: nil,
callback: { (response) in callback(decodeCategories(response!)) }
)
}
public func findObject(_ object: String, _ successCallback: @escaping (SeatsioObject) -> (), _ errorCallback: @escaping () -> ()) {
seatsioWebView.bridge.call(
"findObject",
data: object,
callback: { (response) in
if response == nil {
errorCallback()
} else {
successCallback(decodeSeatsioObject(response!))
}
}
)
}
public func listSelectedObjects(_ callback: @escaping ([SeatsioObject]) -> ()) {
seatsioWebView.bridge.call(
"listSelectedObjects",
data: nil,
callback: { (response) in callback(decodeSeatsioObjects(response!)) }
)
}
}
func toJsonString(_ o: AnyEncodable) -> String {
let data = try! JSONEncoder().encode(o)
return String(data: data, encoding: .utf8)!
}
func nullToNil(value : Any?) -> Any? {
if value is NSNull {
return nil
} else {
return value
}
}
|
0 | //
// AppDelegate.swift
// LearnShareSDK
//
// Created by 仲召俊 on 2019/10/19.
// Copyright © 2019 ZZJ. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
initShareSDK()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
|
0 | //
// PlayerDiscoveryControllerDelegateProtocol.swift
// FireTVKit
//
// Created by crelies on 04.05.2018.
// Copyright © 2018 Christian Elies. All rights reserved.
//
import AmazonFling
import Foundation
protocol PlayerDiscoveryControllerDelegateProtocol: class {
func deviceDiscovered(_ discoveryController: PlayerDiscoveryControllerProtocol, device: RemoteMediaPlayer)
func deviceLost(_ discoveryController: PlayerDiscoveryControllerProtocol, device: RemoteMediaPlayer)
func discoveryFailure(_ discoveryController: PlayerDiscoveryControllerProtocol)
}
|
0 | //
// ScreenViewModelTests.swift
// MusicSearchKitTests
//
// Created by Vitor S do Nascimento on 08-11-19.
//
import XCTest
import RxSwift
@testable import MusicSearchKit
class SongListTests: XCTestCase {
private let disposeBag = DisposeBag()
override func setUp() {
super.setUp()
StubService.stubSongList()
}
func test_loadSongs_success() {
let exp = expectation(description: "songListViewModel_loadSongs_success")
let repository = FakeSongListRemoteAPI()
let sut = SongListViewModel(repository: repository)
sut.loadSongs(search: "")
sut
.dataList
.subscribe(
onNext: { (items) in
XCTAssertEqual(items.count, 20)
XCTAssertEqual(items.first?.trackName, "Track name")
exp.fulfill()
}, onError: { (error) in
XCTFail("\(error)")
exp.fulfill()
}).disposed(by: disposeBag)
waitForExpectations(timeout: 3.0, handler: nil)
}
func test_loadSongs_fail() {
let exp = expectation(description: "songListViewModel_loadSongs_fail")
let repository = FakeSongListRemoteAPIError()
let sut = SongListViewModel(repository: repository)
sut.loadSongs(search: "something")
sut
.dataList
.subscribe(
onNext: { (_) in
XCTFail("That request must fail")
exp.fulfill()
})
.disposed(by: disposeBag)
sut
.errorMessages
.subscribe(onNext: { (errorMessage) in
XCTAssertTrue(errorMessage.title != "")
XCTAssertTrue(errorMessage.message != "")
exp.fulfill()
})
.disposed(by: disposeBag)
waitForExpectations(timeout: 3.0, handler: nil)
}
override func tearDown() {
super.tearDown()
}
}
|
0 | //
// LoginViewController.swift
// BeamWallet
//
// Copyright 2018 Beam Development
//
// 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
class LoginViewController: BaseViewController {
@IBOutlet private weak var bgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
switch Settings.sharedManager().target {
case Testnet:
bgView.image = BackgroundTestnet()
case Masternet:
bgView.image = BackgroundMasternet()
default:
return
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
//MARK: IBAction
@IBAction func onRestoreWallet(sender :UIButton) {
if AppModel.sharedManager().canRestoreWallet() {
self.confirmAlert(title: LocalizableStrings.restore_wallet_title, message: LocalizableStrings.restore_wallet_info, cancelTitle: LocalizableStrings.cancel, confirmTitle: LocalizableStrings.restore_wallet_title, cancelHandler: { (_ ) in
}) { (_ ) in
AppModel.sharedManager().isRestoreFlow = true;
self.pushViewController(vc: InputPhraseViewController())
}
}
else{
self.alert(title: LocalizableStrings.no_space_title, message: LocalizableStrings.no_space_info) { (_ ) in
}
}
}
@IBAction func onCreateWallet(sender :UIButton) {
AppModel.sharedManager().isRestoreFlow = false;
pushViewController(vc: IntroPhraseViewController())
}
}
|
0 | //
// DetailTableViewController.swift
// Freedom
import UIKit
//import XExtension
class DetailTableViewController: TaobaoBaseViewController {
private var titles = ["图文详情", "商品评论", "店铺推荐"]
private var urls = ["http://m.b5m.com/item.html?tid=2614676&mps=____&type=content", "http://m.b5m.com/item.html?tid=2614676&mps=____&type=comment", "http://m.baidu.com"]
var detailView :DetailView!
var data :[[String:Any]]!
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
data = [["title": "Wap商品详情", "author": "伯光", "class": "DetailWapViewController"],["title": "TableView商品详情", "author": "伯光", "class": "DetailTableViewController"],["title": "ScrollView商品详情", "author": "伯光", "class": "DetailScrollViewController"],["title": "Wap商品详情", "author": "伯光", "class": "DetailWapViewController"],["title": "TableView商品详情", "author": "伯光", "class": "DetailTableViewController"],["title": "ScrollView商品详情", "author": "伯光", "class": "DetailScrollViewController"]]
detailView = DetailView(frame: CGRect(x: 0, y: 64, width: view.bounds.size.width, height: view.bounds.size.height - 64))
tableView = BaseTableView(frame: detailView.bounds)
// tableView.delegate = self
// tableView.dataSource = self
if let aView = detailView {
view.addSubview(aView)
}
view.backgroundColor = UIColor.light
tableView.reloadData()
detailView?.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dequeueReusableCellWithIdentifier = "dequeueReusableCellWithIdentifier"
var cell = tableView.dequeueCell(BaseTableViewCell<Any>.self)
cell.textLabel?.text = data[indexPath.row]["title"] as? String
cell.detailTextLabel?.text = data[indexPath.row]["author"] as? String
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
_ = data[indexPath.row]["class"]
navigationController?.pushViewController(UIViewController(), animated: true)
}
}
|
0 | //
// SWUserInfoModel.swift
// LiteraryHeaven
//
// Created by SanW on 2017/7/25.
// Copyright © 2017年 ONON. All rights reserved.
//
import UIKit
class SWUserInfoModel: NSObject,NSCoding {
// 用户ID
var userId : Int?
// 性别
var sex : String?
// 头像
var header : String?
// 联系电话
var phone : String?
// 笔名
var nickName : String?
// 认证(0未,1已)
var auth : Int?
// 等级(0普通,1资深)
var level : Int?
// 评论推送开关 0关 1开
var comm : Int?
// 点赞推送开关 0关 1开
var pra : Int?
// 个人简介
var info : String?
// token
var token : String?
/// 归档
func encode(with aCoder: NSCoder) {
aCoder.encode(userId, forKey: "userId")
aCoder.encode(sex, forKey: "sex")
aCoder.encode(header, forKey: "header")
aCoder.encode(phone, forKey: "phone")
aCoder.encode(nickName, forKey: "nickName")
aCoder.encode(auth, forKey: "auth")
aCoder.encode(level, forKey: "level")
aCoder.encode(comm, forKey: "comm")
aCoder.encode(pra, forKey: "pra")
aCoder.encode(info, forKey: "info")
aCoder.encode(token, forKey: "token")
}
/// 解档
required init?(coder aDecoder: NSCoder) {
super.init()
userId = aDecoder.decodeObject(forKey: "userId") as? Int
sex = aDecoder.decodeObject(forKey: "sex") as? String
header = aDecoder.decodeObject(forKey: "header") as? String
phone = aDecoder.decodeObject(forKey: "phone") as? String
nickName = aDecoder.decodeObject(forKey: "nickName") as? String
auth = aDecoder.decodeObject(forKey: "auth") as? Int
level = aDecoder.decodeObject(forKey: "level") as? Int
comm = aDecoder.decodeObject(forKey: "comm") as? Int
pra = aDecoder.decodeObject(forKey: "pra") as? Int
info = aDecoder.decodeObject(forKey: "info") as? String
token = aDecoder.decodeObject(forKey: "token") as? String
}
override init() {
super.init()
}
}
|
0 | // MIT License
//
// Copyright (c) 2020 Declarative Hub
//
// 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 protocol StateProperty: DynamicProperty {
var storage: StateStorage { get }
}
@propertyWrapper public struct State<Value>: StateProperty {
public let storage: StateStorage
@inlinable
public init(wrappedValue value: Value) {
self.storage = StateStorage(initialValue: value, get: { value }, set: { _ in })
}
@inlinable
public var wrappedValue: Value {
get {
storage.get() as! Value
}
nonmutating set {
storage.set(newValue)
}
}
@inlinable
public var projectedValue: Binding<Value> {
return Binding(get: { self.wrappedValue }, set: { (value, transaction) in self.wrappedValue = value })
}
}
extension State where Value: ExpressibleByNilLiteral {
@inlinable
public init() {
self.init(wrappedValue: nil)
}
}
public class StateStorage {
public var initialValue: Any
public var get: () -> Any
public var set: (Any) -> Void
@inlinable
public init(initialValue: Any, get: @escaping () -> Any, set: @escaping (Any) -> Void) {
self.initialValue = initialValue
self.get = get
self.set = set
}
}
|
0 | //
// ViewController.swift
// ToastMessage
//
// Created by Vibhor Gupta on 8/12/19.
// Copyright © 2019 Vibhor Gupta. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func click(_ sender: UIButton) {
showToastMessage(message: "Hello World")
}
}
extension UIViewController {
func showToastMessage(message: String) {
guard let window = UIApplication.shared.keyWindow else {
return
}
let toastLabel = UILabel()
toastLabel.text = message
toastLabel.textAlignment = .center
toastLabel.font = UIFont.systemFont(ofSize: 18)
toastLabel.textColor = .white
toastLabel.backgroundColor = .gray
toastLabel.adjustsFontSizeToFitWidth = true
toastLabel.numberOfLines = 0
let textSize = toastLabel.intrinsicContentSize
let labelWidth = min(textSize.width, window.frame.height - 40)
let labelHeight = (textSize.width / window.frame.width )*20
let adjustedHeight = max( labelHeight , textSize.height + 20 )
toastLabel.frame = CGRect(x: 20, y: ( window.frame.height - 90) - adjustedHeight , width: labelWidth, height: adjustedHeight)
toastLabel.center.x = window.center.x
toastLabel.layer.cornerRadius = 10
toastLabel.layer.masksToBounds = true
window.addSubview(toastLabel)
UIView.animate(withDuration: 0.8, animations: {
toastLabel.alpha = 0.3
}) { (_) in
toastLabel.removeFromSuperview()
}
}
}
|
0 | //
// ViewController.swift
// Shimmeraiser
//
// Created by Victor Panitz Magalhães on 01/14/2019.
// Copyright (c) 2019 Victor Panitz Magalhães. All rights reserved.
//
import UIKit
import Shimmeraiser
internal class DummyShimmerable: Shimmerable {
func getSettings() -> ShimmerSettings {
return ShimmerSettings()
}
func getPath(containerRect: CGRect) -> CGPath {
let baseDistance: CGFloat = 208
let builder = ShimmerPathBuilder()
builder.appendRectPath(cornerRadius: 3, from:
CGRect(x: 54, y: baseDistance, width: 129, height: 18),
CGRect(x: 54, y: baseDistance + 56, width: containerRect.width-108, height: 3),
CGRect(x: 54, y: baseDistance + 89, width: 250, height: 18),
CGRect(x: 32, y: baseDistance + 209, width: containerRect.width-64, height: 1)
)
(0..<2).forEach { i in
let factor = CGFloat(i)*97
let yValue: CGFloat = 448
builder.appendOvalPath(from:
CGRect(x: 41, y: yValue + factor + 21, width: 24, height: 24)
)
builder.appendRectPath(cornerRadius: 3, from:
CGRect(x: 92, y: yValue + factor, width: 122, height: 18),
CGRect(x: 92, y: yValue + factor + 28, width: 122, height: 18),
CGRect(x: 92, y: yValue + factor + 56, width: 122, height: 18),
CGRect(x: containerRect.width-74, y: yValue + factor + 21, width: 44, height: 18),
CGRect(x: 52, y: yValue + 57 + factor, width: 1, height: 18)
)
}
return builder.makeMaskPath()
}
}
|
0 | //
// AccountService.swift
// IntroWorkshop
//
// Created by Ken Ko on 18/01/2016.
// Copyright © 2016 Commonwealth Bank of Australia. All rights reserved.
//
import Foundation
class AccountService {
private var serviceHelper: ServiceHelper
init(serviceHelper: ServiceHelper = ServiceHelperFactory.makeServiceHelper()) {
self.serviceHelper = serviceHelper
}
func getAccounts(completion: @escaping (Result<[Account], ServiceError>) -> Void) {
serviceHelper.request(urlString: ServiceURLs.getAccounts.rawValue, param: nil) { result in
switch result {
case .success(let json):
let accounts = Account.accountList(json: json)
completion(.success(accounts))
case .failure(let error):
completion(.failure(error))
}
}
}
}
|
0 | //
// ImageTableViewCell.swift
// FoodViewer
//
// Created by arnaud on 27/11/2020.
// Copyright © 2020 Hovering Above. All rights reserved.
//
import UIKit
class ImageTableViewCell: UITableViewCell {
@IBOutlet weak var cellImageView: UIImageView!
/**
Setup the cell with an ecoscore
- parameters :
- image : image to be schown
*/
func setup(ecoscore: Ecoscore?) {
if let validEcoscore = ecoscore {
self.cellImage = validEcoscore.image
} else {
self.cellImage = Ecoscore.unknown.image
}
}
private var cellImage: UIImage? {
didSet {
cellImageView?.image = cellImage
}
}
}
|
0 | //
// CallLog.swift
// LinPhone
//
// Created by Alsey Coleman Miller on 7/4/17.
//
//
import CLinPhone
public extension Call {
public final class Log {
}
}
|
0 | /*
-----------------------------------------------------------------------------
This source file is part of SecurityKit.
Copyright 2017-2018 Jon Griffeth
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-----------------------------------------------------------------------------
*/
import SecurityKit
import XCTest
let testIdentity = Identity(named: "TestUser", type: .person)
let testName = X509Name(from: testIdentity)
// URL of Test Files
let testCACERURL = Bundle.tests.url(forResource: "TestCA", ofType: "cer")!
let testCSRURL = Bundle.tests.url(forResource: "Test", ofType: "csr")!
let testCERURL = Bundle.tests.url(forResource: "Test", ofType: "cer")!
// End of File
|
0 | //
// HttpServer.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public class HttpServer: HttpServerIO {
public static let VERSION: String = {
#if os(Linux)
return "1.4.7"
#else
let bundle = Bundle(for: HttpServer.self)
guard let version = bundle.infoDictionary?["CFBundleShortVersionString"] as? String else { return "Unspecified" }
return version
#endif
}()
private let router = HttpRouter()
public override init() {
self.DELETE = MethodRoute(method: "DELETE", router: router)
self.PATCH = MethodRoute(method: "PATCH", router: router)
self.HEAD = MethodRoute(method: "HEAD", router: router)
self.POST = MethodRoute(method: "POST", router: router)
self.GET = MethodRoute(method: "GET", router: router)
self.PUT = MethodRoute(method: "PUT", router: router)
self.delete = MethodRoute(method: "DELETE", router: router)
self.patch = MethodRoute(method: "PATCH", router: router)
self.head = MethodRoute(method: "HEAD", router: router)
self.post = MethodRoute(method: "POST", router: router)
self.get = MethodRoute(method: "GET", router: router)
self.put = MethodRoute(method: "PUT", router: router)
}
public var DELETE, PATCH, HEAD, POST, GET, PUT: MethodRoute
public var delete, patch, head, post, get, put: MethodRoute
public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
set {
router.register(nil, path: path, handler: newValue)
}
get { return nil }
}
public var routes: [String] {
return router.routes()
}
public var defaultRegexRouters = [RegexRouter]()
public var notFoundHandler: ((HttpRequest) -> HttpResponse)?
public var middleware = [(HttpRequest) -> HttpResponse?]()
override public func dispatch(_ request: HttpRequest) -> ([String: String], (HttpRequest) -> HttpResponse) {
for layer in middleware {
if let response = layer(request) {
return ([:], { _ in response })
}
}
if let result = router.route(request.method, path: request.path) {
return result
}
if let regex = defaultRegexRouters.first(where: { $0.regex.regex(text: request.path) }) {
return ([:], regex.router)
}
if let notFoundHandler = self.notFoundHandler {
return ([:], notFoundHandler)
}
return super.dispatch(request)
}
public struct MethodRoute {
public let method: String
public let router: HttpRouter
public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
set {
router.register(method, path: path, handler: newValue)
}
get { return nil }
}
}
public struct RegexRouter {
public let regex: String
public let router: (HttpRequest) -> HttpResponse
public init(regex: String, router: @escaping (HttpRequest) -> HttpResponse) {
self.regex = regex
self.router = router
}
}
}
|
0 | //
// DouyuUITests.swift
// DouyuUITests
//
// Created by Max on 2019/11/4.
// Copyright © 2019 Max. All rights reserved.
//
import XCTest
class DouyuUITests: 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
// 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.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
|
0 | //
// NSObject+Extension.swift
// Reader
//
// Created by CQSC on 2017/6/22.
// Copyright © 2017年 CQSC. All rights reserved.
//
import Foundation
extension NSObject {
// MARK: -- 对象属性处理
/// 获取对象的所有属性名称
func allPropertyNames() ->[String] {
// 这个类型可以使用CUnsignedInt,对应Swift中的UInt32
var count: UInt32 = 0
let properties = class_copyPropertyList(self.classForCoder, &count)
var propertyNames: [String] = []
// Swift中类型是严格检查的,必须转换成同一类型
for i in 0 ..< Int(count) {
// UnsafeMutablePointer<objc_property_t>是
// 可变指针,因此properties就是类似数组一样,可以
// 通过下标获取
let property = properties![i]
let name = property_getName(property)
// 这里还得转换成字符串
let propertyName = String(cString: name)
propertyNames.append(propertyName)
}
// 释放内存,否则C语言的指针很容易成野指针的
free(properties)
return propertyNames;
}
/// 获取对象的所有属性名称跟值
func allPropertys() ->[String : Any?] {
var dict:[String : Any?] = [String : Any?]()
// 这个类型可以使用CUnsignedInt,对应Swift中的UInt32
var count: UInt32 = 0
let properties = class_copyPropertyList(self.classForCoder, &count)
for i in 0 ..< Int(count) {
// 获取属性名称
let property = properties![i]
let name = property_getName(property)
let propertyName = String(cString: name)
if (!propertyName.isEmpty) {
// 获取Value数据
let propertyValue = self.value(forKey: propertyName)
dict[propertyName] = propertyValue
}
}
// 释放内存,否则C语言的指针很容易成野指针的
free(properties)
return dict
}
}
|
0 | /// A Nimble matcher that succeeds when the actual value is within given range.
public func beWithin<T: Comparable>(_ range: Range<T>) -> Predicate<T> {
let errorMessage = "be within range <(\(range.lowerBound)..<\(range.upperBound))>"
return Predicate.simple(errorMessage) { actualExpression in
if let actual = try actualExpression.evaluate() {
return PredicateStatus(bool: range.contains(actual))
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual value is within given range.
public func beWithin<T: Comparable>(_ range: ClosedRange<T>) -> Predicate<T> {
let errorMessage = "be within range <(\(range.lowerBound)...\(range.upperBound))>"
return Predicate.simple(errorMessage) { actualExpression in
if let actual = try actualExpression.evaluate() {
return PredicateStatus(bool: range.contains(actual))
}
return .fail
}
}
|
0 | //
// ObserverPattern.swift
// Design-Patterns
//
// Created by liupengkun on 2020/5/11.
// Copyright © 2020 刘朋坤. All rights reserved.
//
/*
观察者模式(Observer Pattern):定义对象间的一种一对多的依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象都可以到通知并做相应针对性的处理。
*/
import UIKit
class ObserverPattern: NSObject {
}
protocol ObserverPatternObserver : class {
func willChange(propertyName: String, newPropertyValue: Any?)
func didChange(propertyName: String, oldPropertyValue: Any?)
}
final class TestChambers {
weak var observer:ObserverPatternObserver?
private let testName = "testNameValue"
var testNumber: Int = 0 {
willSet(newValue) {
observer?.willChange(propertyName: testName, newPropertyValue: newValue)
}
didSet {
observer?.didChange(propertyName: testName, oldPropertyValue: oldValue)
}
}
}
final class Observer : ObserverPatternObserver {
func willChange(propertyName: String, newPropertyValue: Any?) {
print("willChange: \(propertyName) \(String(describing: newPropertyValue))")
}
func didChange(propertyName: String, oldPropertyValue: Any?) {
print("didChange: \(propertyName) \(String(describing: oldPropertyValue))")
}
}
|
0 | //
// SwiftModalWebVC.swift
//
// Created by Myles Ringle on 24/06/2015.
// Transcribed from code used in SVWebViewController.
// Copyright (c) 2015 Myles Ringle & Oliver Letterer. All rights reserved.
//
import UIKit
public class SwiftModalWebVC: UINavigationController {
public enum SwiftModalWebVCTheme {
case lightBlue, lightBlack, dark
}
weak var webViewDelegate: UIWebViewDelegate? = nil
var webViewController: SwiftWebVC!
public convenience init(urlString: String) {
self.init(pageURL: URL(string: urlString)!)
}
public convenience init(urlString: String, theme: SwiftModalWebVCTheme) {
self.init(pageURL: URL(string: urlString)!, theme: theme)
}
public convenience init(pageURL: URL) {
self.init(request: URLRequest(url: pageURL))
}
public convenience init(pageURL: URL, theme: SwiftModalWebVCTheme) {
self.init(request: URLRequest(url: pageURL), theme: theme)
}
public init(request: URLRequest, theme: SwiftModalWebVCTheme = .lightBlue) {
webViewController = SwiftWebVC(aRequest: request)
webViewController.storedStatusColor = UINavigationBar.appearance().barStyle
let image = UIImage(named: "SwiftWebVCDismiss",
in: Bundle(for: SwiftModalWebVC.self),
compatibleWith: nil)
let doneButton = UIBarButtonItem(image: image,
style: UIBarButtonItemStyle.plain,
target: webViewController,
action: #selector(SwiftWebVC.doneButtonTapped(_:)))
switch theme {
case .lightBlue:
doneButton.tintColor = nil
webViewController.buttonColor = nil
webViewController.titleColor = UIColor.black
UINavigationBar.appearance().barStyle = UIBarStyle.default
case .lightBlack:
doneButton.tintColor = UIColor.darkGray
webViewController.buttonColor = UIColor.darkGray
webViewController.titleColor = UIColor.black
UINavigationBar.appearance().barStyle = UIBarStyle.default
case .dark:
doneButton.tintColor = UIColor.white
webViewController.buttonColor = UIColor.white
webViewController.titleColor = UIColor.groupTableViewBackground
UINavigationBar.appearance().barStyle = UIBarStyle.black
}
if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad) {
webViewController.navigationItem.leftBarButtonItem = doneButton
}
else {
webViewController.navigationItem.rightBarButtonItem = doneButton
}
super.init(rootViewController: webViewController)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
}
}
|
0 | //
// TimingFunctions.swift
// SETabView
//
// Created by Vinayak Eshwa on 20/03/22.
//
import UIKit
struct SETimingFunction {
public static let seEaseIn = CAMediaTimingFunction(controlPoints: 0.6, 0, 1, 1)
public static let seEaseOut = CAMediaTimingFunction(controlPoints: 0, 0, 0.4, 1)
public static let seEaseInOut = CAMediaTimingFunction(controlPoints: 0.6, 0, 0.4, 1)
}
|
0 | import Foundation
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty<S: Sequence>() -> Predicate<S> {
return Predicate.simple("be empty") { actualExpression in
let actualSeq = try actualExpression.evaluate()
if actualSeq == nil {
return .fail
}
var generator = actualSeq!.makeIterator()
return PredicateStatus(bool: generator.next() == nil)
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> Predicate<String> {
return Predicate.simple("be empty") { actualExpression in
let actualString = try actualExpression.evaluate()
return PredicateStatus(bool: actualString == nil || NSString(string: actualString!).length == 0)
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For NSString instances, it is an empty string.
public func beEmpty() -> Predicate<NSString> {
return Predicate.simple("be empty") { actualExpression in
let actualString = try actualExpression.evaluate()
return PredicateStatus(bool: actualString == nil || actualString!.length == 0)
}
}
// Without specific overrides, beEmpty() is ambiguous for NSDictionary, NSArray,
// etc, since they conform to Sequence as well as NMBCollection.
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> Predicate<NSDictionary> {
return Predicate.simple("be empty") { actualExpression in
let actualDictionary = try actualExpression.evaluate()
return PredicateStatus(bool: actualDictionary == nil || actualDictionary!.count == 0)
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> Predicate<NSArray> {
return Predicate.simple("be empty") { actualExpression in
let actualArray = try actualExpression.evaluate()
return PredicateStatus(bool: actualArray == nil || actualArray!.count == 0)
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> Predicate<NMBCollection> {
return Predicate.simple("be empty") { actualExpression in
let actual = try actualExpression.evaluate()
return PredicateStatus(bool: actual == nil || actual!.count == 0)
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beEmptyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try! actualExpression.evaluate()
failureMessage.postfixMessage = "be empty"
if let value = actualValue as? NMBCollection {
let expr = Expression(expression: ({ value as NMBCollection }), location: location)
return try! beEmpty().matches(expr, failureMessage: failureMessage)
} else if let value = actualValue as? NSString {
let expr = Expression(expression: ({ value as String }), location: location)
return try! beEmpty().matches(expr, failureMessage: failureMessage)
} else if let actualValue = actualValue {
failureMessage.postfixMessage = "be empty (only works for NSArrays, NSSets, NSIndexSets, NSDictionaries, NSHashTables, and NSStrings)"
failureMessage.actualValue = "\(String(describing: type(of: actualValue))) type"
}
return false
}
}
}
#endif
|
0 | import Foundation
import Alamofire
public class PostService {
public init() { }
public init(configuration: NSURLSessionConfiguration) {
manager = Alamofire.Manager(configuration: configuration)
}
public func fetchPost(postID: Int, siteID: Int, completion: (post: Post?, error: NSError?) -> Void) {
manager
.request(RequestRouter.Post(postID: postID, siteID: siteID))
.validate()
.responseJSON { response in
guard response.result.isSuccess else {
completion(post: nil, error: response.result.error)
return
}
let json = response.result.value as! [String: AnyObject]
let post = self.mapJSONToPost(json)
completion(post: post, error: nil)
}
}
public func createPost(siteID siteID: Int, status: String, title: String, body: String, completion: (post: Post?, error: NSError?) -> Void) {
manager
.request(RequestRouter.PostNew(siteID: siteID, status: status, title: title, body: body))
.validate()
.responseJSON { response in
guard response.result.isSuccess else {
completion(post: nil, error: response.result.error)
return
}
let json = response.result.value as! [String: AnyObject]
let post = self.mapJSONToPost(json)
completion(post: post, error: nil)
}
}
func mapJSONToPost(json: [String: AnyObject]) -> Post {
let post = Post()
post.ID = json["ID"] as? Int
post.siteID = json["site_ID"] as! Int
post.created = convertUTCWordPressComDate(json["date"] as! String)
if let modifiedDate = json["modified"] as? String {
post.updated = convertUTCWordPressComDate(modifiedDate)
}
post.title = json["title"] as? String
if let postURL = json["URL"] as? String {
post.URL = NSURL(string: postURL)!
}
if let postShortURL = json["short_URL"] as? String {
post.shortURL = NSURL(string: postShortURL)!
}
post.content = json["content"] as? String
post.guid = json["guid"] as? String
post.status = json["status"] as? String
return post
}
private var manager = Alamofire.Manager.sharedInstance
}
|
0 | //
// DetailViewController.swift
// twitter_alamofire_demo
//
// Created by Joseph Davey on 2/17/18.
// Copyright © 2018 Charles Hieger. All rights reserved.
//
import UIKit
import AlamofireImage
class DetailViewController: UIViewController {
var tweet: Tweet?
var user: User?
@IBOutlet weak var profilePictureView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var handleLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var tweetLabel: UILabel!
@IBOutlet weak var retweetCount: UILabel!
@IBOutlet weak var favoriteCount: UILabel!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var likeButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
profilePictureView.af_setImage(withURL: URL(string: (tweet?.profilePic)!)!)
userNameLabel.text = tweet?.user.name
handleLabel.text = "@\((tweet?.user.handle)!)"
timestampLabel.text = tweet?.createdAtString
tweetLabel.text = tweet?.text
retweetCount.text = "\(String(describing: (tweet?.retweetCount)!)) Retweets"
favoriteCount.text = "\(String(describing: (tweet?.favoriteCount!)!)) Favorites"
if tweet?.retweeted == true {
retweetButton.setImage(#imageLiteral(resourceName: "retweet-icon-green"), for: .normal)
} else {
retweetButton.setImage(#imageLiteral(resourceName: "retweet-icon"), for: .normal)
}
if tweet?.favorited == true {
likeButton.setImage(#imageLiteral(resourceName: "favor-icon-red"), for: .normal)
} else {
likeButton.setImage(#imageLiteral(resourceName: "favor-icon"), for: .normal)
}
}
@IBAction func retweetButton(_ sender: Any) {
if (tweet?.retweeted)! {
APIManager.shared.unRetweet(tweet!) { (tweet: Tweet?, error: Error?) in
if let error = error {
self.retweetButton.isUserInteractionEnabled = true
print("Error unretweeting tweet: \(error.localizedDescription)")
print("Printed here")
} else if let tweet = tweet {
self.retweetButton.isUserInteractionEnabled = true
print("Successfully unretweeted the following Tweet: \n\(tweet.text)")
tweet.retweeted = false
let count = tweet.retweetCount
tweet.retweetCount = count - 1
self.retweetButton.setImage(#imageLiteral(resourceName: "retweet-icon"), for: .normal)
}
}
} else {
APIManager.shared.retweet(tweet!) { (tweet: Tweet?, error: Error?) in
if let error = error {
self.retweetButton.isUserInteractionEnabled = true
print("Error retweeting tweet: \(error)")
print("Printed here")
} else if let tweet = tweet {
self.retweetButton.isUserInteractionEnabled = true
print("Successfully retweeted the following Tweet: \n\(tweet.text)")
tweet.retweeted = true
let count = tweet.retweetCount
tweet.retweetCount = count + 1
self.retweetButton.setImage(#imageLiteral(resourceName: "retweet-icon-green"), for: .normal)
}
}
}
}
@IBAction func favoriteButton(_ sender: Any) {
self.likeButton.isUserInteractionEnabled = false
if let favorited = tweet?.favorited {
if favorited {
APIManager.shared.unfavorite(tweet!, completion: { (tweet, error) in
if let error = error {
self.likeButton.isUserInteractionEnabled = true
print("Error unfavoriting tweet: \(error.localizedDescription)")
print("Printed here")
} else if let tweet = tweet {
self.likeButton.isUserInteractionEnabled = true
print("Successfully unfavorited the following Tweet: \n\(tweet.text)")
self.tweet = tweet
tweet.favorited = false
let count = tweet.favoriteCount
tweet.favoriteCount = count! - 1
self.likeButton.setImage(#imageLiteral(resourceName: "favor-icon"), for: .normal)
}
})
} else {
APIManager.shared.favoriteATweet(tweet!, completion: { (tweet, error) in
if let error = error {
self.likeButton.isUserInteractionEnabled = true
print("Error favoriting tweet: \(error.localizedDescription)")
print("Printed here though!")
} else if let tweet = tweet {
self.likeButton.isUserInteractionEnabled = true
print("Successfully favorited the following Tweet: \n\(tweet.text)")
self.tweet = tweet
tweet.favorited = true
let count = tweet.favoriteCount
tweet.favoriteCount = count! + 1
self.likeButton.setImage(#imageLiteral(resourceName: "favor-icon-red"), for: .normal)
}
})
}
} else {
APIManager.shared.favoriteATweet(tweet!) { (tweet: Tweet?, error: Error?) in
if let error = error {
self.likeButton.isUserInteractionEnabled = true
print("Error favoriting tweet: \(error.localizedDescription)")
} else if let tweet = tweet {
self.likeButton.isUserInteractionEnabled = true
print("Successfully favorited the following Tweet: \n\(tweet.text)")
self.tweet = tweet
tweet.favorited = true
let count = tweet.favoriteCount
tweet.favoriteCount = count! + 1
self.likeButton.setImage(#imageLiteral(resourceName: "favor-icon-red"), for: .normal)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
0 | import Foundation
import Vapor
/// Line Object
public struct Line: Content {
var statusCode: Int?
/// ID of a line
public let id: Int
/// Name of a line
public let name: String
/// ID of the location this line belongs to
public let location: Int?
}
/// Lines object
struct Lines: Content {
static var dataContainer = \Lines.data
/// Status code from API
internal let statusCode: Int?
/// Lines array
let data: [Line]
}
|
0 | //
// MoviePosterImage.swift
// MovieSwift
//
// Created by Thomas Ricouard on 13/06/2019.
// Copyright © 2019 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import Backend
struct MoviePosterImage: View {
@ObservedObject var imageLoader: ImageLoader
@State var isImageLoaded = false
let posterSize: PosterStyle.Size
var body: some View {
if let image = imageLoader.image {
Image(uiImage: image)
.resizable()
.renderingMode(.original)
.posterStyle(loaded: true, size: posterSize)
.onAppear{
isImageLoaded = true
}
} else {
Rectangle()
.foregroundColor(.gray)
.posterStyle(loaded: false, size: posterSize)
}
}
}
|
0 | //
// ViewController.swift
// FachriApp
//
// Created by Fachri Febrian on 17/05/2019.
// Copyright © 2019 fachrifaul. All rights reserved.
//
import UIKit
import Alamofire
import Core
import Account
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Log.d("viewDidLoad")
AccountLog.d("viewDidLoad")
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
}
@IBAction func coreVCAction(_ sender: Any) {
navigationController?.pushViewController(Core.ViewController(), animated: true)
}
@IBAction func accountVCAction(_ sender: Any) {
navigationController?.pushViewController(Account.ViewController(), animated: true)
}
}
|
0 | //
// BrokerageRouter.swift
// Ribbit
//
// Created by Ahsan Ali on 09/04/2021.
//
import UIKit
class BrokerageRouter: Router {
func route(to routeID: String, from context: UIViewController, parameters: Any?, animated: Bool) {
if let vController = UIStoryboard.main.instantiateViewController(withIdentifier: PreviewApplicationVC.identifier) as? PreviewApplicationVC {
context.navigationController?.pushViewController(vController, animated: animated)
}
}
func routeToBrokerage(to routeID: String, from context: UIViewController, parameters: Any?, animated: Bool) {
if let vController = UIStoryboard.main.instantiateViewController(withIdentifier: BrokerageInfoVC.identifier) as? BrokerageInfoVC {
context.navigationController?.pushViewController(vController, animated: animated)
}
}
}
|
0 | //
// ValidationResult.swift
// ResterCore
//
// Created by Sven A. Schmidt on 01/02/2019.
//
import Foundation
public typealias Reason = String
public enum ValidationResult: Equatable {
case valid
case invalid(Reason)
}
|
0 | //
// TKTConfiguration.swift
// TikiTechLibrary
//
// Created by Nguyen Hieu Trung on 9/5/20.
// Copyright © 2020 NHTSOFT. All rights reserved.
//
import Foundation
import UIKit
public class TKTConfiguration{
public var domain: String = ""
public var apiKey: String = ""
public var email: String = ""
public var lang: TKTLanguage?
public init(domain:String, apiKey: String, email: String, language: TKTLanguage) {
self.domain = domain
self.apiKey = apiKey
self.email = email
self.lang = language
}
}
|
0 | //
// FirstViewController.swift
// 古蹟x歷史建築
//
// Created by ddl on 2017/9/26.
// Copyright © 2017年 ddl. All rights reserved.
//
import UIKit
class MonumentViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.dataUrl = "https://cloud.culture.tw/frontsite/trans/emapOpenDataAction.do?method=exportEmapJson&typeId=A&classifyId=1.1"
self.filePath = self.rootPath + "monument.json"
self.showTalbe()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
0 | //
// MIT License
//
// Copyright (c) 2020 micheltlutz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/**
Class for ordered list
### Usage Example: ###
````
let ol = OL()
ol.add("Ordered list item 1")
ol.add("Ordered list item 2")
````
*/
public final class OL: UL {
///Override tag element for input elements. Default is `ol`
override var tag: String {
get {
return "ol"
}
}
}
|
0 | //
// GameViewController.swift
// ALifeGame
//
// Created by Yamazaki Mitsuyoshi on 2019/11/23.
// Copyright © 2019 Yamazaki Mitsuyoshi. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
final class GameViewController: UIViewController {
@IBOutlet private weak var sceneView: SKView! {
didSet {
sceneView.ignoresSiblingOrder = true
sceneView.showsFPS = true
sceneView.showsNodeCount = true
}
}
private let gameScene: GameScene! = GameScene(fileNamed: "GameScene")
override func viewDidLoad() {
super.viewDidLoad()
gameScene.scaleMode = .aspectFill
gameScene.size = sceneView.frame.size
gameScene.gameSceneDelegate = self
sceneView.presentScene(gameScene)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
gameScene.resetFocusing()
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override var prefersStatusBarHidden: Bool {
return true
}
}
extension GameViewController: GameSceneDelegate {
func gameSceneDidEnterALifeWorld(_ scene: GameScene) {
performSegue(withIdentifier: "ShowALifeView", sender: self)
}
}
|
0 | //
// CuisineCell.swift
// Yelp
//
// Created by ximin_zhang on 8/10/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
@objc protocol CuisineCellDelegate {
optional func cuisineCell(switchCell: CuisineCell, didChangeValue: Bool) //
}
class CuisineCell: UITableViewCell {
@IBOutlet weak var onSwitch: UISwitch!
@IBOutlet weak var cuisineLabel: UILabel!
weak var delegate: CuisineCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
onSwitch.addTarget(self, action: #selector(CuisineCell.switchValueChanged), forControlEvents: UIControlEvents.ValueChanged)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func switchValueChanged(){
print("switch value changed")
delegate?.cuisineCell!(self, didChangeValue: onSwitch.on)
}
}
|
0 | //
// Created by Brandon Brisbon on 5/22/15.
// Copyright (c) 2015 Ello. All rights reserved.
//
import Foundation
public class IntroViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
var viewControllers: [IntroPageController] = []
var pageControl: UIPageControl = UIPageControl()
override public func viewDidLoad()
{
super.viewDidLoad()
let storyboard = UIStoryboard(name: "Intro", bundle: nil)
pageViewController = storyboard.instantiateViewControllerWithIdentifier("IntroPager") as? UIPageViewController
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
let frame = CGRect(x: 0, y: 0, width: width, height: height)
pageViewController?.view.frame = frame
pageViewController?.dataSource = self
// Load and set views/pages
let welcomePageViewController = storyboard
.instantiateViewControllerWithIdentifier("WelcomePage") as! WelcomePageController
welcomePageViewController.pageIndex = 0
let inspiredPageViewController = storyboard
.instantiateViewControllerWithIdentifier("InspiredPage") as! InspiredPageController
inspiredPageViewController.pageIndex = 1
let friendsPageViewController = storyboard
.instantiateViewControllerWithIdentifier("FriendsPage") as! FriendsPageController
friendsPageViewController.pageIndex = 2
let lovesPageViewController = storyboard
.instantiateViewControllerWithIdentifier("LovesPage") as! LovesPageController
lovesPageViewController.pageIndex = 3
viewControllers = [
welcomePageViewController,
inspiredPageViewController,
friendsPageViewController,
lovesPageViewController
]
pageViewController!.setViewControllers([welcomePageViewController],
direction: .Forward, animated: false, completion: nil)
pageViewController!.view.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
// Setup the page control
pageControl.frame = CGRect(x: 0, y: 20, width: 80, height: 37)
pageControl.frame.origin.x = view.bounds.size.width / 2 - pageControl.frame.size.width / 2
pageControl.currentPage = 0
pageControl.numberOfPages = viewControllers.count
pageControl.currentPageIndicatorTintColor = .blackColor()
pageControl.pageIndicatorTintColor = .greyA()
pageControl.autoresizingMask = [.FlexibleBottomMargin, .FlexibleRightMargin, .FlexibleLeftMargin]
// Setup skip button
let skipButton = UIButton()
let skipButtonRightMargin: CGFloat = 10
skipButton.frame = CGRect(x: 0, y: 20, width: 0, height: 0)
skipButton.setTitle("Skip", forState: UIControlState.Normal)
skipButton.titleLabel?.font = UIFont.defaultFont(14)
skipButton.sizeToFit()
// Set frame margin from right edge
skipButton.frame.origin.x = view.frame.width - skipButtonRightMargin - skipButton.frame.width
skipButton.center.y = pageControl.center.y
skipButton.autoresizingMask = [.FlexibleBottomMargin, .FlexibleLeftMargin]
skipButton.setTitleColor(UIColor.greyA(), forState: .Normal)
skipButton.addTarget(self, action: #selector(IntroViewController.didTouchSkipIntro(_:)), forControlEvents: .TouchUpInside)
// Add subviews
view.addSubview(pageControl)
view.addSubview(skipButton)
// Add pager controller
addChildViewController(pageViewController!)
view.addSubview(pageViewController!.view)
// Move everything to the front
pageViewController!.didMoveToParentViewController(self)
view.bringSubviewToFront(pageControl)
view.bringSubviewToFront(skipButton)
// add status bar to intro
let bar = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 20))
bar.autoresizingMask = [.FlexibleWidth, .FlexibleBottomMargin]
bar.backgroundColor = UIColor.blackColor()
view.addSubview(bar)
}
func didTouchSkipIntro(sender: UIButton!) {
self.dismissViewControllerAnimated(false, completion:nil)
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?
{
var index = (viewController as! IntroPageController).pageIndex!
pageControl.currentPage = index
if index <= 0 {
return nil
}
index -= 1
return viewControllerAtIndex(index)
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?
{
var index = (viewController as! IntroPageController).pageIndex!
pageControl.currentPage = index
index += 1
if index >= viewControllers.count {
return nil
}
return viewControllerAtIndex(index)
}
func viewControllerAtIndex(index: Int) -> UIViewController? {
if index >= viewControllers.count {
return nil
}
return viewControllers[index] as UIViewController
}
}
|
0 | //
// MHLoginViewController.swift
// MyHarvest
//
// Created by NiuYulong on 2017/9/5.
// Copyright © 2017年 NiuYulong. All rights reserved.
//
import UIKit
class MHLoginViewController: MHBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "登录"
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
0 | //
// SettingsViewController.swift
// tipped
//
// Created by Michael Volovar on 9/29/16.
// Copyright © 2016 Michael Volovar. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBAction func returnToPreviousView(_ sender: AnyObject) {
navigationController?.popViewController(animated: true)
}
}
|
0 | //
// AnimationTabBarController.swift
// HVLoveFreshBeen
//
// Created by Heaven on 1/14/19.
// Copyright © 2019 cenntro. All rights reserved.
//
import UIKit
class AnimationTabBarController: UITabBarController {
var iconsView: [(icon: UIImageView, textLabel: UILabel)] = []
var iconsImageName:[String] = ["v2_home", "v2_order", "shopCart", "v2_my"]
var iconsSelectedImageName:[String] = ["v2_home_r", "v2_order_r", "shopCart_r", "v2_my_r"]
var shopCarIcon: UIImageView?
var isPlayAnimation: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
// NotificationCenter.default.addObserver(self, selector: Selector(("searchViewControllerDeinit")), name: NSNotification.Name(rawValue: "LFBSearchViewControllerDeinit"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func searchViewControllerDeinit() {
if shopCarIcon != nil {
let redDotView = ShopCartNumberView.sharedShopCartNumberView
redDotView.frame = CGRect(x: 21 + 1, y: -3, width: 15, height: 15)
shopCarIcon?.addSubview(redDotView)
}
}
func createViewContainers() -> [String: UIView] {
var containersDict = [String: UIView]()
guard let customItems = tabBar.items as? [HVAnimatedTabBarItem] else
{
return containersDict
}
for index in 0..<customItems.count {
let viewContainer = createViewContainer(index)
containersDict["container\(index)"] = viewContainer
}
return containersDict
}
func createViewContainer(_ index: Int) -> UIView {
let viewWidth: CGFloat = ScreenWidth / CGFloat(tabBar.items!.count)
let viewHeight: CGFloat = tabBar.bounds.size.height
let viewContainer = UIView(frame: CGRect(x: viewWidth * CGFloat(index), y: 0, width: viewWidth, height: viewHeight))
viewContainer.backgroundColor = UIColor.clear
viewContainer.isUserInteractionEnabled = true
tabBar.addSubview(viewContainer)
viewContainer.tag = index
let tap = UITapGestureRecognizer(target: self, action: #selector(tabBar(_:didSelect:)))
viewContainer.addGestureRecognizer(tap)
return viewContainer
}
// @objc func tabBarClick(_ tap: UITapGestureRecognizer ) {
//
// }
func createCustomIcons(_ containers : [String: UIView]) {
if let items = tabBar.items {
for (index, item) in items.enumerated() {
assert(item.image != nil, "add image icon in UITabBarItem")
guard let container = containers["container\(index)"] else
{
print("No container given")
continue
}
container.tag = index
let imageW:CGFloat = 21
let imageX:CGFloat = (ScreenWidth / CGFloat(items.count) - imageW) * 0.5
let imageY:CGFloat = 8
let imageH:CGFloat = 21
let icon = UIImageView(frame: CGRect(x: imageX, y: imageY, width: imageW, height: imageH))
icon.image = item.image
icon.tintColor = UIColor.clear
// text
let textLabel = UILabel()
textLabel.frame = CGRect(x: 0, y: 32, width: ScreenWidth / CGFloat(items.count), height: 49 - 32)
textLabel.text = item.title
textLabel.backgroundColor = UIColor.clear
textLabel.font = UIFont.systemFont(ofSize: 10)
textLabel.textAlignment = NSTextAlignment.center
textLabel.textColor = UIColor.gray
textLabel.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(icon)
container.addSubview(textLabel)
if let tabBarItem = tabBar.items {
let textLabelWidth = tabBar.frame.size.width / CGFloat(tabBarItem.count)
textLabel.bounds.size.width = textLabelWidth
}
if 2 == index {
let redDotView = ShopCartNumberView.sharedShopCartNumberView
redDotView.frame = CGRect(x: imageH + 1, y: -3, width: 15, height: 15)
icon.addSubview(redDotView)
shopCarIcon = icon
}
let iconsAndLabels = (icon:icon, textLabel:textLabel)
iconsView.append(iconsAndLabels)
item.image = nil
item.title = ""
if index == 0 {
selectedIndex = 0
selectItem(0)
}
}
}
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
setSelectIndex(from: selectedIndex, to: item.tag)
}
func selectItem(_ Index: Int) {
let items = tabBar.items as! [HVAnimatedTabBarItem]
let selectIcon = iconsView[Index].icon
selectIcon.image = UIImage(named: iconsSelectedImageName[Index])!
items[Index].selectedState(selectIcon, textLabel: iconsView[Index].textLabel)
}
func setSelectIndex(from: Int,to: Int) {
// if to == 2 {
// let vc = children[selectedIndex]
// let shopCar = ShopCartVC()
// let nav = BaseNavigationController(rootViewController: shopCar)
// vc.present(nav, animated: true, completion: nil)
//
// return
// }
selectedIndex = to
let items = tabBar.items as! [HVAnimatedTabBarItem]
let fromIV = iconsView[from].icon
fromIV.image = UIImage(named: iconsImageName[from])
items[from].deselectAnimation(fromIV, textLabel: iconsView[from].textLabel)
let toIV = iconsView[to].icon
toIV.image = UIImage(named: iconsSelectedImageName[to])
items[to].playAnimation(toIV, textLabel: iconsView[to].textLabel, isPlayAnimation: isPlayAnimation)
}
}
// MARK: 组件
class HVBounceAnimation : HVItemAnimation {
override func playAnimation(_ icon : UIImageView, textLabel : UILabel, isPlayAnimation: Bool) {
textLabel.textColor = textSelectedColor
if isPlayAnimation {
playBounceAnimation(icon)
}
}
override func deselectAnimation(_ icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor) {
textLabel.textColor = defaultTextColor
if let iconImage = icon.image {
let renderImage = iconImage.withRenderingMode(.alwaysOriginal)
icon.image = renderImage
icon.tintColor = defaultTextColor
}
}
override func selectedState(_ icon : UIImageView, textLabel : UILabel) {
textLabel.textColor = textSelectedColor
if let iconImage = icon.image {
let renderImage = iconImage.withRenderingMode(.alwaysOriginal)
icon.image = renderImage
icon.tintColor = textSelectedColor
}
}
func playBounceAnimation(_ icon : UIImageView) {
let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
bounceAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0]
bounceAnimation.duration = TimeInterval(duration)
bounceAnimation.calculationMode = CAAnimationCalculationMode.cubic
icon.layer.add(bounceAnimation, forKey: "bounceAnimation")
if let iconImage = icon.image {
let renderImage = iconImage.withRenderingMode(.alwaysOriginal)
icon.image = renderImage
icon.tintColor = iconSelectedColor
}
}
}
class HVAnimatedTabBarItem: UITabBarItem {
var animation: HVItemAnimation?
/// 是否开启动画 默认开启
var isAnimation: Bool = true
var textColor = UIColor.gray
func playAnimation(_ icon : UIImageView, textLabel : UILabel, isPlayAnimation: Bool) {
guard let animation = animation else {
print("add animation in UITabBarItem")
return
}
animation.playAnimation(icon, textLabel: textLabel, isPlayAnimation: isAnimation)
}
func deselectAnimation(_ icon: UIImageView, textLabel: UILabel) {
animation?.deselectAnimation(icon, textLabel: textLabel, defaultTextColor: textColor)
}
func selectedState(_ icon: UIImageView, textLabel: UILabel) {
animation?.selectedState(icon, textLabel: textLabel)
}
}
protocol HVItemAnimationProtocol {
func playAnimation(_ icon : UIImageView, textLabel : UILabel, isPlayAnimation: Bool)
func deselectAnimation(_ icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor)
func selectedState(_ icon : UIImageView, textLabel : UILabel)
}
class HVItemAnimation: NSObject, HVItemAnimationProtocol {
var duration : CGFloat = 0.6
var textSelectedColor: UIColor = BaseNavigationYellowColor
var iconSelectedColor: UIColor?
func playAnimation(_ icon : UIImageView, textLabel : UILabel, isPlayAnimation: Bool) {
}
func deselectAnimation(_ icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor) {
}
func selectedState(_ icon: UIImageView, textLabel : UILabel) {
}
}
|
0 | //
// Memoization.swift
// RxSwiftly
//
// Created by Bas van Kuijck on 28/07/2017.
// Copyright © 2017 E-sites. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
public protocol Memoization: class { }
extension NSObject: Memoization { }
extension Memoization {
/// Memoizes the the `lazyCreateClosure`
///
/// [Read this](https://nl.wikipedia.org/wiki/Memoization) for more information about memoization:
///
/// - Notes: Memoization will be stored alongside the &key and the `self`.
///
/// - Parameters:
/// - key: The `UnsafeRawPointer` to store the memoized outcome in.
/// - lazyCreateClosure: The closure which creates the object
/// - Returns: The object itself
public func memoize<T>(key: UnsafeRawPointer, lazyCreateClosure: () -> T) -> T {
return _memoize(self, key: key, lazyCreateClosure: lazyCreateClosure)
}
}
extension Reactive {
/// Memoizes the the `lazyCreateClosure`
///
/// [Read this](https://nl.wikipedia.org/wiki/Memoization) for more information about memoization:
///
/// - Notes: Memoization will be stored alongside the &key and the `self.base` of the Reactive instance.
///
/// - Parameters:
/// - key: The `UnsafeRawPointer` to store the memoized outcome in.
/// - lazyCreateClosure: The closure which creates the object
/// - Returns: The object itself
public func memoize<T>(key: UnsafeRawPointer, lazyCreateClosure: () -> Observable<T>) -> Observable<T> {
return _memoize(self.base, key: key, lazyCreateClosure: lazyCreateClosure)
}
}
fileprivate func _memoize<T>(_ object: Any, key: UnsafeRawPointer, lazyCreateClosure: () -> T) -> T {
objc_sync_enter(object); defer { objc_sync_exit(object) }
if let instance = objc_getAssociatedObject(object, key) as? T {
return instance
}
let instance = lazyCreateClosure()
objc_setAssociatedObject(object, key, instance, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return instance
}
|
0 | //
// bitcrushTests.swift
// AudioKit
//
// Created by Aurelius Prochazka on 8/9/16.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
import AudioKit
import XCTest
class BitcrushTests: AKTestCase {
override func setUp() {
super.setUp()
duration = 1.0
}
func testDefault() {
let input = AKOscillator()
input.start()
output = AKOperationEffect(input) { input, _ in
return input.bitCrush()
}
AKTestMD5("7a7cc018565b8f99afac21bb6182cbce")
}
}
|
0 | //
// UIViewExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import UIKit
public enum ShakeDirection {
case horizontal
case vertical
}
public enum AngleUnit {
case degrees
case radians
}
public enum ShakeAnimationType {
case linear
case easeIn
case easeOut
case easeInOut
}
public extension UIView {
/// Add shadow to view
public func addShadow(ofColor color: UIColor = UIColor(netHex: 0x137992),
radius: CGFloat = 3,
offset: CGSize = CGSize(width: 0, height: 0),
opacity: Float = 0.5) {
layer.shadowColor = color.cgColor
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = opacity
layer.masksToBounds = true
}
/// Add array of subviews to view.
public func add(subViews: [UIView]) {
subViews.forEach({self.addSubview($0)})
}
/// Border color of view; also inspectable from Storyboard.
@IBInspectable
public var borderColor: UIColor? {
get {
guard let color = layer.borderColor else {
return nil
}
return UIColor(cgColor: color)
}
set {
guard let color = newValue else {
layer.borderColor = nil
return
}
layer.borderColor = color.cgColor
}
}
/// Border width of view; also inspectable from Storyboard.
@IBInspectable
public var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
/// Corner radius of view; also inspectable from Storyboard.
@IBInspectable
public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.masksToBounds = true
layer.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100)
}
}
/// Fade in view.
public func fadeIn(duration: TimeInterval = 1, completion:((Bool) -> Void)? = nil) {
if self.isHidden {
self.isHidden = false
}
UIView.animate(withDuration: duration, animations: {
self.alpha = 0
}, completion: completion)
}
/// Fade out view.
public func fadeOut(duration: TimeInterval = 1, completion:((Bool) -> Void)? = nil) {
if self.isHidden {
self.isHidden = false
}
UIView.animate(withDuration: duration, animations: {
self.alpha = 1
}, completion: completion)
}
/// First responder.
public var firstResponder: UIView? {
guard !self.isFirstResponder else {
return self
}
for subView in subviews {
if subView.isFirstResponder {
return subView
}
}
return nil
}
// Height of view
public var height: CGFloat {
get {
return self.frame.size.height
}
set {
self.frame.size.height = newValue
}
}
/// Return true if view is in RTL format.
public var isRightToLeft: Bool {
if #available(iOS 10.0, *) {
return effectiveUserInterfaceLayoutDirection == .rightToLeft
} else {
return false
}
}
/// Return true if view is visible in screen currently and not hidden.
public var isVisible: Bool {
// https://github.com/hilen/TimedSilver/blob/master/Sources/UIKit/UIView%2BTSExtension.swift
if self.window == nil || self.isHidden || self.alpha == 0 {
return true
}
let viewRect = self.convert(self.bounds, to: nil)
guard let window = UIApplication.shared.keyWindow else {
return true
}
return viewRect.intersects(window.bounds) == false
}
/// Load view from nib
class func loadFromNibNamed(nibNamed: String, bundle : Bundle? = nil) -> UIView? {
return UINib(nibName: nibNamed, bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as? UIView
}
/// Remove all subviews in view.
public func removeSubViews() {
self.subviews.forEach({$0.removeFromSuperview()})
}
/// Remove all gesture recognizers from view.
public func removeGestureRecognizers() {
gestureRecognizers?.forEach(removeGestureRecognizer)
}
/// Rotate view by angle on relative axis.
public func rotate(byAngle angle : CGFloat, ofType type: AngleUnit, animated: Bool = false, duration: TimeInterval = 1, completion:((Bool) -> Void)? = nil) {
let angleWithType = (type == .degrees) ? CGFloat(M_PI) * angle / 180.0 : angle
if animated {
UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () -> Void in
self.transform = self.transform.rotated(by: angleWithType)
}, completion: completion)
} else {
self.transform = self.transform.rotated(by: angleWithType)
completion?(true)
}
}
/// Rotate view to angle on fixed axis.
public func rotate(toAngle angle: CGFloat, ofType type: AngleUnit, animated: Bool = false, duration: TimeInterval = 1, completion:((Bool) -> Void)? = nil) {
let angleWithType = (type == .degrees) ? CGFloat(M_PI) * angle / 180.0 : angle
if animated {
UIView.animate(withDuration: duration, animations: {
self.transform = CGAffineTransform(rotationAngle: angleWithType)
}, completion: completion)
} else {
transform = CGAffineTransform(rotationAngle: angleWithType)
completion?(true)
}
}
/// Scale view by offset.
public func scale(by offset: CGPoint, animated: Bool = false, duration: TimeInterval = 1, completion:((Bool) -> Void)? = nil) {
if animated {
UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () -> Void in
self.transform = self.transform.scaledBy(x: offset.x, y: offset.y)
}, completion: completion)
} else {
self.transform = self.transform.scaledBy(x: offset.x, y: offset.y)
completion?(true)
}
}
/// Take screenshot of view.
public var screenShot: UIImage? {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0.0);
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext()
}
/// Shadow color of view; also inspectable from Storyboard.
@IBInspectable
public var shadowColor: UIColor? {
get {
guard let color = layer.shadowColor else {
return nil
}
return UIColor(cgColor: color)
}
set {
layer.shadowColor = newValue?.cgColor
}
}
/// Shadow offset of view; also inspectable from Storyboard.
@IBInspectable
public var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
/// Shadow opacity of view; also inspectable from Storyboard.
@IBInspectable
public var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
/// Shadow radius of view; also inspectable from Storyboard.
@IBInspectable
public var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
/// Shake view.
public func shake(direction: ShakeDirection = .horizontal, duration: TimeInterval = 1, animationType: ShakeAnimationType = .easeOut, completion:(() -> Void)? = nil) {
CATransaction.begin()
let animation: CAKeyframeAnimation
switch direction {
case .horizontal:
animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
case .vertical:
animation = CAKeyframeAnimation(keyPath: "transform.translation.y")
}
switch animationType {
case .linear:
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
case .easeIn:
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
case .easeOut:
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
case .easeInOut:
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
CATransaction.setCompletionBlock(completion)
animation.duration = duration
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
CATransaction.commit()
}
// Size of view
public var size: CGSize {
get {
return self.frame.size
}
set {
self.width = newValue.width
self.height = newValue.height
}
}
// Width of view
public var width: CGFloat {
get {
return self.frame.size.width
}
set {
self.frame.size.width = newValue
}
}
}
|
0 | //
// CodeClimate.swift
// stts
//
import Foundation
class CodeClimate: StatusPageService {
let name = "Code Climate"
let url = URL(string: "http://status.codeclimate.com")!
let statusPageID = "rh2cj4bllp8l"
}
|
0 | import Foundation
open class BufferedOutput: InstantiatableOutput {
private let dateProvider: DateProvider = DefaultDateProvider()
internal let readWriteQueue = DispatchQueue(label: "com.cookpad.Puree.Logger.BufferedOutput", qos: .background)
required public init(logStore: LogStore, tagPattern: TagPattern, options: OutputOptions? = nil) {
self.logStore = logStore
self.tagPattern = tagPattern
}
public struct Chunk: Hashable {
public let logs: Set<LogEntry>
private(set) var retryCount: Int = 0
fileprivate init(logs: Set<LogEntry>) {
self.logs = logs
}
fileprivate mutating func incrementRetryCount() {
retryCount += 1
}
public static func == (lhs: Chunk, rhs: Chunk) -> Bool {
return lhs.logs == rhs.logs
}
public func hash(into hasher: inout Hasher) {
hasher.combine(logs)
}
}
public struct Configuration {
public var logEntryCountLimit: Int
public var flushInterval: TimeInterval
public var retryLimit: Int
public static let `default` = Configuration(logEntryCountLimit: 5, flushInterval: 10, retryLimit: 3)
}
public let tagPattern: TagPattern
private let logStore: LogStore
public var configuration: Configuration = .default
private var buffer: Set<LogEntry> = []
private var currentWritingChunks: Set<Chunk> = []
private var timer: Timer?
private var lastFlushDate: Date?
private var logLimit: Int {
return configuration.logEntryCountLimit
}
private var flushInterval: TimeInterval {
return configuration.flushInterval
}
private var retryLimit: Int {
return configuration.retryLimit
}
private var currentDate: Date {
return dateProvider.now
}
deinit {
timer?.invalidate()
}
public func start() {
reloadLogStore()
readWriteQueue.sync {
flush()
}
setUpTimer()
}
public func resume() {
reloadLogStore()
readWriteQueue.sync {
flush()
}
setUpTimer()
}
public func suspend() {
timer?.invalidate()
}
public func emit(log: LogEntry) {
readWriteQueue.sync {
buffer.insert(log)
logStore.add(log, for: storageGroup, completion: nil)
if buffer.count >= logLimit {
flush()
}
}
}
open func write(_ chunk: Chunk, completion: @escaping (Bool) -> Void) {
completion(false)
}
open var storageGroup: String {
let typeName = String(describing: type(of: self))
return "\(tagPattern.pattern)_\(typeName)"
}
private func setUpTimer() {
self.timer?.invalidate()
let timer = Timer(timeInterval: 1.0,
target: self,
selector: #selector(tick(_:)),
userInfo: nil,
repeats: true)
RunLoop.main.add(timer, forMode: .common)
self.timer = timer
}
@objc private func tick(_ timer: Timer) {
if let lastFlushDate = lastFlushDate {
if currentDate.timeIntervalSince(lastFlushDate) > flushInterval {
readWriteQueue.async {
self.flush()
}
}
} else {
readWriteQueue.async {
self.flush()
}
}
}
private func reloadLogStore() {
readWriteQueue.sync {
buffer.removeAll()
let semaphore = DispatchSemaphore(value: 0)
logStore.retrieveLogs(of: storageGroup) { logs in
let filteredLogs = logs.filter { log in
return !currentWritingChunks.contains { chunk in
return chunk.logs.contains(log)
}
}
buffer = buffer.union(filteredLogs)
semaphore.signal()
}
semaphore.wait()
}
}
private func flush() {
dispatchPrecondition(condition: .onQueue(readWriteQueue))
lastFlushDate = currentDate
if buffer.isEmpty {
return
}
let logCount = min(buffer.count, logLimit)
let newBuffer = Set(buffer.dropFirst(logCount))
let dropped = buffer.subtracting(newBuffer)
buffer = newBuffer
let chunk = Chunk(logs: dropped)
callWriteChunk(chunk)
}
open func delay(try count: Int) -> TimeInterval {
return 2.0 * pow(2.0, Double(count - 1))
}
private func callWriteChunk(_ chunk: Chunk) {
dispatchPrecondition(condition: .onQueue(readWriteQueue))
currentWritingChunks.insert(chunk)
write(chunk) { success in
if success {
self.readWriteQueue.async {
self.currentWritingChunks.remove(chunk)
self.logStore.remove(chunk.logs, from: self.storageGroup, completion: nil)
}
return
}
var chunk = chunk
chunk.incrementRetryCount()
if chunk.retryCount <= self.retryLimit {
let delay: TimeInterval = self.delay(try: chunk.retryCount)
self.readWriteQueue.asyncAfter(deadline: .now() + delay) {
self.callWriteChunk(chunk)
}
}
}
}
}
|
0 | /*
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 Swift project authors
*/
import Foundation
/// Protocol for request-response based servers.
public protocol DocumentationServerProtocol {
/// Processes the given message and responds using the given completion closure.
func process(_ message: Data, completion: @escaping (Data) -> ())
}
|
0 | //
// ApiProperty.swift
// OnTheMap
//
// Created by Jan Skála on 30/03/2020.
// Copyright © 2020 Jan Skála. All rights reserved.
//
import Foundation
class ApiProperty<T : Decodable> : ObservableProperty<ApiResult<T>>{
let state = ApiResult<T>()
var request : ApiRequest<T>?
private var requestTask : URLSessionTask? = nil
init(withId id: String? = nil, andRequest request: ApiRequest<T>? = nil){
super.init(withId: id)
self.request = request
callbacks = [:]
}
/* Load data from request (or use previous request for nil) */
func load(request newRequest: ApiRequest<T>? = nil){
guard let req = newRequest ?? self.request else { return }
self.request = req
//guard request != nil || !state.isLoading() else { return }
cancelPreviousRequest()
state.setLoading()
setValue(state)
requestTask = req.execute(callback: { (data, error) in
if error != nil {
print("Property error")
self.state.state = .error
self.state.error = error
}else{
print("Property success")
self.state.state = .success
self.state.value = data
}
self.setValue(self.state)
})
}
func cancelPreviousRequest(){
requestTask?.cancel()
requestTask = nil
}
override func beforeCallbackAdd() {
if state.isError() || state.isIdle() {
load()
}
}
override func afterCallbackRemove() {
if callbacks.isEmpty {
cancelPreviousRequest()
}
}
}
|
0 | //
// PhotoListCellConfiguration.swift
// HXPHPickerExample
//
// Created by Slience on 2020/12/29.
// Copyright © 2020 Silence. All rights reserved.
//
import UIKit
// MARK: 照片列表Cell配置类
public struct PhotoListCellConfiguration {
/// 自定义不带选择框的cell
/// 继承 PhotoPickerBaseViewCell 只有UIImageView,其他控件需要自己添加
/// 继承 PhotoPickerViewCell 在自带的基础上修改
public var customSingleCellClass: PhotoPickerBaseViewCell.Type?
/// 自定义带选择框的cell
/// 继承 PhotoPickerBaseViewCell 只有UIImageView,其他控件需要自己添加
/// 继承 PhotoPickerViewCell 带有图片和类型控件,选择按钮控件需要自己添加
/// 继承 PhotoPickerSelectableViewCell 加以修改
public var customSelectableCellClass: PhotoPickerBaseViewCell.Type?
/// 如果资产在iCloud上,是否显示iCloud标示
public var showICloudMark: Bool = true
/// 背景颜色
public var backgroundColor: UIColor?
/// 暗黑风格下背景颜色
public var backgroundDarkColor: UIColor?
/// 缩略图的清晰度,越大越清楚,越小越模糊
/// 默认为 250
public var targetWidth: CGFloat = 250
/// cell在不可选择状态下是否显示禁用遮罩
/// 如果限制了照片/视频的文件大小,则无效
public var showDisableMask: Bool = true
/// 照片视频不能同时选择并且视频最大选择数为1时视频cell是否隐藏选择框
public var singleVideoHideSelect: Bool = true
/// 选择框顶部的间距
public var selectBoxTopMargin: CGFloat = 5
/// 选择框右边的间距
public var selectBoxRightMargin: CGFloat = 5
/// 选择框相关配置
public var selectBox: SelectBoxConfiguration = .init()
#if canImport(Kingfisher)
public var kf_indicatorColor: UIColor?
#endif
public init() { }
}
|
0 | import Foundation
internal protocol SpecDocumentContext {
// MARK: - Instance Methods
func component<T: Codable>(at componentURI: String, document: SpecDocument) throws -> SpecComponent<T>
}
|
0 | // This file is generated.
import Foundation
/// Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed.
public enum Scheme: String, Codable {
/// Slippy map tilenames scheme.
case xyz = "xyz"
/// OSGeo spec scheme.
case tms = "tms"
}
/// The encoding used by this source. Mapbox Terrain RGB is used by default
public enum Encoding: String, Codable {
/// Terrarium format PNG tiles. See https://aws.amazon.com/es/public-datasets/terrain/ for more info.
case terrarium = "terrarium"
/// Mapbox Terrain RGB tiles. See https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb for more info.
case mapbox = "mapbox"
}
// End of generated file.
|
0 | //
// AppDelegate.swift
// ios-app-showcase
//
// Created by Ilya Shaisultanov on 1/24/16.
// Copyright © 2016 Ilya Shaisultanov. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return FBSDKApplicationDelegate
.sharedInstance()
.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate
.sharedInstance()
.application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
}
|
0 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var d {
class B : d {
class d<T where I.Element == compose(t: A
func a<Int>: Bool)
func a<T>: d {
protocol A {
typealias b : b
class
|
0 | //
// UINavigationControllerExtensions.swift
// Snapshot
//
// Created by Dao Duy Duong on 1/9/18.
// Copyright © 2018 Halliburton. All rights reserved.
//
import UIKit
extension UINavigationController {
func popViewController(animated: Bool, completions: ((UIViewController?) -> Void)?) {
let page = topViewController
if animated {
CATransaction.begin()
CATransaction.setCompletionBlock { completions?(page) }
popViewController(animated: animated)
CATransaction.commit()
} else {
popViewController(animated: animated)
completions?(page)
}
}
func pushViewController(_ viewController: UIViewController, animated: Bool, completions: (() -> Void)?) {
if animated {
CATransaction.begin()
CATransaction.setCompletionBlock(completions)
pushViewController(viewController, animated: animated)
CATransaction.commit()
} else {
popViewController(animated: animated)
completions?()
}
}
}
|
0 | // The MIT License (MIT)
//
// Copyright (c) 2020–2022 Alexander Grebenyuk (github.com/kean).
#if os(iOS)
import UIKit
import SwiftUI
@available(iOS 13.0, *)
extension UIImage {
static func make(systemName: String, textStyle: UIFont.TextStyle) -> UIImage {
UIImage(systemName: systemName)?
.withConfiguration(UIImage.SymbolConfiguration(textStyle: textStyle)) ?? UIImage()
}
}
extension UIView {
static func vStack(
alignment: UIStackView.Alignment = .fill,
distribution: UIStackView.Distribution = .fill,
spacing: CGFloat = 0,
margins: UIEdgeInsets? = nil,
_ views: [UIView]
) -> UIStackView {
makeStackView(axis: .vertical, alignment: alignment, distribution: distribution, spacing: spacing, margins: margins, views)
}
static func hStack(
alignment: UIStackView.Alignment = .fill,
distribution: UIStackView.Distribution = .fill,
spacing: CGFloat = 0,
margins: UIEdgeInsets? = nil,
_ views: [UIView]
) -> UIStackView {
makeStackView(axis: .horizontal, alignment: alignment, distribution: distribution, spacing: spacing, margins: margins, views)
}
}
private extension UIView {
static func makeStackView(axis: NSLayoutConstraint.Axis, alignment: UIStackView.Alignment, distribution: UIStackView.Distribution, spacing: CGFloat, margins: UIEdgeInsets?, _ views: [UIView]) -> UIStackView {
let stack = UIStackView(arrangedSubviews: views)
stack.axis = axis
stack.alignment = alignment
stack.distribution = distribution
stack.spacing = spacing
if let margins = margins {
stack.isLayoutMarginsRelativeArrangement = true
stack.layoutMargins = margins
}
return stack
}
}
extension UIView {
func pinToSuperview(insets: UIEdgeInsets = .zero) {
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
topAnchor.constraint(equalTo: superview!.topAnchor, constant: insets.top),
trailingAnchor.constraint(equalTo: superview!.trailingAnchor, constant: -insets.right),
leadingAnchor.constraint(equalTo: superview!.leadingAnchor, constant: insets.left),
bottomAnchor.constraint(equalTo: superview!.bottomAnchor, constant: -insets.bottom)
])
}
}
@available(iOS 13.0, *)
extension UIViewController {
@discardableResult
static func present<ContentView: View>(_ closure: (_ dismiss: @escaping () -> Void) -> ContentView) -> UIViewController? {
present { UIHostingController(rootView: closure($0)) }
}
@discardableResult
static func present(_ closure: (_ dismiss: @escaping () -> Void) -> UIViewController) -> UIViewController? {
guard let keyWindow = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first,
var topController = keyWindow.rootViewController else {
return nil
}
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
let vc = closure({ [weak topController] in
topController?.dismiss(animated: true, completion: nil)
})
topController.present(vc, animated: true, completion: nil)
return vc
}
}
#endif
|
0 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: OS=ios
import UIKit
func printOrientation(o: UIDeviceOrientation) {
print("\(o.isPortrait) \(UIDeviceOrientationIsPortrait(o)), ", terminator: "")
print("\(o.isLandscape) \(UIDeviceOrientationIsLandscape(o)), ", terminator: "")
print("\(o.isFlat), ", terminator: "")
print("\(o.isValidInterfaceOrientation) \(UIDeviceOrientationIsValidInterfaceOrientation(o))")
}
print("Device orientations")
printOrientation(UIDeviceOrientation.unknown)
printOrientation(UIDeviceOrientation.portrait)
printOrientation(UIDeviceOrientation.portraitUpsideDown)
printOrientation(UIDeviceOrientation.landscapeLeft)
printOrientation(UIDeviceOrientation.landscapeRight)
printOrientation(UIDeviceOrientation.faceUp)
printOrientation(UIDeviceOrientation.faceDown)
// CHECK: Device orientations
// CHECK-NEXT: false false, false false, false, false false
// CHECK-NEXT: true true, false false, false, true true
// CHECK-NEXT: true true, false false, false, true true
// CHECK-NEXT: false false, true true, false, true true
// CHECK-NEXT: false false, true true, false, true true
// CHECK-NEXT: false false, false false, true, false false
// CHECK-NEXT: false false, false false, true, false false
func printOrientation(o: UIInterfaceOrientation) {
print("\(o.isPortrait) \(UIInterfaceOrientationIsPortrait(o)), ", terminator: "")
print("\(o.isLandscape) \(UIInterfaceOrientationIsLandscape(o))")
}
print("Interface orientations")
printOrientation(UIInterfaceOrientation.unknown)
printOrientation(UIInterfaceOrientation.portrait)
printOrientation(UIInterfaceOrientation.portraitUpsideDown)
printOrientation(UIInterfaceOrientation.landscapeLeft)
printOrientation(UIInterfaceOrientation.landscapeRight)
// CHECK: Interface orientations
// CHECK-NEXT: false false, false false
// CHECK-NEXT: true true, false false
// CHECK-NEXT: true true, false false
// CHECK-NEXT: false false, true true
// CHECK-NEXT: false false, true true
var inset1 = UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.0, right: 4.0)
var inset2 = UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.1, right: 4.0)
print("inset1 == inset1: \(inset1 == inset1)")
print("inset1 != inset1: \(inset1 != inset1)")
print("inset1 == inset2: \(inset1 == inset2)")
// CHECK: inset1 == inset1: true
// CHECK: inset1 != inset1: false
// CHECK: inset1 == inset2: false
var offset1 = UIOffset(horizontal: 1.0, vertical: 2.0)
var offset2 = UIOffset(horizontal: 1.0, vertical: 3.0)
print("offset1 == offset1: \(offset1 == offset1)")
print("offset1 != offset1: \(offset1 != offset1)")
print("offset1 == offset2: \(offset1 == offset2)")
// CHECK: offset1 == offset1: true
// CHECK: offset1 != offset1: false
// CHECK: offset1 == offset2: false
var inset0 = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
var insetDot0 = UIEdgeInsets.zero
print("inset0 == insetDot0: \(inset0 == insetDot0)")
// CHECK: inset0 == insetDot0: true
var offset0 = UIOffset(horizontal: 0.0, vertical: 0.0)
var offsetDot0 = UIOffset.zero
print("offset0 == offsetDot0: \(offset0 == offsetDot0)")
// CHECK: offset0 == offsetDot0: true
|
0 | //
// TweetsViewController.swift
// Eagle
//
// Created by Kyle Leung on 2/27/17.
// Copyright © 2017 Kyle Leung. All rights reserved.
//
import UIKit
class TweetsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tweets: [Tweet]?
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Table View Setup
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 125
// Do any additional setup after loading the view.
TwitterClient.sharedInstance?.homeTimeLine(success: { (tweets: [Tweet]) -> () in
self.tweets = tweets
self.tableView.reloadData()
}, failure: { (error: Error) in
print(error.localizedDescription)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogoutButton(_ sender: Any) {
User.currentUser = nil
TwitterClient.sharedInstance?.logout()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let tweets = tweets {
return tweets.count
}
else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tweetCell", for: indexPath) as! TweetCell
cell.tweet = tweets![indexPath.row]
cell.selectionStyle = .none
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "toDetail") {
let cell = sender as! TweetCell
let indexPath = tableView.indexPath(for: cell)
let tweet = tweets![(indexPath!.row)]
let detailedViewController = segue.destination as! TweetDetailedViewController
detailedViewController.tweet = tweet
}
else if (segue.identifier == "profile") {
let cellButton = sender as! UIButton
let cell = cellButton.superview?.superview as! TweetCell
let indexPath = tableView.indexPath(for: cell)
let tweet = tweets![(indexPath!.row)]
let navController = segue.destination as! UINavigationController
let profileViewController = navController.viewControllers[0] as! ProfileViewController
profileViewController.tweet = tweet
}
}
}
|
0 | //
// SetPinnedChats.swift
// tl2swift
//
// Generated automatically. Any changes will be lost!
// Based on TDLib 1.8.4-07b7faf6
// https://github.com/tdlib/td/tree/07b7faf6
//
import Foundation
/// Changes the order of pinned chats
public struct SetPinnedChats: Codable, Equatable {
/// The new list of pinned chats
public let chatIds: [Int64]?
/// Chat list in which to change the order of pinned chats
public let chatList: ChatList?
public init(
chatIds: [Int64]?,
chatList: ChatList?
) {
self.chatIds = chatIds
self.chatList = chatList
}
}
|
0 | /*
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import IGListKit
import IGListSwiftKit
final class ListeningSectionController: ListSectionController, IncrementListener {
private var value: Int = 0
init(announcer: IncrementAnnouncer) {
super.init()
announcer.addListener(listener: self)
}
func configureCell(cell: LabelCell) {
cell.text = "Section: \(self.section), value: \(value)"
}
// MARK: ListSectionController Overrides
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 55)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
let cell: LabelCell = collectionContext.dequeueReusableCell(for: self, at: index)
configureCell(cell: cell)
return cell
}
// MARK: IncrementListener
func didIncrement(announcer: IncrementAnnouncer, value: Int) {
self.value = value
guard let cell = collectionContext?.cellForItem(at: 0, sectionController: self) as? LabelCell else { return }
configureCell(cell: cell)
}
}
|
0 | //
// ViewFrame.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/28.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
class ViewFrame: NSObject {
//: 视图高度
var height:CGFloat = 0.0
//: 内容大小
var contentSize:CGSize = .zero
}
|
0 | //
// GameList.swift
// GamerSky
//
// Created by Insect on 2018/4/23.
// Copyright © 2018年 QY. All rights reserved.
//
import Foundation
struct GameList: Codable {
/// 游戏总数
let gamesCount: Int
/// 游戏信息
let childelements: [GameChildElement]
}
struct GameChildElement: Codable {
/// 游戏ID
let Id: Int
/// 游戏名称
let title: String
/// 游戏评分
let userScore: Float?
/// 游戏图片
let image: String
/// 是否显示活动图片
let position: String?
}
|
0 | //
// ViewController.swift
// MICountryPicker
//
// Created by Ibrahim, Mustafa on 1/24/16.
// Copyright © 2016 Mustafa Ibrahim. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func openPickerAction(sender: AnyObject) {
let picker = MICountryPicker { (name, code) -> () in
print(code)
}
// Optional: To pick from custom countries list
picker.customCountriesCode = ["EG", "US", "AF", "AQ", "AX"]
// delegate
picker.delegate = self
// or closure
// picker.didSelectCountryClosure = { name, code in
// print(code)
// }
navigationController?.pushViewController(picker, animated: true)
}
}
extension ViewController: MICountryPickerDelegate {
func countryPicker(picker: MICountryPicker, didSelectCountryWithName name: String, code: String) {
label.text = "Selected Country: \(name)"
}
}
|
0 | /*
* Copyright IBM Corporation 2017
*
* 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 Kitura
import SwiftyJSON
import LoggerAPI
import HeliumLogger
import Foundation
import Dispatch
Log.logger = HeliumLogger(.info)
let port = Int(ProcessInfo.processInfo.environment["PORT"] ?? "8080") ?? 8080
// 'Think' time (ms) of the /think/sync and /think/async routes
let thinkTime:Int = Int(ProcessInfo.processInfo.environment["THINKTIME"] ?? "5") ?? 5
let thinkTimeUs:UInt32 = UInt32(thinkTime) * 1000
let router = Router()
router.post("/unparsedPost") {
request, response, next in
response.status(.OK).send("OK")
try response.end()
}
router.post("/parsedPost", middleware: BodyParser())
router.post("/parsedPost") {
request, response, next in
guard let parsedBody = request.body else {
response.status(.badRequest).send("Error reading request body")
try response.end()
return
}
switch(parsedBody) {
case .raw(let rawBody):
let contentLength = rawBody.count
response.status(.OK).send("Length of POST: \(contentLength) bytes")
default:
response.status(.badRequest).send("Expected a raw message body")
}
try response.end()
}
router.get("/think/sync") {
request, response, next in
usleep(thinkTimeUs)
response.status(.OK).send("OK")
try response.end()
}
router.get("/think/async") {
request, response, next in
DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(thinkTime)) {
do {
response.status(.OK).send("OK")
try response.end()
} catch {
print("Disaster")
}
}
}
let oneKBData = Data(repeating: 0x75, count: 1024)
let tenKBData = Data(repeating: 0x76, count: 10240)
let hundredKBData = Data(repeating: 0x77, count: 102400)
let oneMBData = Data(repeating: 0x78, count: 1048576)
router.get("/1k") {
request, response, next in
response.status(.OK).send(data: oneKBData)
try response.end()
}
router.get("/10k") {
request, response, next in
response.status(.OK).send(data: tenKBData)
try response.end()
}
router.get("/100k") {
request, response, next in
response.status(.OK).send(data: hundredKBData)
try response.end()
}
router.get("/1mb") {
request, response, next in
response.status(.OK).send(data: oneMBData)
try response.end()
}
Kitura.addHTTPServer(onPort: port, with: router)
Kitura.run()
|
0 | //
// SourceKittenSwiftCode.swift
// Synopsis
//
// Created by incetro on 11/23/20.
// Copyright © 2020 Incetro Inc. All rights reserved.
//
import Files
import Foundation
// MARK: - SourceKittenSwiftCode
/// Any swift source code file
/// parsed with SourceKitten
public struct SourceKittenSwiftCode: SourceCode {
// MARK: - Properties
/// Target file url
public let fileURL: URL
/// A dictionary which describes your source code
/// from file at `fileURL`
public let sourceCodeDictionary: [String: Any]
/// Target file content
public var content: String {
let content = try? File(path: fileURL.absoluteString).readAsString()
return content ?? ""
}
/// Source code substructure representation
public var substructure: [Parameters] {
guard let dictionary = sourceCodeDictionary[fileURL.absoluteString] as? Parameters else {
return []
}
return dictionary.substructure
}
}
|
0 | // Playground - noun: a place where people can play
import Cocoa
import PGSQLKit
var conn: PGSQLConnection;
conn = PGSQLConnection();
conn.UserName = "postgres";
conn.Password = "test";
conn.ConnectionString = "host=localhost port=5432 dbname=postgres user=postgres password=gr8orthan0";
if (!conn.connect())
{
print("Connection Failed");
print(conn.LastError);
conn.close();
} else {
print("Connected");
var rs: GenDBRecordset
rs = conn.open("select current_database()")
var rCount = rs.rowCount()
var currentState = rs.IsEOF
if (!rs.IsEOF)
{
print("table: " + rs.fieldByIndex(0).asString())
// rs.moveNext()
}
rs.close()
conn.close();
}
|
0 | //
// PartyMembersView.swift
// party-joiner-mobile
//
// Created by Evgeny Gerdt on 01.12.2021.
//
import SwiftUI
struct PartyMembersView: View {
@State var members: [Party.Member]
var body: some View {
NavigationView {
Form {
Text("Members")
}
}
}
}
|
0 | //
// ThemeManager.swift
// DKVideo
//
// Created by 朱德坤 on 2019/3/7.
// Copyright © 2019 DKJone. All rights reserved.
//
import RxCocoa
import RxSwift
import RxTheme
import UIKit
import ChameleonFramework
let globalStatusBarStyle = BehaviorRelay<UIStatusBarStyle>(value: .default)
let themeService = ThemeType.service(initial: ThemeType.currentTheme())
protocol Theme {
/// 白背景色
var primary: UIColor { get }
var primaryDark: UIColor { get }
/// 导航栏颜色- 主题色
var secondary: UIColor { get }
var secondaryDark: UIColor { get }
/// 分割线颜色
var separator: UIColor { get }
/// 文字颜色 - 黑色
var text: UIColor { get }
/// 文字颜色 - 灰色
var textGray: UIColor { get }
/// 背景色
var background: UIColor { get }
var statusBarStyle: UIStatusBarStyle { get }
var barStyle: UIBarStyle { get }
var keyboardAppearance: UIKeyboardAppearance { get }
var blurStyle: UIBlurEffect.Style { get }
init(colorTheme: ColorTheme)
}
struct LightTheme: Theme {
let primary = UIColor.white
let primaryDark = UIColor.flatWhite
var secondary = UIColor(hex: 0x24a2fd)!
var secondaryDark = UIColor.white
let separator = UIColor(hexString: "#dbdbdd")!
let text = UIColor.flatBlack
let textGray = UIColor(hex: 0x98999a)!//UIColor.flatGray
let background = UIColor(hexString: "#F5F7FA")!
let statusBarStyle = UIStatusBarStyle.default
let barStyle = UIBarStyle.default
let keyboardAppearance = UIKeyboardAppearance.light
let blurStyle = UIBlurEffect.Style.extraLight
init(colorTheme: ColorTheme) {
self.secondary = colorTheme.color
self.secondaryDark = colorTheme.colorDark
}
}
struct DarkTheme: Theme {
let primary = UIColor.flatBlack
let primaryDark = UIColor.flatBlackDark
var secondary = UIColor(hex: 0x24a2fd)!.darken()
var secondaryDark = UIColor.flatWhiteDark
let separator = UIColor.flatWhite
let text = UIColor.flatWhite
let textGray = UIColor.flatGray
let background = UIColor.flatBlackDark
let statusBarStyle = UIStatusBarStyle.lightContent
let barStyle = UIBarStyle.black
let keyboardAppearance = UIKeyboardAppearance.dark
let blurStyle = UIBlurEffect.Style.dark
init(colorTheme: ColorTheme) {
self.secondary = colorTheme.color
self.secondaryDark = colorTheme.colorDark
}
}
enum ColorTheme: Int {
case red, green, blue, skyBlue, magenta, purple, watermelon, lime, pink
static let allValues = [red, green, blue, skyBlue, magenta, purple, watermelon, lime, pink]
var color: UIColor {
switch self {
case .red: return UIColor.flatRed
case .green: return UIColor.flatGreen
case .blue: return UIColor.flatBlue
case .skyBlue: return UIColor.flatSkyBlue
case .magenta: return UIColor.flatMagenta
case .purple: return UIColor.flatPurple
case .watermelon: return UIColor.flatWatermelon
case .lime: return UIColor.flatLime
case .pink: return UIColor.flatPink
}
}
var colorDark: UIColor {
switch self {
case .red: return UIColor.flatRedDark()
case .green: return UIColor.flatGreenDark()
case .blue: return UIColor.flatBlueDark()
case .skyBlue: return UIColor.flatSkyBlueDark()
case .magenta: return UIColor.flatMagentaDark()
case .purple: return UIColor.flatPurpleDark()
case .watermelon: return UIColor.flatWatermelonDark()
case .lime: return UIColor.flatLimeDark()
case .pink: return UIColor.flatPinkDark()
}
}
var title: String {
switch self {
case .red: return "Red"
case .green: return "Green"
case .blue: return "Blue"
case .skyBlue: return "Sky Blue"
case .magenta: return "Magenta"
case .purple: return "Purple"
case .watermelon: return "Watermelon"
case .lime: return "Lime"
case .pink: return "Pink"
}
}
}
enum ThemeType: ThemeProvider {
case light(color: ColorTheme)
case dark(color: ColorTheme)
var associatedObject: Theme {
switch self {
case .light(let color): return LightTheme(colorTheme: color)
case .dark(let color): return DarkTheme(colorTheme: color)
}
}
var isDark: Bool {
switch self {
case .dark: return true
default: return false
}
}
func toggled() -> ThemeType {
var theme: ThemeType
switch self {
case .light(let color):
theme = ThemeType.dark(color: color)
globalStatusBarStyle.accept(.lightContent)
case .dark(let color):
theme = ThemeType.light(color: color)
if #available(iOS 13.0, *) {
globalStatusBarStyle.accept(.darkContent)
} else {
globalStatusBarStyle.accept(.default)
}
}
theme.save()
return theme
}
func withColor(color: ColorTheme) -> ThemeType {
var theme: ThemeType
switch self {
case .light: theme = ThemeType.light(color: color)
case .dark: theme = ThemeType.dark(color: color)
}
theme.save()
return theme
}
}
extension ThemeType {
static func currentTheme() -> ThemeType {
let isDark = UserDefaults.standard.isDark
let colorTheme = ColorTheme(rawValue: UserDefaults.standard.themeColor) ?? ColorTheme.red
let theme = isDark ? ThemeType.dark(color: colorTheme) : ThemeType.light(color: colorTheme)
theme.save()
return theme
}
func save() {
UserDefaults.standard.isDark = isDark
switch self {
case .light(let color): UserDefaults.standard.themeColor = color.rawValue
case .dark(let color): UserDefaults.standard.themeColor = color.rawValue
}
}
}
extension Reactive where Base: UIView {
var backgroundColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
view.backgroundColor = attr
}
}
var borderColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
view.borderColor = attr
}
}
}
extension Reactive where Base: UITextField {
var placeholderColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
if let color = attr {
view.setPlaceHolderTextColor(color)
}
}
}
}
extension Reactive where Base: TextView {
var placeholderColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
if let color = attr {
view.placeholderColor = color
}
}
}
}
extension Reactive where Base: UITableView {
var separatorColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
view.separatorColor = attr
}
}
}
//extension Reactive where Base: UITabBarItem {
// var iconColor: Binder<UIColor> {
// return Binder(self.base) { view, attr in
// view.imagec
// view.image = view.image?.filled(withColor: attr)
// }
// }
//
// var textColor: Binder<UIColor> {
// return Binder(self.base) { view, attr in
// view.titl = attr
// view.deselectAnimation()
// }
// }
//}
//
//extension Reactive where Base: RAMItemAnimation {
// var iconSelectedColor: Binder<UIColor> {
// return Binder(self.base) { view, attr in
// view.iconSelectedColor = attr
// }
// }
//
// var textSelectedColor: Binder<UIColor> {
// return Binder(self.base) { view, attr in
// view.textSelectedColor = attr
// }
// }
//}
extension Reactive where Base:UITabBar{
var unselectedItemTintColor: Binder<UIColor> {
return Binder(self.base){bar,color in
bar.unselectedItemTintColor = color
}
}
}
extension Reactive where Base: UINavigationBar {
@available(iOS 11.0, *)
var largeTitleTextAttributes: Binder<[NSAttributedString.Key: Any]?> {
return Binder(self.base) { view, attr in
view.largeTitleTextAttributes = attr
}
}
}
extension Reactive where Base: UIApplication {
var statusBarStyle: Binder<UIStatusBarStyle> {
return Binder(self.base) { _, attr in
globalStatusBarStyle.accept(attr)
}
}
}
extension Reactive where Base: KafkaRefreshDefaults {
var themeColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
view.themeColor = attr
}
}
}
public extension Reactive where Base: UISwitch {
var onTintColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
view.onTintColor = attr
}
}
var thumbTintColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
view.thumbTintColor = attr
}
}
}
|
0 | //
// Constraint.swift
// Layout
//
// Created by Mitch Treece on 7/15/20.
//
import Foundation
public class Constraint {
public let constraint: NSLayoutConstraint
public let type: ConstraintType
public let key: String?
internal init(_ constraint: NSLayoutConstraint,
type: ConstraintType,
key: String?) {
self.constraint = constraint
self.type = type
self.key = key
}
internal func wrapped() -> WrappedConstraint {
return WrappedConstraint(self)
}
}
extension Constraint: ConstraintUpdatable {
@discardableResult
public func constant(to constant: Constant) -> Self {
self.constraint.constant = constant.value
return self
}
@discardableResult
public func offset(by offset: Constant) -> Self {
self.constraint.constant = (self.constraint.constant + offset.value)
return self
}
@discardableResult
public func inset(by inset: Constant) -> Self {
self.constraint.constant = (self.constraint.constant - inset.value)
return self
}
@discardableResult
public func multiplied(by multiplier: Constant) -> Self {
self.constraint.constant = (self.constraint.constant * multiplier.value)
return self
}
@discardableResult
public func divided(by divisor: Constant) -> Self {
self.constraint.constant = (self.constraint.constant / divisor.value)
return self
}
@discardableResult
public func priority(_ priority: LayoutPriority) -> Self {
self.constraint.priority = priority
return self
}
}
|
0 | //
// UINavigationControllor+SWFBuilder.swift
// TestSwift
//
// Created by wsy on 2018/1/10.
// Copyright © 2018年 wangshengyuan. All rights reserved.
//
import Foundation
import UIKit
extension UINavigationController
{
open static func initializes() {
self.objSwizzlingOrReplaceMethod(originSelector: #selector(pushViewController(_:animated:)), newSelector: #selector(cus_pushViewController(_:animated:)))
}
@objc func cus_pushViewController(_ viewController: UIViewController, animated: Bool){
if self.viewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true //这个方便隐藏导航栏
self.interactivePopGestureRecognizer?.delegate = self as? UIGestureRecognizerDelegate //左滑返回手势
}
self.cus_pushViewController(viewController, animated: animated)
}
func naviBgImage(_ image: UIImage) -> UINavigationController {
self.navigationBar .setBackgroundImage(image, for: UIBarMetrics.default)
return self
}
func naviBgColor(_ color: UIColor) -> UINavigationController {
let image = color.colorImage()
self.navigationBar .setBackgroundImage(image, for: UIBarMetrics.default)
return self
}
}
|
0 | /**
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
// MARK: AcceptsTokens
/// Applied to card descriptors that accept tokens
protocol AcceptsTokens {
var tokenSlots: [TokenSlot] { get }
}
|
0 | //
// Common.swift
// SinaWeibo
//
// Created by Minghe on 11/10/15.
// Copyright © 2015 Stanford swift. All rights reserved.
//
import Foundation
// MARK: - 保存全局通知 ------------------------------
/// 自定义转场显示通知
let MHzPopoverViewControllerShowClick = "MHzPopoverViewControllerShowClick"
/// 自定义转场消失通知
let MHzPopoverViewControllerDismissClick = "MHzPopoverViewControllerDismissClick"
/// 切换根控制器通知
let MHzRootViewControllerChanged = "MHzRootViewControllerChanged"
// MARK: - 授权信息 ------------------------------
let MHz_App_Key = "550720174"
let MHz_APP_Secret = "ijt3e030ug5biutv1uetl3ayv6t90b25"
let MHz_Redirect_URI = "http://www.goalhi.com"
|
0 | //
// RequestHandler.swift
// AppToolkit
//
// Created by Alex Zablotskiy on 10/23/17.
// Copyright © 2017 Jibo Inc. All rights reserved.
//
import Alamofire
fileprivate struct Refresher {
var isRefreshing = false
}
// MARK: - RequestHandler
final class RequestHandler: RequestAdapter, RequestRetrier {
fileprivate typealias RefreshCompletion = (_ succeeded: Bool) -> ()
fileprivate lazy var oauthService = OAuthService(executor: requestExecutor)
fileprivate var refresher = Refresher()
fileprivate var authorizers: [URL: RequestAuthorizer] = [:]
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
if let url = urlRequest.url, let authorizer = authorizers[url] {
return authorizer.authorize(request: urlRequest)
}
return urlRequest
}
func should(_ manager: Alamofire.SessionManager,
retry request: Alamofire.Request,
with error: Error,
completion: @escaping Alamofire.RequestRetryCompletion) {
if let response = request.task?.response as? HTTPURLResponse,
response.statusCode == 401 {
guard let _ = KeychainUtils.obtainOrRemoveTokenIfNotValid() else {
completion(false, 0.0)
return
}
defer {
KeychainUtils.removeToken()
KeychainUtils.removeCertificates()
}
print("Invalid token, trying to refresh...")
completion(true, retryDelay(for: response))
if let url = request.request?.url {
refreshTokens(for: url, completion: {_ in })
}
} else {
completion(false, 0.0)
}
}
func registerAuthorizer(_ authorizer: RequestAuthorizer?, for urlRequest: URLRequestConvertible) {
do {
let urlRequest = try urlRequest.asURLRequest()
if let url = urlRequest.url {
authorizers[url] = authorizer
}
} catch {
}
}
}
// MARK: - Private
extension RequestHandler {
// MARK: - Refresh Tokens
fileprivate func refreshTokens(for url: URL, completion: @escaping RefreshCompletion) {
guard !refresher.isRefreshing,
let clientInfo = ClientInfo.makeInfo() else {
completion(false)
return
}
refresher.isRefreshing = true
oauthService.refreshToken(clientInfo: clientInfo) { [weak self] result in
guard let sself = self else {
completion(false)
return
}
switch result {
case (.failure(let error), _):
print("RefreshToken failed: \(error.localizedDescription)")
completion(false)
case (.success(let success), let token):
print("RefreshToken succeed")
if let authorizer = sself.authorizers[url] {
authorizer.updateToken(token: token)
}
completion(success)
}
sself.refresher.isRefreshing = false
}
}
// MARK: - Refresh delay
fileprivate func retryDelay(for response: HTTPURLResponse) -> TimeInterval {
guard let retryAfter = response.allHeaderFields["retry-after"] as? String else { return 15.0 }
return TimeInterval(retryAfter) ?? 15
}
}
|
0 | // RUN: %empty-directory(%t)
// RUN: touch %t/file-01.swift
// RUN: touch %t/file-02.swift
// RUN: cd %t
// RUN: %target-swift-frontend -emit-module -primary-file file-01.swift -primary-file file-02.swift -o file-01.swiftmodule -o file-02.swiftmodule -module-name foo
// RUN: test -e file-01.swiftmodule -a -e file-02.swiftmodule
|
0 | //
// GotCell.swift
// GameOfThrones
//
// Created by Bienbenido Angeles on 11/19/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import UIKit
class GotCell: UITableViewCell {
@IBOutlet weak var episodeImageView: UIImageView!
@IBOutlet weak var seasonNameLabel: UILabel!
@IBOutlet weak var seasonEpisodeLabel: UILabel!
func configureCell(for episode: GOTEpisode){
episodeImageView.image = UIImage(named: episode.mediumImageID)
seasonNameLabel.text = episode.name
seasonEpisodeLabel.text = "S:\(episode.season) E:\(episode.number)"
}
}
|
0 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-stdlib -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Swift
import Foundation
import CoreGraphics
// CHECK: [[INT32:@[0-9]+]] = {{.*}} c"i\00"
// CHECK: [[OBJECT:@[0-9]+]] = {{.*}} c"@\00"
@objc enum ObjCEnum: Int32 { case X }
@objc class ObjCClass: NSObject {}
class NonObjCClass {}
@_silgen_name("use")
func use(_: Builtin.RawPointer)
func getObjCTypeEncoding<T>(_: T) {
// CHECK: call swiftcc void @use({{.* i8]\*}} [[INT32]],
use(Builtin.getObjCTypeEncoding(Int32.self))
// CHECK: call swiftcc void @use({{.* i8]\*}} [[INT32]]
use(Builtin.getObjCTypeEncoding(ObjCEnum.self))
// CHECK: call swiftcc void @use({{.* i8]\*}} [[CGRECT:@[0-9]+]],
use(Builtin.getObjCTypeEncoding(CGRect.self))
// CHECK: call swiftcc void @use({{.* i8]\*}} [[NSRANGE:@[0-9]+]],
use(Builtin.getObjCTypeEncoding(NSRange.self))
// CHECK: call swiftcc void @use({{.* i8]\*}} [[OBJECT]]
use(Builtin.getObjCTypeEncoding(AnyObject.self))
// CHECK: call swiftcc void @use({{.* i8]\*}} [[OBJECT]]
use(Builtin.getObjCTypeEncoding(NSObject.self))
// CHECK: call swiftcc void @use({{.* i8]\*}} [[OBJECT]]
use(Builtin.getObjCTypeEncoding(ObjCClass.self))
// CHECK: call swiftcc void @use({{.* i8]\*}} [[OBJECT]]
use(Builtin.getObjCTypeEncoding(NonObjCClass.self))
}
|
0 | //
// Operators.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import UIKit
// Two way binding operator between control property and variable, that's all it takes {
infix operator <-> : DefaultPrecedence
public func nonMarkedText(_ textInput: UITextInput) -> String? {
let start = textInput.beginningOfDocument
let end = textInput.endOfDocument
guard let rangeAll = textInput.textRange(from: start, to: end),
let text = textInput.text(in: rangeAll) else {
return nil
}
guard let markedTextRange = textInput.markedTextRange else {
return text
}
guard let startRange = textInput.textRange(from: start, to: markedTextRange.start),
let endRange = textInput.textRange(from: markedTextRange.end, to: end) else {
return text
}
return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "")
}
public func <-> <Base: UITextInput>(textInput: TextInput<Base>, variable: Variable<String>) -> Disposable {
let bindToUIDisposable = variable.asObservable()
.bindTo(textInput.text)
let bindToVariable = textInput.text
.subscribe(onNext: { [weak base = textInput.base] n in
guard let base = base else {
return
}
let nonMarkedTextValue = nonMarkedText(base)
/**
In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying
value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know.
The can be reproed easily if replace bottom code with
if nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue ?? ""
}
and you hit "Done" button on keyboard.
*/
if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue
}
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
public func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
if T.self == String.self {
#if DEBUG
fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx_text` property directly to variable.\n" +
"That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" +
"REMEDY: Just use `textField <-> variable` instead of `textField.rx_text <-> variable`.\n" +
"Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n"
)
#endif
}
let bindToUIDisposable = variable.asObservable()
.bindTo(property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
// MARK: - IgnoreErrors
extension ObservableType {
public func ignoreErrors() -> Observable<E> {
return self.catchError { _ in .empty() }
}
}
extension Observable where Element: Equatable {
public func ignore(value: Element) -> Observable<Element> {
return filter { (e) -> Bool in
return value != e
}
}
}
extension ObservableType where E == Bool {
/// Boolean not operator
public func not() -> Observable<Bool> {
return self.map(!)
}
}
extension Collection where Iterator.Element: ObservableType, Iterator.Element.E: BooleanType {
func combineLatestAnd() -> Observable<Bool> {
return Observable.combineLatest(self) { bools -> Bool in
return bools.reduce(true, { (memo, element) in
return memo && element.boolValue
})
}
}
func combineLatestOr() -> Observable<Bool> {
return Observable.combineLatest(self) { bools in
bools.reduce(false, { (memo, element) in
return memo || element.boolValue
})
}
}
}
protocol BooleanType {
var boolValue: Bool { get }
}
extension Bool: BooleanType {
public var boolValue: Bool { return self }
}
|
0 | //
// BlePeripheral.swift
// bluefruitconnect
//
// Created by Antonio García on 23/09/15.
// Copyright © 2015 Adafruit. All rights reserved.
//
import Foundation
import CoreBluetooth
class BlePeripheral {
var peripheral: CBPeripheral!
var advertisementData: [String: AnyObject]
var rssi: Int
var lastSeenTime: CFAbsoluteTime
var name: String? {
get {
return peripheral.name
}
}
init(peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: Int) {
self.peripheral = peripheral
self.advertisementData = advertisementData
self.rssi = RSSI
self.lastSeenTime = CFAbsoluteTimeGetCurrent()
}
// MARK: - Uart
private static let kUartServiceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e" // UART service UUID
class UartData {
var receivedBytes : Int64 = 0
var sentBytes : Int64 = 0
}
var uartData = UartData()
func isUartAdvertised() -> Bool {
var isUartAdvertised = false
if let serviceUUIds = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] {
isUartAdvertised = serviceUUIds.contains(CBUUID(string: BlePeripheral.kUartServiceUUID))
}
return isUartAdvertised
}
func hasUart() -> Bool {
var hasUart = false
if let services = peripheral.services {
hasUart = services.contains({ (service : CBService) -> Bool in
service.UUID.isEqual(CBUUID(string: BlePeripheral.kUartServiceUUID))
})
}
return hasUart
}
}
|
0 | @testable import MongoSwift
import Nimble
/// A enumeration of the different objects a `TestOperation` may be performed against.
enum TestOperationObject: String, Decodable {
case client, database, collection, gridfsbucket
}
/// Struct containing an operation and an expected outcome.
struct TestOperationDescription: Decodable {
/// The operation to run.
let operation: AnyTestOperation
/// The object to perform the operation on.
let object: TestOperationObject
/// The return value of the operation, if any.
let result: TestOperationResult?
/// Whether the operation should expect an error.
let error: Bool?
public enum CodingKeys: CodingKey {
case object, result, error
}
public init(from decoder: Decoder) throws {
self.operation = try AnyTestOperation(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.object = try container.decode(TestOperationObject.self, forKey: .object)
self.result = try container.decodeIfPresent(TestOperationResult.self, forKey: .result)
self.error = try container.decodeIfPresent(Bool.self, forKey: .error)
}
/// Runs the operation and asserts its results meet the expectation.
func validateExecution(
client: MongoClient,
database: MongoDatabase?,
collection: MongoCollection<Document>?,
session: ClientSession?
) throws {
let target: TestOperationTarget
switch self.object {
case .client:
target = .client(client)
case .database:
guard let database = database else {
throw InvalidArgumentError(message: "got database object but was not provided a database")
}
target = .database(database)
case .collection:
guard let collection = collection else {
throw InvalidArgumentError(message: "got collection object but was not provided a collection")
}
target = .collection(collection)
case .gridfsbucket:
throw InvalidArgumentError(message: "gridfs tests should be skipped")
}
do {
let result = try self.operation.execute(on: target, session: session)
expect(self.error ?? false)
.to(beFalse(), description: "expected to fail but succeeded with result \(String(describing: result))")
if let expectedResult = self.result {
expect(result).to(equal(expectedResult))
}
} catch {
expect(self.error ?? false).to(beTrue(), description: "expected no error, got \(error)")
}
}
}
/// Object in which an operation should be executed on.
/// Not all target cases are supported by each operation.
enum TestOperationTarget {
/// Execute against the provided client.
case client(MongoClient)
/// Execute against the provided database.
case database(MongoDatabase)
/// Execute against the provided collection.
case collection(MongoCollection<Document>)
}
/// Protocol describing the behavior of a spec test "operation"
protocol TestOperation: Decodable {
/// Execute the operation given the context.
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult?
}
/// Wrapper around a `TestOperation.swift` allowing it to be decoded from a spec test.
struct AnyTestOperation: Decodable, TestOperation {
let op: TestOperation
private enum CodingKeys: String, CodingKey {
case name, arguments
}
// swiftlint:disable:next cyclomatic_complexity
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let opName = try container.decode(String.self, forKey: .name)
switch opName {
case "aggregate":
self.op = try container.decode(Aggregate.self, forKey: .arguments)
case "countDocuments":
self.op = try container.decode(CountDocuments.self, forKey: .arguments)
case "estimatedDocumentCount":
self.op = EstimatedDocumentCount()
case "distinct":
self.op = try container.decode(Distinct.self, forKey: .arguments)
case "find":
self.op = try container.decode(Find.self, forKey: .arguments)
case "findOne":
self.op = try container.decode(FindOne.self, forKey: .arguments)
case "updateOne":
self.op = try container.decode(UpdateOne.self, forKey: .arguments)
case "updateMany":
self.op = try container.decode(UpdateMany.self, forKey: .arguments)
case "insertOne":
self.op = try container.decode(InsertOne.self, forKey: .arguments)
case "insertMany":
self.op = try container.decode(InsertMany.self, forKey: .arguments)
case "deleteOne":
self.op = try container.decode(DeleteOne.self, forKey: .arguments)
case "deleteMany":
self.op = try container.decode(DeleteMany.self, forKey: .arguments)
case "bulkWrite":
self.op = try container.decode(BulkWrite.self, forKey: .arguments)
case "findOneAndDelete":
self.op = try container.decode(FindOneAndDelete.self, forKey: .arguments)
case "findOneAndReplace":
self.op = try container.decode(FindOneAndReplace.self, forKey: .arguments)
case "findOneAndUpdate":
self.op = try container.decode(FindOneAndUpdate.self, forKey: .arguments)
case "replaceOne":
self.op = try container.decode(ReplaceOne.self, forKey: .arguments)
case "rename":
self.op = try container.decode(RenameCollection.self, forKey: .arguments)
case "drop":
self.op = DropCollection()
case "listDatabaseNames":
self.op = ListDatabaseNames()
case "listDatabases":
self.op = ListDatabases()
case "listDatabaseObjects":
self.op = ListMongoDatabases()
case "listIndexes":
self.op = ListIndexes()
case "listIndexNames":
self.op = ListIndexNames()
case "listCollections":
self.op = ListCollections()
case "listCollectionObjects":
self.op = ListMongoCollections()
case "listCollectionNames":
self.op = ListCollectionNames()
case "watch":
self.op = Watch()
case "mapReduce", "download_by_name", "download", "count":
self.op = NotImplemented(name: opName)
default:
throw LogicError(message: "unsupported op name \(opName)")
}
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
return try self.op.execute(on: target, session: session)
}
}
struct Aggregate: TestOperation {
let pipeline: [Document]
let options: AggregateOptions
private enum CodingKeys: String, CodingKey { case pipeline }
init(from decoder: Decoder) throws {
self.options = try AggregateOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.pipeline = try container.decode([Document].self, forKey: .pipeline)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to aggregate")
}
return try TestOperationResult(
from: collection.aggregate(self.pipeline, options: self.options, session: session)
)
}
}
struct CountDocuments: TestOperation {
let filter: Document
let options: CountDocumentsOptions
private enum CodingKeys: String, CodingKey { case filter }
init(from decoder: Decoder) throws {
self.options = try CountDocumentsOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to count")
}
return .int(try collection.countDocuments(self.filter, options: self.options, session: session))
}
}
struct Distinct: TestOperation {
let fieldName: String
let filter: Document?
let options: DistinctOptions
private enum CodingKeys: String, CodingKey { case fieldName, filter }
init(from decoder: Decoder) throws {
self.options = try DistinctOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.fieldName = try container.decode(String.self, forKey: .fieldName)
self.filter = try container.decodeIfPresent(Document.self, forKey: .filter)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to distinct")
}
let result = try collection.distinct(
fieldName: self.fieldName,
filter: self.filter ?? [:],
options: self.options,
session: session
)
return .array(result)
}
}
struct Find: TestOperation {
let filter: Document
let options: FindOptions
private enum CodingKeys: String, CodingKey { case filter }
init(from decoder: Decoder) throws {
self.options = try FindOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to find")
}
return try TestOperationResult(from: collection.find(self.filter, options: self.options, session: session))
}
}
struct FindOne: TestOperation {
let filter: Document
let options: FindOneOptions
private enum CodingKeys: String, CodingKey { case filter }
init(from decoder: Decoder) throws {
self.options = try FindOneOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to findOne")
}
return try TestOperationResult(from: collection.findOne(self.filter, options: self.options, session: session))
}
}
struct UpdateOne: TestOperation {
let filter: Document
let update: Document
let options: UpdateOptions
private enum CodingKeys: String, CodingKey { case filter, update }
init(from decoder: Decoder) throws {
self.options = try UpdateOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
self.update = try container.decode(Document.self, forKey: .update)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to updateOne")
}
let result = try collection.updateOne(
filter: self.filter,
update: self.update,
options: self.options,
session: session
)
return TestOperationResult(from: result)
}
}
struct UpdateMany: TestOperation {
let filter: Document
let update: Document
let options: UpdateOptions
private enum CodingKeys: String, CodingKey { case filter, update }
init(from decoder: Decoder) throws {
self.options = try UpdateOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
self.update = try container.decode(Document.self, forKey: .update)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to ")
}
let result = try collection.updateMany(
filter: self.filter,
update: self.update,
options: self.options,
session: session
)
return TestOperationResult(from: result)
}
}
struct DeleteMany: TestOperation {
let filter: Document
let options: DeleteOptions
private enum CodingKeys: String, CodingKey { case filter }
init(from decoder: Decoder) throws {
self.options = try DeleteOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to deleteMany")
}
let result = try collection.deleteMany(self.filter, options: self.options, session: session)
return TestOperationResult(from: result)
}
}
struct DeleteOne: TestOperation {
let filter: Document
let options: DeleteOptions
private enum CodingKeys: String, CodingKey { case filter }
init(from decoder: Decoder) throws {
self.options = try DeleteOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to deleteOne")
}
let result = try collection.deleteOne(self.filter, options: self.options, session: session)
return TestOperationResult(from: result)
}
}
struct InsertOne: TestOperation {
let document: Document
func execute(on target: TestOperationTarget, session _: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to insertOne")
}
return TestOperationResult(from: try collection.insertOne(self.document))
}
}
struct InsertMany: TestOperation {
let documents: [Document]
let options: InsertManyOptions
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to insertMany")
}
let result = try collection.insertMany(self.documents, options: self.options, session: session)
return TestOperationResult(from: result)
}
}
/// Extension of `WriteModel` adding `Decodable` conformance.
extension WriteModel: Decodable {
private enum CodingKeys: CodingKey {
case name, arguments
}
private enum InsertOneKeys: CodingKey {
case document
}
private enum DeleteKeys: CodingKey {
case filter
}
private enum ReplaceOneKeys: CodingKey {
case filter, replacement
}
private enum UpdateKeys: CodingKey {
case filter, update
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let name = try container.decode(String.self, forKey: .name)
switch name {
case "insertOne":
let args = try container.nestedContainer(keyedBy: InsertOneKeys.self, forKey: .arguments)
let doc = try args.decode(CollectionType.self, forKey: .document)
self = .insertOne(doc)
case "deleteOne", "deleteMany":
let options = try container.decode(DeleteModelOptions.self, forKey: .arguments)
let args = try container.nestedContainer(keyedBy: DeleteKeys.self, forKey: .arguments)
let filter = try args.decode(Document.self, forKey: .filter)
self = name == "deleteOne" ? .deleteOne(filter, options: options) : .deleteMany(filter, options: options)
case "replaceOne":
let options = try container.decode(ReplaceOneModelOptions.self, forKey: .arguments)
let args = try container.nestedContainer(keyedBy: ReplaceOneKeys.self, forKey: .arguments)
let filter = try args.decode(Document.self, forKey: .filter)
let replacement = try args.decode(CollectionType.self, forKey: .replacement)
self = .replaceOne(filter: filter, replacement: replacement, options: options)
case "updateOne", "updateMany":
let options = try container.decode(UpdateModelOptions.self, forKey: .arguments)
let args = try container.nestedContainer(keyedBy: UpdateKeys.self, forKey: .arguments)
let filter = try args.decode(Document.self, forKey: .filter)
let update = try args.decode(Document.self, forKey: .update)
self = name == "updateOne" ?
.updateOne(filter: filter, update: update, options: options) :
.updateMany(filter: filter, update: update, options: options)
default:
throw DecodingError.typeMismatch(
WriteModel.self,
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Unknown write model: \(name)"
)
)
}
}
}
struct BulkWrite: TestOperation {
let requests: [WriteModel<Document>]
let options: BulkWriteOptions
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to bulk write")
}
let result = try collection.bulkWrite(self.requests, options: self.options, session: session)
return TestOperationResult(from: result)
}
}
struct FindOneAndUpdate: TestOperation {
let filter: Document
let update: Document
let options: FindOneAndUpdateOptions
private enum CodingKeys: String, CodingKey { case filter, update }
init(from decoder: Decoder) throws {
self.options = try FindOneAndUpdateOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
self.update = try container.decode(Document.self, forKey: .update)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to findOneAndUpdate")
}
let doc = try collection.findOneAndUpdate(
filter: self.filter,
update: self.update,
options: self.options,
session: session
)
return TestOperationResult(from: doc)
}
}
struct FindOneAndDelete: TestOperation {
let filter: Document
let options: FindOneAndDeleteOptions
private enum CodingKeys: String, CodingKey { case filter }
init(from decoder: Decoder) throws {
self.options = try FindOneAndDeleteOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to findOneAndDelete")
}
let result = try collection.findOneAndDelete(self.filter, options: self.options, session: session)
return TestOperationResult(from: result)
}
}
struct FindOneAndReplace: TestOperation {
let filter: Document
let replacement: Document
let options: FindOneAndReplaceOptions
private enum CodingKeys: String, CodingKey { case filter, replacement }
init(from decoder: Decoder) throws {
self.options = try FindOneAndReplaceOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
self.replacement = try container.decode(Document.self, forKey: .replacement)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to findOneAndReplace")
}
let result = try collection.findOneAndReplace(
filter: self.filter,
replacement: self.replacement,
options: self.options,
session: session
)
return TestOperationResult(from: result)
}
}
struct ReplaceOne: TestOperation {
let filter: Document
let replacement: Document
let options: ReplaceOptions
private enum CodingKeys: String, CodingKey { case filter, replacement }
init(from decoder: Decoder) throws {
self.options = try ReplaceOptions(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.filter = try container.decode(Document.self, forKey: .filter)
self.replacement = try container.decode(Document.self, forKey: .replacement)
}
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to replaceOne")
}
return TestOperationResult(from: try collection.replaceOne(
filter: self.filter,
replacement: self.replacement,
options: self.options,
session: session
))
}
}
struct RenameCollection: TestOperation {
let to: String
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to renameCollection")
}
let databaseName = collection.namespace.db
let cmd: Document = [
"renameCollection": .string(databaseName + "." + collection.name),
"to": .string(databaseName + "." + self.to)
]
return try TestOperationResult(from: collection._client.db("admin").runCommand(cmd, session: session))
}
}
struct DropCollection: TestOperation {
func execute(on target: TestOperationTarget, session _: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to dropCollection")
}
try collection.drop()
return nil
}
}
struct ListDatabaseNames: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .client(client) = target else {
throw InvalidArgumentError(message: "client not provided to listDatabaseNames")
}
return try .array(client.listDatabaseNames(session: session).map { .string($0) })
}
}
struct ListIndexes: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to listIndexes")
}
return try TestOperationResult(from: collection.listIndexes(session: session))
}
}
struct ListIndexNames: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to listIndexNames")
}
return try .array(collection.listIndexNames(session: session).map { .string($0) })
}
}
struct ListDatabases: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .client(client) = target else {
throw InvalidArgumentError(message: "client not provided to listDatabases")
}
return try TestOperationResult(from: client.listDatabases(session: session))
}
}
struct ListMongoDatabases: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .client(client) = target else {
throw InvalidArgumentError(message: "client not provided to listDatabases")
}
_ = try client.listMongoDatabases(session: session)
return nil
}
}
struct ListCollections: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .database(database) = target else {
throw InvalidArgumentError(message: "database not provided to listCollections")
}
return try TestOperationResult(from: database.listCollections(session: session))
}
}
struct ListMongoCollections: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .database(database) = target else {
throw InvalidArgumentError(message: "database not provided to listCollectionObjects")
}
_ = try database.listMongoCollections(session: session)
return nil
}
}
struct ListCollectionNames: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .database(database) = target else {
throw InvalidArgumentError(message: "database not provided to listCollectionNames")
}
return try .array(database.listCollectionNames(session: session).map { .string($0) })
}
}
struct Watch: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
switch target {
case let .client(client):
_ = try client.watch(session: session)
case let .database(database):
_ = try database.watch(session: session)
case let .collection(collection):
_ = try collection.watch(session: session)
}
return nil
}
}
struct EstimatedDocumentCount: TestOperation {
func execute(on target: TestOperationTarget, session: ClientSession?) throws -> TestOperationResult? {
guard case let .collection(collection) = target else {
throw InvalidArgumentError(message: "collection not provided to estimatedDocumentCount")
}
return try .int(collection.estimatedDocumentCount(session: session))
}
}
/// Dummy `TestOperation` that can be used in place of an unimplemented one (e.g. findOne)
struct NotImplemented: TestOperation {
internal let name: String
func execute(on _: TestOperationTarget, session _: ClientSession?) throws -> TestOperationResult? {
throw LogicError(message: "\(self.name) not implemented in the driver, skip this test")
}
}
|
0 | @testable import SwiftPlot
import SVGRenderer
#if canImport(AGGRenderer)
import AGGRenderer
#endif
#if canImport(QuartzRenderer)
import QuartzRenderer
#endif
@available(tvOS 13, watchOS 13, *)
extension AnnotationTests {
func testAnnotationTextBoundingBox() throws {
let fileName = "_30_text_bounding_box_annotation"
let x:[Float] = [10,100,263,489]
let y:[Float] = [10,120,500,800]
var lineGraph = LineGraph<Float, Float>(enablePrimaryAxisGrid: true)
lineGraph.addSeries(x, y, label: "Plot 1", color: .lightBlue)
lineGraph.plotTitle.title = "SINGLE SERIES"
lineGraph.plotLabel.xLabel = "X-AXIS"
lineGraph.plotLabel.yLabel = "Y-AXIS"
lineGraph.plotLineThickness = 3.0
lineGraph.addAnnotation(annotation: Text(text: "HELLO WORLD",
color: .black,
size: 50.0,
location: Point(300, 300),
boundingBox: Box(color: .pink),
borderWidth: 5.0))
try renderAndVerify(lineGraph, fileName: fileName)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.