hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
9b2b28318527acb24d95f3ce58dbe29963c6d408 | 1,115 | //
// AnimatedCell.swift
// AnimateTableViewCell
//
// Created by suckerl on 2017/5/24.
// Copyright © 2017年 suckel. All rights reserved.
//
import UIKit
struct cellItem {
var name : String
}
class AnimatedCell: UITableViewCell {
//MARK:- 渐变色
let gradientLayer = CAGradientLayer()
override func awakeFromNib() {
super.awakeFromNib()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
gradientLayer.frame = self.contentView.bounds
let color1 = UIColor(white: 1, alpha: 0.5)
let color2 = UIColor(white: 1, alpha: 0.3)
let color3 = UIColor(white: 1, alpha: 0.1)
let color4 = UIColor(white: 1, alpha: 0.05)
gradientLayer.colors = [color1,color2,color3,color4]
gradientLayer.locations = [0.0, 0.1, 0.95, 1.0]
self.contentView.layer.insertSublayer(gradientLayer, at: 0)
}
}
| 24.777778 | 74 | 0.634081 |
3a61a62c90f1c36f0309511924f62598c0ee5cb1 | 895 | //
// isPalindromeNumber.swift
// AlgorithmDemo
//
// Created by 王嘉宁 on 2020/4/21.
// Copyright © 2020 王嘉宁. All rights reserved.
//
import Foundation
extension Solution {
func isPalindrome2(_ x: Int) -> Bool {
if x < 0 {
return false
}
if String(x).count == 1 {
return true
}
return String(x) == String(String(x).reversed())
}
func isPalindrome(_ x: Int) -> Bool {
if x < 0 {
return false
}
let lengthOfX = String(x).count
if lengthOfX == 1 {
return true
}
var varibleX = x
var right = 0
for _ in 0...lengthOfX/2-1 {
right = right * 10 + varibleX%10
varibleX /= 10
}
if lengthOfX%2 != 0 {
varibleX /= 10
}
return right == varibleX
}
}
| 20.813953 | 56 | 0.471508 |
3ac09afc4cd186de64623a9e2f430501823c7062 | 55 | protocol RawIntValue {
var rawValue: Int { get }
}
| 13.75 | 29 | 0.654545 |
f87497293c3763e3bfe9310cbb769adaa3e3dd1f | 954 | //
// TransactionTableViewCell.swift
// saltedge-ios_Example
//
// Created by Vlad Somov.
// Copyright (c) 2019 Salt Edge. All rights reserved.
//
import UIKit
import SaltEdge
final class TransactionTableViewCell: UITableViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var amountLabel: UILabel!
let amountFormatter: NumberFormatter = {
let amountFormatter = NumberFormatter()
amountFormatter.numberStyle = .currency
return amountFormatter
}()
func set(with transaction: SETransaction) {
descriptionLabel.text = transaction.description
dateLabel.text = DateFormatter.localizedString(from: transaction.madeOn, dateStyle: .medium, timeStyle: .none)
amountFormatter.currencyCode = transaction.currencyCode
amountLabel.text = amountFormatter.string(from: NSNumber(value: transaction.amount))
}
}
| 31.8 | 118 | 0.722222 |
61fbd88f6f603080484b0344960ca076cb380a5f | 1,672 | //
// MPSGLayerConv2D.swift
//
//
// Created by Maxim Volgin on 03/04/2021.
//
import os.log
import Foundation
import MetalPerformanceShaders
import MetalPerformanceShadersGraph
@available(macOS 11, iOS 14, *)
public class MPSGLayerConv2D: MPSGLayer {
public let graph: MPSGraph
public let name: String?
public private(set) var variableData: [MPSGModel.VariableData]
let weightVariableData: MPSGModel.VariableData
let biasVariableData: MPSGModel.VariableData
let desc: MPSGraphConvolution2DOpDescriptor
public init(graph: MPSGraph,
weightsShape: Shape,
desc: MPSGraphConvolution2DOpDescriptor,
name: String? = nil
) {
self.graph = graph
self.weightVariableData = Self.add(layerVariable: .weight(layerShape: weightsShape, layerName: name), to: graph)
self.biasVariableData = Self.add(layerVariable: .bias(layerShape: weightsShape, layerName: name), to: graph)
self.variableData = [weightVariableData, biasVariableData]
self.desc = desc
self.name = name
}
public func callAsFunction(_ inputTensor: MPSGraphTensor) -> MPSGraphTensor {
let convTensor = graph.convolution2D(inputTensor,
weights: weightVariableData.tensor,
descriptor: desc,
name: name)
let convBiasTensor = graph.addition(convTensor,
biasVariableData.tensor,
name: nil)
return convBiasTensor
}
}
| 34.122449 | 120 | 0.605861 |
fc8b0ff62d2879563aa52f8d22f2f3f566538aa1 | 4,705 | //
// AppDelegate.swift
// anti-piracy-iOS-app
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let rootViewController = window?.rootViewController as! UINavigationController
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
if #available(iOS 13.0, *) {
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.configureWithOpaqueBackground()
navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
navBarAppearance.backgroundColor = UIColor.init(red: 55.0/255.0, green: 71.0/255.0, blue: 79.0/255.0, alpha: 1)
rootViewController.navigationBar.standardAppearance = navBarAppearance
rootViewController.navigationBar.scrollEdgeAppearance = navBarAppearance
}
UILabel.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).textColor = UIColor.white
if (!UserDefaults.standard.bool(forKey: AppSettings.HIDE_DISCLAIMER)) {
let disclaimerViewController = DisclaimerViewController(nibName:"Disclaimer", bundle:nil)
rootViewController.setViewControllers([disclaimerViewController], animated: true)
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "asam")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 48.010204 | 285 | 0.706057 |
e2b6a29a761579b24850cf3babd732216f2e76d4 | 136 | import XCTest
import Swift_MusicBrainzTests
var tests = [XCTestCaseEntry]()
tests += MusicBrainzSearchTests.allTests()
XCTMain(tests)
| 17 | 42 | 0.808824 |
22158d515b301645bd9d5140ac191542f01d9750 | 11,883 | //
// CheckoutV2ViewController.swift
// Afterpay
//
// Created by Adam Campbell on 23/11/20.
// Copyright © 2020 Afterpay. All rights reserved.
//
import Foundation
import os.log
import UIKit
import WebKit
// swiftlint:disable:next colon type_body_length
final class CheckoutV2ViewController:
UIViewController,
UIAdaptivePresentationControllerDelegate,
WKNavigationDelegate,
WKScriptMessageHandler,
WKUIDelegate
{ // swiftlint:disable:this opening_brace
private let configuration: Configuration
private let options: CheckoutV2Options
private var token: Token?
// MARK: Callbacks
private let didCommenceCheckoutClosure: DidCommenceCheckoutClosure?
private let shippingAddressDidChangeClosure: ShippingAddressDidChangeClosure?
private let shippingOptionDidChangeClosure: ShippingOptionDidChangeClosure?
private let completion: (_ result: CheckoutResult) -> Void
private var didCommenceCheckout: DidCommenceCheckoutClosure? {
didCommenceCheckoutClosure ?? getCheckoutV2Handler()?.didCommenceCheckout
}
private var shippingAddressDidChange: ShippingAddressDidChangeClosure? {
shippingAddressDidChangeClosure ?? getCheckoutV2Handler()?.shippingAddressDidChange
}
private var shippingOptionDidChange: ShippingOptionDidChangeClosure? {
shippingOptionDidChangeClosure ?? getCheckoutV2Handler()?.shippingOptionDidChange
}
// MARK: URLs
private var bootstrapURL: URL { configuration.environment.checkoutBootstrapURL }
// MARK: Web Views
private var loadingWebView: WKWebView?
private var bootstrapWebView: WKWebView!
private var checkoutWebView: WKWebView?
// MARK: Initialization
init(
configuration: Configuration,
options: CheckoutV2Options,
didCommenceCheckout: DidCommenceCheckoutClosure?,
shippingAddressDidChange: ShippingAddressDidChangeClosure?,
shippingOptionDidChange: ShippingOptionDidChangeClosure?,
completion: @escaping (_ result: CheckoutResult) -> Void
) {
self.configuration = configuration
self.options = options
self.didCommenceCheckoutClosure = didCommenceCheckout
self.shippingAddressDidChangeClosure = shippingAddressDidChange
self.shippingOptionDidChangeClosure = shippingOptionDidChange
self.completion = completion
super.init(nibName: nil, bundle: nil)
presentationController?.delegate = self
if #available(iOS 13.0, *) {
isModalInPresentation = true
overrideUserInterfaceStyle = .light
}
}
override func loadView() {
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
preferences.javaScriptCanOpenWindowsAutomatically = true
let userContentController = WKUserContentController()
userContentController.add(self, name: "iOS")
let processPool = WKProcessPool()
let bootstrapConfiguration = WKWebViewConfiguration()
bootstrapConfiguration.processPool = processPool
bootstrapConfiguration.applicationNameForUserAgent = WKWebViewConfiguration.appNameForUserAgent
bootstrapConfiguration.preferences = preferences
bootstrapConfiguration.userContentController = userContentController
bootstrapWebView = WKWebView(frame: .zero, configuration: bootstrapConfiguration)
bootstrapWebView.isHidden = true
bootstrapWebView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bootstrapWebView.navigationDelegate = self
bootstrapWebView.uiDelegate = self
let loadingConfiguration = WKWebViewConfiguration()
loadingConfiguration.processPool = processPool
let loadingWebView = WKWebView(frame: .zero, configuration: loadingConfiguration)
loadingWebView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.loadingWebView = loadingWebView
let view = UIView()
[bootstrapWebView, loadingWebView].forEach(view.addSubview)
self.view = view
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
bootstrapWebView.configuration.userContentController.removeScriptMessageHandler(forName: "iOS")
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .light
} else {
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Cancel",
style: .plain,
target: self,
action: #selector(presentCancelConfirmation)
)
}
loadingWebView?.loadHTMLString(StaticContent.loadingHTML, baseURL: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let webView: WKWebView = bootstrapWebView
webView.removeCache(
for: configuration.environment.bootstrapCacheDisplayName
) {
[bootstrapURL] in webView.load(URLRequest(url: bootstrapURL))
}
}
// MARK: UIAdaptivePresentationControllerDelegate
func presentationControllerDidAttemptToDismiss(
_ presentationController: UIPresentationController
) {
presentCancelConfirmation()
}
// MARK: Actions
@objc private func presentCancelConfirmation() {
let actionSheet = Alerts.areYouSureYouWantToCancel {
self.dismiss(animated: true) { self.completion(.cancelled(reason: .userInitiated)) }
}
present(actionSheet, animated: true, completion: nil)
}
// MARK: WKNavigationDelegate
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
guard let url = navigationAction.request.url, navigationAction.targetFrame == nil else {
return decisionHandler(.allow)
}
decisionHandler(.cancel)
UIApplication.shared.open(url)
}
func webView(
_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error
) {
handleError(webView: webView, error: error)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView == checkoutWebView {
checkoutWebView?.isHidden = false
loadingWebView?.removeFromSuperview()
loadingWebView = nil
} else if webView == bootstrapWebView {
commenceCheckout()
}
}
private func commenceCheckout() {
guard let didCommenceCheckout = didCommenceCheckout else {
return assertionFailure(
"For checkout to function you must set `didCommenceCheckout` via either "
+ "`Afterpay.presentCheckoutV2Modally` or `Afterpay.setCheckoutV2Handler`"
)
}
didCommenceCheckout { [weak self] result in
DispatchQueue.main.async {
switch result {
case (.success(let token)):
self?.handleToken(token: token)
case (.failure(let error)):
self?.handleError(webView: nil, error: error)
}
}
}
}
private func handleToken(token: Token) {
let checkout = CheckoutV2(token: token, configuration: configuration, options: options)
// swiftlint:disable:next force_try
let json = String(data: try! encoder.encode(checkout), encoding: .utf8)!
bootstrapWebView.evaluateJavaScript("openCheckout('\(json)');")
}
private func handleError(webView: WKWebView?, error: Error) {
let dismiss = {
self.dismiss(animated: true) {
self.completion(.cancelled(reason: .networkError(error)))
}
}
let reload = {
switch webView {
case self.bootstrapWebView:
self.bootstrapWebView.load(URLRequest(url: self.bootstrapURL))
case self.checkoutWebView where self.token != nil:
self.handleToken(token: self.token!)
case self.checkoutWebView, nil:
self.commenceCheckout()
default:
dismiss()
}
}
let alert = Alerts.failedToLoad(retry: reload, cancel: dismiss)
present(alert, animated: true, completion: nil)
}
func webView(
_ webView: WKWebView,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
let handled = authenticationChallengeHandler(challenge, completionHandler)
if handled == false {
completionHandler(.performDefaultHandling, nil)
}
}
// MARK: WKUIDelegate
func webView(
_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures
) -> WKWebView? {
let checkoutWebView = WKWebView(frame: view.bounds, configuration: configuration)
checkoutWebView.isHidden = true
checkoutWebView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
checkoutWebView.allowsLinkPreview = false
checkoutWebView.scrollView.bounces = false
checkoutWebView.navigationDelegate = self
view.addSubview(checkoutWebView)
self.checkoutWebView = checkoutWebView
return checkoutWebView
}
// MARK: WKScriptMessageHandler
typealias Completion = CheckoutV2Completion
typealias Message = CheckoutV2Message
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
func userContentController(
_ userContentController: WKUserContentController,
didReceive receivedMessage: WKScriptMessage
) {
let jsonData = (receivedMessage.body as? String)?.data(using: .utf8)
let message = jsonData.flatMap { try? decoder.decode(Message.self, from: $0) }
let completion = jsonData.flatMap { try? decoder.decode(Completion.self, from: $0) }
let evaluateJavascript = { [bootstrapWebView] (javaScript: String) in
DispatchQueue.main.async { bootstrapWebView?.evaluateJavaScript(javaScript) }
}
let postMessage = { [encoder] (message: Message) in
Result { String(data: try encoder.encode(message), encoding: .utf8) }
.fold(successTransform: { $0 }, errorTransform: { _ in nil })
.map { evaluateJavascript("postMessageToCheckout('\($0)');") }
}
if let message = message, let payload = message.payload {
switch payload {
case .address(let address):
shippingAddressDidChange?(address) { shippingOptions in
let requestId = message.requestId
let responseMessage = shippingOptions.fold(
successTransform: { Message(requestId: requestId, payload: .shippingOptions($0)) },
errorTransform: { Message(requestId: requestId, payload: .errorMessage($0.rawValue)) }
)
postMessage(responseMessage)
}
case .errorMessage(let errorMessage):
// Error messages raised in the webview are logged when in Debug for ease of debugging
os_log("%@", log: .checkout, type: .debug, errorMessage)
case .shippingOption(let shippingOption):
shippingOptionDidChange?(shippingOption) { updatedShippingOption in
let requestId = message.requestId
let responseMessage = updatedShippingOption?.fold(
successTransform: { Message(requestId: requestId, payload: .shippingOptionUpdate($0)) },
errorTransform: { Message(requestId: requestId, payload: .errorMessage($0.rawValue)) }
)
postMessage(responseMessage ?? Message(requestId: requestId, payload: nil))
}
case .shippingOptions:
break
case .shippingOptionUpdate:
break
}
} else if let completion = completion {
switch completion {
case .success(let token):
dismiss(animated: true) { self.completion(.success(token: token)) }
case .cancelled:
dismiss(animated: true) { self.completion(.cancelled(reason: .userInitiated)) }
}
} else {
let message = receivedMessage.body as? String
os_log("Unable to parse message from bootstrap: %@", log: .checkout, type: .error, message ?? "<<empty>>")
}
}
// MARK: Unavailable
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 32.556164 | 112 | 0.719768 |
2113f86b47aba768787c3e1bcf8af84369b98c44 | 1,346 | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
@testable import TensorFlowLite
import XCTest
class InterpreterOptionsTests: XCTestCase {
func testInterpreterOptions_InitWithDefaultValues() {
let options = InterpreterOptions()
XCTAssertNil(options.threadCount)
}
func testInterpreterOptions_InitWithCustomValues() {
var options = InterpreterOptions()
options.threadCount = 2
XCTAssertEqual(options.threadCount, 2)
}
func testInterpreterOptions_Equatable() {
var options1 = InterpreterOptions()
var options2 = InterpreterOptions()
XCTAssertEqual(options1, options2)
options1.threadCount = 2
options2.threadCount = 2
XCTAssertEqual(options1, options2)
options2.threadCount = 3
XCTAssertNotEqual(options1, options2)
}
}
| 30.590909 | 75 | 0.7526 |
c145301c57bf2d98c228d78532d2fda56a1599af | 710 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// ___COPYRIGHT___
//
@testable import ___PROJECTNAME___
import XCTest
class ___VARIABLE_ModuleName___InteractorTests: XCTestCase {
override func setUpWithError() throws {
try super.setUpWithError()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
try super.tearDownWithError()
}
class MockPresenter: ___VARIABLE_ModuleName___InteractorOutput {
}
}
| 25.357143 | 111 | 0.726761 |
01fcf76cc80ba38aebb15d920b072de5a551b83d | 9,009 | //
// FocusSquare.swift
// FocusNode
//
// Created by Max Cobb on 12/5/18.
// Copyright © 2018 Apple Inc. All rights reserved.
//
import ARKit
/// This example class is taken almost entirely from Apple's own examples.
/// I have simply moved some things around to keep only what's necessary
///
/// An `SCNNode` which is used to provide uses with visual cues about the status of ARKit world tracking.
/// - Tag: FocusSquare
public class FocusSquare: FocusNode {
// MARK: - Types
public enum State: Equatable {
case initializing
case detecting(hitTestResult: ARHitTestResult, camera: ARCamera?)
}
// MARK: - Configuration Properties
/// Original size of the focus square in meters.
static let size: Float = 0.17
/// Thickness of the focus square lines in meters.
static let thickness: Float = 0.018
/// Scale factor for the focus square when it is closed, w.r.t. the original size.
static let scaleForClosedSquare: Float = 0.97
/// Side length of the focus square segments when it is open (w.r.t. to a 1x1 square).
static let sideLengthForOpenSegments: CGFloat = 0.2
/// Duration of the open/close animation
static let animationDuration = 0.7
static var primaryColor = #colorLiteral(red: 1, green: 0.8, blue: 0, alpha: 1)
/// Color of the focus square fill.
static var fillColor = #colorLiteral(red: 1, green: 0.9254901961, blue: 0.4117647059, alpha: 1)
/// Indicates whether the segments of the focus square are disconnected.
private var isOpen = true
/// List of the segments in the focus square.
private var segments: [FocusSquare.Segment] = []
// MARK: - Initialization
public override init() {
super.init()
opacity = 0.0
/*
The focus square consists of eight segments as follows, which can be individually animated.
s1 s2
_ _
s3 | | s4
s5 | | s6
- -
s7 s8
*/
let s1 = Segment(name: "s1", corner: .topLeft, alignment: .horizontal)
let s2 = Segment(name: "s2", corner: .topRight, alignment: .horizontal)
let s3 = Segment(name: "s3", corner: .topLeft, alignment: .vertical)
let s4 = Segment(name: "s4", corner: .topRight, alignment: .vertical)
let s5 = Segment(name: "s5", corner: .bottomLeft, alignment: .vertical)
let s6 = Segment(name: "s6", corner: .bottomRight, alignment: .vertical)
let s7 = Segment(name: "s7", corner: .bottomLeft, alignment: .horizontal)
let s8 = Segment(name: "s8", corner: .bottomRight, alignment: .horizontal)
segments = [s1, s2, s3, s4, s5, s6, s7, s8]
let sl: Float = 0.5 // segment length
let c: Float = FocusSquare.thickness / 2 // correction to align lines perfectly
s1.simdPosition += SIMD3<Float>(-(sl / 2 - c), -(sl - c), 0)
s2.simdPosition += SIMD3<Float>(sl / 2 - c, -(sl - c), 0)
s3.simdPosition += SIMD3<Float>(-sl, -sl / 2, 0)
s4.simdPosition += SIMD3<Float>(sl, -sl / 2, 0)
s5.simdPosition += SIMD3<Float>(-sl, sl / 2, 0)
s6.simdPosition += SIMD3<Float>(sl, sl / 2, 0)
s7.simdPosition += SIMD3<Float>(-(sl / 2 - c), sl - c, 0)
s8.simdPosition += SIMD3<Float>(sl / 2 - c, sl - c, 0)
for segment in segments {
self.positioningNode.addChildNode(segment)
segment.open()
}
self.positioningNode.addChildNode(fillPlane)
self.positioningNode.simdScale = SIMD3<Float>(repeating: FocusSquare.size * FocusSquare.scaleForClosedSquare)
// Always render focus square on top of other content.
self.displayNodeHierarchyOnTop(true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
// MARK: Animations
override public func stateChanged(newPlane: Bool) {
if self.onPlane {
self.onPlaneAnimation(newPlane: newPlane)
} else {
self.offPlaneAniation()
}
}
public func offPlaneAniation() {
// Open animation
guard !isOpen else {
isAnimating = false
return
}
isOpen = true
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
positioningNode.opacity = 1.0
for segment in segments {
segment.open()
}
SCNTransaction.completionBlock = {
self.positioningNode.runAction(pulseAction(), forKey: "pulse")
// This is a safe operation because `SCNTransaction`'s completion block is called back on the main thread.
self.isAnimating = false
}
SCNTransaction.commit()
// Add a scale/bounce animation.
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
positioningNode.simdScale = SIMD3<Float>(repeating: FocusSquare.size)
SCNTransaction.commit()
}
public func onPlaneAnimation(newPlane: Bool = false) {
guard isOpen else {
isAnimating = false
return
}
isOpen = false
positioningNode.removeAction(forKey: "pulse")
positioningNode.opacity = 1.0
// Close animation
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 2
positioningNode.opacity = 0.99
SCNTransaction.completionBlock = {
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
for segment in self.segments {
segment.close()
}
SCNTransaction.completionBlock = {
self.isAnimating = false
}
SCNTransaction.commit()
}
SCNTransaction.commit()
// Scale/bounce animation
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.x"), forKey: "transform.scale.x")
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.y"), forKey: "transform.scale.y")
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.z"), forKey: "transform.scale.z")
if newPlane {
let waitAction = SCNAction.wait(duration: FocusSquare.animationDuration * 0.75)
let fadeInAction = SCNAction.fadeOpacity(to: 0.25, duration: FocusSquare.animationDuration * 0.125)
let fadeOutAction = SCNAction.fadeOpacity(to: 0.0, duration: FocusSquare.animationDuration * 0.125)
fillPlane.runAction(SCNAction.sequence([waitAction, fadeInAction, fadeOutAction]))
let flashSquareAction = flashAnimation(duration: FocusSquare.animationDuration * 0.25)
for segment in segments {
segment.runAction(.sequence([waitAction, flashSquareAction]))
}
}
}
// MARK: Convenience Methods
private func scaleAnimation(for keyPath: String) -> CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: keyPath)
let easeOut = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
let easeInOut = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
let linear = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
let size = FocusSquare.size
let ts = FocusSquare.size * FocusSquare.scaleForClosedSquare
let values = [size, size * 1.15, size * 1.15, ts * 0.97, ts]
let keyTimes: [NSNumber] = [0.00, 0.25, 0.50, 0.75, 1.00]
let timingFunctions = [easeOut, linear, easeOut, easeInOut]
scaleAnimation.values = values
scaleAnimation.keyTimes = keyTimes
scaleAnimation.timingFunctions = timingFunctions
scaleAnimation.duration = FocusSquare.animationDuration
return scaleAnimation
}
private lazy var fillPlane: SCNNode = {
let correctionFactor = FocusSquare.thickness / 2 // correction to align lines perfectly
let length = CGFloat(1.0 - FocusSquare.thickness * 2 + correctionFactor)
let plane = SCNPlane(width: length, height: length)
let node = SCNNode(geometry: plane)
node.name = "fillPlane"
node.opacity = 0.0
let material = plane.firstMaterial!
material.diffuse.contents = FocusSquare.fillColor
material.isDoubleSided = true
material.ambient.contents = UIColor.black
material.lightingModel = .constant
material.emission.contents = FocusSquare.fillColor
return node
}()
}
// MARK: - Animations and Actions
private func pulseAction() -> SCNAction {
let pulseOutAction = SCNAction.fadeOpacity(to: 0.4, duration: 0.5)
let pulseInAction = SCNAction.fadeOpacity(to: 1.0, duration: 0.5)
pulseOutAction.timingMode = .easeInEaseOut
pulseInAction.timingMode = .easeInEaseOut
return SCNAction.repeatForever(SCNAction.sequence([pulseOutAction, pulseInAction]))
}
private func flashAnimation(duration: TimeInterval) -> SCNAction {
let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) -> Void in
// animate color from HSB 48/100/100 to 48/30/100 and back
let elapsedTimePercentage = elapsedTime / CGFloat(duration)
let saturation = 2.8 * (elapsedTimePercentage - 0.5) * (elapsedTimePercentage - 0.5) + 0.3
if let material = node.geometry?.firstMaterial {
material.diffuse.contents = UIColor(hue: 0.1333, saturation: saturation, brightness: 1.0, alpha: 1.0)
}
}
return action
}
| 35.468504 | 111 | 0.732712 |
67e2c486b6bce4959b455cfe0e12771b295a6242 | 1,360 | //
// SessionRoutes.swift
// HubKit
//
// Created by Loïc GRIFFIE on 25/09/2018.
// Copyright © 2018 Loïc GRIFFIE. All rights reserved.
//
import Alamofire
import HubkitModel
import Foundation
extension HubkitModel.Session {
/// Create a new session
@discardableResult
public static func create(in project: Project,
_ metas: [String: Any] = [:],
_ capturedAt: Date,
completion: @escaping (Result<Self, AFError>) -> Void) -> DataRequest? {
Hubkit.shared.post(action: "sessions",
parameters: project.form(capturedAt: capturedAt),
completion: completion)
}
/// Get the session for the given identifier
@discardableResult
public static func get(with identifier: String,
completion: @escaping (Result<Self, AFError>) -> Void) -> DataRequest? {
Hubkit.shared.get(action: "sessions/\(identifier)", parameters: [String: String](), completion: completion)
}
/// Change a session state to ready
@discardableResult
public func ready(completion: @escaping (Result<Self, AFError>) -> Void) -> DataRequest? {
Hubkit.shared.patch(action: "sessions/\(id)/ready", parameters: [String: String](), completion: completion)
}
}
| 35.789474 | 115 | 0.604412 |
1d0075a2f49ce3f34fcf5beef8e0deb29434b5e3 | 713 | //
// Copyright © 2018 Essential Developer. All rights reserved.
//
import Foundation
public final class RemoteFeedLoader: FeedLoader {
private let url: URL
private let client: HTTPClient
public enum Error: Swift.Error {
case connectivity
case invalidData
}
public init(url: URL, client: HTTPClient) {
self.url = url
self.client = client
}
public func load(completion: @escaping (FeedLoader.Result) -> Void) {
client.get(from: url) { [weak self] result in
guard self != nil else { return }
switch result {
case let .success((data, response)):
completion(FeedImagesMapper.map(data, from: response))
case .failure:
completion(.failure(Error.connectivity))
}
}
}
}
| 20.371429 | 70 | 0.695652 |
fc0c8b8587d6a66ee285e63cee1eee4a6952519f | 863 | //
// ToggleSwitch.swift
// AudioKitSynthOne
//
// Created by AudioKit Contributors on 8/2/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import UIKit
@IBDesignable
class ToggleSwitch: UIView, S1Control {
// MARK: - ToggleButton
var isOn = false {
didSet {
setNeedsDisplay()
}
}
var value: Double = 0 {
didSet {
isOn = (value == 1)
setNeedsDisplay()
}
}
public var callback: (Double) -> Void = { _ in }
override func draw(_ rect: CGRect) {
ToggleSwitchStyleKit.drawToggleSwitch(isToggled: value == 0 ? false : true )
}
// MARK: - Handle Touches
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for _ in touches {
value = 1 - value
callback(value)
}
}
}
| 20.069767 | 84 | 0.561993 |
33516b8ce58cddd3ac80a57332d2cc09eb2dbd61 | 1,388 | //
// SRReaderPageVC.swift
// SRReader
//
// Created by yudai on 2019/1/22.
// Copyright © 2019 yudai. All rights reserved.
//
import UIKit
import DTCoreText
class SRReaderPageVC: UIViewController {
/// 所属章节和页面序号
public var indexPath = IndexPath(row: 0, section: 0)
/// 当前章节总页数
public var totalPage = -1
/// 页面模型
public var dataSource: SRReaderPage? {
didSet {
pageLabel.text = "第 \(indexPath.row+1)/\(totalPage) 页"
attriLabel.attributedString = dataSource?.pageAttriStr
}
}
private let attriLabel = DTAttributedLabel(frame: SRReaderConfig.shared.contentFrame)
private let pageLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
view.addSubview(attriLabel)
attriLabel.backgroundColor = UIColor.brown
pageLabel.frame = CGRect(x: attriLabel.frame.origin.x, y: attriLabel.frame.maxY, width: attriLabel.frame.width, height: UIScreen.main.bounds.height - attriLabel.frame.maxY)
pageLabel.textAlignment = .right
pageLabel.font = UIFont.systemFont(ofSize: 12)
pageLabel.textColor = UIColor.lightGray
view.addSubview(pageLabel)
}
deinit {
// print("TextController deinit -------------")
}
}
| 26.692308 | 180 | 0.62464 |
8f774e744ae1e0ac7fa9096f39c4598517398891 | 2,398 | //
// MSFlightMapView.swift
// MSFlightMapView
//
// Created by Muhammad Abdul Subhan on 03/12/2018.
// Copyright © 2018 Subhan. All rights reserved.
//
import UIKit
import GoogleMaps
class MSFlightMapView: GMSMapView {
var pathColor: UIColor = MSConstants.secondaryColor {
didSet {
redraw()
}
}
var markerColor: UIColor = MSConstants.primaryColor {
didSet {
redraw()
}
}
var iconColor: UIColor = MSConstants.primaryColor {
didSet {
redraw()
}
}
var flights: [MSFlight] = [] {
didSet {
redraw()
}
}
var defaultLocation: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 24.9056, longitude: 67.0822) {
didSet {
let camera = GMSCameraUpdate.setCamera(GMSCameraPosition.camera(withLatitude: defaultLocation.latitude, longitude: defaultLocation.longitude, zoom: 3.0))
self.animate(with: camera)
}
}
func redraw() {
self.clear()
let markerBuilder = MSMarkerViewBuilder()
for flight in flights {
let path = GeodesicPathBuilder.buildGeodesicPathBetween(flight.firstLocation, flight.secondLocation)
let departureMarker = markerBuilder.buildMarkerView(withPosition: flight.firstLocation, withColor: flight.markerColor ?? markerColor)
let arrivalMarker = markerBuilder.buildMarkerView(withPosition: flight.secondLocation, withColor: flight.markerColor ?? markerColor)
let airplaneMarker = markerBuilder.buildAirplaneMarker(withFlight: flight, andPath: path, andColor: flight.iconColor ?? iconColor)
let polyline = MSPathBuilder().buildGeodesicPolyline(path, andColor: flight.pathColor ?? pathColor)
departureMarker.map = self
arrivalMarker.map = self
airplaneMarker.map = self
polyline.map = self
}
self.focusMapToRoutes()
}
func focusMapToRoutes() {
var bounds = GMSCoordinateBounds()
for flight in flights {
bounds = bounds.includingCoordinate(flight.firstLocation)
bounds = bounds.includingCoordinate(flight.secondLocation)
}
let update = GMSCameraUpdate.fit(bounds, withPadding: CGFloat(20))
self.animate(with: update)
}
}
| 31.973333 | 165 | 0.636364 |
9c3d7bb64c62361067c55b0220364918bea6cf8e | 1,675 | //
// MediaTapDetectingView.swift
// MediaBrowser
//
// Created by Seungyoun Yi on 2017. 9. 6..
// Copyright © 2017년 Seungyoun Yi. All rights reserved.
//
//
import UIKit
class MediaTapDetectingView: UIView {
weak var tapDelegate: TapDetectingViewDelegate?
init() {
super.init(frame: .zero)
isUserInteractionEnabled = true
}
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let tapCount = touch.tapCount
switch tapCount {
case 1: handleSingleTap(touch: touch)
case 2: handleDoubleTap(touch: touch)
case 3: handleTripleTap(touch: touch)
default: break
}
}
next?.touchesEnded(touches, with: event)
}
private func handleSingleTap(touch: UITouch) {
tapDelegate?.singleTapDetectedInView(view: self, touch: touch)
}
private func handleDoubleTap(touch: UITouch) {
tapDelegate?.doubleTapDetectedInView(view: self, touch: touch)
}
private func handleTripleTap(touch: UITouch) {
tapDelegate?.tripleTapDetectedInView(view: self, touch: touch)
}
}
protocol TapDetectingViewDelegate: class {
func singleTapDetectedInView(view: UIView, touch: UITouch)
func doubleTapDetectedInView(view: UIView, touch: UITouch)
func tripleTapDetectedInView(view: UIView, touch: UITouch)
}
| 27.016129 | 79 | 0.640597 |
4af77c2736c0c79fa52075385a39477bbf1c7e35 | 2,579 | //
// Union.swift
// SwiftGraph
//
// Copyright (c) 2018 Ferran Pujol Camins
//
// 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.
// MARK: - Extension to UniqueVerticesGraph with Union initializer
public extension UniqueElementsGraph where E == UnweightedEdge {
/// Creates a new UniqueVerticesGraph that is the union of several UniqueVerticesGraphs.
///
/// This operation is commutative in the sense that g1 ∪ g2 has the same vertices and edges
/// than g2 ∪ g1. However, the indices of the vertices are not guaranteed to be conserved.
///
/// This operation is O(k*n^2), where k is the number of graphs and n the number of vertices of
/// the largest graph.
///
/// - Parameters:
/// - graphs: Array of graphs to build the union from.
static func unionOf(_ graphs: [UniqueElementsGraph]) -> UniqueElementsGraph{
let union = UniqueElementsGraph()
guard let firstGraph = graphs.first else { return union }
let others = graphs.dropFirst()
// We know vertices in lhs are unique, so we call Graph.addVertex to avoid the uniqueness check of UniqueElementsGraph.addVertex.
for vertex in firstGraph.vertices {
_ = union.addVertex(vertex)
}
// When vertices are removed from Graph, edges might mutate,
// so we need to add new copies of them for the result graph.
for edge in firstGraph.edges.joined() {
union.addEdge(edge, directed: true)
}
for g in others {
// Vertices in rhs might be equal to some vertex in lhs, so we need to add them
// with self.addVertex to guarantee uniqueness.
for vertex in g.vertices {
_ = union.addVertex(vertex)
}
for edge in g.edges.joined() {
union.addEdge(from: g[edge.u], to: g[edge.v], directed: true)
}
}
return union
}
static func unionOf(_ graphs: UniqueElementsGraph...) -> UniqueElementsGraph{
return unionOf(graphs)
}
}
| 38.492537 | 137 | 0.652966 |
01af9d45921e8b74b10f3c37bda48ef3470726bf | 25,993 | import Quick
import Moya
import RxSwift
import Nimble
final class SingleMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes closed range upperbound") {
let data = Data()
let single = Response(statusCode: 10, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0...9).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes closed range lowerbound") {
let data = Data()
let single = Response(statusCode: -1, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0...9).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes with range upperbound") {
let data = Data()
let single = Response(statusCode: 10, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0..<10).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes with range lowerbound") {
let data = Data()
let single = Response(statusCode: -1, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0..<10).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = Data()
let single = Response(statusCode: 404, data: data).asSingle()
var errored = false
_ = single.filterSuccessfulStatusCodes().subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = Data()
let single = Response(statusCode: 404, data: data).asSingle()
var errored = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = Data()
let single = Response(statusCode: 304, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("knows how to filter individual status code") {
let data = Data()
let single = Response(statusCode: 42, data: data).asSingle()
var called = false
_ = single.filter(statusCode: 42).subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("filters out different individual status code") {
let data = Data()
let single = Response(statusCode: 43, data: data).asSingle()
var errored = false
_ = single.filter(statusCode: 42).subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = Image.testPNGImage(named: "testImage")
guard let data = image.asJPEGRepresentation(0.75) else {
fatalError("Failed creating Data from Image")
}
let single = Response(statusCode: 200, data: data).asSingle()
var size: CGSize?
_ = single.mapImage().subscribe(onSuccess: { image in
size = image.size
})
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapImage().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .error(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.imageMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
fatalError("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedJSON: [String: String]?
_ = single.mapJSON().subscribe(onSuccess: { json in
if let json = json as? [String: String] {
receivedJSON = json
}
})
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
guard let data = json.data(using: .utf8) else {
fatalError("Failed creating Data from JSON String")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapJSON().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .error(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
switch receivedError {
case .some(.jsonMapping):
break
default:
fail("expected NSError with \(NSCocoaErrorDomain) domain")
}
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
guard let data = string.data(using: .utf8) else {
fatalError("Failed creating Data from String")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedString: String?
_ = single.mapString().subscribe(onSuccess: { string in
receivedString = string
})
expect(receivedString).to(equal(string))
}
it("maps data representing a string at a key path to a string") {
let string = "You have the rights to the remains of a silent attorney."
let json = ["words_to_live_by": string]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
fatalError("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedString: String?
_ = single.mapString(atKeyPath: "words_to_live_by").subscribe(onSuccess: { string in
receivedString = string
})
expect(receivedString).to(equal(string))
}
it("ignores invalid data") {
let data = Data(bytes: [0x11FFFF] as [UInt32], count: 1) //Byte exceeding UTF8
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapString().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .error(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.stringMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("object mapping") {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let json: [String: Any] = [
"title": "Hello, Moya!",
"createdAt": "1995-01-14T12:34:56"
]
it("maps data representing a json to a decodable object") {
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObject: Issue?
_ = single.map(Issue.self, using: decoder).subscribe(onSuccess: { object in
receivedObject = object
})
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to an array of decodable objects") {
let jsonArray = [json, json, json]
guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObjects: [Issue]?
_ = single.map([Issue].self, using: decoder).subscribe(onSuccess: { objects in
receivedObjects = objects
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 3
expect(receivedObjects?.map { $0.title }) == ["Hello, Moya!", "Hello, Moya!", "Hello, Moya!"]
}
it("maps empty data to a decodable object with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: OptionalIssue?
_ = single.map(OptionalIssue.self, using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: [OptionalIssue]?
_ = single.map([OptionalIssue].self, using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
context("when using key path mapping") {
it("maps data representing a json to a decodable object") {
let json: [String: Any] = ["issue": json] // nested json
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObject: Issue?
_ = single.map(Issue.self, atKeyPath: "issue", using: decoder).subscribe(onSuccess: { object in
receivedObject = object
})
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to a decodable object (#1311)") {
let json: [String: Any] = ["issues": [json]] // nested json array
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObjects: [Issue]?
_ = single.map([Issue].self, atKeyPath: "issues", using: decoder).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title) == "Hello, Moya!"
expect(receivedObjects?.first?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps empty data to a decodable object with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: OptionalIssue?
_ = single.map(OptionalIssue.self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: [OptionalIssue]?
_ = single.map([OptionalIssue].self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
it("map Int data to an Int value") {
let json: [String: Any] = ["count": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var count: Int?
_ = observable.map(Int.self, atKeyPath: "count", using: decoder).subscribe(onSuccess: { value in
count = value
})
expect(count).notTo(beNil())
expect(count) == 1
}
it("map Bool data to a Bool value") {
let json: [String: Any] = ["isNew": true]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var isNew: Bool?
_ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onSuccess: { value in
isNew = value
})
expect(isNew).notTo(beNil())
expect(isNew) == true
}
it("map String data to a String value") {
let json: [String: Any] = ["description": "Something interesting"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var description: String?
_ = observable.map(String.self, atKeyPath: "description", using: decoder).subscribe(onSuccess: { value in
description = value
})
expect(description).notTo(beNil())
expect(description) == "Something interesting"
}
it("map String data to a URL value") {
let json: [String: Any] = ["url": "http://www.example.com/test"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var url: URL?
_ = observable.map(URL.self, atKeyPath: "url", using: decoder).subscribe(onSuccess: { value in
url = value
})
expect(url).notTo(beNil())
expect(url) == URL(string: "http://www.example.com/test")
}
it("shouldn't map Int data to a Bool value") {
let json: [String: Any] = ["isNew": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var isNew: Bool?
_ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onSuccess: { value in
isNew = value
})
expect(isNew).to(beNil())
}
it("shouldn't map String data to an Int value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: Int?
_ = observable.map(Int.self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
it("shouldn't map Array<String> data to an String value") {
let json: [String: Any] = ["test": ["123", "456"]]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: String?
_ = observable.map(String.self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
it("shouldn't map String data to an Array<String> value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: [String]?
_ = observable.map([String].self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
}
it("ignores invalid data") {
var json = json
json["createdAt"] = "Hahaha" // invalid date string
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: Error?
_ = single.map(Issue.self, using: decoder).subscribe { event in
switch event {
case .success:
fail("success called for invalid data")
case .error(let error):
receivedError = error
}
}
if case let MoyaError.objectMapping(nestedError, _)? = receivedError {
expect(nestedError).to(beAKindOf(DecodingError.self))
} else {
fail("expected <MoyaError.objectMapping>, got <\(String(describing: receivedError))>")
}
}
}
}
}
| 44.356655 | 150 | 0.497057 |
5b909bea183244d6177224b795c3266cfc30a75e | 161 | // © 2019 J. G. Pusey (see LICENSE.md)
internal protocol ItemDescriptor {
var count: Int { get }
var item: Any { get }
var offset: UInt64 { get }
}
| 20.125 | 38 | 0.608696 |
c15544f22d1707e16b9e16270f1b515f4609a760 | 3,686 | import Foundation
/// Pre-defined event that is used to signal the success of a purchase action.
@objc public class PurchaseSuccessfulEvent: Event {
private enum Keys {
static let purchaseAmount = "purchaseAmountMicros"
static let numberOfItems = "numberOfItems"
static let currencyCode = "currencyCode"
static let itemIdList = "itemIdList"
}
var purchaseAmount = -1
var numberOfItems = -1
var currencyCode = "UNKNOWN"
var itemList = [String]()
/// For broadcasting to RAT SDK. 'eventType' field will be removed.
override var analyticsParameters: [String: Any] {
return [
"eventName": super.name,
"timestamp": super.timestamp,
Keys.purchaseAmount: self.purchaseAmount,
Keys.numberOfItems: self.numberOfItems,
Keys.currencyCode: self.currencyCode,
Keys.itemIdList: self.itemList
]
}
var customAttributes: [CustomAttribute] {
return [
CustomAttribute(withKeyName: Keys.purchaseAmount, withIntValue: self.purchaseAmount),
CustomAttribute(withKeyName: Keys.numberOfItems, withIntValue: self.numberOfItems),
CustomAttribute(withKeyName: Keys.currencyCode, withStringValue: self.currencyCode),
CustomAttribute(withKeyName: Keys.itemIdList, withStringValue: self.itemList.joined(separator: "|"))
]
}
@objc
public init() {
super.init(type: EventType.purchaseSuccessful,
name: Constants.Event.purchaseSuccessful)
}
init(
withPurchaseAmount purchaseAmount: Int,
withNumberOfItems numberOfItems: Int,
withCurrencyCode currencyCode: String,
withItems itemList: [String],
timestamp: Int64) {
self.purchaseAmount = purchaseAmount
self.numberOfItems = numberOfItems
self.currencyCode = currencyCode
self.itemList = itemList
super.init(type: EventType.purchaseSuccessful,
name: Constants.Event.purchaseSuccessful,
timestamp: timestamp)
}
required public init(from decoder: Decoder) throws {
fatalError("init(from:) has not been implemented")
}
override public func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
}
@objc @discardableResult
public func setPurchaseAmount(_ purchaseAmount: Int) -> PurchaseSuccessfulEvent {
self.purchaseAmount = purchaseAmount
return self
}
@objc @discardableResult
public func setNumberOfItems(_ numberOfItems: Int) -> PurchaseSuccessfulEvent {
self.numberOfItems = numberOfItems
return self
}
@objc @discardableResult
public func setCurrencyCode(_ currencyCode: String) -> PurchaseSuccessfulEvent {
self.currencyCode = currencyCode
return self
}
@objc @discardableResult
public func setItemList(_ itemList: [String]) -> PurchaseSuccessfulEvent {
self.itemList = itemList
return self
}
override func getAttributeMap() -> [String: CustomAttribute] {
return [
Keys.purchaseAmount: CustomAttribute(withKeyName: Keys.purchaseAmount, withIntValue: self.purchaseAmount),
Keys.numberOfItems: CustomAttribute(withKeyName: Keys.numberOfItems, withIntValue: self.numberOfItems),
Keys.currencyCode: CustomAttribute(withKeyName: Keys.currencyCode, withStringValue: self.currencyCode),
Keys.itemIdList: CustomAttribute(withKeyName: Keys.itemIdList, withStringValue: self.itemList.joined(separator: "|"))
]
}
}
| 35.786408 | 129 | 0.665762 |
cc8f2223cdcc12d01cf9e2f7bc0d2c8e8ee15955 | 6,213 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
import _Concurrency
// ==== Any Actor -------------------------------------------------------------
/// Shared "base" protocol for both (local) `Actor` and (potentially remote)
/// `DistributedActor`.
///
/// FIXME(distributed): We'd need Actor to also conform to this, but don't want to add that conformance in _Concurrency yet.
@_marker
@available(SwiftStdlib 5.7, *)
public protocol AnyActor: Sendable, AnyObject {
}
// ==== Distributed Actor -----------------------------------------------------
/// Common protocol to which all distributed actors conform implicitly.
///
/// It is not possible to conform to this protocol manually explicitly.
/// Only a 'distributed actor' declaration or protocol with 'DistributedActor'
/// requirement may conform to this protocol.
///
/// The 'DistributedActor' protocol provides the core functionality of any
/// distributed actor.
@available(SwiftStdlib 5.7, *)
public protocol DistributedActor:
AnyActor,
Identifiable,
Hashable, Codable
where ID == ActorSystem.ActorID {
/// The type of transport used to communicate with actors of this type.
associatedtype ActorSystem: DistributedActorSystem
/// The serialization requirement to apply to all distributed declarations inside the actor.
typealias SerializationRequirement = ActorSystem.SerializationRequirement
/// Logical identity of this distributed actor.
///
/// Many distributed actor references may be pointing at, logically, the same actor.
/// For example, calling `resolve(id:using:)` multiple times, is not guaranteed
/// to return the same exact resolved actor instance, however all the references would
/// represent logically references to the same distributed actor, e.g. on a different node.
///
/// Conformance to this requirement is synthesized automatically for any
/// `distributed actor` declaration.
nonisolated override var id: ID { get }
/// The `ActorSystem` that is managing this distributed actor.
///
/// It is immutable and equal to the system passed in the local/resolve
/// initializer.
///
/// Conformance to this requirement is synthesized automatically for any
/// `distributed actor` declaration.
nonisolated var actorSystem: ActorSystem { get }
/// Resolves the passed in `id` against the `system`, returning
/// either a local or remote actor reference.
///
/// The system will be asked to `resolve` the identity and return either
/// a local instance or request a proxy to be created for this identity.
///
/// A remote distributed actor reference will forward all invocations through
/// the system, allowing it to take over the remote messaging with the
/// remote actor instance.
///
/// - Parameter id: identity uniquely identifying a, potentially remote, actor in the system
/// - Parameter system: `system` which should be used to resolve the `identity`, and be associated with the returned actor
static func resolve(id: ID, using system: ActorSystem) throws -> Self
}
// ==== Hashable conformance ---------------------------------------------------
@available(SwiftStdlib 5.7, *)
extension DistributedActor {
nonisolated public func hash(into hasher: inout Hasher) {
self.id.hash(into: &hasher)
}
nonisolated public static func ==(lhs: Self, rhs: Self) -> Bool {
lhs.id == rhs.id
}
}
// ==== Codable conformance ----------------------------------------------------
extension CodingUserInfoKey {
@available(SwiftStdlib 5.7, *)
public static let actorSystemKey = CodingUserInfoKey(rawValue: "$distributed_actor_system")!
}
@available(SwiftStdlib 5.7, *)
extension DistributedActor {
nonisolated public init(from decoder: Decoder) throws {
guard let system = decoder.userInfo[.actorSystemKey] as? ActorSystem else {
throw DistributedActorCodingError(message:
"Missing system (for key .actorSystemKey) " +
"in Decoder.userInfo, while decoding \(Self.self).")
}
let id: ID = try Self.ID(from: decoder)
self = try Self.resolve(id: id, using: system)
}
nonisolated public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.id)
}
}
// ==== Local actor special handling -------------------------------------------
@available(SwiftStdlib 5.7, *)
extension DistributedActor {
/// Executes the passed 'body' only when the distributed actor is local instance.
///
/// The `Self` passed to the the body closure is isolated, meaning that the
/// closure can be used to call non-distributed functions, or even access actor
/// state.
///
/// When the actor is remote, the closure won't be executed and this function will return nil.
public nonisolated func whenLocal<T: Sendable>(
_ body: @Sendable (isolated Self) async throws -> T
) async rethrows -> T? {
if __isLocalActor(self) {
return try await body(self)
} else {
return nil
}
}
}
/******************************************************************************/
/************************* Runtime Functions **********************************/
/******************************************************************************/
// ==== isRemote / isLocal -----------------------------------------------------
@_silgen_name("swift_distributed_actor_is_remote")
func __isRemoteActor(_ actor: AnyObject) -> Bool
func __isLocalActor(_ actor: AnyObject) -> Bool {
return !__isRemoteActor(actor)
}
// ==== Proxy Actor lifecycle --------------------------------------------------
@_silgen_name("swift_distributedActor_remote_initialize")
func _distributedActorRemoteInitialize(_ actorType: Builtin.RawPointer) -> Any
| 37.884146 | 124 | 0.636086 |
fc0715af020140324e45a2ae5d0baa539ca1e0fc | 1,540 | //
// Result.swift
// SwiftFilePath
//
// Created by nori0620 on 2015/01/11.
// Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved.
//
public enum Result<S,F> {
case Success(S)
case Failure(F)
public init(success:S){
self = .Success(success)
}
public init(failure:F){
self = .Failure(failure)
}
public var isSuccess:Bool {
switch self {
case .Success: return true
case .Failure: return false
}
}
public var isFailure:Bool {
switch self {
case .Success: return false
case .Failure: return true
}
}
public var value:S? {
switch self {
case .Success(let success):
return success
case .Failure(_):
return .None
}
}
public var error:F? {
switch self {
case .Success(_):
return .None
case .Failure(let error):
return error
}
}
public func onFailure(handler:(F) -> Void ) -> Result<S,F> {
switch self {
case .Success(_):
return self
case .Failure(let error):
handler( error )
return self
}
}
public func onSuccess(handler:(S) -> Void ) -> Result<S,F> {
switch self {
case .Success(let success):
handler(success )
return self
case .Failure(_):
return self
}
}
} | 20.533333 | 64 | 0.486364 |
03f02506145d4b5e14e04c7684f63c2eadf25727 | 254 | //
// P14B_BucketListApp.swift
// P14B BucketList
//
// Created by Julian Moorhouse on 11/04/2021.
//
import SwiftUI
@main
struct P14B_BucketListApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 14.111111 | 46 | 0.602362 |
03e95b92b3d3f492f8cb2f8fd088295ed2ef96c0 | 356 | //
// Common.swift
// DouYu
//
// Created by 张萌 on 2017/9/12.
// Copyright © 2017年 JiaYin. All rights reserved.
//
import UIKit
let kStatusBarH: CGFloat = 20
let kNavigateBarH: CGFloat = 44
let kTabBarH: CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
let kBaseUrl = "http://capi.douyucdn.cn/api/"
| 18.736842 | 50 | 0.710674 |
46a5d29cc522d9891a63b1fe946cee55e7f4abe1 | 1,084 | //
// ArrayTests.swift
// DCKit
//
// Created by Kristijan Delivuk on 10/13/15.
// Copyright © 2015 Vladimir Kolbas. All rights reserved.
//
import XCTest
@testable import DCKit
class ArrayTests: XCTestCase {
var array = ["One" , "Two" , "Three" , "Four" , "Five"]
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testIfArrayConstainsObject() {
XCTAssertTrue(array.dc_contains("One"), "Array 'dc_contains' function isn't working properly.")
}
func testRemovingObjectFromArray() {
XCTAssertTrue(array.dc_removeObject("One"), "Array 'dc_removeObject' function isn't working properly.")
XCTAssertFalse(array.dc_contains("One"), "Array 'dc_removeObject' function didn't remove object from the array.")
}
} | 28.526316 | 121 | 0.654059 |
87c3c377484d39993523eda43e46459d9487778b | 2,549 | //
// ContentController.swift
// WWDCScholars
//
// Created by Andrew Walker on 11/05/2017.
// Copyright © 2017 WWDCScholars. All rights reserved.
//
import Foundation
protocol ContentController: AnyObject {
var sectionContent: [SectionContent] { get set }
func reloadContent()
func add(sectionContent: SectionContent)
func add(sectionContent: [SectionContent])
func removeAllContent()
}
extension ContentController {
// MARK: - Functions
func numberOfSections() -> Int {
return self.sectionContent.count
}
func numberOfItems(in section: Int) -> Int {
return self.sectionContent[section].cellContent.count
}
func reuseIdentifier(for indexPath: IndexPath) -> String {
return self.sectionContent[indexPath.section].cellContent[indexPath.item].reuseIdentifier
}
func cellContentFor(indexPath: IndexPath) -> CellContent {
return self.sectionContentFor(index: indexPath.section).cellContent[indexPath.row]
}
func sectionContentFor(index: Int) -> SectionContent {
return self.sectionContent[index]
}
func set(sectionContent: SectionContent) {
self.sectionContent = [sectionContent]
}
func add(sectionContent: SectionContent) {
self.sectionContent.append(sectionContent)
}
func add(sectionContent: [SectionContent]) {
self.sectionContent.append(contentsOf: sectionContent)
}
func removeAllContent() {
self.sectionContent.removeAll()
}
func indexPath(of cellContent: CellContent) -> IndexPath? {
guard let sectionContentIndex = self.sectionContentIndex(of: cellContent) else {
return nil
}
guard let cellContentIndex = self.index(of: cellContent, sectionContentIndex: sectionContentIndex) else {
return nil
}
let indexPath = IndexPath(item: cellContentIndex, section: sectionContentIndex)
return indexPath
}
func index(of cellContent: CellContent, sectionContentIndex: Int) -> Int? {
guard let index = self.sectionContentFor(index: sectionContentIndex).cellContent.firstIndex(where: { $0 === cellContent }) else {
return nil
}
return index
}
func sectionContentIndex(of cellContent: CellContent) -> Int? {
guard let index = self.sectionContent.firstIndex(where: { $0.cellContent.contains(where: { $0 === cellContent }) }) else {
return nil
}
return index
}
}
| 28.640449 | 137 | 0.66379 |
e675b125555c908b9514f79871d0c9d8ffecb006 | 258 | //
// YNNACollectionViewCell.swift
// Tochoku
//
// Created by Matsui Keiji on 2018/10/21.
// Copyright © 2018年 Matsui Keiji. All rights reserved.
//
import UIKit
class YNNACollectionViewCell: UICollectionViewCell {
@IBOutlet var Label: UILabel!
}
| 18.428571 | 56 | 0.724806 |
6a42a94c2f36816c4b4f6af7afb1bc21d48b8718 | 3,959 | //
// Copyright (c) 2018 Adyen B.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import Foundation
/// Defines the functions that should be implemented in order to use the PaymentController.
public protocol PaymentControllerDelegate: AnyObject {
/// Invoked when the payment flow has started and a payment session is required from the backend.
/// Use this opportunity to make a request to the /paymentSession API from your backend, including the token.
/// The value of `paymentSession` inside the response should be passed in the responseHandler.
///
/// - Parameters:
/// - paymentController: The payment controller that requires a payment session.
/// - token: The token to submit to the /paymentSession endpoint.
/// - responseHandler: The closure to invoke when payment session has been received.
func requestPaymentSession(withToken token: String, for paymentController: PaymentController, responseHandler: @escaping Completion<String>)
/// Invoked when the payment methods available to complete the payment are retrieved.
/// Use this opportunity to present a list of payment methods to the user and asking the user to fill the required payment details.
///
/// When the payment method contains payment details in its `details` property, make sure to set them before handing back the payment method through the `selectionHandler`.
///
/// - Parameters:
/// - paymentMethods: The payment methods from which a payment method can be selected.
/// - paymentController: The payment controller that requires a payment method.
/// - selectionHandler: The closure to invoke when a payment method has been selected.
func selectPaymentMethod(from paymentMethods: SectionedPaymentMethods, for paymentController: PaymentController, selectionHandler: @escaping Completion<PaymentMethod>)
/// Invoked when a redirect to a URL is required in order to complete the payment.
/// It's recommended to use either `SFSafariViewController` or `UIApplication`'s `openURL:` to perform the redirect.
///
/// Make sure to invoke `applicationDidOpen(_:)` in your `UIApplicationDelegate`'s `application(_:open:options:)` in order for Adyen to be able to handle the result.
///
/// - Parameters:
/// - url: The URL to redirect the user to.
/// - paymentController: The payment controller that requires a redirect.
func redirect(to url: URL, for paymentController: PaymentController)
/// Invoked when the payment is finished.
///
/// A successful result contains a `payload`. Submit this `payload` through your backend to the `/payments/result` endpoint to verify the integrity of the payment.
///
/// - Parameters:
/// - result: The result of the payment.
/// - paymentController: The payment controller that finished the payment.
func didFinish(with result: Result<PaymentResult>, for paymentController: PaymentController)
/// Invoked when additional payment details are needed.
///
/// - Parameters:
/// - additionalDetails: Structure containing the details that need to be filled and additional redirect data.
/// - paymentMethod: The payment method that is requesting additional details.
/// - detailsHandler: The closure to invoke when details are filled.
func provideAdditionalDetails(_ additionalDetails: AdditionalPaymentDetails, for paymentMethod: PaymentMethod, detailsHandler: @escaping Completion<[PaymentDetail]>)
}
extension PaymentControllerDelegate {
public func provideAdditionalDetails(_ additionalDetails: AdditionalPaymentDetails, for paymentMethod: PaymentMethod, detailsHandler: @escaping Completion<[PaymentDetail]>) {
print("Payment method requires additional details but `provideAdditionalDetails(_:for:detailsHandler)` delegate was not implemented.")
}
}
| 60.907692 | 178 | 0.735792 |
6a096c54a743e761fb1b239ffac100d8441fd263 | 1,209 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch)
// REQUIRES: concurrency
// REQUIRES: executable_test
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
// UNSUPPORTED: single_threaded_concurrency
// for sleep
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import WinSDK
#endif
class Canary {
deinit {
print("canary died")
}
}
if #available(SwiftStdlib 5.1, *) {
let task = detach {
let canary = Canary()
_ = await Task.withCancellationHandler {
print(canary)
} operation: {
await Task.sleep(1_000_000)
}
}
task.cancel()
#if os(Windows)
Sleep(1 * 1000)
#else
sleep(1)
#endif
detach {
await Task.withCancellationHandler {
print("Task was cancelled!")
}
operation: {
print("Running the operation...")
}
}
#if os(Windows)
Sleep(10 * 1000)
#else
sleep(10)
#endif
} else {
// Fake prints to satisfy FileCheck.
print("Canary")
print("canary died")
print("Running the operation...")
}
// CHECK: Canary
// CHECK-NEXT: canary died
// CHECK-NEXT: Running the operation...
| 19.5 | 96 | 0.66584 |
b9b3836eeeddea86c8c1e46e13a13455de469896 | 1,801 | //
// AnalyticsService.swift
// DataModule
//
// Created by Ahmad Mahmoud on 05/05/2021.
//
public class AnalyticsService: AnalyticsWithStrategyServiceProtocol {
private let analyticsServices: [AnalyticsServiceProtocol]
required public init(analyticsServices: AnalyticsServiceProtocol...) {
self.analyticsServices = analyticsServices
}
public func enableLogging() -> Bool {
return true
}
public func log(userId: Int, strategies: AnalyticsStrategy...) {
self.forEachStrategyIn(strategies: strategies) { service in
service.log(userId: userId)
}
}
public func log(event: AnalyticsEvents, strategies: AnalyticsStrategy...) {
self.forEachStrategyIn(strategies: strategies) { service in
service.log(event: event)
}
}
public func log(event: AnalyticsEvents, params: [String: Any], strategies: AnalyticsStrategy...) {
self.forEachStrategyIn(strategies: strategies) { service in
service.log(event: event, params: params)
}
}
public func forEachStrategyIn(strategies: [AnalyticsStrategy],
action: (AnalyticsServiceProtocol) -> Void) {
if(strategies.isEmpty) {
self.analyticsServices.forEach { action($0) }
}
else {
strategies.forEach { strategy in
if let analyticsService = self.analyticsServices.first(where: { $0.strategy == strategy }) {
action(analyticsService)
}
else {
fatalError("No AnalyticsServiceProtocol found matching \(strategy) strategy, please provide one through the class initializer!")
}
}
}
}
}
| 32.745455 | 148 | 0.606885 |
2652ea77db2bd6e63ad8439bda1ec47a9dc212dc | 3,566 | //
// SettingViewController.swift
// MVC-Code
//
// Created by giftbot on 2017. 10. 2..
// Copyright © 2017년 giftbot. All rights reserved.
//
import UIKit
final class SettingViewController: BaseViewController {
typealias Language = ServiceSetting.Language
typealias UserID = ServiceSetting.UserID
typealias SortType = ServiceSetting.SortType
// MARK: Properties
private let sectionHeaders = ["\(Language.self)", "\(UserID.self)", "\(SortType.self)"]
private let sectionValues = [
Language.allValues.map { "\($0)" },
UserID.allValues.map { "\($0)" },
SortType.allValues.map { "\($0)" }
]
private var currentSetting: ServiceSetting!
private var saveActionHandler: ((ServiceSetting) -> ())!
// MARK: Initialize
static func createWith(initialData: ServiceSetting, completion: @escaping (ServiceSetting) -> ()) -> SettingViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let `self` = storyboard.instantiateViewController(ofType: SettingViewController.self)
self.currentSetting = initialData
self.saveActionHandler = completion
return self
}
// MARK: Action Handler
@IBAction func saveCurrentSetting() {
saveActionHandler(currentSetting)
navigationController?.popViewController(animated: true)
}
}
// MARK: - TableViewDelegate
extension SettingViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
guard let selectedIndexPaths = tableView.indexPathsForSelectedRows else { return nil }
selectedIndexPaths
.filter { $0.section == indexPath.section }
.forEach { tableView.deselectRow(at: $0, animated: false) }
return indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == sectionHeaders.index(of: "\(Language.self)") {
currentSetting.language = Language.allValues[indexPath.row]
} else if indexPath.section == sectionHeaders.index(of: "\(UserID.self)") {
currentSetting.userID = UserID.allValues[indexPath.row]
} else {
currentSetting.sortType = SortType.allValues[indexPath.row]
}
}
func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let headerView = view as? UITableViewHeaderFooterView else { return }
headerView.textLabel?.textColor = .darkGray
}
}
// MARK: - TableViewDataSource
extension SettingViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sectionHeaders.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionValues[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(SettingTableViewCell.self, for: indexPath)
let title = sectionValues[indexPath.section][indexPath.row]
cell.setTitleText(title.capitalized)
let settings = ["\(currentSetting.language)", "\(currentSetting.userID)", "\(currentSetting.sortType)"]
if settings.contains(title) {
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionHeaders[section]
}
}
| 34.288462 | 126 | 0.722098 |
56960e389b9c51cd05b8109ec4875f732657e835 | 249 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{func f{protocol a{class
case,
>
>
| 24.9 | 87 | 0.742972 |
e87753c71a65bafc7871fba3c509fbfae80779c2 | 2,872 | import SwiftUI
// MARK: - CustomSlider
struct CustomSlider: UIViewRepresentable {
// MARK: property
@Binding var value: Double
var `in` = 0.0...1.0
var minimumTrackTintColor: Color?
var maximumTrackTintColor: Color?
var backgroundColor: Color?
var thumbTintColor: Color?
var thumbImage: UIImage?
var highlightedThumbImage: UIImage?
var thresholdValue: Double?
var thresholdSecond: TimeInterval?
// MARK: UIViewRepresentable
func makeUIView(context: Context) -> UISlider {
let slider = UISlider(frame: .zero)
if let thumbTintColor = thumbTintColor {
slider.thumbTintColor = UIColor(thumbTintColor)
}
if let minimumTrackTintColor = minimumTrackTintColor {
slider.minimumTrackTintColor = UIColor(minimumTrackTintColor)
}
if let maximumTrackTintColor = maximumTrackTintColor {
slider.maximumTrackTintColor = UIColor(maximumTrackTintColor)
}
if let minimumTrackTintColor = minimumTrackTintColor {
slider.minimumTrackTintColor = UIColor(minimumTrackTintColor)
}
if let maximumTrackTintColor = maximumTrackTintColor {
slider.maximumTrackTintColor = UIColor(maximumTrackTintColor)
}
slider.maximumValue = Float(self.in.upperBound)
slider.minimumValue = Float(self.in.lowerBound)
slider.value = Float(value)
slider.setThumbImage(thumbImage, for: .normal)
slider.setThumbImage(highlightedThumbImage, for: .highlighted)
slider.addTarget(
context.coordinator,
action: #selector(Coordinator.valueChanged(_:)),
for: .valueChanged
)
return slider
}
func updateUIView(_ uiView: UISlider, context: Context) {
uiView.value = Float(value)
}
func makeCoordinator() -> CustomSlider.Coordinator {
Coordinator(value: $value, thresholdValue: thresholdValue ?? 0.0, thresholdSecond: thresholdSecond ?? 0.0)
}
// MARK: Coordinator
final class Coordinator: NSObject {
var value: Binding<Double>
var second: TimeInterval
var thresholdValue: Double
var thresholdSecond: TimeInterval
init(value: Binding<Double>, second: TimeInterval = Date().timeIntervalSince1970, thresholdValue: Double = 0.0, thresholdSecond: TimeInterval = 0.0) {
self.value = value
self.second = second
self.thresholdValue = thresholdValue
self.thresholdSecond = thresholdSecond
}
@objc
func valueChanged(_ sender: UISlider) {
let now = Date()
if abs(value.wrappedValue - Double(sender.value)) > thresholdValue && abs(now.timeIntervalSince1970 - second) > thresholdSecond {
value.wrappedValue = Double(sender.value)
second = now.timeIntervalSince1970
}
}
}
}
// MARK: - CustomSlider_Previews
struct CustomSlider_Previews: PreviewProvider {
static var previews: some View {
CustomSlider(
value: .constant(0.5)
)
}
}
| 30.553191 | 154 | 0.711003 |
f58bdcacbbd1895055e041a1ac9a28d36e272815 | 1,329 | //
// L10n+StuffWidget.swift
// StuffWidgetsExtension
//
// Created by Данис Тазетдинов on 13.02.2022.
//
import Foundation
import Localization
extension L10n {
enum RecentChecklists: String, Localizable {
case widgetTitle = "recentChecklists.widget.title" // "Checklists"
case widgetDescription = "recentChecklists.widget.description" // "List of recent checklists."
case viewTitle = "recentChecklists.view.title" // "Recent checklists"
case addButton = "recentChecklists.button.add" // "Add..."
case noChecklists = "recentChecklists.noChecklists" // "No checklists"
case openAppToSync = "recentChecklists.openAppToSync" // "Open app to sync"
case totalNumberOfChecklists = "recentChecklists.totalNumberOfChecklist"
}
enum ChecklistEntries: String, Localizable {
case widgetTitle = "checklistEntries.widget.title" // "Checklist"
case widgetDescription = "checklistEntries.widget.description" // "Checklist display."
case noEntries = "checklistEntries.noEntries" // "No entries"
case pickChecklist = "checklistEntries.pickChecklist" // "Pick a checklist"
case checkedOfTotalEntries = "checklistEntries.checkedOfTotalEntries"
case totalNumberOfEntries = "checklistEntries.totalNumberOfEntries"
}
}
| 40.272727 | 102 | 0.714071 |
d6bf063f8b6dca5e5634f76190a189a414296a46 | 1,547 | /* Question: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return
the original string. You can assume the string has only uppercase and lowercase letters (a - z) */
import UIKit
extension String
{
subscript (location: Int)-> Character
{
return self[self.index(self.startIndex, offsetBy: location)]
}
func compress()-> String
{
var occurence: Int = 1
var compressedLength: Int = 0
var compressedString: String = ""
let originalLength: Int = self.characters.count
var currentCharacter: Character = self[self.startIndex]
for i in 1..<originalLength
{
if self[i] == currentCharacter
{
occurence += 1
}
else
{
compressedString.append(String(currentCharacter) + String(occurence))
currentCharacter = self[i]
occurence = 1
compressedLength += 2
}
}
compressedString.append(String(currentCharacter) + String(occurence))
compressedLength += 2
return compressedLength > originalLength ? self : compressedString
}
}
print("aabcccccaaa".compress())
print("XbWZiGbirS".compress())
print("zzdNJsWzyQ".compress())
print("jjkHHHHXe".compress()) | 32.914894 | 272 | 0.619263 |
8f0c00716ff788a257631da301c71e9a1ecae06a | 27,970 | import Foundation
import SwiftUI
/**
Identifiers for different axes presented by the chart.
These are provided as a convenient way to reference axes by their position and orientation.
The type of axis will vary depending on the type of chart presented. As an example, for scatter, bubble, and bar charts the `x` axis is a numeric axis; but for all other chart types the `x` axis is the category axis.
*/
public enum ChartAxisId: String {
/// X axis. Normally the category or horizontal axis.
case x
/// Y axis. Normally the value or vertical axis.
case y
/// :nodoc:
case radius
/// :nodoc:
case dual
/// Category or X axis.
case category
}
/**
* Axis context struct.
*/
struct AxisTickValues {
/*
* The actual plottable min/max.
* This is the smallest value between tick min and data min, and the biggest
* value between tick max and data max.
*/
let plotMinimum: CGFloat
let plotMaximum: CGFloat
/*
* Indicate the value and position of the origin of a chart.
* If the y axis zero value is visible in the plottable area, zero is the
* baseline. Otherwise it will be the closest visible value to the y axis
* zero value... the origin.
*/
let plotBaselineValue: CGFloat
let plotBaselinePosition: CGFloat
/*
* The min/max represented by the tick marks.
*/
let tickMinimum: CGFloat
let tickMaximum: CGFloat
/*
* The min/max values in the data.
*/
let dataMinimum: CGFloat
let dataMaximum: CGFloat
/*
* The range between plot min and plot max.
*/
let plotRange: CGFloat
/*
* The range between tick min and tick max.
*/
let tickRange: CGFloat
/*
* The range between data min and data max.
*/
let dataRange: CGFloat
/*
* The range between plot min and plot max.
*/
let plotScale: CGFloat
/*
* The range between tick min and tick max.
*/
let tickScale: CGFloat
/*
* The range between data min and data max.
*/
let dataScale: CGFloat
/*
* The size of the tick distance from one tick mark to another.
*/
let tickStepSize: CGFloat
/*
* Array of tick values that are to be represented.
*/
let tickValues: [CGFloat]
/*
* Array of tick values that are to be represented.
*/
let tickPositions: [CGFloat]
/*
* Amount of ticks that are to be represented.
*/
let tickCount: UInt
init(plotMinimum: CGFloat, plotMaximum: CGFloat, plotBaselineValue: CGFloat, plotBaselinePosition: CGFloat, tickMinimum: CGFloat, tickMaximum: CGFloat, dataMinimum: CGFloat, dataMaximum: CGFloat, plotRange: CGFloat, tickRange: CGFloat, dataRange: CGFloat, plotScale: CGFloat, tickScale: CGFloat, dataScale: CGFloat, tickStepSize: CGFloat, tickValues: [CGFloat], tickPositions: [CGFloat], tickCount: UInt) {
self.plotMinimum = plotMinimum
self.plotMaximum = plotMaximum
self.plotBaselineValue = plotBaselineValue
self.plotBaselinePosition = plotBaselinePosition
self.tickMinimum = tickMinimum
self.tickMaximum = tickMaximum
self.dataMinimum = dataMinimum
self.dataMaximum = dataMaximum
self.plotRange = plotRange
self.tickRange = tickRange
self.dataRange = dataRange
self.plotScale = plotScale
self.tickScale = tickScale
self.dataScale = dataScale
self.tickStepSize = tickStepSize
self.tickValues = tickValues
self.tickPositions = tickPositions
self.tickCount = tickCount
}
init() {
self.init(plotMinimum: 0, plotMaximum: 1, plotBaselineValue: 0, plotBaselinePosition: 0, tickMinimum: 0, tickMaximum: 1, dataMinimum: 0, dataMaximum: 1, plotRange: 1, tickRange: 1, dataRange: 1, plotScale: 1, tickScale: 1, dataScale: 1, tickStepSize: 1, tickValues: [0, 1], tickPositions: [0, 1], tickCount: 2)
}
}
extension AxisTickValues: CustomStringConvertible {
var description: String {
let nf = NumberFormatter()
nf.numberStyle = .none
nf.maximumFractionDigits = 2
return """
{
"AxisTickValues": {
"plotMinimum": \(nf.string(from: NSNumber(value: Double(self.plotMinimum))) ?? ""),
"plotMaximum": \(nf.string(from: NSNumber(value: Double(self.plotMaximum))) ?? ""),
"plotBaselineValue": \(nf.string(from: NSNumber(value: Double(self.plotBaselineValue))) ?? ""),
"plotBaselinePosition": \(nf.string(from: NSNumber(value: Double(self.plotBaselinePosition))) ?? ""),
"tickMinimum": \(nf.string(from: NSNumber(value: Double(self.tickMinimum))) ?? ""),
"tickMaximum": \(nf.string(from: NSNumber(value: Double(self.tickMaximum))) ?? ""),
"dataMinimum": \(nf.string(from: NSNumber(value: Double(self.dataMinimum))) ?? ""),
"dataMaximum": \(nf.string(from: NSNumber(value: Double(self.dataMaximum))) ?? ""),
"plotRange": \(nf.string(from: NSNumber(value: Double(self.plotRange))) ?? ""),
"tickRange": \(nf.string(from: NSNumber(value: Double(self.tickRange))) ?? ""),
"dataRange": \(nf.string(from: NSNumber(value: Double(self.dataRange))) ?? ""),
"plotScale": \(nf.string(from: NSNumber(value: Double(self.plotScale))) ?? ""),
"tickScale": \(nf.string(from: NSNumber(value: Double(self.tickScale))) ?? ""),
"dataScale": \(nf.string(from: NSNumber(value: Double(self.dataScale))) ?? ""),
"tickStepSize": \(nf.string(from: NSNumber(value: Double(self.tickStepSize))) ?? ""),
"tickValues": \(String(describing: self.tickValues)),
"tickPositions": \(String(describing: self.tickPositions)),
"tickCount": \(String(describing: self.tickCount))
}
}
"""
}
}
public class ChartAxisAttributes: ObservableObject, Identifiable, NSCopying, CustomStringConvertible {
/// Provides an identifier that associates the axis with a position and orientation in the chart.
@Published public var axisId: ChartAxisId?
/**
Properties for the axis baseline, which is typically usually 0.
- Only numeric axes have a baseline.
*/
@Published public var baseline: ChartBaselineAttributes
/// Properties for the axis gridlines.
@Published public var gridlines: ChartGridlineAttributes
/// Properties for the axis gridline labels.
@Published public var labels: ChartLabelAttributes
/// Properties of the axis title label.
@Published public var titleLabel: ChartLabelAttributes
/// Title of the axis.
@Published public var title: String?
public let id = UUID()
public init(axisId: ChartAxisId? = nil, baseline: ChartBaselineAttributes? = nil, gridlines: ChartGridlineAttributes? = nil, labels: ChartLabelAttributes? = nil, titleLabel: ChartLabelAttributes? = nil, title: String? = nil) {
self._axisId = Published(initialValue: axisId)
if let baselineAttributes = baseline {
self._baseline = Published(initialValue: baselineAttributes)
} else {
let bl = ChartBaselineAttributes()
self._baseline = Published(initialValue: bl)
}
if let gridlinesAttributes = gridlines {
self._gridlines = Published(initialValue: gridlinesAttributes)
} else {
self._gridlines = Published(initialValue: ChartGridlineAttributes())
}
if let labelsAttributes = labels {
self._labels = Published(initialValue: labelsAttributes)
} else {
self._labels = Published(initialValue: ChartLabelAttributes())
}
if let titleLabelsAttributes = titleLabel {
self._titleLabel = Published(initialValue: titleLabelsAttributes)
} else {
self._titleLabel = Published(initialValue: ChartLabelAttributes())
}
self._title = Published(initialValue: title)
}
// swiftlint:disable force_cast
public func copy(with zone: NSZone? = nil) -> Any {
ChartAxisAttributes(axisId: self.axisId,
baseline: self.baseline.copy() as! ChartBaselineAttributes,
gridlines: self.gridlines.copy() as! ChartGridlineAttributes,
labels: self.labels.copy() as! ChartLabelAttributes,
titleLabel: self.titleLabel.copy() as! ChartLabelAttributes,
title: self.title)
}
public var description: String {
"""
{
"ChartAxisAttributes": {
"baseline": \(String(describing: self.baseline)),
"gridlines": \(String(describing: self.gridlines)),
"labels": \(String(describing: self.labels)),
"titleLabel": \(String(describing: self.titleLabel)),
"title": "\(String(describing: self.title))"
}
}
"""
}
}
/**
ChartNumericAxis contains properties of axes for ranges of floating point values.
The position and orientation of a numeric axis depends on the chart type. For example:
- Bar charts display the numeric axis as the X axis.
- Line, column, and combo charts display the numeric axis as the Y axis.
*/
public class ChartNumericAxisAttributes: ChartAxisAttributes {
public init(axisId: ChartAxisId? = nil,
baseline: ChartBaselineAttributes? = nil,
gridlines: ChartGridlineAttributes? = nil,
labels: ChartLabelAttributes? = nil,
titleLabel: ChartLabelAttributes? = nil,
title: String? = nil,
isZeroBased: Bool = true,
allowLooseLabels: Bool = false,
fudgeAxisRange: Bool = false,
adjustToNiceValues: Bool = true,
abbreviatesLabels: Bool = false,
isMagnitudedDisplayed: Bool = true,
explicitMin: Double? = nil,
explicitMax: Double? = nil,
formatter: NumberFormatter?,
abbreviatedFormatter: NumberFormatter?)
{
if let formatter = formatter {
self._formatter = Published(initialValue: formatter)
} else {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
self._formatter = Published(initialValue: formatter)
}
if let abbreviatedFormatter = abbreviatedFormatter {
self._abbreviatedFormatter = Published(initialValue: abbreviatedFormatter)
} else if let formatter = formatter {
self._abbreviatedFormatter = Published(initialValue: formatter)
} else {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
self._abbreviatedFormatter = Published(initialValue: formatter)
}
self._isZeroBased = Published(initialValue: isZeroBased)
self._allowLooseLabels = Published(initialValue: allowLooseLabels)
self._fudgeAxisRange = Published(initialValue: fudgeAxisRange)
self._adjustToNiceValues = Published(initialValue: adjustToNiceValues)
self._abbreviatesLabels = Published(initialValue: abbreviatesLabels)
self._isMagnitudedDisplayed = Published(initialValue: isMagnitudedDisplayed)
self._explicitMin = Published(initialValue: ChartUtility.cgfloatOptional(from: explicitMin))
self._explicitMax = Published(initialValue: ChartUtility.cgfloatOptional(from: explicitMax))
super.init(axisId: axisId, baseline: baseline, gridlines: gridlines, labels: labels, titleLabel: titleLabel, title: title)
}
public convenience init() {
self.init(axisId: nil, baseline: nil, gridlines: nil, labels: nil, titleLabel: nil, title: nil, isZeroBased: true, allowLooseLabels: false, fudgeAxisRange: false, adjustToNiceValues: true, abbreviatesLabels: false, isMagnitudedDisplayed: true, explicitMin: nil, explicitMax: nil, formatter: nil, abbreviatedFormatter: nil)
}
// swiftlint:disable force_cast
override public func copy(with zone: NSZone? = nil) -> Any {
let copy = ChartNumericAxisAttributes(axisId: axisId,
baseline: baseline.copy() as! ChartBaselineAttributes,
gridlines: gridlines.copy() as! ChartGridlineAttributes,
labels: labels.copy() as! ChartLabelAttributes,
titleLabel: titleLabel.copy() as! ChartLabelAttributes,
title: title,
isZeroBased: self.isZeroBased,
allowLooseLabels: self.allowLooseLabels,
fudgeAxisRange: self.fudgeAxisRange,
adjustToNiceValues: self.adjustToNiceValues,
abbreviatesLabels: self.abbreviatesLabels,
isMagnitudedDisplayed: self.isMagnitudedDisplayed,
explicitMin: ChartUtility.doubleOptional(from: self.explicitMin),
explicitMax: ChartUtility.doubleOptional(from: self.explicitMax),
formatter: self.formatter.copy() as? NumberFormatter,
abbreviatedFormatter: self.abbreviatedFormatter.copy() as? NumberFormatter)
return copy
}
func myCustomDesc(for nf: NumberFormatter) -> String {
"""
{
"NumberFormatter": {
"numberStyle": \(nf.numberStyle.rawValue),
"minimumFractionDigits": \(nf.minimumFractionDigits),
"maximumFractionDigits": \(nf.maximumFractionDigits)
}
}
"""
}
override public var description: String {
"""
{
"ChartNumericAxisAttributes": {
"baseline": \(String(describing: baseline)),
"gridlines": \(String(describing: gridlines)),
"labels": \(String(describing: labels)),
"titleLabel": \(String(describing: titleLabel)),
"title": "\(String(describing: title))",
"isZeroBased": \(self.isZeroBased),
"allowLooseLabels": \(self.allowLooseLabels),
"fudgeYAxisRange": \(self.fudgeAxisRange),
"adjustToNiceValues": \(self.adjustToNiceValues),
"abbreviatesLabels": \(self.abbreviatesLabels),
"isMagnitudedDisplayed": \(self.isMagnitudedDisplayed),
"explicitMin": "\(String(describing: self.explicitMin))",
"explicitMax": "\(String(describing: self.explicitMax))",
"formatter": \(self.myCustomDesc(for: self.formatter)),
"abbreviatedFormatter": \(self.myCustomDesc(for: self.abbreviatedFormatter))
}
}
"""
}
/**
Indicates whether the baseline starts at zero or the minimum value in the data set.
Applicable only to data sets with all positive, or all negative values, otherwise the baseline is always zero.
Default is true.
*/
@Published public var isZeroBased: Bool
/***
Allows labels to exceed the data range.
It is inconsistent when it comes to enabling it.
• ellipse - yes
• waterfall - yes
• stacked column - no
• line - no
• column - no
• combo - yes
*/
@Published var allowLooseLabels = false
/***
Flag that indicates wether the Y Axis should be adjusted to better fit the available space.
By default, all column based charts have this enabled and all line based don't.
*/
@Published var fudgeAxisRange = false
/***
Flag that indicates if we should adjust to nice values, or use the data
minimum and maximum to calculate the range.
Chart scale is adjusted so that gridlines (ticks) fall on "nice" values. Explicit min/max overrides this.
*/
@Published var adjustToNiceValues = true
/**
Formatter used for the axis gridline labels.
Defines the formatting for both extended and abbreviated states set through `ChartNumericAxis.abbreviatesLabels`.
Defaults to a localized decimal formatter.
*/
@Published public var formatter: NumberFormatter
/**
True if values will be abbreviated. For example, "1,234,567.89" to "1.23k". Default is true.
The `ChartNumericAxis.formatter` defines the formatting for both extended and abbreviated states.
*/
@Published public var abbreviatesLabels: Bool
/// True if the value's magnitude is included in abbreviated labels. For example, the "k" in "1.23k".
@Published public var isMagnitudedDisplayed: Bool
@Published public var abbreviatedFormatter: NumberFormatter
// override func labelForValue(_ value: Double) -> String? {
//
// return nil
// }
/**
Allows you to specify the minimum value for the axis, overriding the minimum value applied by the chart.
`explicitMin` and `explicitMax` override the data min and max range values presented in the `ChartNumericAxis`.
If the data minimum and maximum values are 0 and 100, the `ChartNumericAxis` will present the range between 0 and 100.
By setting `explicitMin` and `explicitMax` to -20 and 120, would have the `ChartNumericAxis` display a new range between -20 and 120.
Normally `explicitMin` and `explicitMax` are used when multiple charts share a context and should have the same axis ranges. Like in a trellis situation.
Default is nil.
*/
@Published public var explicitMin: CGFloat?
/**
Allows you to specify the maximum value for the axis, overriding the maximum value applied by the chart.
`explicitMin` and `explicitMax` override the data min and max range values presented in the `ChartNumericAxis`.
If the data minimum and maximum values are 0 and 100, the `ChartNumericAxis` will present the range between 0 and 100.
By setting `explicitMin` and `explicitMax` to -20 and 120, would have the `ChartNumericAxis` display a new range between -20 and 120.
Normally `explicitMin` and `explicitMax` are used when multiple charts share a context and should have the same axis ranges. Like in a trellis situation.
Default is nil.
*/
@Published public var explicitMax: CGFloat?
}
/**
Defines the policy used to determine which labels are presented along the horizontal category axis.
*/
public enum ChartCategoryAxisLabelLayoutStyle: CustomStringConvertible {
/**
The `allOrNothing` layout style will display all labels, or no labels when they cannot be presented without overlapping.
- Labels may be truncated to fit.
- A minimum gap between each label is enforced.
- All labels are center aligned beneath their respective point, column, cluster, etc.
This is the default layout mode.
*/
case allOrNothing
/**
The `range` layout style is intended for time series, or numeric ranges where horizontal space is limited.
Only labels for the first and last category members will be displayed.
- The first label is aligned to the left edge of the axis.
- The last label is aligned to the right edge of the axis.
*/
case range
public var description: String {
switch self {
case .allOrNothing:
return "allOrNothing"
case .range:
return "range"
}
}
}
/**
ChartCategoryAxis contains properties of the axes for categorical collections of values.
All chart types have at most a single category axis.
The position and orientation of the category axis depends on the chart type. For example:
- Bar charts display the category axis as the Y axis.
- Line, column, and combo charts display the category axis as the X axis.
*/
public class ChartCategoryAxisAttributes: ChartNumericAxisAttributes {
public init(axisId: ChartAxisId? = nil,
baseline: ChartBaselineAttributes? = nil,
gridlines: ChartGridlineAttributes? = nil,
labels: ChartLabelAttributes? = nil,
titleLabel: ChartLabelAttributes? = nil,
title: String? = nil,
isZeroBased: Bool = true,
allowLooseLabels: Bool = false,
fudgeAxisRange: Bool = false,
adjustToNiceValues: Bool = true,
abbreviatesLabels: Bool = true,
isMagnitudedDisplayed: Bool = true,
explicitMin: Double? = nil,
explicitMax: Double? = nil,
formatter: NumberFormatter?,
abbreviatedFormatter: NumberFormatter?,
labelLayoutStyle: ChartCategoryAxisLabelLayoutStyle)
{
self._labelLayoutStyle = Published(initialValue: labelLayoutStyle)
super.init(axisId: axisId, baseline: baseline, gridlines: gridlines, labels: labels, titleLabel: titleLabel, title: title, isZeroBased: isZeroBased, allowLooseLabels: allowLooseLabels, fudgeAxisRange: fudgeAxisRange, adjustToNiceValues: adjustToNiceValues, abbreviatesLabels: abbreviatesLabels, isMagnitudedDisplayed: isMagnitudedDisplayed, explicitMin: explicitMin, explicitMax: explicitMax, formatter: formatter, abbreviatedFormatter: abbreviatedFormatter)
}
public convenience init(labelLayoutStyle: ChartCategoryAxisLabelLayoutStyle) {
self.init(axisId: nil, baseline: nil, gridlines: nil, labels: nil, titleLabel: nil, title: nil, isZeroBased: false, allowLooseLabels: false, fudgeAxisRange: false, adjustToNiceValues: true, abbreviatesLabels: true, isMagnitudedDisplayed: true, explicitMin: nil, explicitMax: nil, formatter: nil, abbreviatedFormatter: nil, labelLayoutStyle: labelLayoutStyle)
}
public convenience init() {
self.init(labelLayoutStyle: .allOrNothing)
}
// swiftlint:disable force_cast
override public func copy(with zone: NSZone? = nil) -> Any {
let copy = ChartCategoryAxisAttributes(axisId: axisId,
baseline: baseline.copy() as! ChartBaselineAttributes,
gridlines: gridlines.copy() as! ChartGridlineAttributes,
labels: labels.copy() as! ChartLabelAttributes,
titleLabel: titleLabel.copy() as! ChartLabelAttributes,
title: title,
isZeroBased: isZeroBased,
allowLooseLabels: allowLooseLabels,
fudgeAxisRange: fudgeAxisRange,
adjustToNiceValues: adjustToNiceValues,
abbreviatesLabels: abbreviatesLabels,
isMagnitudedDisplayed: isMagnitudedDisplayed,
explicitMin: ChartUtility.doubleOptional(from: explicitMin),
explicitMax: ChartUtility.doubleOptional(from: explicitMax),
formatter: formatter.copy() as? NumberFormatter,
abbreviatedFormatter: abbreviatedFormatter.copy() as? NumberFormatter,
labelLayoutStyle: self.labelLayoutStyle)
return copy
}
override public var description: String {
"""
{
"ChartCategoryAxisAttributes": {
"baseline": \(String(describing: baseline)),
"gridlines": \(String(describing: gridlines)),
"labels": \(String(describing: labels)),
"titleLabel": \(String(describing: titleLabel)),
"title": "\(String(describing: title))",
"isZeroBased": \(isZeroBased),
"allowLooseLabels": \(allowLooseLabels),
"fudgeYAxisRange": \(fudgeAxisRange),
"adjustToNiceValues": \(adjustToNiceValues),
"abbreviatesLabels": \(abbreviatesLabels),
"isMagnitudedDisplayed": \(isMagnitudedDisplayed),
"explicitMin": "\(String(describing: explicitMin))",
"explicitMax": "\(String(describing: explicitMax))",
"formatter": \(myCustomDesc(for: formatter)),
"abbreviatedFormatter": \(myCustomDesc(for: abbreviatedFormatter)),
"labelLayoutStyle": "\(String(describing: self.labelLayoutStyle))"
}
}
"""
}
/// Defines the manner in which labels will be presented when they are provided by the data source, and not hidden.
@Published public var labelLayoutStyle: ChartCategoryAxisLabelLayoutStyle
}
extension ChartAxisAttributes: Equatable {
public static func == (lhs: ChartAxisAttributes, rhs: ChartAxisAttributes) -> Bool {
lhs.axisId == rhs.axisId &&
lhs.baseline == rhs.baseline &&
lhs.gridlines == rhs.gridlines &&
lhs.labels == rhs.labels &&
lhs.titleLabel == rhs.titleLabel &&
lhs.title == rhs.title
}
}
public extension ChartNumericAxisAttributes {
/// conform to Equatable
static func == (lhs: ChartNumericAxisAttributes, rhs: ChartNumericAxisAttributes) -> Bool {
lhs.axisId == rhs.axisId &&
lhs.baseline == rhs.baseline &&
lhs.gridlines == rhs.gridlines &&
lhs.labels == rhs.labels &&
lhs.titleLabel == rhs.titleLabel &&
lhs.title == rhs.title &&
lhs.isZeroBased == rhs.isZeroBased &&
lhs.abbreviatesLabels == rhs.abbreviatesLabels &&
lhs.isMagnitudedDisplayed == rhs.isMagnitudedDisplayed &&
lhs.explicitMin == rhs.explicitMin &&
lhs.explicitMax == rhs.explicitMax // &&
// lhs.formatter == rhs.formatter &&
// lhs.abbreviatedFormatter == rhs.abbreviatedFormatter
}
}
public extension ChartCategoryAxisAttributes {
/// conform to Equatable
static func == (lhs: ChartCategoryAxisAttributes, rhs: ChartCategoryAxisAttributes) -> Bool {
lhs.axisId == rhs.axisId &&
lhs.baseline == rhs.baseline &&
lhs.gridlines == rhs.gridlines &&
lhs.labels == rhs.labels &&
lhs.titleLabel == rhs.titleLabel &&
lhs.title == rhs.title &&
lhs.isZeroBased == rhs.isZeroBased &&
lhs.abbreviatesLabels == rhs.abbreviatesLabels &&
lhs.isMagnitudedDisplayed == rhs.isMagnitudedDisplayed &&
lhs.explicitMin == rhs.explicitMin &&
lhs.explicitMax == rhs.explicitMax &&
// lhs.formatter == rhs.formatter &&
// lhs.abbreviatedFormatter == rhs.abbreviatedFormatter &&
lhs.labelLayoutStyle == rhs.labelLayoutStyle
}
}
| 44.752 | 466 | 0.611834 |
f90fdda03dc82e2ce03953a878ef312c423e6c5c | 28,030 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=SWIFT_COMPLETIONS | %FileCheck %s -check-prefix=SWIFT_COMPLETIONS
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=FW_UNQUAL_1 > %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO_SUB < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO_HELPER < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO_HELPER_SUB < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_BAR < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_BOTH_FOO_BAR < %t.compl.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_QUAL_FOO_1 > %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO_SUB < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_QUAL_FOO_NEGATIVE < %t.compl.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_QUAL_BAR_1 > %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_QUAL_BAR_1 < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_BAR < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_QUAL_BAR_NEGATIVE < %t.compl.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_QUAL_FOO_2 | %FileCheck %s -check-prefix=CLANG_QUAL_FOO_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=FUNCTION_CALL_1 | %FileCheck %s -check-prefix=FUNCTION_CALL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=FUNCTION_CALL_2 | %FileCheck %s -check-prefix=FUNCTION_CALL_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_STRUCT_MEMBERS_1 | %FileCheck %s -check-prefix=CLANG_STRUCT_MEMBERS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_CLASS_MEMBERS_1 | %FileCheck %s -check-prefix=CLANG_CLASS_MEMBERS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_CLASS_MEMBERS_2 | %FileCheck %s -check-prefix=CLANG_CLASS_MEMBERS_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_INSTANCE_MEMBERS_1 | %FileCheck %s -check-prefix=CLANG_INSTANCE_MEMBERS_1
import Foo
// Don't import FooHelper directly in this test!
// import FooHelper
// Framework 'Foo' re-exports the 'FooHelper' framework. Make sure that we get
// completion results for both frameworks.
import Bar
struct SwiftStruct {
var instanceVar : Int
}
// Test that we don't include Clang completions in unexpected places.
func testSwiftCompletions(foo: SwiftStruct) {
foo.#^SWIFT_COMPLETIONS^#
// SWIFT_COMPLETIONS: Begin completions
// SWIFT_COMPLETIONS-NEXT: Keyword[self]/CurrNominal: self[#SwiftStruct#]; name=self
// SWIFT_COMPLETIONS-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// SWIFT_COMPLETIONS-NEXT: End completions
}
// CLANG_FOO: Begin completions
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooEnum1[#FooEnum1#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum1X[#FooEnum1#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooEnum2[#FooEnum2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum2X[#FooEnum2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum2Y[#FooEnum2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooEnum3[#FooEnum3#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum3X[#FooEnum3#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum3Y[#FooEnum3#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Enum]/OtherModule[Foo]: FooComparisonResult[#FooComparisonResult#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooRuncingOptions[#FooRuncingOptions#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooStruct1[#FooStruct1#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooStruct2[#FooStruct2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[TypeAlias]/OtherModule[Foo]: FooStructTypedef1[#FooStruct2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooStructTypedef2[#FooStructTypedef2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[TypeAlias]/OtherModule[Foo]: FooTypedef1[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: fooIntVar[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFunc1AnonymousParam({#Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFunc3({#(a): Int32#}, {#(b): Float#}, {#(c): Double#}, {#(d): UnsafeMutablePointer<Int32>!#})[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithBlock({#(blk): ((Float) -> Int32)!##(Float) -> Int32#})[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment1()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment2()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment3()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment4()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment5()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Protocol]/OtherModule[Foo]: FooProtocolBase[#FooProtocolBase#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Protocol]/OtherModule[Foo]: FooProtocolDerived[#FooProtocolDerived#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Class]/OtherModule[Foo]: FooClassBase[#FooClassBase#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Class]/OtherModule[Foo]: FooClassDerived[#FooClassDerived#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_1[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_2[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_3[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_4[#UInt32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_5[#UInt64#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_REDEF_1[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_REDEF_2[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: theLastDeclInFoo()[#Void#]{{; name=.+$}}
// CLANG_FOO: End completions
// CLANG_FOO_SUB: Begin completions
// CLANG_FOO_SUB-DAG: Decl[FreeFunction]/OtherModule[Foo.FooSub]: fooSubFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO_SUB-DAG: Decl[Struct]/OtherModule[Foo.FooSub]: FooSubEnum1[#FooSubEnum1#]{{; name=.+$}}
// CLANG_FOO_SUB-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: FooSubEnum1X[#FooSubEnum1#]{{; name=.+$}}
// CLANG_FOO_SUB-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: FooSubEnum1Y[#FooSubEnum1#]{{; name=.+$}}
// CLANG_FOO_SUB-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: FooSubUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_FOO_SUB: End completions
// CLANG_FOO_HELPER: Begin completions
// CLANG_FOO_HELPER-DAG: Decl[FreeFunction]/OtherModule[FooHelper]: fooHelperFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO_HELPER-DAG: Decl[GlobalVar]/OtherModule[FooHelper]: FooHelperUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_FOO_HELPER-DAG: Decl[GlobalVar]/OtherModule[FooHelper]: FooHelperUnnamedEnumeratorA2[#Int#]{{; name=.+$}}
// CLANG_FOO_HELPER: End completions
// CLANG_FOO_HELPER_SUB: Begin completions
// CLANG_FOO_HELPER_SUB-DAG: Decl[FreeFunction]/OtherModule[FooHelper.FooHelperSub]: fooHelperSubFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB-DAG: Decl[Struct]/OtherModule[FooHelper.FooHelperSub]: FooHelperSubEnum1[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: FooHelperSubEnum1X[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: FooHelperSubEnum1Y[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: FooHelperSubUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB: End completions
// CLANG_BAR: Begin completions
// CLANG_BAR-DAG: Decl[FreeFunction]/OtherModule[Bar]: barFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[Class]/OtherModule[Bar]: BarForwardDeclaredClass[#BarForwardDeclaredClass#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[Struct]/OtherModule[Bar]: BarForwardDeclaredEnum[#BarForwardDeclaredEnum#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[GlobalVar]/OtherModule[Bar]: BarForwardDeclaredEnumValue[#BarForwardDeclaredEnum#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[GlobalVar]/OtherModule[Bar]: BAR_MACRO_1[#Int32#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[Struct]/OtherModule[Bar]: SomeItemSet[#SomeItemSet#]
// CLANG_BAR-DAG: Decl[TypeAlias]/OtherModule[Bar]: SomeEnvironment[#SomeItemSet#]
// CLANG_BAR: End completions
// CLANG_BOTH_FOO_BAR: Begin completions
// CLANG_BOTH_FOO_BAR-DAG: Decl[FreeFunction]/OtherModule[{{(Foo|Bar)}}]: redeclaredInMultipleModulesFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_BOTH_FOO_BAR: End completions
// CLANG_QUAL_FOO_NEGATIVE-NOT: bar
// CLANG_QUAL_FOO_NEGATIVE-NOT: :{{.*}}Bar
// CLANG_QUAL_FOO_NEGATIVE-NOT: BAR
// CLANG_QUAL_BAR_NEGATIVE-NOT: foo
// CLANG_QUAL_BAR_NEGATIVE-NOT: :{{.*}}Foo
// CLANG_QUAL_BAR_NEGATIVE-NOT: FOO
func testClangModule() {
#^FW_UNQUAL_1^#
}
func testCompleteModuleQualifiedFoo1() {
Foo.#^CLANG_QUAL_FOO_1^#
}
func testCompleteModuleQualifiedFoo2() {
Foo#^CLANG_QUAL_FOO_2^#
// If the number of results below changes, then you need to add a result to the
// list below.
// CLANG_QUAL_FOO_2: Begin completions, 76 items
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooClassBase[#FooClassBase#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooClassDerived[#FooClassDerived#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .ClassWithInternalProt[#ClassWithInternalProt#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: ._InternalStruct[#_InternalStruct#]
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooClassPropertyOwnership[#FooClassPropertyOwnership#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: ._internalTopLevelFunc()[#Void#]
// CLANG_QUAL_FOO_2-DAG: Decl[Enum]/OtherModule[Foo]: .FooComparisonResult[#FooComparisonResult#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFunc1AnonymousParam({#Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFunc3({#(a): Int32#}, {#(b): Float#}, {#(c): Double#}, {#(d): UnsafeMutablePointer<Int32>!#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncNoreturn1()[#Never#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncNoreturn2()[#Never#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithBlock({#(blk): ((Float) -> Int32)!##(Float) -> Int32#})[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithFunctionPointer({#(fptr): ((Float) -> Int32)!##(Float) -> Int32#})[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment1()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment2()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment3()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment4()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment5()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[FooHelper]: .fooHelperFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[FooHelper.FooHelperSub]: .fooHelperSubFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo.FooSub]: .fooSubFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[{{(Foo|Bar)}}]: .redeclaredInMultipleModulesFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .theLastDeclInFoo()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_1[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_2[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_3[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_4[#UInt32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_5[#UInt64#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_6[#typedef_int_t#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_7[#typedef_int_t#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_OR[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_AND[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_REDEF_1[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_REDEF_2[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum1X[#FooEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum2X[#FooEnum2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum2Y[#FooEnum2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum3X[#FooEnum3#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum3Y[#FooEnum3#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: .FooHelperSubEnum1X[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: .FooHelperSubEnum1Y[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: .FooHelperSubUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper]: .FooHelperUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper]: .FooHelperUnnamedEnumeratorA2[#Int#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: .FooSubEnum1X[#FooSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: .FooSubEnum1Y[#FooSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: .FooSubUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .fooIntVar[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Protocol]/OtherModule[Foo]: ._InternalProt[#_InternalProt#]
// CLANG_QUAL_FOO_2-DAG: Decl[Protocol]/OtherModule[Foo]: .FooProtocolBase[#FooProtocolBase#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Protocol]/OtherModule[Foo]: .FooProtocolDerived[#FooProtocolDerived#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooEnum1[#FooEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooEnum2[#FooEnum2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooEnum3[#FooEnum3#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[FooHelper.FooHelperSub]: .FooHelperSubEnum1[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooRuncingOptions[#FooRuncingOptions#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooStruct1[#FooStruct1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooStruct2[#FooStruct2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooStructTypedef2[#FooStructTypedef2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo.FooSub]: .FooSubEnum1[#FooSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[TypeAlias]/OtherModule[Foo]: .FooStructTypedef1[#FooStruct2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooUnavailableMembers[#FooUnavailableMembers#]
// CLANG_QUAL_FOO_2-DAG: Decl[TypeAlias]/OtherModule[Foo]: .FooTypedef1[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooCFType[#FooCFType#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooRepeatedMembers[#FooRepeatedMembers#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooClassWithClassProperties[#FooClassWithClassProperties#];
// CLANG_QUAL_FOO_2-DAG: Decl[Enum]/OtherModule[Foo]: .SCNFilterMode[#SCNFilterMode#];
// CLANG_QUAL_FOO_2: End completions
}
func testCompleteModuleQualifiedBar1() {
Bar.#^CLANG_QUAL_BAR_1^#
// If the number of results below changes, this is an indication that you need
// to add a result to the appropriate list. Do not just bump the number!
// CLANG_QUAL_BAR_1: Begin completions, 8 items
}
func testCompleteFunctionCall1() {
fooFunc1#^FUNCTION_CALL_1^#
// FUNCTION_CALL_1: Begin completions
// FUNCTION_CALL_1-NEXT: Decl[FreeFunction]/OtherModule[Foo]: ({#(a): Int32#})[#Int32#]{{; name=.+$}}
// FUNCTION_CALL_1-NEXT: Keyword[self]/CurrNominal: .self[#(Int32) -> Int32#]; name=self
// FUNCTION_CALL_1-NEXT: End completions
}
func testCompleteFunctionCall2() {
fooFunc1AnonymousParam#^FUNCTION_CALL_2^#
// FUNCTION_CALL_2: Begin completions
// FUNCTION_CALL_2-NEXT: Decl[FreeFunction]/OtherModule[Foo]: ({#Int32#})[#Int32#]{{; name=.+$}}
// FUNCTION_CALL_2-NEXT: Keyword[self]/CurrNominal: .self[#(Int32) -> Int32#]; name=self
// FUNCTION_CALL_2-NEXT: End completions
}
func testCompleteStructMembers1() {
FooStruct1#^CLANG_STRUCT_MEMBERS_1^#
// CLANG_STRUCT_MEMBERS_1: Begin completions
// CLANG_STRUCT_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ()[#FooStruct1#]{{; name=.+$}}
// CLANG_STRUCT_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ({#x: Int32#}, {#y: Double#})[#FooStruct1#]{{; name=.+$}}
// CLANG_STRUCT_MEMBERS_1-NEXT: Keyword[self]/CurrNominal: .self[#FooStruct1.Type#]; name=self
// CLANG_STRUCT_MEMBERS_1-NEXT: Keyword/CurrNominal: .Type[#FooStruct1.Type#]; name=Type
// CLANG_STRUCT_MEMBERS_1-NEXT: End completions
}
func testCompleteClassMembers1() {
FooClassBase#^CLANG_CLASS_MEMBERS_1^#
// FIXME: do we want to show curried instance functions for Objective-C classes?
// CLANG_CLASS_MEMBERS_1: Begin completions
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .fooBaseInstanceFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFunc0({#(self): FooClassBase#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .fooBaseInstanceFunc1({#(anObject): Any!#})[#FooClassBase!#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFunc1({#(self): FooClassBase#})[#(Any?) -> FooClassBase?#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ()[#FooClassBase!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ({#float: Float#})[#FooClassBase!#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .fooBaseInstanceFuncOverridden()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFuncOverridden({#(self): FooClassBase#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .fooBaseClassFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ({#(x): Int32#})[#FooClassBase!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: ._internalMeth3()[#Any!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: ._internalMeth3({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: ._internalMeth2()[#Any!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: ._internalMeth2({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .nonInternalMeth()[#Any!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .nonInternalMeth({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: ._internalMeth1()[#Any!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: ._internalMeth1({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_1-NEXT: Keyword[self]/CurrNominal: .self[#FooClassBase.Type#]; name=self
// CLANG_CLASS_MEMBERS_1-NEXT: Keyword/CurrNominal: .Type[#FooClassBase.Type#]; name=Type
// CLANG_CLASS_MEMBERS_1-NEXT: End completions
}
func testCompleteClassMembers2() {
FooClassDerived#^CLANG_CLASS_MEMBERS_2^#
// CLANG_CLASS_MEMBERS_2: Begin completions
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(self): FooClassDerived#})[#(Int32) -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc2({#(self): FooClassDerived#})[#(Int32, withB: Int32) -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFuncOverridden({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/CurrNominal: .fooClassFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[Constructor]/CurrNominal: ()[#FooClassDerived!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[Constructor]/CurrNominal: ({#float: Float#})[#FooClassDerived!#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFunc({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFuncWithExtraIndentation1({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFuncWithExtraIndentation2({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/CurrNominal: .fooProtoClassFunc()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .fooBaseInstanceFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: .fooBaseInstanceFunc0({#(self): FooClassBase#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .fooBaseInstanceFunc1({#(anObject): Any!#})[#FooClassBase!#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: .fooBaseInstanceFunc1({#(self): FooClassBase#})[#(Any?) -> FooClassBase?#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .fooBaseInstanceFuncOverridden()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .fooBaseClassFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: ._internalMeth3()[#Any!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: ._internalMeth3({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: ._internalMeth2()[#Any!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: ._internalMeth2({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .nonInternalMeth()[#Any!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: .nonInternalMeth({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: ._internalMeth1()[#Any!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: ._internalMeth1({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_2-NEXT: Keyword[self]/CurrNominal: .self[#FooClassDerived.Type#]; name=self
// CLANG_CLASS_MEMBERS_2-NEXT: Keyword/CurrNominal: .Type[#FooClassDerived.Type#]; name=Type
// CLANG_CLASS_MEMBERS_2-NEXT: End completions
}
func testCompleteInstanceMembers1(fooObject: FooClassDerived) {
fooObject#^CLANG_INSTANCE_MEMBERS_1^#
// CLANG_INSTANCE_MEMBERS_1: Begin completions
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooProperty1[#Int32#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooProperty2[#Int32#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooProperty3[#Int32#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(a): Int32#})[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc2({#(a): Int32#}, {#withB: Int32#})[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFuncOverridden()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFunc()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFuncWithExtraIndentation1()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFuncWithExtraIndentation2()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: .fooBaseInstanceFunc0()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: .fooBaseInstanceFunc1({#(anObject): Any!#})[#FooClassBase!#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: ._internalMeth3()[#Any!#]
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: ._internalMeth2()[#Any!#]
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: .nonInternalMeth()[#Any!#]
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: ._internalMeth1()[#Any!#]
// CLANG_INSTANCE_MEMBERS_1-NOT: Instance
}
| 83.671642 | 213 | 0.711488 |
8fbfefe0ac438d43b59771cfd82dd7eb135fb6a9 | 237 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{{{
struct A{struct B
}}}
}func e{let a{
struct a
{
class
case c,
{
| 16.928571 | 87 | 0.721519 |
e9a536488962a9cfebda283a7bf3d521ccb0d315 | 2,133 | //
// ViewController.swift
// FoodyCrawler
//
// Created by Cole Doan on 10/17/17.
// Copyright © 2017 Trong Cuong Doan. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet fileprivate weak var button: NSButton!
@IBOutlet fileprivate weak var foodyAuthUDIDTextField: NSTextField!
@IBOutlet fileprivate weak var foodyAuthTextField: NSTextField!
@IBOutlet fileprivate weak var cityComboBox: CityComboBox!
private var service: ApplicationService = DefaultApplicationService()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
button.target = self
button.action = #selector(crawl)
foodyAuthUDIDTextField.becomeFirstResponder()
}
func crawl() {
let udid = foodyAuthUDIDTextField.stringValue
let auth = foodyAuthTextField.stringValue
let cityComboBoxSelectedIndex = cityComboBox.indexOfSelectedItem
if cityComboBoxSelectedIndex == -1 {
showAlert(title: "Invalid City!!!", message: "You must select a valid city to crawl.", style: .warning)
return
}
if udid.isEmpty || auth.isEmpty {
showAlert(title: "Argument Missing!!!", message: "You must provide UDID and Auth!!!", style: .warning)
return
}
let city = Cities.allCities[cityComboBoxSelectedIndex]
service.crawl(foodyAuthUDID: udid, foodyAuth: auth, city: city) { [weak self] result in
guard let `self` = self else { return }
switch result {
case .failure(let error):
self.showAlert(title: "Crawl Failed!!!", message: error.localizedDescription, style: .warning)
case .success:
self.showAlert(title: "Crawl Successfully!!!", message: "Successfully crawl foody data", style: .informational)
}
}
}
}
extension NSViewController {
func showAlert(title: String, message: String, style: NSAlertStyle) {
let alert = NSAlert()
alert.messageText = title
alert.informativeText = message
alert.addButton(withTitle: "OK")
alert.alertStyle = style
alert.beginSheetModal(for: self.view.window!, completionHandler: nil)
}
}
| 31.835821 | 119 | 0.707923 |
7a095ecf257c1d4c8a46073c44c9e4c530b77166 | 848 | //
// Copyright 2019, 2021, Optimizely, Inc. and contributors
//
// 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.
//
/// Do not edit this field.
/// - It is auto updated (Scripts/updated_version.sh) to reflect the current version
/// - Do not put underscores in the name (Swiftlint can modify unexpectedly)
let OPTIMIZELYSDKVERSION = "3.7.0"
| 40.380952 | 84 | 0.740566 |
482f606cbd073a8b2d1c778ad07125df129bf618 | 11,378 | //
// NativeTokenGrpcViewController.swift
// Cosmostation
//
// Created by 정용주 on 2021/08/20.
// Copyright © 2021 wannabit. All rights reserved.
//
import UIKit
class NativeTokenGrpcViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
@IBOutlet weak var naviTokenImg: UIImageView!
@IBOutlet weak var naviTokenSymbol: UILabel!
@IBOutlet weak var naviPerPrice: UILabel!
@IBOutlet weak var naviUpdownPercent: UILabel!
@IBOutlet weak var naviUpdownImg: UIImageView!
@IBOutlet weak var topCard: CardView!
@IBOutlet weak var topKeyState: UIImageView!
@IBOutlet weak var topDpAddress: UILabel!
@IBOutlet weak var topValue: UILabel!
@IBOutlet weak var tokenTableView: UITableView!
@IBOutlet weak var btnBepSend: UIButton!
@IBOutlet weak var btnIbcSend: UIButton!
@IBOutlet weak var btnSend: UIButton!
var nativeDenom = ""
var nativeDivideDecimal: Int16 = 6
var nativeDisplayDecimal: Int16 = 6
var totalAmount = NSDecimalNumber.zero
override func viewDidLoad() {
super.viewDidLoad()
self.account = BaseData.instance.selectAccountById(id: BaseData.instance.getRecentAccountId())
self.chainType = WUtils.getChainType(account!.account_base_chain)
self.tokenTableView.delegate = self
self.tokenTableView.dataSource = self
self.tokenTableView.separatorStyle = UITableViewCell.SeparatorStyle.none
self.tokenTableView.register(UINib(nibName: "TokenDetailNativeCell", bundle: nil), forCellReuseIdentifier: "TokenDetailNativeCell")
self.tokenTableView.register(UINib(nibName: "TokenDetailVestingDetailCell", bundle: nil), forCellReuseIdentifier: "TokenDetailVestingDetailCell")
self.tokenTableView.register(UINib(nibName: "NewHistoryCell", bundle: nil), forCellReuseIdentifier: "NewHistoryCell")
let tapTotalCard = UITapGestureRecognizer(target: self, action: #selector(self.onClickActionShare))
self.topCard.addGestureRecognizer(tapTotalCard)
if (ChainType.isHtlcSwappableCoin(chainType, nativeDenom)) {
self.btnBepSend.isHidden = false
} else {
self.btnIbcSend.isHidden = false
}
self.onInitView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
@objc func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func onInitView() {
if (chainType == ChainType.OSMOSIS_MAIN) {
WUtils.DpOsmosisTokenName(naviTokenSymbol, nativeDenom)
WUtils.DpOsmosisTokenImg(naviTokenImg, nativeDenom)
if (nativeDenom == OSMOSIS_ION_DENOM) {
nativeDivideDecimal = 6
nativeDisplayDecimal = 6
totalAmount = BaseData.instance.getAvailableAmount_gRPC(nativeDenom)
}
} else if (chainType == ChainType.EMONEY_MAIN) {
naviTokenSymbol.text = nativeDenom.uppercased()
naviTokenImg.af_setImage(withURL: URL(string: EMONEY_COIN_IMG_URL + nativeDenom + ".png")!)
nativeDivideDecimal = 6
nativeDisplayDecimal = 6
totalAmount = BaseData.instance.getAvailableAmount_gRPC(nativeDenom)
} else if (chainType == ChainType.KAVA_MAIN) {
WUtils.DpKavaTokenName(naviTokenSymbol, nativeDenom)
naviTokenImg.af_setImage(withURL: URL(string: WUtils.getKavaCoinImg(nativeDenom))!)
nativeDivideDecimal = WUtils.getKavaCoinDecimal(nativeDenom)
nativeDisplayDecimal = WUtils.getKavaCoinDecimal(nativeDenom)
totalAmount = WUtils.getKavaTokenAll(nativeDenom)
} else if (chainType == ChainType.CRESCENT_MAIN || chainType == ChainType.CRESCENT_TEST) {
if (nativeDenom == CRESCENT_BCRE_DENOM) {
naviTokenSymbol.text = nativeDenom.uppercased()
naviTokenImg.image = UIImage(named: "tokenBcre")
nativeDivideDecimal = 6
nativeDisplayDecimal = 6
totalAmount = BaseData.instance.getAvailableAmount_gRPC(nativeDenom)
}
}
self.naviPerPrice.attributedText = WUtils.dpPerUserCurrencyValue(nativeDenom, naviPerPrice.font)
self.naviUpdownPercent.attributedText = WUtils.dpValueChange(nativeDenom, font: naviUpdownPercent.font)
let changeValue = WUtils.valueChange(nativeDenom)
if (changeValue.compare(NSDecimalNumber.zero).rawValue > 0) { naviUpdownImg.image = UIImage(named: "priceUp") }
else if (changeValue.compare(NSDecimalNumber.zero).rawValue < 0) { naviUpdownImg.image = UIImage(named: "priceDown") }
else { naviUpdownImg.image = nil }
self.topCard.backgroundColor = WUtils.getChainBg(chainType)
if (account?.account_has_private == true) {
self.topKeyState.image = topKeyState.image?.withRenderingMode(.alwaysTemplate)
self.topKeyState.tintColor = WUtils.getChainColor(chainType)
}
self.topDpAddress.text = account?.account_address
self.topDpAddress.adjustsFontSizeToFitWidth = true
self.topValue.attributedText = WUtils.dpUserCurrencyValue(nativeDenom, totalAmount, nativeDivideDecimal, topValue.font)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return 1
} else if (section == 1) {
if (BaseData.instance.onParseRemainVestingsByDenom_gRPC(nativeDenom).count > 0) { return 1 }
else { return 0 }
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier:"TokenDetailNativeCell") as? TokenDetailNativeCell
cell?.onBindNativeToken(chainType, nativeDenom)
return cell!
} else if (indexPath.section == 1) {
let cell = tableView.dequeueReusableCell(withIdentifier:"TokenDetailVestingDetailCell") as? TokenDetailVestingDetailCell
cell?.onBindVestingToken(chainType!, nativeDenom)
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier:"NewHistoryCell") as? NewHistoryCell
return cell!
}
}
@objc func onClickActionShare() {
self.shareAddress(account!.account_address, WUtils.getWalletName(account))
}
@IBAction func onClickBack(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func onClickIbcSend(_ sender: UIButton) {
if (!account!.account_has_private) {
self.onShowAddMenomicDialog()
return
}
let stakingDenom = WUtils.getMainDenom(chainType)
let feeAmount = WUtils.getEstimateGasFeeAmount(chainType!, TASK_IBC_TRANSFER, 0)
if (BaseData.instance.getAvailableAmount_gRPC(stakingDenom).compare(feeAmount).rawValue <= 0) {
self.onShowToast(NSLocalizedString("error_not_enough_balance_to_send", comment: ""))
return
}
self.onAlertIbcTransfer()
}
func onAlertIbcTransfer() {
let unAuthTitle = NSLocalizedString("str_notice", comment: "")
let unAuthMsg = NSLocalizedString("str_msg_ibc", comment: "")
let noticeAlert = UIAlertController(title: unAuthTitle, message: unAuthMsg, preferredStyle: .alert)
noticeAlert.addAction(UIAlertAction(title: NSLocalizedString("continue", comment: ""), style: .default, handler: { _ in
self.onStartIbc()
}))
self.present(noticeAlert, animated: true) {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissAlertController))
noticeAlert.view.superview?.subviews[0].addGestureRecognizer(tapGesture)
}
}
func onStartIbc() {
let txVC = UIStoryboard(name: "GenTx", bundle: nil).instantiateViewController(withIdentifier: "TransactionViewController") as! TransactionViewController
txVC.mIBCSendDenom = nativeDenom
txVC.mType = TASK_IBC_TRANSFER
txVC.hidesBottomBarWhenPushed = true
self.navigationItem.title = ""
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false;
self.navigationController?.pushViewController(txVC, animated: true)
}
@IBAction func onClickSend(_ sender: UIButton) {
if (!account!.account_has_private) {
self.onShowAddMenomicDialog()
return
}
let stakingDenom = WUtils.getMainDenom(chainType)
let feeAmount = WUtils.getEstimateGasFeeAmount(chainType!, COSMOS_MSG_TYPE_TRANSFER2, 0)
if (BaseData.instance.getAvailableAmount_gRPC(stakingDenom).compare(feeAmount).rawValue <= 0) {
self.onShowToast(NSLocalizedString("error_not_enough_balance_to_send", comment: ""))
return
}
let txVC = UIStoryboard(name: "GenTx", bundle: nil).instantiateViewController(withIdentifier: "TransactionViewController") as! TransactionViewController
txVC.mToSendDenom = nativeDenom
txVC.mType = COSMOS_MSG_TYPE_TRANSFER2
txVC.hidesBottomBarWhenPushed = true
self.navigationItem.title = ""
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false;
self.navigationController?.pushViewController(txVC, animated: true)
}
@IBAction func onClickBepSend(_ sender: Any) {
if (!SUPPORT_BEP3_SWAP) {
self.onShowToast(NSLocalizedString("error_bep3_swap_temporary_disable", comment: ""))
return
}
if (!account!.account_has_private) {
self.onShowAddMenomicDialog()
return
}
let stakingDenom = WUtils.getMainDenom(chainType)
let feeAmount = WUtils.getEstimateGasFeeAmount(chainType!, TASK_TYPE_HTLC_SWAP, 0)
if (BaseData.instance.getAvailableAmount_gRPC(stakingDenom).compare(feeAmount).rawValue <= 0) {
self.onShowToast(NSLocalizedString("error_not_enough_balance_to_send", comment: ""))
return
}
let txVC = UIStoryboard(name: "GenTx", bundle: nil).instantiateViewController(withIdentifier: "TransactionViewController") as! TransactionViewController
txVC.mType = TASK_TYPE_HTLC_SWAP
txVC.mHtlcDenom = nativeDenom
txVC.hidesBottomBarWhenPushed = true
self.navigationItem.title = ""
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false;
self.navigationController?.pushViewController(txVC, animated: true)
}
}
| 45.694779 | 160 | 0.677008 |
e8e6e5559edfd3c1ceedc5ffbe775c0e8d363f4f | 4,358 | //
// LinkedDocChooser.swift
// TruTracePOC
//
// Created by Republic Systems on 2020-01-11.
// Copyright © 2020 Republic Systems. All rights reserved.
//
import SwiftUI
struct LinkedDocChoser: View {
@EnvironmentObject var viewRouter: ViewRouter
@EnvironmentObject var sessionData: SessionData
var documentCard : DocumentDTO
@State private var selectedRows = Set<Int>()
var body: some View {
NavigationView {
VStack {
List(self.sessionData.allLinkable, selection: $selectedRows) { doc in
LinkedDocPreviewDetail(documentCard : doc)
}
.navigationBarItems(trailing : EditButton())
.navigationBarTitle(Text("Linked Docs (\(self.listAll()))"), displayMode: .inline)
}
}.onAppear(perform: loadLinkedDocData)
.onDisappear(perform: setChosenLinkedDocs)
}
func listAll() -> String{
//self.setChosenRecipients()
return String(selectedRows.count)
}
func getLinkedDocForId(id: Int) -> DocumentDTO {
for item in self.sessionData.allLinkable {
if(item.id == id){
return item
}
}
return DocumentDTO()
}
//
// Load all recipients
//
func loadLinkedDocData() {
guard let url = URL(string:
(sessionData.serverURL + RESTServer.REST_GET_LINKABLE_DOCS_FRO_USER_ALL))
else {
print("invalid URL")
return
}
var request = URLRequest(url : url)
request.httpMethod = "GET"
request.setValue(sessionData.userCredentials.username, forHTTPHeaderField: "user-name")
URLSession.shared.dataTask(with: request) {
(data, response, error) in
guard let data = data else { return }
let decodedResponse = try! JSONDecoder().decode([DocumentDTO].self, from: data)
DispatchQueue.main.async {
print("Document Data Response --> \(decodedResponse)")
self.sessionData.allLinkable = decodedResponse
print("Number of Recipients : \(self.sessionData.allLinkable.count)")
//
// Set chosen Recipients
for item in self.getDocument().linkedDocuments{
self.selectedRows.insert(item.id)
}
print("Number of Selected Docs <card> : \(self.getDocument().linkedDocuments.count)")
print("Number of Selected Docs : \(self.selectedRows.count)")
}
}.resume()
}
func getDocument() -> DocumentDTO{
if let index = sessionData.myDocumentList.firstIndex(of: documentCard) {
return sessionData.myDocumentList[index]
}
if sessionData.newWorkDocumentFlag == true { return sessionData.newWorkDocument }
return DocumentDTO()
}
func setChosenLinkedDocs(){
var myDocs = [DocumentDTO]()
for item in selectedRows {
print(item)
myDocs.append(self.getLinkedDocForId(id: item))
}
if let index = sessionData.myDocumentList.firstIndex(of: documentCard) {
sessionData.myDocumentList[index].linkedDocuments = myDocs
}
if sessionData.newWorkDocumentFlag == true { sessionData.newWorkDocument.linkedDocuments = myDocs}
}
}
struct LinkedDocChoser_Previews: PreviewProvider {
static var previews: some View {
LinkedDocChoser(documentCard : DocumentDTO())
.environmentObject(ViewRouter())
.environmentObject(SessionData())
}
}
struct LinkedDocPreviewDetail: View {
var documentCard : DocumentDTO
var body: some View {
NavigationLink(destination: FeedDocumentDetails(documentCard: self.documentCard)){
HStack {
VStack {
Text(documentCard.owner)
.font(.title)
.fontWeight(.bold)
Text(documentCard.documentType)
.font(.footnote)
.fontWeight(.regular)
}
}
}
}
}
| 32.044118 | 107 | 0.564938 |
181a9e68588da1826d635ffaf78172d16907f058 | 552 | //
// ViewController.swift
// ioscourse
//
// Created by Jakov Mestrovic on 01/11/2016.
// Copyright © 2016 InVita d.o.o. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("Hello World!")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.714286 | 80 | 0.648551 |
26e1f397c967d494a72bd0a76b02fd7d95b95bee | 790 | //
// PreworkUITestsLaunchTests.swift
// PreworkUITests
//
// Created by Anna S on 1/31/22.
//
import XCTest
class PreworkUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 23.939394 | 88 | 0.66962 |
e539bf07dfad251209d66a57ec56086a9b00fd54 | 1,884 | //
// TextLanguageType.swift
// Universe_Docs_View
//
// Created by Kumar Muthaiah on 31/10/18.
//
//Copyright 2020 Kumar Muthaiah
//
//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
public class UVCTextLanguageType {
static public var None = UVCTextLanguageType("uvcTextLanguageType.None", "None")
static public var English = UVCTextLanguageType("uvcTextLanguageType.English", "English")
static public var Tamil = UVCTextLanguageType("uvcTextLanguageType.Tamil", "Tamil")
static public var Hindi = UVCTextLanguageType("uvcTextLanguageType.Hindi", "Hindi")
static public var Bengali = UVCTextLanguageType("uvcTextLanguageType.Bengali", "Bengali")
public var name: String = ""
public var description: String = ""
private init(_ name: String, _ description: String) {
self.name = name
self.description = description
}
}
| 60.774194 | 462 | 0.7638 |
16e104613e7a5d87163ca4b6fbd12ee0dae5fe3c | 222 | import SwiftIO
var arguments = CommandLine.arguments.dropFirst().makeIterator()
guard let command = arguments.next() else {
errorPrint("fatal: No arguments")
exit(.EX_USAGE)
}
try exec(command, arguments: arguments)
| 22.2 | 64 | 0.756757 |
2210775ffa1c3da8dd923a744455d63d23392026 | 3,114 | import UIKit
import SnapKit
class SendMemoView: UIView {
private let delegate: ISendMemoViewDelegate
private let inputFieldFont = UIFont.subhead1I
private let holderView = UIView()
private let memoInputField = UITextField()
private var memoHidden: Bool = false
init(delegate: ISendMemoViewDelegate) {
self.delegate = delegate
super.init(frame: .zero)
backgroundColor = .clear
addSubview(holderView)
holderView.addSubview(memoInputField)
holderView.snp.makeConstraints { maker in
maker.top.equalToSuperview().offset(CGFloat.margin3x)
maker.leading.trailing.equalToSuperview().inset(CGFloat.margin4x)
maker.bottom.equalToSuperview()
}
holderView.layer.cornerRadius = CGFloat.cornerRadius2x
holderView.layer.borderWidth = .heightOneDp
holderView.layer.borderColor = UIColor.themeSteel20.cgColor
holderView.backgroundColor = .themeLawrence
memoInputField.snp.makeConstraints { maker in
maker.top.bottom.equalToSuperview()
maker.leading.trailing.equalToSuperview().inset(CGFloat.margin3x)
maker.centerY.equalToSuperview()
maker.height.equalTo(inputFieldFont.lineHeight + CGFloat.margin3x * 2)
}
memoInputField.textColor = .themeOz
memoInputField.font = inputFieldFont
memoInputField.attributedPlaceholder = NSAttributedString(string: "send.confirmation.memo_placeholder".localized, attributes: [NSAttributedString.Key.foregroundColor: UIColor.themeGray50])
memoInputField.keyboardAppearance = .themeDefault
memoInputField.tintColor = .themeInputFieldTintColor
memoInputField.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("not implemented")
}
}
extension SendMemoView: ISendMemoView {
var memo: String? {
memoHidden ? nil : memoInputField.text
}
func set(hidden: Bool) {
memoHidden = hidden
holderView.snp.updateConstraints { maker in
maker.top.equalToSuperview().offset(hidden ? 0 : CGFloat.margin3x)
}
memoInputField.snp.updateConstraints { maker in
maker.height.equalTo(hidden ? 0 : inputFieldFont.lineHeight + CGFloat.margin3x * 2)
}
layoutIfNeeded()
}
}
extension SendMemoView: UITextFieldDelegate {
private func validate(text: String) -> Bool {
if delegate.validate(memo: text) {
return true
} else {
memoInputField.shakeView()
return false
}
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = memoInputField.text, let textRange = Range(range, in: text) {
let text = text.replacingCharacters(in: textRange, with: string)
guard !text.isEmpty else {
return true
}
return validate(text: text)
}
return validate(text: string)
}
}
| 30.831683 | 196 | 0.663455 |
18184b4b1438a7288809fc364fd367f20c9825d8 | 516 | //
// LocalState.swift
// Bankey
//
// Created by Taiki on 4/01/5.
//
import Foundation
public class LocalState {
private enum Keys: String {
case hasOnboarded
}
public static var hasOnboarded: Bool {
get {
return UserDefaults.standard.bool(forKey: Keys.hasOnboarded.rawValue)
}
set(newValue) {
UserDefaults.standard.set(newValue, forKey: Keys.hasOnboarded.rawValue)
UserDefaults.standard.synchronize()
}
}
}
| 19.846154 | 83 | 0.604651 |
7a912735cf291d5107e0bfdcf21663313edd3a25 | 1,377 | import XCTest
import class Foundation.Bundle
final class metal_nnTests: XCTestCase {
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
// Some of the APIs that we use below are available in macOS 10.13 and above.
guard #available(macOS 10.13, *) else {
return
}
let fooBinary = productsDirectory.appendingPathComponent("metal-nn")
let process = Process()
process.executableURL = fooBinary
let pipe = Pipe()
process.standardOutput = pipe
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
XCTAssertEqual(output, "Hello, world!\n")
}
/// Returns path to the built products directory.
var productsDirectory: URL {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return bundle.bundleURL.deletingLastPathComponent()
}
fatalError("couldn't find the products directory")
#else
return Bundle.main.bundleURL
#endif
}
static var allTests = [
("testExample", testExample),
]
}
| 28.6875 | 87 | 0.634713 |
d7ded6c5435f88883d701f73e609ccac467c337e | 2,813 | //
// PopUpPresetController
// ROM Player
//
// Created by Matthew Fecher on 9/5/17.
// Copyright © 2017 AudioKit Pro. All rights reserved.
//
import UIKit
protocol PresetPopOverDelegate {
func didSelectNewPreset(presetIndex: Int)
}
class PopUpPresetController: UIViewController {
@IBOutlet weak var presetsTableView: UITableView!
@IBOutlet weak var popupView: UIView!
var delegate: PresetPopOverDelegate?
var presets: [String] = []
var presetIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
// presetsTableView.reloadData()
presetsTableView.separatorColor = #colorLiteral(red: 0.3333333333, green: 0.3333333333, blue: 0.3333333333, alpha: 1)
popupView.layer.borderColor = #colorLiteral(red: 0.1333333333, green: 0.1333333333, blue: 0.1333333333, alpha: 1)
popupView.layer.borderWidth = 2
popupView.layer.cornerRadius = 3
}
override func viewDidAppear(_ animated: Bool) {
// Populate Preset current values
let indexPath = IndexPath(row: presetIndex, section: 0)
presetsTableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
}
}
// *****************************************************************
// MARK: - TableViewDataSource
// *****************************************************************
extension PopUpPresetController: UITableViewDataSource {
func numberOfSections(in categoryTableView: UITableView) -> Int {
return 1
}
@objc(tableView:heightForRowAtIndexPath:) func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if presets.isEmpty {
return 1
} else {
return presets.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "PresetCell") as? PresetCell {
// Cell updated in PresetCell.swift
cell.configureCell(presetName: presets[indexPath.row])
return cell
} else {
return PresetCell()
}
}
}
//*****************************************************************
// MARK: - TableViewDelegate
//*****************************************************************
extension PopUpPresetController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
presetIndex = (indexPath as NSIndexPath).row
delegate?.didSelectNewPreset(presetIndex: presetIndex)
}
}
| 30.247312 | 136 | 0.592606 |
debfd7f14eec379d3400f9b6a176d9df43a42bd6 | 2,194 | //
// AppDelegate.swift
// TestTopic
//
// Created by [email protected] on 01/17/2019.
// Copyright (c) 2019 [email protected]. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.680851 | 285 | 0.754786 |
3a15d01d58a6acd328cc0ef03ee313002d99afb9 | 8,870 | //
// Geocoder.swift
// LMGeocoderSwift
//
// Created by LMinh on 12/18/18.
// Copyright © 2018 LMinh. All rights reserved.
//
import UIKit
import CoreLocation
/// LMGeocoder error codes.
public enum GeocoderError: Error {
case invalidCoordinate
case invalidAddressString
}
/// LMGeocoder service API.
public enum GeocoderService {
case GoogleService
case AppleService
}
/// Google Geocoding API const
private let googleGeocodingURLString = "https://maps.googleapis.com/maps/api/geocode/json?sensor=true"
/// Handler that reports a geocoding response, or error.
public typealias GeocodeCallback = (_ results: [Address]?, _ error: Error?) -> Void
/// Exposes a service for geocoding and reverse geocoding.
open class Geocoder {
// MARK: - PROPERTIES
/// Indicating whether the receiver is in the middle of geocoding its value.
private(set) var isGeocoding: Bool = false
/// To set google API key.
public var googleAPIKey: String? = nil
/// Apple Geocoder.
private lazy var appleGeocoder: CLGeocoder = CLGeocoder()
/// Google Geocoder Task
private lazy var googleGeocoderTask: URLSessionDataTask? = nil
// MARK: SINGLETON
public static let shared = Geocoder()
// MARK: GEOCODING
/// Submits a forward-geocoding request using the specified string.
/// After initiating a forward-geocoding request, do not attempt to initiate another forward- or reverse-geocoding request.
/// Geocoding requests are rate-limited for each app, so making too many requests in a
/// short period of time may cause some of the requests to fail.
/// When the maximum rate is exceeded, the geocoder passes an error object to your completion handler.
///
/// - Parameters:
/// - address: The string describing the location you want to look up.
/// - service: The service API used to geocode.
/// - completionHandler: The callback to invoke with the geocode results. The callback will be invoked asynchronously from the main thread.
public func geocode(_ address: String, service: GeocoderService, completionHandler: GeocodeCallback?) {
isGeocoding = true
// Check adress string
guard address.count != 0 else {
isGeocoding = false
if let completionHandler = completionHandler {
completionHandler(nil, GeocoderError.invalidAddressString)
}
return
}
// Check service
if service == .GoogleService
{
// Geocode using Google service
var urlString = googleGeocodingURLString + "&address=\(address)"
if let key = googleAPIKey {
urlString = urlString + "&key=" + key
}
buildAsynchronousRequest(urlString: urlString) { (results, error) in
self.isGeocoding = false
if let completionHandler = completionHandler {
completionHandler(results, error)
}
}
}
else if service == .AppleService
{
// Geocode using Apple service
appleGeocoder.geocodeAddressString(address) { (placemarks, error) in
let results = self.parseGeocodingResponse(placemarks, service: .AppleService)
self.isGeocoding = false
if let completionHandler = completionHandler {
completionHandler(results, error)
}
}
}
}
/// Submits a reverse-geocoding request for the specified coordinate.
/// After initiating a reverse-geocoding request, do not attempt to initiate another reverse- or forward-geocoding request.
/// Geocoding requests are rate-limited for each app, so making too many requests in a
/// short period of time may cause some of the requests to fail.
/// When the maximum rate is exceeded, the geocoder passes an error object to your completion handler.
///
/// - Parameters:
/// - address: The coordinate to look up.
/// - service: The service API used to reverse geocode.
/// - completionHandler: The callback to invoke with the reverse geocode results.The callback will be invoked asynchronously from the main thread.
public func reverseGeocode(_ coordinate: CLLocationCoordinate2D, service: GeocoderService, completionHandler: GeocodeCallback?) {
isGeocoding = true
// Check location coordinate
guard CLLocationCoordinate2DIsValid(coordinate) else {
isGeocoding = false
if let completionHandler = completionHandler {
completionHandler(nil, GeocoderError.invalidCoordinate)
}
return
}
// Check service
if service == .GoogleService
{
// Reverse geocode using Google service
var urlString = googleGeocodingURLString + "&latlng=\(coordinate.latitude),\(coordinate.longitude)"
if let key = googleAPIKey {
urlString = urlString + "&key=" + key
}
buildAsynchronousRequest(urlString: urlString) { (results, error) in
self.isGeocoding = false
if let completionHandler = completionHandler {
completionHandler(results, error)
}
}
}
else if service == .AppleService
{
// Reverse geocode using Apple service
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
appleGeocoder.reverseGeocodeLocation(location) { (placemarks, error) in
let results = self.parseGeocodingResponse(placemarks, service: .AppleService)
self.isGeocoding = false
if let completionHandler = completionHandler {
completionHandler(results, error)
}
}
}
}
/// Cancels a pending geocoding request.
public func cancelGeocode() {
appleGeocoder.cancelGeocode()
googleGeocoderTask?.cancel()
}
}
// MARK: - SUPPORT
extension Geocoder {
/// Build asynchronous request
func buildAsynchronousRequest(urlString: String, completionHandler: GeocodeCallback?) {
let urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL(string: urlString)!
googleGeocoderTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let data = data, error == nil {
do {
let result = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String, Any>
// Check status value
if let status = result["status"] as? String, status == "OK" {
// Status OK --> Parse response results
let locationDicts = result["results"] as? [AnyObject]
let finalResults = self.parseGeocodingResponse(locationDicts, service: .GoogleService)
if let completionHandler = completionHandler {
completionHandler(finalResults, nil)
}
}
else {
// Other status --> Return error
if let completionHandler = completionHandler {
completionHandler(nil, error)
}
}
}
catch {
// Parse failed --> Return error
if let completionHandler = completionHandler {
completionHandler(nil, error)
}
}
}
else {
// Request failed --> Return error
if let completionHandler = completionHandler {
completionHandler(nil, error)
}
}
})
googleGeocoderTask?.resume()
}
/// Parse geocoding response
func parseGeocodingResponse(_ results: [AnyObject]?, service: GeocoderService) -> [Address]? {
guard let results = results else { return nil }
var finalResults = [Address]()
for respondObject in results {
let address = Address(locationData: respondObject, serviceType: service)
finalResults.append(address)
}
return finalResults
}
}
| 37.905983 | 152 | 0.584442 |
0e0bd1bc65eab84852d664ed9becbfd9c9afedde | 25,560 | //
// Utilities.swift
// 3DViewer
//
// Created by Eugene Bokhan on 1/9/18.
// Copyright © 2018 Eugene Bokhan. All rights reserved.
//
import UIKit
import Foundation
import ARKit
// - MARK: UIImage extensions
extension UIImage {
func inverted() -> UIImage? {
guard let ciImage = CIImage(image: self) else {
return nil
}
return UIImage(ciImage: ciImage.applyingFilter("CIColorInvert"))
}
static func composeButtonImage(from thumbImage: UIImage, alpha: CGFloat = 1.0) -> UIImage {
let maskImage = #imageLiteral(resourceName: "buttonring")
let thumbnailImage = thumbImage
// if let invertedImage = thumbImage.inverted() {
// thumbnailImage = invertedImage
// }
// Compose a button image based on a white background and the inverted thumbnail image.
UIGraphicsBeginImageContextWithOptions(maskImage.size, false, 0.0)
let maskDrawRect = CGRect(origin: CGPoint.zero,
size: maskImage.size)
let thumbDrawRect = CGRect(origin: CGPoint((maskImage.size - thumbImage.size) / 2),
size: thumbImage.size)
maskImage.draw(in: maskDrawRect, blendMode: .normal, alpha: alpha)
thumbnailImage.draw(in: thumbDrawRect, blendMode: .normal, alpha: alpha)
let composedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return composedImage!
}
}
// MARK: - Collection extensions
extension Array where Iterator.Element == CGFloat {
var average: CGFloat? {
guard !isEmpty else {
return nil
}
var ret = self.reduce(CGFloat(0)) { (cur, next) -> CGFloat in
var cur = cur
cur += next
return cur
}
let fcount = CGFloat(count)
ret /= fcount
return ret
}
}
extension Array where Iterator.Element == SCNVector3 {
var average: SCNVector3? {
guard !isEmpty else {
return nil
}
var ret = self.reduce(SCNVector3Zero) { (cur, next) -> SCNVector3 in
var cur = cur
cur.x += next.x
cur.y += next.y
cur.z += next.z
return cur
}
let fcount = Float(count)
ret.x /= fcount
ret.y /= fcount
ret.z /= fcount
return ret
}
}
extension Array where Iterator.Element == SCNMatrix4 {
var average: SCNMatrix4? {
guard !isEmpty else {
return nil
}
var ret = self.reduce(SCNMatrix4()) { (cur, next) -> SCNMatrix4 in
var cur = cur
cur.m11 += next.m11
cur.m12 += next.m12
cur.m13 += next.m13
cur.m14 += next.m14
cur.m21 += next.m21
cur.m22 += next.m22
cur.m23 += next.m23
cur.m24 += next.m24
cur.m31 += next.m31
cur.m32 += next.m32
cur.m33 += next.m33
cur.m34 += next.m34
cur.m41 += next.m41
cur.m42 += next.m42
cur.m43 += next.m43
cur.m44 += next.m44
return cur
}
let fcount = Float(count)
ret.m11 /= fcount
ret.m12 /= fcount
ret.m13 /= fcount
ret.m14 /= fcount
ret.m21 /= fcount
ret.m22 /= fcount
ret.m23 /= fcount
ret.m24 /= fcount
ret.m31 /= fcount
ret.m32 /= fcount
ret.m33 /= fcount
ret.m34 /= fcount
ret.m41 /= fcount
ret.m42 /= fcount
ret.m43 /= fcount
ret.m44 /= fcount
return ret
}
}
extension RangeReplaceableCollection {
mutating func keepLast(_ elementsToKeep: Int) {
if count > elementsToKeep {
self.removeFirst(count - elementsToKeep)
}
}
}
// MARK: - SCNNode extension
extension SCNNode {
func setUniformScale(_ scale: Float) {
self.scale = SCNVector3Make(scale, scale, scale)
}
func renderOnTop() {
self.renderingOrder = 2
if let geom = self.geometry {
for material in geom.materials {
material.readsFromDepthBuffer = false
}
}
for child in self.childNodes {
child.renderOnTop()
}
}
}
// MARK: - SCNVector3 extensions
extension SCNVector3 {
init(_ vec: vector_float3) {
self.init()
self.x = vec.x
self.y = vec.y
self.z = vec.z
}
func length() -> Float {
return sqrtf(x * x + y * y + z * z)
}
mutating func setLength(_ length: Float) {
self.normalize()
self *= length
}
mutating func setMaximumLength(_ maxLength: Float) {
if self.length() <= maxLength {
return
} else {
self.normalize()
self *= maxLength
}
}
mutating func normalize() {
self = self.normalized()
}
func normalized() -> SCNVector3 {
if self.length() == 0 {
return self
}
return self / self.length()
}
static func positionFromTransform(_ transform: matrix_float4x4) -> SCNVector3 {
return SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z)
}
func friendlyString() -> String {
return "(\(String(format: "%.2f", x)), \(String(format: "%.2f", y)), \(String(format: "%.2f", z)))"
}
func dot(_ vec: SCNVector3) -> Float {
return (self.x * vec.x) + (self.y * vec.y) + (self.z * vec.z)
}
func cross(_ vec: SCNVector3) -> SCNVector3 {
return SCNVector3(self.y * vec.z - self.z * vec.y, self.z * vec.x - self.x * vec.z, self.x * vec.y - self.y * vec.x)
}
}
public let SCNVector3One: SCNVector3 = SCNVector3(1.0, 1.0, 1.0)
func SCNVector3Uniform(_ value: Float) -> SCNVector3 {
return SCNVector3Make(value, value, value)
}
func SCNVector3Uniform(_ value: CGFloat) -> SCNVector3 {
return SCNVector3Make(Float(value), Float(value), Float(value))
}
func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z)
}
func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z)
}
func += (left: inout SCNVector3, right: SCNVector3) {
left = left + right
}
func -= (left: inout SCNVector3, right: SCNVector3) {
left = left - right
}
func / (left: SCNVector3, right: Float) -> SCNVector3 {
return SCNVector3Make(left.x / right, left.y / right, left.z / right)
}
func * (left: SCNVector3, right: Float) -> SCNVector3 {
return SCNVector3Make(left.x * right, left.y * right, left.z * right)
}
func /= (left: inout SCNVector3, right: Float) {
left = left / right
}
func *= (left: inout SCNVector3, right: Float) {
left = left * right
}
// MARK: - SCNMaterial extensions
extension SCNMaterial {
static func material(withDiffuse diffuse: Any?, respondsToLighting: Bool = true) -> SCNMaterial {
let material = SCNMaterial()
material.diffuse.contents = diffuse
material.isDoubleSided = true
if respondsToLighting {
material.locksAmbientWithDiffuse = true
} else {
material.ambient.contents = UIColor.black
material.lightingModel = .constant
material.emission.contents = diffuse
}
return material
}
}
// MARK: - CGPoint extensions
extension CGPoint {
init(_ size: CGSize) {
self.init()
self.x = size.width
self.y = size.height
}
init(_ vector: SCNVector3) {
self.init()
self.x = CGFloat(vector.x)
self.y = CGFloat(vector.y)
}
func distanceTo(_ point: CGPoint) -> CGFloat {
return (self - point).length()
}
func length() -> CGFloat {
return sqrt(self.x * self.x + self.y * self.y)
}
func midpoint(_ point: CGPoint) -> CGPoint {
return (self + point) / 2
}
func friendlyString() -> String {
return "(\(String(format: "%.2f", x)), \(String(format: "%.2f", y)))"
}
}
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func += (left: inout CGPoint, right: CGPoint) {
left = left + right
}
func -= (left: inout CGPoint, right: CGPoint) {
left = left - right
}
func / (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x / right, y: left.y / right)
}
func * (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x * right, y: left.y * right)
}
func /= (left: inout CGPoint, right: CGFloat) {
left = left / right
}
func *= (left: inout CGPoint, right: CGFloat) {
left = left * right
}
// MARK: - CGSize extensions
extension CGSize {
init(_ point: CGPoint) {
self.init()
self.width = point.x
self.height = point.y
}
func friendlyString() -> String {
return "(\(String(format: "%.2f", width)), \(String(format: "%.2f", height)))"
}
}
func + (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width + right.width, height: left.height + right.height)
}
func - (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width - right.width, height: left.height - right.height)
}
func += (left: inout CGSize, right: CGSize) {
left = left + right
}
func -= (left: inout CGSize, right: CGSize) {
left = left - right
}
func / (left: CGSize, right: CGFloat) -> CGSize {
return CGSize(width: left.width / right, height: left.height / right)
}
func * (left: CGSize, right: CGFloat) -> CGSize {
return CGSize(width: left.width * right, height: left.height * right)
}
func /= (left: inout CGSize, right: CGFloat) {
left = left / right
}
func *= (left: inout CGSize, right: CGFloat) {
left = left * right
}
// MARK: - CGRect extensions
extension CGRect {
var mid: CGPoint {
return CGPoint(x: midX, y: midY)
}
}
func rayIntersectionWithHorizontalPlane(rayOrigin: SCNVector3, direction: SCNVector3, planeY: Float) -> SCNVector3? {
let direction = direction.normalized()
// Special case handling: Check if the ray is horizontal as well.
if direction.y == 0 {
if rayOrigin.y == planeY {
// The ray is horizontal and on the plane, thus all points on the ray intersect with the plane.
// Therefore we simply return the ray origin.
return rayOrigin
} else {
// The ray is parallel to the plane and never intersects.
return nil
}
}
// The distance from the ray's origin to the intersection point on the plane is:
// (pointOnPlane - rayOrigin) dot planeNormal
// --------------------------------------------
// direction dot planeNormal
// Since we know that horizontal planes have normal (0, 1, 0), we can simplify this to:
let dist = (planeY - rayOrigin.y) / direction.y
// Do not return intersections behind the ray's origin.
if dist < 0 {
return nil
}
// Return the intersection point.
return rayOrigin + (direction * dist)
}
extension ARSCNView {
struct HitTestRay {
let origin: SCNVector3
let direction: SCNVector3
}
func hitTestRayFromScreenPos(_ point: CGPoint) -> HitTestRay? {
guard let frame = self.session.currentFrame else {
return nil
}
let cameraPos = SCNVector3.positionFromTransform(frame.camera.transform)
// Note: z: 1.0 will unproject() the screen position to the far clipping plane.
let positionVec = SCNVector3(x: Float(point.x), y: Float(point.y), z: 1.0)
let screenPosOnFarClippingPlane = self.unprojectPoint(positionVec)
var rayDirection = screenPosOnFarClippingPlane - cameraPos
rayDirection.normalize()
return HitTestRay(origin: cameraPos, direction: rayDirection)
}
func hitTestWithInfiniteHorizontalPlane(_ point: CGPoint, _ pointOnPlane: SCNVector3) -> SCNVector3? {
guard let ray = hitTestRayFromScreenPos(point) else {
return nil
}
// Do not intersect with planes above the camera or if the ray is almost parallel to the plane.
if ray.direction.y > -0.03 {
return nil
}
// Return the intersection of a ray from the camera through the screen position with a horizontal plane
// at height (Y axis).
return rayIntersectionWithHorizontalPlane(rayOrigin: ray.origin, direction: ray.direction, planeY: pointOnPlane.y)
}
struct FeatureHitTestResult {
let position: SCNVector3
let distanceToRayOrigin: Float
let featureHit: SCNVector3
let featureDistanceToHitResult: Float
}
func hitTestWithFeatures(_ point: CGPoint, coneOpeningAngleInDegrees: Float,
minDistance: Float = 0,
maxDistance: Float = Float.greatestFiniteMagnitude,
maxResults: Int = 1) -> [FeatureHitTestResult] {
var results = [FeatureHitTestResult]()
guard let features = self.session.currentFrame?.rawFeaturePoints else {
return results
}
guard let ray = hitTestRayFromScreenPos(point) else {
return results
}
let maxAngleInDeg = min(coneOpeningAngleInDegrees, 360) / 2
let maxAngle = ((maxAngleInDeg / 180) * Float.pi)
let points = features.__points
for i in 0...features.__count {
let feature = points.advanced(by: Int(i))
let featurePos = SCNVector3(feature.pointee)
let originToFeature = featurePos - ray.origin
let crossProduct = originToFeature.cross(ray.direction)
let featureDistanceFromResult = crossProduct.length()
let hitTestResult = ray.origin + (ray.direction * ray.direction.dot(originToFeature))
let hitTestResultDistance = (hitTestResult - ray.origin).length()
if hitTestResultDistance < minDistance || hitTestResultDistance > maxDistance {
// Skip this feature - it is too close or too far away.
continue
}
let originToFeatureNormalized = originToFeature.normalized()
let angleBetweenRayAndFeature = acos(ray.direction.dot(originToFeatureNormalized))
if angleBetweenRayAndFeature > maxAngle {
// Skip this feature - is is outside of the hit test cone.
continue
}
// All tests passed: Add the hit against this feature to the results.
results.append(FeatureHitTestResult(position: hitTestResult,
distanceToRayOrigin: hitTestResultDistance,
featureHit: featurePos,
featureDistanceToHitResult: featureDistanceFromResult))
}
// Sort the results by feature distance to the ray.
results = results.sorted(by: { (first, second) -> Bool in
return first.distanceToRayOrigin < second.distanceToRayOrigin
})
// Cap the list to maxResults.
var cappedResults = [FeatureHitTestResult]()
var i = 0
while i < maxResults && i < results.count {
cappedResults.append(results[i])
i += 1
}
return cappedResults
}
func hitTestWithFeatures(_ point: CGPoint) -> [FeatureHitTestResult] {
var results = [FeatureHitTestResult]()
guard let ray = hitTestRayFromScreenPos(point) else {
return results
}
if let result = self.hitTestFromOrigin(origin: ray.origin, direction: ray.direction) {
results.append(result)
}
return results
}
func hitTestFromOrigin(origin: SCNVector3, direction: SCNVector3) -> FeatureHitTestResult? {
guard let features = self.session.currentFrame?.rawFeaturePoints else {
return nil
}
let points = features.__points
// Determine the point from the whole point cloud which is closest to the hit test ray.
var closestFeaturePoint = origin
var minDistance = Float.greatestFiniteMagnitude
for i in 0...features.__count {
let feature = points.advanced(by: Int(i))
let featurePos = SCNVector3(feature.pointee)
let originVector = origin - featurePos
let crossProduct = originVector.cross(direction)
let featureDistanceFromResult = crossProduct.length()
if featureDistanceFromResult < minDistance {
closestFeaturePoint = featurePos
minDistance = featureDistanceFromResult
}
}
// Compute the point along the ray that is closest to the selected feature.
let originToFeature = closestFeaturePoint - origin
let hitTestResult = origin + (direction * direction.dot(originToFeature))
let hitTestResultDistance = (hitTestResult - origin).length()
return FeatureHitTestResult(position: hitTestResult,
distanceToRayOrigin: hitTestResultDistance,
featureHit: closestFeaturePoint,
featureDistanceToHitResult: minDistance)
}
}
// MARK: - Simple geometries
func createAxesNode(quiverLength: CGFloat, quiverThickness: CGFloat) -> SCNNode {
let quiverThickness = (quiverLength / 50.0) * quiverThickness
let chamferRadius = quiverThickness / 2.0
let xQuiverBox = SCNBox(width: quiverLength, height: quiverThickness, length: quiverThickness, chamferRadius: chamferRadius)
xQuiverBox.materials = [SCNMaterial.material(withDiffuse: UIColor.red, respondsToLighting: false)]
let xQuiverNode = SCNNode(geometry: xQuiverBox)
xQuiverNode.position = SCNVector3Make(Float(quiverLength / 2.0), 0.0, 0.0)
let yQuiverBox = SCNBox(width: quiverThickness, height: quiverLength, length: quiverThickness, chamferRadius: chamferRadius)
yQuiverBox.materials = [SCNMaterial.material(withDiffuse: UIColor.green, respondsToLighting: false)]
let yQuiverNode = SCNNode(geometry: yQuiverBox)
yQuiverNode.position = SCNVector3Make(0.0, Float(quiverLength / 2.0), 0.0)
let zQuiverBox = SCNBox(width: quiverThickness, height: quiverThickness, length: quiverLength, chamferRadius: chamferRadius)
zQuiverBox.materials = [SCNMaterial.material(withDiffuse: UIColor.blue, respondsToLighting: false)]
let zQuiverNode = SCNNode(geometry: zQuiverBox)
zQuiverNode.position = SCNVector3Make(0.0, 0.0, Float(quiverLength / 2.0))
let quiverNode = SCNNode()
quiverNode.addChildNode(xQuiverNode)
quiverNode.addChildNode(yQuiverNode)
quiverNode.addChildNode(zQuiverNode)
quiverNode.name = "Axes"
return quiverNode
}
func createCrossNode(size: CGFloat = 0.01, color: UIColor = UIColor.green, horizontal: Bool = true, opacity: CGFloat = 1.0) -> SCNNode {
// Create a size x size m plane and put a grid texture onto it.
let planeDimension = size
var fileName = ""
switch color {
case UIColor.blue:
fileName = "crosshair_blue"
case UIColor.yellow:
fallthrough
default:
fileName = "crosshair_yellow"
}
let path = Bundle.main.path(forResource: fileName, ofType: "png", inDirectory: "Models.scnassets")!
let image = UIImage(contentsOfFile: path)
let planeNode = SCNNode(geometry: createSquarePlane(size: planeDimension, contents: image))
if let material = planeNode.geometry?.firstMaterial {
material.ambient.contents = UIColor.black
material.lightingModel = .constant
}
if horizontal {
planeNode.eulerAngles = SCNVector3Make(Float.pi / 2.0, 0, Float.pi) // Horizontal.
} else {
planeNode.constraints = [SCNBillboardConstraint()] // Facing the screen.
}
let cross = SCNNode()
cross.addChildNode(planeNode)
cross.opacity = opacity
return cross
}
func createSquarePlane(size: CGFloat, contents: AnyObject?) -> SCNPlane {
let plane = SCNPlane(width: size, height: size)
plane.materials = [SCNMaterial.material(withDiffuse: contents)]
return plane
}
func createPlane(size: CGSize, contents: AnyObject?) -> SCNPlane {
let plane = SCNPlane(width: size.width, height: size.height)
plane.materials = [SCNMaterial.material(withDiffuse: contents)]
return plane
}
public func animationWithKeyPath(_ keyPath: String, damping: CGFloat = 10, initialVelocity: CGFloat = 0, stiffness: CGFloat) -> CABasicAnimation {
guard #available(iOS 9, *) else {
let basic = CABasicAnimation(keyPath: keyPath)
basic.duration = 0.16
basic.fillMode = .forwards
basic.timingFunction = CAMediaTimingFunction(name: .default)
return basic
}
let spring = CASpringAnimation(keyPath: keyPath)
spring.duration = spring.settlingDuration
spring.damping = damping
spring.initialVelocity = initialVelocity
spring.stiffness = stiffness
spring.fillMode = .forwards
spring.timingFunction = CAMediaTimingFunction(name: .default)
return spring
}
public func animationWithKeyPath(_ keyPath: String, damping: CGFloat = 10, initialVelocity: CGFloat = 0, stiffness: CGFloat, duration: Double) -> CABasicAnimation {
guard #available(iOS 9, *) else {
let basic = CABasicAnimation(keyPath: keyPath)
basic.duration = duration
basic.fillMode = .forwards
basic.timingFunction = CAMediaTimingFunction(name: .default)
return basic
}
let spring = CASpringAnimation(keyPath: keyPath)
spring.duration = spring.settlingDuration
spring.damping = damping
spring.initialVelocity = initialVelocity
spring.stiffness = stiffness
spring.fillMode = .forwards
spring.timingFunction = CAMediaTimingFunction(name: .default)
return spring
}
public func getButtonTransfromForPresentation(button: UIButton, presentationDirection: PresentationDirection) -> (CGAffineTransform, CGAffineTransform) {
var initialButtonTransform: CGAffineTransform!
let finalButtonTransform = button.transform
switch presentationDirection {
case .down:
initialButtonTransform = CGAffineTransform(translationX: 0, y: -button.frame.maxY)
case .up:
initialButtonTransform = CGAffineTransform(translationX: 0, y: button.frame.maxY)
case .left:
initialButtonTransform = CGAffineTransform(translationX: button.frame.maxX, y: 0)
case .right:
initialButtonTransform = CGAffineTransform(translationX: -button.frame.maxX, y: 0)
}
return (initialButtonTransform, finalButtonTransform)
}
public func getViewTransfromForPresentation(view: UIView, presentationDirection: PresentationDirection) -> (CGAffineTransform, CGAffineTransform) {
var initialViewTransform: CGAffineTransform!
let finalViewTransform = view.transform
switch presentationDirection {
case .down:
initialViewTransform = CGAffineTransform(translationX: 0, y: -view.frame.maxY)
case .up:
initialViewTransform = CGAffineTransform(translationX: 0, y: view.frame.maxY)
case .left:
initialViewTransform = CGAffineTransform(translationX: view.frame.maxX, y: 0)
case .right:
initialViewTransform = CGAffineTransform(translationX: -view.frame.maxX, y: 0)
}
return (initialViewTransform, finalViewTransform)
}
public func degreesToRadians(degrees: CGFloat) -> CGFloat {
return degrees * .pi / 180
}
public func radiansToDegress(radians: CGFloat) -> CGFloat {
return radians * 180 / .pi
}
public enum PresentationDirection {
case right
case left
case up
case down
}
extension MutableCollection {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in indices.dropLast() {
let diff = distance(from: i, to: endIndex)
let j = index(i, offsetBy: numericCast(arc4random_uniform(numericCast(diff))))
swapAt(i, j)
}
}
}
extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Element] {
var result = Array(self)
result.shuffle()
return result
}
}
| 31.95 | 164 | 0.60759 |
f9c5495f1302fbe969e35a1e386c4d332c9bd7f8 | 776 | //
// ArrowView.swift
// Sokoban
//
// Created by Tom Cousin on 04/02/2021.
//
import SwiftUI
struct ArrowView: View {
// MARK: - Body
var body: some View {
VStack(spacing: -10) {
CircleButton(name: "arrow.up", action: {}, width: 75, height: 75)
HStack(spacing: 50) {
CircleButton(name: "arrow.left", action: {}, width: 75, height: 75)
CircleButton(name: "arrow.right", action: {}, width: 75, height: 75)
}
CircleButton(name: "arrow.down", action: {}, width: 75, height: 75)
}
}
}
struct ArrowView_Previews: PreviewProvider {
static var previews: some View {
ArrowView()
ArrowView()
.preferredColorScheme(.dark)
}
}
| 23.515152 | 84 | 0.545103 |
e62730c6624a2640842265a3689d7f499efc0621 | 882 | import SwiftUI
import CoreLocation
struct Landmark: Hashable, Codable, Identifiable {
var id: Int
var name: String
fileprivate var imageName: String
fileprivate var coordinates: Coordinates
var state: String
var park: String
var category: Category
var isFavorite: Bool
var locationCoordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(
latitude: coordinates.latitude,
longitude: coordinates.longitude)
}
enum Category: String, CaseIterable, Codable, Hashable {
case featured = "Featured"
case lakes = "Lakes"
case rivers = "Rivers"
case mountains = "Mountains"
}
}
extension Landmark {
var image: Image {
ImageStore.shared.image(name: imageName)
}
}
struct Coordinates: Hashable, Codable {
var latitude: Double
var longitude: Double
}
| 23.210526 | 60 | 0.668934 |
1621133f9d370ac385ae2e4027bafb4d934dfca7 | 2,544 | import Dye
// A stream holds the original and current state regarding colors and style of
// the text that's going to be printed to the terminal.
var stream = OutputStream.standardOutput()
// We can set the color and/or style for the text and clear them to reset to
// the original state when the stream instance is created. Then use it as a
// normal `TextOutputStream`(https://developer.apple.com/documentation/swift/textoutputstream).
print("Hello, ", terminator: "")
stream.color.foreground = .red
stream.style = .underlined
print("Terminal", terminator: "", to: &stream)
// Remember to call this so that your terminal resets to the state it began with. This is important in certain
// terminal simulators (e.g. Windows Command Prompt).
stream.clear()
print("!", terminator: "\n\n")
// You can pair text segments with their desired style with a batch-writing API:
// Note with this API, `.clear()` is invoked automatically at the end.
//
// Each of the 8 primary colors has a "intense" version. The 2 versions can be converted to each other. For
// example, `OutputStream.Color.red.intensified.softened` converts red to intense red and back.
stream.write(
("black ", [.foreground(.intenseBlack ), .background(.black )]),
("red ", [.foreground(.intenseRed ), .background(.red )]),
("green ", [.foreground(.intenseGreen ), .background(.green )]),
("yellow ", [.foreground(.intenseYellow ), .background(.yellow )]),
("blue ", [.foreground(.intenseBlue ), .background(.blue )]),
("magenta ", [.foreground(.intenseMagenta), .background(.magenta)]),
("cyan ", [.foreground(.intenseCyan ), .background(.cyan )]),
("white ", [.foreground(.intenseWhite ), .background(.white )])
)
print("", terminator: "\n\n")
// The above API can also take in a array, it's more useful if you need to
// generate styled output else where (to make it testable, for example).
var segments = [(String, [OutputStream.StyleSegment])]()
for foreground in UInt8(8)..<16 { // intense color for forground
for background in UInt8(0)..<8 { // normal color for background
segments.append(
(
"\(String(foreground, radix: 16))\(String(background, radix: 16))",
[
.foreground(OutputStream.Color(ansiValue: foreground)!),
.background(OutputStream.Color(ansiValue: background)!),
]
)
)
}
segments.append(("\n", []))
}
stream.write(segments)
| 44.631579 | 110 | 0.649371 |
62aa0d12a8f31fd5b2fc9b72fea6c07bee77f8fe | 2,451 | //
// UnitTestcaseRowType.swift
// watchOS Example Extension
//
// Created by Apollo Zhu on 12/27/17.
//
// Copyright (c) 2017-2021 EyreFree <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import WatchKit
extension String {
static let passed = "Passed"
static let testing = "Testing..."
}
class UnitTestcaseRowType: NSObject {
@IBOutlet private var testcaseNameLabel: WKInterfaceLabel? {
didSet {
testcaseNameLabel?.setText(test?.name)
}
}
@IBOutlet private var testcaseStatusLabel: WKInterfaceLabel? {
didSet {
testcaseStatusLabel?.setText(status)
}
}
public var test: (name: String, testcase: Testcase)? {
didSet {
testcaseNameLabel?.setText(test?.name)
status = .testing
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
self?.status = self?.test?.testcase() ?? .passed
}
}
}
private var status: String = .testing {
didSet {
testcaseStatusLabel?.setText(status)
switch status {
case .testing:
testcaseStatusLabel?.setTextColor(.white)
case .passed:
testcaseStatusLabel?.setTextColor(.green)
default:
testcaseStatusLabel?.setTextColor(.red)
}
}
}
}
| 36.044118 | 81 | 0.658507 |
ef03863093e9d450c1ee8f70d6bdd9b29a2d23f7 | 2,237 | // Copyright (c) 2019 André Gillfrost
// Licensed under the MIT license
import XCTest
import AnchorChain
class ConstantTests: XCTestCase {
// MARK: - Anchor API
func testAnchorApi_YAnchoringWithConstant() {
siblings { one, two in
let constraint = one.anchor(.top, to: .bottom, of: two, constant: 123)
XCTAssertEqual(constraint.constant, 123)
}
}
func testAnchorApi_XAnchoringWithConstant() {
siblings { one, two in
let constraint = one.anchor(.right, to: .left, of: two, constant: 231)
XCTAssertEqual(constraint.constant, 231)
}
}
func testAnchorApi_DirectionalXAnchoringWithConstant() {
siblings { one, two in
let constraint = one.anchor(.leading, to: .trailing, of: two, constant: 312)
XCTAssertEqual(constraint.constant, 312)
}
}
func testAnchorApi_DimensionalAnchoringToOtherWithConstant() {
siblings { one, two in
let constraint = one.anchor(.width, to: .height, of: two, constant: 123)
XCTAssertEqual(constraint.constant, 123)
}
}
// MARK: - Anchoring API
func testAnchoringApi_YAnchoringWithConstant() throws {
try siblings { one, two in
let constraint = try one.anchoring(.top, to: .bottom, of: two, constant: 123)
.superview?
.constraints
.onlyElement()
XCTAssertEqual(constraint?.constant, 123)
}
}
func testAnchoringApi_XAnchoringWithConstant() throws {
try siblings { one, two in
let constraint = try one.anchoring(.right, to: .left, of: two, constant: 231)
.superview?
.constraints
.onlyElement()
XCTAssertEqual(constraint?.constant, 231)
}
}
func testAnchoringApi_DirectionalXAnchoringWithConstant() throws {
try siblings { one, two in
let constraint = try one.anchoring(.leading, to: .trailing, of: two, constant: 312)
.superview?
.constraints
.onlyElement()
XCTAssertEqual(constraint?.constant, 312)
}
}
}
| 26.317647 | 95 | 0.590076 |
56f87c653f979d959176cd6aec16fd58b3326cac | 735 | import SwiftIconFont
import UIKit
open class GBarButtonItem: UIBarButtonItem {
private var onClick: (() -> Void)?
public func onClick(_ command: @escaping () -> Void) -> Self {
onClick = command
target = self
action = #selector(performClick)
return self
}
@objc private func performClick() {
if let callback = self.onClick {
callback()
}
}
public func icon(_ icon: GIcon) -> Self {
super.icon(from: icon.font, code: icon.code, ofSize: 20)
return self
}
public func title(_ text: String) -> Self {
super.title = text
return self
}
public func end() {
// End chaining initialisation
}
}
| 21.617647 | 66 | 0.571429 |
1e8a11913d120f1e12f8805fad321b5b8eaf4602 | 2,770 | import Foundation
import ProjectDescription
import TSCBasic
import TuistCore
import TuistGraph
import TuistSupport
import XCTest
@testable import TuistLoader
@testable import TuistSupportTesting
final class SchemeManifestMapperTests: TuistUnitTestCase {
func test_from_when_the_scheme_has_no_actions() throws {
// Given
let manifest = ProjectDescription.Scheme.test(name: "Scheme",
shared: false)
let projectPath = AbsolutePath("/somepath/Project")
let generatorPaths = GeneratorPaths(manifestDirectory: projectPath)
// When
let model = try TuistGraph.Scheme.from(manifest: manifest, generatorPaths: generatorPaths)
// Then
try assert(scheme: model, matches: manifest, path: projectPath, generatorPaths: generatorPaths)
}
func test_from_when_the_scheme_has_actions() throws {
// Given
let arguments = ProjectDescription.Arguments.test(environment: ["FOO": "BAR", "FIZ": "BUZZ"],
launchArguments: [
LaunchArgument(name: "--help", isEnabled: true),
LaunchArgument(name: "subcommand", isEnabled: false),
])
let projectPath = AbsolutePath("/somepath")
let generatorPaths = GeneratorPaths(manifestDirectory: projectPath)
let buildAction = ProjectDescription.BuildAction.test(targets: ["A", "B"])
let runActions = ProjectDescription.RunAction.test(config: .release,
executable: "A",
arguments: arguments)
let testAction = ProjectDescription.TestAction.test(targets: ["B"],
arguments: arguments,
config: .debug,
coverage: true)
let manifest = ProjectDescription.Scheme.test(name: "Scheme",
shared: true,
buildAction: buildAction,
testAction: testAction,
runAction: runActions)
// When
let model = try TuistGraph.Scheme.from(manifest: manifest, generatorPaths: generatorPaths)
// Then
try assert(scheme: model, matches: manifest, path: projectPath, generatorPaths: generatorPaths)
}
}
| 46.949153 | 115 | 0.513357 |
e2046c0de39a2929d09056eb000e2274bef76c5d | 3,299 | //
// sgd_opt.swift
// serrano
//
// Created by ZHONGHAO LIU on 10/13/17.
// Copyright © 2017 ZHONGHAO LIU. All rights reserved.
//
import Foundation
/**
Stochastic gradient descent.
*/
public class SGDOptimizer: Optimizer {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: - Attributes
/// Learning rate.
/// Should `>= 0`.
public var learningRate: Float
/// Initial leanring rate
public var initLearningRate: Float {
get {
return self.initialLR
}
}
/// LR Decay method
public var decayMethod: LearningRateDecayMethod
/// Learning rate decay per epoch.
/// Before each epoch's parmaeter updating, do `learningRate -= learningRate * decay`.
/// Should `>= 0`.
public var decay: Float
/// Momentum.
/// Should `>= 0`.
public var momentum: Float
/// Whether to turn on Nesterov momentum.
/// Default is `false`.
public var nesterov: Bool
/// Initial leanring rate
internal var initialLR: Float
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: - Init
public init(learningRate: Float = 0.001, momentum: Float = 0.0,
decayMethod: LearningRateDecayMethod = LearningRateDecayMethod.Step, decay: Float = 0.0,
nesterov: Bool = false) {
self.initialLR = learningRate
self.learningRate = learningRate
self.momentum = momentum
self.decayMethod = decayMethod
self.decay = decay
self.nesterov = false
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: - Methods conforming Optimizer protocol
/// Do some preparing work before each epoch training
///
/// - Parameter graph: target graph
public func prepare(_ graph: Graph) {
// decay learning rate
self.learningRate = self.decayMethod.decayLR(initialLR: self.initialLR, decay: self.decay, epoch: graph.epoch)
}
/// Update a data symbol's updated value
///
//// - Parameters:
/// - dataSymbol: target symbol
/// - gradValue: gradvalue fot this time updating
public func updateParameter(_ dataSymbol: DataSymbol, gradValue: DataSymbolSupportedDataType) {
// momentum
if dataSymbol.symbolType == SymbolType.Scalar {
var scalarSymbol = dataSymbol as! ScalarSymbol
let value: Float = scalarSymbol.bindedData! as! Float
let v: Float = self.momentum * scalarSymbol.currentGrad!.scarlarValue - self.learningRate * gradValue.scarlarValue
if self.nesterov {
scalarSymbol.bindedData! = value + self.momentum * v - self.learningRate * gradValue.scarlarValue
} else {
scalarSymbol.bindedData! = value + v
}
} else {
var tensorSymbol = dataSymbol as! TensorSymbol
let grad = tensorSymbol.currentGrad as! Tensor
let v: Tensor = self.momentum * grad &- self.learningRate * gradValue.tensorValue
if self.nesterov {
// self.learningRate * gradValue.tensorValue cannot use inplace operation. will effect passed-in argument
tensorSymbol.bindedData!.tensorValue &+ (self.momentum &* v) &- self.learningRate * gradValue.tensorValue
} else {
tensorSymbol.bindedData!.tensorValue &+ v
}
print("\(tensorSymbol.symbolLabel)",grad.flatArrayFloat())
}
}
}
| 31.419048 | 121 | 0.623219 |
1d81ad5346aaf79f02a535600d119ae01e41230c | 2,428 | //
// GYZMyProfileCell.swift
// JSMachine
// 个人信息cell
// Created by gouyz on 2018/11/23.
// Copyright © 2018 gouyz. All rights reserved.
//
import UIKit
class GYZMyProfileCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = kWhiteColor
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI(){
contentView.addSubview(userImgView)
contentView.addSubview(desLab)
contentView.addSubview(nameLab)
contentView.addSubview(rightIconView)
nameLab.snp.makeConstraints { (make) in
make.top.bottom.equalTo(contentView)
make.left.equalTo(contentView).offset(kMargin)
make.right.equalTo(desLab.snp.left).offset(-kMargin)
}
userImgView.snp.makeConstraints { (make) in
make.centerY.equalTo(contentView)
make.right.equalTo(rightIconView.snp.left).offset(-kMargin)
make.size.equalTo(CGSize.init(width: 50, height: 50))
}
desLab.snp.makeConstraints { (make) in
make.top.bottom.equalTo(contentView)
make.right.equalTo(rightIconView.snp.left).offset(-5)
make.width.equalTo(kScreenWidth * 0.5)
}
rightIconView.snp.makeConstraints { (make) in
make.centerY.equalTo(contentView)
make.right.equalTo(contentView).offset(-kMargin)
make.size.equalTo(rightArrowSize)
}
}
/// 用户头像
lazy var userImgView : UIImageView = {
let img = UIImageView()
img.cornerRadius = 25
img.borderColor = kWhiteColor
img.borderWidth = klineDoubleWidth
return img
}()
/// cell title
lazy var nameLab : UILabel = {
let lab = UILabel()
lab.font = k15Font
lab.textColor = kBlackFontColor
return lab
}()
lazy var desLab : UILabel = {
let lab = UILabel()
lab.font = k13Font
lab.textColor = kGaryFontColor
lab.textAlignment = .right
return lab
}()
/// 右侧箭头图标
lazy var rightIconView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_right_arrow"))
}
| 29.975309 | 106 | 0.611203 |
f427b71fcf4cd42f83bf71f17f7147b0e228f11f | 469 | import Cocoa
extension NSView {
public func addTextField(stringValue: String,
fontName: String = "Courier",
fontSize: CGFloat = 160.0,
alphaValue: CGFloat) {
let textField = NSTextField(frame: bounds)
textField.stringValue = stringValue
textField.font = NSFont(name: fontName, size: fontSize)
textField.alphaValue = alphaValue
addSubview(textField)
}
}
| 29.3125 | 63 | 0.592751 |
2fdf576fce72f4c7daa2a7ee22b4e994614448ec | 276 | import Foundation
class Square {
func draw() {
print("Draw Square")
}
}
/**
let customSquare = Square() {
override func draw() {
print("Custom")
}
}
*/
let square = Square()
print(String(describing: type(of: square)))
print(1)
| 10.615385 | 43 | 0.550725 |
7570f73fa75fa9db46e23b49dce5075052a25dcb | 2,009 | //
// ListOrderCodes.swift
// Asclepius
// Module: STU3
//
// Copyright (c) 2022 Bitmatic Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
Base values for the order of the items in a list resource.
URL: http://terminology.hl7.org/CodeSystem/list-order
ValueSet: http://hl7.org/fhir/ValueSet/list-order
*/
public enum ListOrderCodes: String, AsclepiusPrimitiveType {
/// The list was sorted by a user. The criteria the user used are not specified.
case user
/// The list was sorted by the system. The criteria the user used are not specified; define additional codes to
/// specify a particular order (or use other defined codes).
case system
/// The list is sorted by the data of the event. This can be used when the list has items which are dates with past
/// or future events.
case eventDate = "event-date"
/// The list is sorted by the date the item was added to the list. Note that the date added to the list is not
/// explicit in the list itself.
case entryDate = "entry-date"
/// The list is sorted by priority. The exact method in which priority has been determined is not specified.
case priority
/// The list is sorted alphabetically by an unspecified property of the items in the list.
case alphabetic
/// The list is sorted categorically by an unspecified property of the items in the list.
case category
/// The list is sorted by patient, with items for each patient grouped together.
case patient
}
| 37.203704 | 117 | 0.724739 |
fe30b87430bdb419d9202fb52a21507d49063b6b | 1,401 | //
// LineChartDataPoint.swift
//
//
// Created by Will Dale on 24/01/2021.
//
import SwiftUI
/**
Data for a single data point.
*/
public struct LineChartDataPoint: CTStandardLineDataPoint, IgnoreMe {
public let id: UUID = UUID()
public var value: Double
public var xAxisLabel: String?
public var description: String?
public var date: Date?
public var pointColour: PointColour?
public var ignoreMe: Bool = false
public var legendTag: String = ""
public var xPosition: Double? = nil
/// Data model for a single data point with colour for use with a line chart.
/// - Parameters:
/// - value: Value of the data point
/// - xAxisLabel: Label that can be shown on the X axis.
/// - description: A longer label that can be shown on touch input.
/// - date: Date of the data point if any data based calculations are required.
/// - pointColour: Colour of the point markers.
public init(
value: Double,
xAxisLabel: String? = nil,
description: String? = nil,
date: Date? = nil,
pointColour: PointColour? = nil,
xPosition: Double? = nil
) {
self.value = value
self.xAxisLabel = xAxisLabel
self.description = description
self.date = date
self.pointColour = pointColour
self.xPosition = xPosition
}
}
| 27.470588 | 85 | 0.623126 |
f9fc0d642d106d476e9b3aea3caf63578ceb011a | 587 |
import Foundation
import Vapor
import FluentSQLiteDriver
import GraphZahl
import GraphZahlVaporSupport
import GraphZahlFluentSupport
let app = Application()
let sqliteConfig = SQLiteConfiguration(storage: .file(path: "db.sqlite"))
let databaseConfigFactory = DatabaseConfigurationFactory.sqlite(sqliteConfig)
app.databases.use(databaseConfigFactory, as: .sqlite)
app.databases.default(to: .sqlite)
app.migrations.add(User.Migration())
app.migrations.add(Todo.Migration())
try app.autoMigrate().wait()
app.routes.graphql(use: API.self, includeGraphiQL: true) { $0.db }
try app.run()
| 26.681818 | 77 | 0.804089 |
67f851b197fa5c8ed30f3ef75764beb508ab3d8a | 291 | // RUN: not %target-swift-frontend %s -parse
// 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 b {
let start = 0) {
case c, x }))(c()
var b(")
protocol B : a {
func a
| 22.384615 | 87 | 0.690722 |
08dabe3581121a7dba6d815740076bc625afb79d | 1,422 | //
// Reusable.swift
// ACKategories
//
// Created by Jakub Olejník on 09/01/2020.
//
import MapKit
public protocol Reusable { }
extension Reusable {
/// Reuse identifier
public static var reuseIdentifier: String {
return NSStringFromClass(self as! AnyObject.Type)
}
}
extension MKAnnotationView: Reusable { }
extension MKMapView {
/// Dequeues `MKAnnotationView` generically according to expression result type.
///
/// Annotation view doesn't need to be registered as this method registers it before usage.
///
/// For iOS versions lower than `iOS 11.0` the Annotation view is dequeued at first and then created if non-exitent.
public func dequeueAnnotationView<T>(for annotation: MKAnnotation) -> T where T: MKAnnotationView {
if #available(iOS 11.0, macOS 10.13, *) {
register(T.classForCoder(), forAnnotationViewWithReuseIdentifier: T.reuseIdentifier)
return dequeueReusableAnnotationView(withIdentifier: T.reuseIdentifier, for: annotation) as! T
} else {
if let annotationView = dequeueReusableAnnotationView(withIdentifier: T.reuseIdentifier) {
annotationView.annotation = annotation
return annotationView as! T
}
let annotationView = T()
annotationView.annotation = annotation
return annotationView
}
}
}
| 33.069767 | 120 | 0.668073 |
f56b7f0e0c5a8ff7ce90d56ff41c70cedecf1bde | 745 | import SwiftUI
/// PathBuilders define how a navigation path is built into a view hierarchy
public protocol PathBuilder {
associatedtype Content: View
func build(pathElement: NavigationPathElement) -> Content?
}
/// Convenience type to define PathBuilders based on a build closure
public struct _PathBuilder<Content: View>: PathBuilder {
private let _buildPathElement: (NavigationPathElement) -> Content?
public init(_ buildPathElement: @escaping (NavigationPathElement) -> Content?) {
self._buildPathElement = buildPathElement
}
public func build(pathElement: NavigationPathElement) -> Content? {
return _buildPathElement(pathElement)
}
}
/// Namespace enum for all available PathBuilders
public enum PathBuilders {}
| 31.041667 | 82 | 0.775839 |
626fa6b31b64d310939eb471577ceeb12e90edb4 | 4,798 | //
// ManagedObject.swift
// Moody
//
// Created by Florian on 29/05/15.
// Copyright (c) 2015 objc.io. All rights reserved.
//
import CoreData
public protocol Managed: class, NSFetchRequestResult {
static var entity: NSEntityDescription { get }
static var entityName: String { get }
static var defaultSortDescriptors: [NSSortDescriptor] { get }
static var defaultPredicate: NSPredicate { get }
var managedObjectContext: NSManagedObjectContext? { get }
}
public protocol DefaultManaged: Managed {}
extension DefaultManaged {
public static var defaultPredicate: NSPredicate { return NSPredicate(value: true) }
}
extension Managed {
public static var defaultSortDescriptors: [NSSortDescriptor] { return [] }
public static var defaultPredicate: NSPredicate { return NSPredicate(value: true) }
public static var sortedFetchRequest: NSFetchRequest<Self> {
let request = NSFetchRequest<Self>(entityName: entityName)
request.sortDescriptors = defaultSortDescriptors
request.predicate = defaultPredicate
// <<managed-object-type-extension-1>>
return request
}
public static func sortedFetchRequest(with predicate: NSPredicate) -> NSFetchRequest<Self> {
let request = sortedFetchRequest
guard let existingPredicate = request.predicate else { fatalError("must have predicate") }
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [existingPredicate, predicate])
return request
}
public static func predicate(format: String, _ args: CVarArg...) -> NSPredicate {
let p = withVaList(args) { NSPredicate(format: format, arguments: $0) }
return predicate(p)
}
public static func predicate(_ predicate: NSPredicate) -> NSPredicate {
return NSCompoundPredicate(andPredicateWithSubpredicates: [defaultPredicate, predicate])
}
}
extension Managed where Self: NSManagedObject {
public static var entity: NSEntityDescription { return entity() }
public static var entityName: String { return entity.name! }
public static func findOrCreate(in context: NSManagedObjectContext, matching predicate: NSPredicate, configure: (Self) -> ()) -> Self {
guard let object = findOrFetch(in: context, matching: predicate) else {
let newObject: Self = context.insertObject()
configure(newObject)
return newObject
}
return object
}
public static func findOrFetch(in context: NSManagedObjectContext, matching predicate: NSPredicate) -> Self? {
guard let object = materializedObject(in: context, matching: predicate) else {
return fetch(in: context) { request in
request.predicate = predicate
request.returnsObjectsAsFaults = false
request.fetchLimit = 1
}.first
}
return object
}
public static func fetch(in context: NSManagedObjectContext, configurationBlock: (NSFetchRequest<Self>) -> () = { _ in }) -> [Self] {
let request = NSFetchRequest<Self>(entityName: Self.entityName)
configurationBlock(request)
return try! context.fetch(request)
}
public static func count(in context: NSManagedObjectContext, configure: (NSFetchRequest<Self>) -> () = { _ in }) -> Int {
let request = NSFetchRequest<Self>(entityName: entityName)
configure(request)
return try! context.count(for: request)
}
public static func materializedObject(in context: NSManagedObjectContext, matching predicate: NSPredicate) -> Self? {
for object in context.registeredObjects where !object.isFault {
guard let result = object as? Self, predicate.evaluate(with: result) else { continue }
return result
}
return nil
}
}
extension Managed where Self: NSManagedObject {
public static func fetchSingleObject(in context: NSManagedObjectContext, cacheKey: String, configure: (NSFetchRequest<Self>) -> ()) -> Self? {
if let cached = context.object(forSingleObjectCacheKey: cacheKey) as? Self { return cached
}
let result = fetchSingleObject(in: context, configure: configure)
context.set(result, forSingleObjectCacheKey: cacheKey)
return result
}
fileprivate static func fetchSingleObject(in context: NSManagedObjectContext, configure: (NSFetchRequest<Self>) -> ()) -> Self? {
let result = fetch(in: context) { request in
configure(request)
request.fetchLimit = 2
}
switch result.count {
case 0: return nil
case 1: return result[0]
default: fatalError("Returned multiple objects, expected max 1")
}
}
}
| 36.348485 | 146 | 0.675698 |
3a78875e16a445c900c9dba1fc4f804fff2c6152 | 2,266 | //
// HTMLParser.swift
// Timely2
//
// Created by Mihai Leonte on 1/10/19.
// Copyright © 2019 Mihai Leonte. All rights reserved.
//
import Foundation
extension NSMutableAttributedString {
func setFontFace(font: UIFont, color: UIColor? = nil) {
beginEditing()
self.enumerateAttribute(.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
if let f = value as? UIFont, let newFontDescriptor = f.fontDescriptor.withFamily(font.familyName).withSymbolicTraits(f.fontDescriptor.symbolicTraits) {
let newFont = UIFont(descriptor: newFontDescriptor, size: font.pointSize)
removeAttribute(.font, range: range)
addAttribute(.font, value: newFont, range: range)
if let color = color {
removeAttribute(.foregroundColor, range: range)
addAttribute(.foregroundColor, value: color, range: range)
}
}
}
endEditing()
}
}
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .unicode) else { return NSAttributedString() }
do {
//return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
let attributedString = try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
//Change the font, size and color only - but leave the other attributes in place (eg: bold, italic)
let mutableAttrString = NSMutableAttributedString(attributedString: attributedString) as NSMutableAttributedString
mutableAttrString.setFontFace(font: UIFont.systemFont(ofSize: 14), color: .darkGray)
return mutableAttrString as NSAttributedString
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
| 42.754717 | 188 | 0.634598 |
2f458985db48ee551f3765b4f5f1e936a046b379 | 1,291 | //
// UIViewController+Format.swift
// Common
//
// Created by Paul Calnan on 8/13/18.
// Copyright © 2018 Bose Corporation. All rights reserved.
//
import UIKit
/// String formatting utilities
extension UIViewController {
/// Utility to format radians as degrees with two decimal places and a degree symbol.
func format(radians: Double) -> String {
let degrees = radians * 180 / Double.pi
return String(format: "%.02f°", degrees)
}
/// Utility to format radians as degrees with two decimal places and a degree symbol.
func format(radians: Float) -> String {
let degrees = radians * 180 / Float.pi
return String(format: "%.02f°", degrees)
}
/// Utility to format degrees with two decimal places and a degree symbol.
func format(degrees: Double) -> String {
return String(format: "%.02f°", degrees)
}
/// Utility to format a double with four decimal places.
func format(decimal: Double) -> String {
return String(format: "%.04f", decimal)
}
/// Converts the byte sequence of this Data object into a hexadecimal representation (two lowercase characters per byte).
func format(data: Data?) -> String? {
return data?.map({ String(format: "%02hhX", $0) }).joined()
}
}
| 31.487805 | 125 | 0.651433 |
ff4943852f6c55dc131130acbb04ffa9965bfd12 | 633 | //
// Problem_137Tests.swift
// Problem 137Tests
//
// Created by sebastien FOCK CHOW THO on 2019-10-09.
// Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved.
//
import XCTest
@testable import Problem_137
class Problem_137Tests: XCTestCase {
func test_bitArray() {
var ba = BitArray(size: 10)
ba.set(i: 5, val: true)
print(ba.get(i: 0))
print(ba.get(i: 5))
print(ba.get(i: 11))
ba.set(i: 11, val: true)
ba.set(i: 0, val: true)
ba.set(i: 5, val: false)
print(ba.get(i: 0))
print(ba.get(i: 5))
print(ba.get(i: 11))
}
}
| 21.827586 | 66 | 0.5703 |
906787032a634e5a9085e9802cb9ac5422085f60 | 1,432 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
public final class AtomicValue<Value> {
let lock = NSLock()
var value: Value
public init(initialValue: Value) {
self.value = initialValue
}
public func get() -> Value {
lock.lock()
defer {
lock.unlock()
}
return value
}
public func set(_ newValue: Value) {
lock.lock()
defer {
lock.unlock()
}
value = newValue
}
/// Sets AtomicValue to `newValue` and returns the old value
public func getAndSet(_ newValue: Value) -> Value {
lock.lock()
defer {
lock.unlock()
}
let oldValue = value
value = newValue
return oldValue
}
/// Performs `block` with the current value, preventing other access until the block exits.
public func atomicallyPerform(block: (Value) -> Void) {
lock.lock()
defer {
lock.unlock()
}
block(value)
}
/// Performs `block` with an `inout` value, preventing other access until the block exits,
/// and enabling the block to mutate the value
public func with(block: (inout Value) -> Void) {
lock.lock()
defer {
lock.unlock()
}
block(&value)
}
}
| 21.69697 | 95 | 0.552374 |
e22ba231ef7294802bdc7693fa64b18b426a39d0 | 1,824 | //
// Operators.swift
// RxAlgebra
//
// Created by Arnon Keereena on 14/2/2562 BE.
// Copyright © 2562 AMOS Thailand. All rights reserved.
//
import Foundation
// MARK: - Transform operators
/// map
infix operator >>>: AdditionPrecedence
/// flatMap
infix operator >->: AdditionPrecedence
/// flatMapLatest
infix operator >--: AdditionPrecedence
/// flatMapFirst
infix operator >-|: AdditionPrecedence
// MARK: - Side effects
/// do onNext
infix operator +>>: AdditionPrecedence
/// do onError
infix operator +!>: AdditionPrecedence
/// do onCompleted
infix operator ++>: AdditionPrecedence
/// take || dispose
infix operator |: AdditionPrecedence
/// Tracking extraction
infix operator |>: AdditionPrecedence
// MARK: - Binding
/// Subscribe, one-way binding
infix operator -->: AdditionPrecedence
/// Two-way binding
infix operator <->: AdditionPrecedence
// MARK: - Filtration
/// filter
infix operator ~~~: AdditionPrecedence
/// unwrap
postfix operator ~~!
/// distinctUntilChanged
prefix operator ==
// MARK: - Merging
/// startWith
infix operator |>>: AdditionPrecedence
/// withLatestFrom (right)
infix operator ||&: AdditionPrecedence
/// withLatestFrom (left, right)
infix operator |&&: AdditionPrecedence
/// combineLatest
postfix operator +++
infix operator +++: AdditionPrecedence
/// zip
postfix operator +-+
infix operator +-+: AdditionPrecedence
/// merge
infix operator ***: MultiplicationPrecedence
// MARK: - Util
/// debounce
infix operator --/: AdditionPrecedence
/// throttle
infix operator /--: AdditionPrecedence
// MARK: - Special combination
///// combineLatest { == }, but this is declared by foundation
//infix operator ===: LogicalConjunctionPrecedence
/// combineLatest { && }
infix operator &&&: LogicalConjunctionPrecedence
/// reduce
prefix operator ∑
| 17.882353 | 62 | 0.717105 |
4a1ce1f1d2e2af5519b7332aeb9b5f44e5740250 | 9,387 | //
// PermissionsViewControllerTests.swift
// SonarTests
//
// Created by NHSX on 4/1/20.
// Copyright © 2020 NHSX. All rights reserved.
//
import CoreBluetooth
import XCTest
@testable import Sonar
class PermissionsViewControllerTests: TestCase {
func test_ios13_BluetoothNotDetermined_callsContinueHandlerWhenBothGranted() {
let authManagerDouble = AuthorizationManagerDouble(bluetooth: .notDetermined)
let remoteNotificationManagerDouble = RemoteNotificationManagerDouble()
let nursery = BluetoothNurseryDouble()
let persistence = PersistenceDouble()
let vc = PermissionsViewController.instantiate()
var continued = false
vc.inject(authManager: authManagerDouble,
remoteNotificationManager: remoteNotificationManagerDouble,
bluetoothNursery: nursery,
persistence: persistence,
uiQueue: QueueDouble()) {
continued = true
}
parentViewControllerForTests.viewControllers = [vc]
XCTAssertNotNil(vc.view)
vc.didTapContinue()
XCTAssertTrue(persistence.bluetoothPermissionRequested)
#if targetEnvironment(simulator)
// We skip Bluetooth on the simulator.
#else
authManagerDouble.bluetooth = .allowed
nursery.stateObserver.btleListener(BTLEListenerDouble(), didUpdateState: .poweredOn)
#endif
XCTAssertFalse(continued)
XCTAssertNotNil(authManagerDouble.notificationsCompletion)
authManagerDouble.notificationsCompletion?(.allowed)
XCTAssertTrue(continued)
}
func test_ios12_BluetoothNotDetermined_callsContinueHandlerWhenViewAppearsAfterBothGranted() {
let authManagerDouble = AuthorizationManagerDouble(bluetooth: .notDetermined)
let remoteNotificationManagerDouble = RemoteNotificationManagerDouble()
let nursery = BluetoothNurseryDouble()
let persistence = PersistenceDouble()
let vc = PermissionsViewController.instantiate()
var continued = false
vc.inject(authManager: authManagerDouble,
remoteNotificationManager: remoteNotificationManagerDouble,
bluetoothNursery: nursery,
persistence: persistence,
uiQueue: QueueDouble()) {
continued = true
}
parentViewControllerForTests.viewControllers = [vc]
XCTAssertNotNil(vc.view)
vc.didTapContinue()
XCTAssertTrue(persistence.bluetoothPermissionRequested)
#if targetEnvironment(simulator)
// We skip Bluetooth on the simulator.
#else
nursery.stateObserver.btleListener(BTLEListenerDouble(), didUpdateState: .poweredOn)
authManagerDouble.bluetooth = .allowed
vc.viewWillAppear(false) // called when the user returns to the app
XCTAssertNotNil(authManagerDouble.bluetoothCompletion)
authManagerDouble.bluetoothCompletion?(.allowed)
#endif
XCTAssertFalse(continued)
XCTAssertNotNil(authManagerDouble.notificationsCompletion)
authManagerDouble.notificationsCompletion?(.allowed)
XCTAssertTrue(continued)
}
func test_ios12_BluetoothNotDetermined_requestsNotificationAuthWhenBluetoothDenied() {
let authManagerDouble = AuthorizationManagerDouble(bluetooth: .notDetermined)
let remoteNotificationManagerDouble = RemoteNotificationManagerDouble()
let nursery = BluetoothNurseryDouble()
let persistence = PersistenceDouble()
let vc = PermissionsViewController.instantiate()
var continued = false
vc.inject(authManager: authManagerDouble,
remoteNotificationManager: remoteNotificationManagerDouble,
bluetoothNursery: nursery,
persistence: persistence,
uiQueue: QueueDouble()) {
continued = true
}
parentViewControllerForTests.viewControllers = [vc]
XCTAssertNotNil(vc.view)
vc.didTapContinue()
XCTAssertTrue(persistence.bluetoothPermissionRequested)
#if targetEnvironment(simulator)
// We skip Bluetooth on the simulator.
#else
nursery.stateObserver.btleListener(BTLEListenerDouble(), didUpdateState: .poweredOn)
authManagerDouble.bluetooth = .allowed
vc.viewWillAppear(false) // called when the user returns to the app
XCTAssertNotNil(authManagerDouble.bluetoothCompletion)
authManagerDouble.bluetoothCompletion?(.denied)
#endif
XCTAssertFalse(continued)
XCTAssertNotNil(authManagerDouble.notificationsCompletion)
}
func testBluetoothNotDetermined_callsContinueHandlerOnChangeToDenied() throws {
#if targetEnvironment(simulator)
throw XCTSkip("This test can't run in the simulator.")
#else
let authManagerDouble = AuthorizationManagerDouble(bluetooth: .notDetermined)
let remoteNotificationManagerDouble = RemoteNotificationManagerDouble()
let nursery = BluetoothNurseryDouble()
let persistence = PersistenceDouble()
let vc = PermissionsViewController.instantiate()
var continued = false
vc.inject(authManager: authManagerDouble,
remoteNotificationManager: remoteNotificationManagerDouble,
bluetoothNursery: nursery,
persistence: persistence,
uiQueue: QueueDouble()) {
continued = true
}
parentViewControllerForTests.viewControllers = [vc]
XCTAssertNotNil(vc.view)
vc.didTapContinue()
XCTAssertTrue(persistence.bluetoothPermissionRequested)
authManagerDouble.bluetooth = .denied
nursery.stateObserver.btleListener(BTLEListenerDouble(), didUpdateState: .poweredOn)
XCTAssert(continued)
#endif
}
func testBluetoothAllowed_promptsForNotificationWhenShown() {
let authManagerDouble = AuthorizationManagerDouble(bluetooth: .allowed)
let remoteNotificationManagerDouble = RemoteNotificationManagerDouble()
let vc = PermissionsViewController.instantiate()
var continued = false
vc.inject(authManager: authManagerDouble,
remoteNotificationManager: remoteNotificationManagerDouble,
bluetoothNursery: BluetoothNurseryDouble(),
persistence: PersistenceDouble(),
uiQueue: QueueDouble()) {
continued = true
}
parentViewControllerForTests.viewControllers = [vc]
XCTAssertNotNil(vc.view)
vc.viewWillAppear(false)
XCTAssertFalse(continued)
XCTAssertNotNil(authManagerDouble.bluetoothCompletion)
authManagerDouble.bluetoothCompletion?(.allowed)
XCTAssertNotNil(authManagerDouble.notificationsCompletion)
authManagerDouble.notificationsCompletion?(.allowed)
XCTAssertTrue(continued)
}
func testPreventsDoubleSubmit() {
let authManagerDouble = AuthorizationManagerDouble(bluetooth: .allowed)
let remoteNotificationManagerDouble = RemoteNotificationManagerDouble()
let vc = PermissionsViewController.instantiate()
vc.inject(authManager: authManagerDouble,
remoteNotificationManager: remoteNotificationManagerDouble,
bluetoothNursery: BluetoothNurseryDouble(),
persistence: PersistenceDouble(),
uiQueue: QueueDouble()) {}
parentViewControllerForTests.viewControllers = [vc]
XCTAssertNotNil(vc.view)
vc.viewWillAppear(false)
XCTAssertTrue(vc.activityIndicator.isHidden)
XCTAssertFalse(vc.continueButton.isHidden)
vc.didTapContinue()
XCTAssertFalse(vc.activityIndicator.isHidden)
XCTAssertTrue(vc.activityIndicator.isAnimating)
XCTAssertTrue(vc.continueButton.isHidden)
}
func testBluetoothAlreadyDetermined() {
let authManagerDouble = AuthorizationManagerDouble(bluetooth: .allowed)
let remoteNotificationManagerDouble = RemoteNotificationManagerDouble()
let vc = PermissionsViewController.instantiate()
var continued = false
vc.inject(authManager: authManagerDouble,
remoteNotificationManager: remoteNotificationManagerDouble,
bluetoothNursery: BluetoothNurseryDouble(),
persistence: PersistenceDouble(),
uiQueue: QueueDouble()) {
continued = true
}
parentViewControllerForTests.viewControllers = [vc]
XCTAssertNotNil(vc.view)
vc.didTapContinue()
XCTAssertNotNil(authManagerDouble.notificationsCompletion)
authManagerDouble.notificationsCompletion!(.notDetermined)
XCTAssertNotNil(remoteNotificationManagerDouble.requestAuthorizationCompletion)
remoteNotificationManagerDouble.requestAuthorizationCompletion?(.success(true))
XCTAssert(continued)
}
}
fileprivate struct DummyBTLEListener: BTLEListener {
func start(stateDelegate: BTLEListenerStateDelegate?, delegate: BTLEListenerDelegate?) { }
func connect(_ peripheral: BTLEPeripheral) { }
func isHealthy() -> Bool { return false }
}
| 39.1125 | 98 | 0.691808 |
ffaac3f93b8877af4015ec18908b656dc9dac608 | 2,726 | import XCTest
import IrohaCrypto
import RobinHood
@testable import fearless
class SubscanTests: XCTestCase {
func testFetchPriceDifference() throws {
do {
guard let url = WalletAssetId.kusama.subscanUrl?
.appendingPathComponent(SubscanApi.price) else {
XCTFail("unexpected empty url")
return
}
let subscan = SubscanOperationFactory()
let currentTime = Int64(Date().timeIntervalSince1970)
let prevTime = currentTime - 24 * 3600
let currentPriceOperation = subscan.fetchPriceOperation(url, time: currentTime)
let prevPriceOperation = subscan.fetchPriceOperation(url, time: prevTime)
let diffOperation: BaseOperation<Decimal> = ClosureOperation {
let currentPrice = try currentPriceOperation
.extractResultData(throwing: BaseOperationError.parentOperationCancelled)
let prevPrice = try prevPriceOperation
.extractResultData(throwing: BaseOperationError.parentOperationCancelled)
guard let currentPriceString = currentPrice.records
.first(where: { $0.time <= currentTime})?.price else {
return Decimal.zero
}
guard let currentPriceValue = Decimal(string: currentPriceString) else {
throw NetworkBaseError.unexpectedResponseObject
}
let prevPriceValue: Decimal
if let prevPriceString = prevPrice.records.first(where: { $0.time <= prevTime} )?.price {
guard let value = Decimal(string: prevPriceString) else {
throw NetworkBaseError.unexpectedResponseObject
}
prevPriceValue = value
} else {
prevPriceValue = .zero
}
guard prevPriceValue > .zero else {
return 100
}
return ((currentPriceValue - prevPriceValue) / prevPriceValue) * 100.0
}
diffOperation.addDependency(currentPriceOperation)
diffOperation.addDependency(prevPriceOperation)
OperationQueue().addOperations([currentPriceOperation, prevPriceOperation, diffOperation],
waitUntilFinished: true)
let result = try diffOperation
.extractResultData(throwing: BaseOperationError.parentOperationCancelled)
Logger.shared.debug("Did receive result: \(result)")
} catch {
XCTFail("Did receive error \(error)")
}
}
}
| 38.394366 | 105 | 0.586941 |
e89e56690de41cdaa8a2a83acc07991713012d84 | 622 | //
// ButtonViewSnapshotTests.swift
// HeremindersTests
//
// Created by sara.batista.d.felix on 19/08/21.
// Copyright © 2021 Rodrigo Borges. All rights reserved.
//
import XCTest
import SnapshotTesting
@testable import Hereminders
class ButtonViewSnapshotTests: XCTestCase {
func testButtonView(){
let button = ButtonView()
let buttonViewModel = ButtonViewModel(titleButton: "Add new place")
button.configure(with: buttonViewModel)
assertSnapshot(matching: button, as: Snapshotting.image(size: CGSize(width: 343, height: 44)), record: false)
}
}
| 24.88 | 117 | 0.686495 |
5bfebeba8666b05c36c56ab9e068a90ba17a52b7 | 287 | //
// TMDbApiConfiguration.swift
// YoyoFramework
//
// Created by Amadeu Cavalcante Filho on 04/11/18.
// Copyright © 2018 Amadeu Cavalcante Filho. All rights reserved.
//
import Foundation
import Foundation
import CoreData
public class TMDbApiConfiguration: NSManagedObject {
}
| 17.9375 | 66 | 0.763066 |
d768e89a6b00a3c37e7259e4b7b9d5b97f47d86d | 789 | //
// HTGKBannerDelegate.swift
// HTGKBannerKit
//
// Created by yujinhai on 2019/5/16.
// Copyright © 2019 Forever High Tech Ltd. All rights reserved.
//
import UIKit
@objc public protocol HTGKBannerDelegate: NSObjectProtocol {
/// 点击图片
@objc optional func bannerView(_ bannerView: HTGKBannerView, didSelectItemAt index: Int)
}
@objc public protocol HTGKBannerDataSource: NSObjectProtocol {
/// 返回个数
func numberOfRows(_ bannerView: HTGKBannerView) -> Int
/// 需要渲染的cell
func bannerViewCell(_ cell: UICollectionViewCell, for index: NSInteger, bannerView: HTGKBannerView)
func bannerViewCellIdentifier() -> String
@objc optional func bannerViewCellClassForBannerView() -> AnyClass
@objc optional func bannerViewCellNibForBannerView() -> UINib
}
| 28.178571 | 103 | 0.74398 |
561d4d6e1aa0b62ecc5010ae6cfa003c3ed4f333 | 245 | //
// PokemonListModel+.swift
// Presentation
//
// Created by Tomosuke Okada on 2020/06/20.
//
import Domain
import Foundation
extension PokemonListModel.Pokemon: Identifiable {
public var id: Int {
return self.number
}
}
| 14.411765 | 50 | 0.681633 |
cc3c6024eb6792ab991b46a7adcff4a82c3346a4 | 1,175 | //
// PKHapticFeedbackUITests.swift
// PKHapticFeedbackUITests
//
// Created by Pranav Kasetti on 10/07/2017.
// Copyright © 2017 Pranav Kasetti. All rights reserved.
//
import XCTest
class PKHapticFeedbackUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 31.756757 | 176 | 0.729362 |
6a5669b0a00f776a963e791c9d90569f029320bf | 5,351 | //
// UIImageExtension.swift
// PWImageNetDemo
//
// Created by 王炜程 on 16/7/7.
// Copyright © 2016年 weicheng wang. All rights reserved.
//
import UIKit
import ImageIO
enum PWImageType {
case Unknwon
case JPEG
case PNG
case GIF
case TIFF
}
extension UIImage {
class func imageFormat(data: NSData) -> UIImage? {
if UIImage.contentType(data) == PWImageType.GIF {
return UIImage.animatedImage(data: data)
}else{
return UIImage(data: data)
}
}
class func contentType(url: NSURL) -> PWImageType {
if let type = url.pathExtension {
switch type.lowercaseString {
case "jpg", "jpeg":
return .JPEG
case "png":
return .PNG
case "gif":
return .GIF
case "tiff":
return .TIFF
default:
return .Unknwon
}
}
return .Unknwon
}
class func contentType(imageData: NSData) -> PWImageType {
var c = [UInt8](count: 1, repeatedValue: 0)
imageData.getBytes(&c, length: 1)
switch c[0] {
case 0xFF:
return .JPEG
case 0x89:
return .PNG
case 0x47:
return .GIF
case 0x49, 0x4D:
return .TIFF
default:
return .Unknwon
}
}
class func animatedImage(data data: NSData) -> UIImage? {
guard let source = CGImageSourceCreateWithData(data, nil) else {
return nil
}
return UIImage.animatedImage(source: source)
}
class func animatedImage(source source: CGImageSource) -> UIImage? {
let count = CGImageSourceGetCount(source)
var animatedImages = [CGImageRef]()
var delays = [Int]()
for i in 0..<count {
if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
animatedImages.append(image)
}
let delay = UIImage.delayForImageAtIndex(i, source: source)
delays.append(Int(delay * 1000.0)) // 转成毫秒存下来
}
// 计算总时长
let duration: Int = {
var sum = 0
for val: Int in delays {
sum += val
}
return sum
}()
// Get frames
let gcd = UIImage.gcdForArray(delays)
var frames = [UIImage]()
var frame: UIImage
var frameCount: Int
for i in 0..<count {
frame = UIImage(CGImage: animatedImages[Int(i)])
frameCount = Int(delays[Int(i)] / gcd)
for _ in 0..<frameCount {
frames.append(frame)
}
}
let animation = UIImage.animatedImageWithImages(frames,
duration: Double(duration) / 1000.0)
return animation
}
/**
获取 gif 图片的每一帧的时间数组
- author: wangweicheng
- parameter index: 索引
- parameter source: 图片源
- returns: 帧数组
*/
class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double {
var delay = 0.1
// Get dictionaries
let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
let gifProperties: CFDictionaryRef = unsafeBitCast(
CFDictionaryGetValue(cfProperties,
unsafeAddressOf(kCGImagePropertyGIFDictionary)),
CFDictionary.self)
// Get delay time
var delayObject: AnyObject = unsafeBitCast(
CFDictionaryGetValue(gifProperties,
unsafeAddressOf(kCGImagePropertyGIFUnclampedDelayTime)),
AnyObject.self)
if delayObject.doubleValue == 0 {
delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,
unsafeAddressOf(kCGImagePropertyGIFDelayTime)), AnyObject.self)
}
delay = delayObject as! Double
if delay < 0.1 {
delay = 0.1 // Make sure they're not too fast
}
return delay
}
class func gcdForArray(array: Array<Int>) -> Int {
if array.isEmpty {
return 1
}
var gcd = array[0]
for val in array {
gcd = UIImage.gcdForPair(val, gcd)
}
return gcd
}
class func gcdForPair(a: Int?, _ b: Int?) -> Int {
var a = a
var b = b
// Check if one of them is nil
if b == nil || a == nil {
if b != nil {
return b!
} else if a != nil {
return a!
} else {
return 0
}
}
// Swap for modulo
if a < b {
let c = a
a = b
b = c
}
// Get greatest common divisor
var rest: Int
while true {
rest = a! % b!
if rest == 0 {
return b! // Found it
} else {
a = b
b = rest
}
}
}
}
| 25.240566 | 92 | 0.478789 |
799940a51e1adf5d6e7b7ee268804cf20495b374 | 209 | import UIFlow
class OnboardingViewController: UIFlowViewController {
var finishedOnboarding: (() -> Void)?
@IBAction func finishedButtonTouchUpInside(_ sender: Any) {
finishedOnboarding?()
}
}
| 19 | 60 | 0.732057 |
d6b9d5e1503e285f5e8c973ba5bb85af48913372 | 240 | //
// Instantiable.swift
// Marvel
//
// Created by Diego Rogel on 23/1/22.
//
import Foundation
protocol ViewModelInstantiable {
associatedtype ViewModelProtocol
static func instantiate(viewModel: ViewModelProtocol) -> Self
}
| 17.142857 | 65 | 0.733333 |
262a489bc6930b9decb222a7e0b2696538cfbdf2 | 331 | //
// BurstThroughView.swift
// Burst
//
// Created by Jovins on 2021/3/18.
//
import UIKit
final class BurstThroughView: UIView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
return view == self ? nil : view
}
}
| 18.388889 | 78 | 0.607251 |
674534b97a138fb6d32521023aa58b7d96beca3d | 1,777 | //
// AppDelegate.swift
// sumubackup
//
// Created by Hamik on 3/29/20.
// Copyright © 2020 Sumu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
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.
}
}
extension UIImage {
public func sha256() -> String {
if let imageData = cgImage?.dataProvider?.data as Data? {
return Utilities.HexStringFromData(input: Utilities.Digest(input: imageData as NSData))
}
return ""
}
}
extension Data {
public func sha256() -> String {
return Utilities.HexStringFromData(input: Utilities.Digest(input: self as NSData))
}
}
| 36.265306 | 179 | 0.723129 |
f96d2736f8379891c2cdf1f25d4df23cde180690 | 2,969 | //
// UIView+CornerRadius.swift
// FZBuildingBlock
//
// Created by FranZhou on 2019/2/21.
//
import Foundation
extension FZBuildingBlockWrapper where Base: UIView {
/// 传统方式给view添加圆角,内部会将masksToBounds设为true
///
/// - Parameters:
/// - radius: 圆角半径
/// - borderColor: default = .clear, border color
/// - borderWidth: default = 0, border width
public func addCornerRadius(withRadius radius: CGFloat, borderColor: UIColor = .clear, borderWidth: CGFloat = 0) {
base.layer.masksToBounds = true
base.layer.borderWidth = borderWidth
base.layer.borderColor = borderColor.cgColor
base.layer.cornerRadius = radius
}
/// 使用maskLayer给view添加圆角
///
/// - Parameters:
/// - leftTop: 左上方圆角半径
/// - leftBottom: 左下方圆角半径
/// - rightBottom: 右下方圆角半径
/// - rightTop: 右上方圆角半径
/// - borderColor: default = .clear, border color
/// - borderWidth: default = 0, border width
/// - lineDashPattern: default = nil, 虚线中实线部分和间隔部分分别的长度,默认是实线的
public func addMaskLayerCornerRadius(leftTop: CGFloat, leftBottom: CGFloat, rightBottom: CGFloat, rightTop: CGFloat, borderColor: UIColor = .clear, borderWidth: CGFloat = 0, lineDashPattern: [NSNumber]? = nil) {
base.layoutIfNeeded()
let bezier = UIBezierPath.init()
bezier.lineWidth = borderWidth
borderColor.setStroke()
let width = base.frame.size.width
let height = base.frame.size.height
// 左上方圆角
bezier.move(to: CGPoint(x: leftTop, y: 0))
bezier.addArc(withCenter: CGPoint(x: leftTop, y: leftTop), radius: leftTop, startAngle: -CGFloat.pi/2.0, endAngle: -CGFloat.pi, clockwise: false)
bezier.addLine(to: CGPoint(x: 0, y: height-leftBottom))
// 左下方圆角
bezier.addArc(withCenter: CGPoint(x: leftBottom, y: height-leftBottom), radius: leftBottom, startAngle: -CGFloat.pi, endAngle: -CGFloat.pi*1.5, clockwise: false)
bezier.addLine(to: CGPoint(x: width-rightBottom, y: height))
// 右下方圆角
bezier.addArc(withCenter: CGPoint(x: width-rightBottom, y: height-rightBottom), radius: rightBottom, startAngle: -CGFloat.pi*0.5, endAngle: 0, clockwise: false)
bezier.addLine(to: CGPoint(x: width, y: rightTop))
// 右上方圆角
bezier.addArc(withCenter: CGPoint(x: width-rightTop, y: rightTop), radius: rightTop, startAngle: 0, endAngle: -CGFloat.pi*0.5, clockwise: false)
bezier.addLine(to: CGPoint(x: leftTop, y: 0))
// 封闭未形成闭环的路径
bezier.close()
// 路径绘制
bezier.stroke()
let maskLayer = CAShapeLayer()
maskLayer.frame = base.bounds
maskLayer.lineDashPattern = lineDashPattern
maskLayer.path = bezier.cgPath
base.layer.mask = maskLayer
}
}
| 34.126437 | 215 | 0.612664 |
e977e0de151520d9497adb9c419d6ed8ee8d529d | 3,328 | //
// CHSTProfileController.swift
// weiboCopy
//
// Created by 王 on 15/12/12.
// Copyright © 2015年 王. All rights reserved.
//
import UIKit
class CHSTProfileController: CHSBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
guestView?.setUpThePages("登录后,你的微博、相册、个人资料会显示在这里,展示给别人", imageNmae: "visitordiscover_image_profile")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 34.309278 | 157 | 0.688702 |
cc16798e5e803db498e20b8abbb64fff593d8b43 | 2,610 | //
// BonsaiPopupUtility.swift
// BonsaiController_Example
//
// Created by Warif Akhand Rishi on 1/6/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import BonsaiController
class BonsaiPopupUtility: NSObject {
static let shared = BonsaiPopupUtility()
let popupSize = CGSize(width: 280, height: 150)
func show(viewController: UIViewController) {
viewController.transitioningDelegate = self
viewController.modalPresentationStyle = .custom
topViewController()?.present(viewController, animated: true, completion: nil)
}
}
extension BonsaiPopupUtility {
func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
extension BonsaiPopupUtility: BonsaiControllerDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
let frame = frameOfPresentedView(in: source.view.frame)
let originFrame = frame.insetBy(dx: -20, dy: -20)
var blurEffectStyle = UIBlurEffect.Style.light
if #available(iOS 13.0, *) {
blurEffectStyle = .systemChromeMaterial
}
let bonsaiController = BonsaiController(fromView: UIView(frame: originFrame), blurEffectStyle: blurEffectStyle, presentedViewController: presented, delegate: self)
bonsaiController.springWithDamping = 0.5
bonsaiController.duration = 0.5
bonsaiController.isDisabledTapOutside = true
bonsaiController.isDisabledDismissAnimation = true
return bonsaiController
}
func frameOfPresentedView(in containerViewFrame: CGRect) -> CGRect {
return CGRect(origin: CGPoint(x: (containerViewFrame.width - popupSize.width) / 2, y: (containerViewFrame.height - popupSize.height) / 2), size: popupSize)
}
}
| 34.8 | 171 | 0.682375 |
db3b66be1edc904d99bc0659e1f1490e8ee250dd | 1,140 | //
// SubTitles.swift
// MMPlayerView
//
// Created by Millman on 2019/12/13.
//
import Foundation
public class MMSubTitles<C: ConverterProtocol> {
let converter: C
public init(_ converter: C) {
self.converter = converter
}
public func parseText(_ value: String) {
converter.parseText(value)
}
public func search(duration: TimeInterval, completed: @escaping ((C.Element)->Void), queue: DispatchQueue?) {
converter.search(duration: duration) { (e) in
if let q = queue {
q.async {
completed(e)
}
} else {
completed(e)
}
}
}
}
//
// let value = Bundle.main.path(forResource: "test", ofType: "srt")!
// if let str = try? String.init(contentsOfFile: value) {
// srt.parseText(str)
// srt.search(duration: 100.95, completed: { (info) in
// print(info)
// })
//
////
//// srt.search(duration: 200, completed: { (info) in
//// print(info)
//// })
//
// }
//
| 23.75 | 113 | 0.497368 |
395256e0dc02aa96245ead1e7d8e6aaf1d522257 | 518 | //
// ErrorScreen.swift
// iosApp
//
// Created by Developer on 29/11/21.
// Copyright © 2021 orgName. All rights reserved.
//
import SwiftUI
struct ErrorScreen: View {
var message: String
var onRetry: ()->Void
var body: some View {
VStack{
Text(message)
PrimaryButton(text: "Retry", onClick: onRetry)
}
}
}
struct ErrorScreen_Previews: PreviewProvider {
static var previews: some View {
ErrorScreen(message: "Test", onRetry: {})
}
}
| 18.5 | 58 | 0.602317 |
fc1f357ed1b08b70ee49dc5d99b6802d79e1633b | 2,344 | //
// AuthInfoList.swift
// MsdGateLock
//
// Created by ox o on 2017/7/23.
// Copyright © 2017年 xiaoxiao. All rights reserved.
//
import UIKit
import ObjectMapper
class AuthInfoListReq: Mappable {
var userId : Int = 0
var lockId : String = ""
var roleType : Int = 1 //1查询授权用户 2 零食用户
init(_ userId : Int,lockId : String,roleType : Int){
self.userId = userId
self.lockId = lockId
self.roleType = roleType
}
required init?(map: Map) {}
func mapping(map: Map) {
userId <- map["userId"]
lockId <- map["lockId"]
roleType <- map["roleType"]
}
}
class AuthInfoListResp: Mappable {
var userId : String = ""
var lockId : String = ""
var roleType : Int = -1 //0拥有者 1查询授权用户 2 零食用户
var sourceName : String = ""
var userImage : String = ""
var startTime : String = ""
var endTime : String = ""
var userTel : String = ""
var isPermenant : Int = 0 //是否永久
required init?(map: Map) {}
func mapping(map: Map) {
userId <- map["userId"]
lockId <- map["lockId"]
roleType <- map["roleType"]
sourceName <- map["sourceName"]
userImage <- map["userImage"]
startTime <- map["startTime"]
endTime <- map["endTime"]
userTel <- map["userTel"]
isPermenant <- map["isPermenant"]
}
}
class AddAuthUserReq: Mappable {
var ownerId : Int = 0
var mobile : String = ""
var memberName : String = ""
var level : Int = 0
var lockId : String = ""
var permissions : String = ""
var code : String = ""
init(_ ownerId : Int,mobile : String,memberName : String,level : Int,lockId : String,permissions : String,code : String){
self.ownerId = ownerId
self.mobile = mobile
self.memberName = memberName
self.level = level
self.lockId = lockId
self.permissions = permissions
self.code = code
}
required init?(map: Map) {}
func mapping(map: Map) {
ownerId <- map["ownerId"]
mobile <- map["mobile"]
memberName <- map["memberName"]
level <- map["level"]
lockId <- map["lockId"]
permissions <- map["permissions"]
code <- map["code"]
}
}
| 22.538462 | 125 | 0.548208 |
ef7252fd9882dd78013d4065a249115ea950e487 | 15,919 | //
// StoreListFilterView.swift
// YogiYoCloneIOS
//
// Created by 김믿음 on 2020/09/15.
// Copyright © 2020 김동현. All rights reserved.
//
import UIKit
import Foundation
import SnapKit
protocol StoreListFilterViewDelegate : class {
func presentStorefilterView(selectedOrder: Int, selectedPayment: Int)
}
class StoreListFilterView: UIView {
// MARK: Properties
var selectedOrder = 0
var selectedPayment = 0
weak var filterViewDelegate: StoreListFilterViewDelegate?
private var storeFilterBigView: StoreFilterbigView?
private let indicatorView : UIView = {
let view = UIView()
return view
}()
private let filterLabel : UILabel = {
let label = UILabel()
label.text = "필터"
label.font = UIFont(name: FontModel.customSemibold, size: 18)
return label
}()
private let closeButton : UIButton = {
let button = UIButton()
button.setImage(UIImage(systemName: "xmark"), for: .normal)
button.imageView?.tintColor = .black
button.addTarget(self, action: #selector(filtercloseButton), for: .touchUpInside)
return button
}()
private let setinit : UIButton = {
let button = UIButton()
button.setTitle("초기화", for: .normal)
button.setTitleColor(.black, for: .normal)
button.addTarget(self, action: #selector(setInitButtonClicked), for: .touchUpInside)
return button
}()
private let horizontalIndicator : UIView = {
let view = UIView()
view.backgroundColor = .systemGray
return view
}()
private let verticalIndicator : UIView = {
let view = UIView()
view.backgroundColor = .systemGray
return view
}()
private let enterButton : UIButton = {
let button = UIButton()
button.setTitle("적용", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(enterButtontaped), for: .touchUpInside)
button.backgroundColor = ColorPiker.customRed
button.titleEdgeInsets = UIEdgeInsets(top: -50, left: 0, bottom: 0, right: 0)
return button
}()
private let filterselectedview : UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
private var orderArrayButtons : [UIButton] = []
private var paymentArrayButtons : [UIButton] = []
private let filterbutton : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("요기요 랭킹순", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(orderfilterButtontaped), for: .touchUpInside)
button.tag = 0
return button
}()
private let filterbutton2 : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("배달 요금순", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(orderfilterButtontaped), for: .touchUpInside)
button.tag = 1
return button
}()
private let filterbutton3 : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("별점순", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(orderfilterButtontaped), for: .touchUpInside)
button.tag = 2
return button
}()
private let filterbutton4 : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("리뷰 많은순", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(orderfilterButtontaped), for: .touchUpInside)
button.tag = 3
return button
}()
private let filterbutton5 : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("최소 주문 금액순", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(orderfilterButtontaped), for: .touchUpInside)
button.tag = 4
return button
}()
private let filterbutton6 : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("결제수단 전체", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(paymentfilterButtontaped(_:)), for: .touchUpInside)
button.tag = 0
return button
}()
private let filterbutton7 : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("현금", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(paymentfilterButtontaped), for: .touchUpInside)
button.tag = 1
return button
}()
private let filterbutton8 : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("현장카드", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(paymentfilterButtontaped), for: .touchUpInside)
button.tag = 2
return button
}()
private let filterbutton9 : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.setImage(UIImage(systemName: "circle"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.setTitleColor( .darkGray, for: .normal)
button.imageView?.tintColor = .darkGray
button.setTitle("요기서결제", for: .normal)
button.titleLabel?.font = UIFont(name: FontModel.customMedium, size: 15)
button.addTarget(self, action: #selector(paymentfilterButtontaped), for: .touchUpInside)
button.tag = 3
return button
}()
// MARK: LifeCycle
override init(frame: CGRect) {
super.init(frame: frame)
configUiSet()
orderArrayButtons.append(filterbutton)
orderArrayButtons.append(filterbutton2)
orderArrayButtons.append(filterbutton3)
orderArrayButtons.append(filterbutton4)
orderArrayButtons.append(filterbutton5)
paymentArrayButtons.append(filterbutton6)
paymentArrayButtons.append(filterbutton7)
paymentArrayButtons.append(filterbutton8)
paymentArrayButtons.append(filterbutton9)
selectChosenOrder(selectedOrder)
selectChosenPayment(selectedPayment)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Configure
func configUiSet() {
backgroundColor = .white
addSubview(indicatorView)
indicatorView.addSubview(filterLabel)
[horizontalIndicator,verticalIndicator,closeButton,setinit,enterButton].forEach({
self.addSubview($0)
})
horizontalIndicator.snp.makeConstraints { (make) in
make.top.equalTo(filterLabel.snp.bottom).offset(12)
make.leading.trailing.equalTo(0)
make.width.equalTo(self.frame.width)
make.height.equalTo(0.5)
}
verticalIndicator.snp.makeConstraints { (make) in
make.top.equalTo(horizontalIndicator.snp.bottom)
make.bottom.equalTo(0)
make.leading.equalTo(self.snp.centerX)
make.width.equalTo(0.5)
}
filterLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self.safeAreaLayoutGuide.snp.centerX)
make.top.equalTo(self.safeAreaLayoutGuide.snp.top).inset(10)
}
closeButton.snp.makeConstraints { (make) in
make.centerY.equalTo(filterLabel.snp.centerY)
make.bottom.top.equalTo(filterLabel)
make.leading.equalTo(self.snp.leading).inset(10)
}
setinit.snp.makeConstraints { (make) in
make.centerY.equalTo(filterLabel.snp.centerY)
make.bottom.top.equalTo(filterLabel)
make.trailing.equalTo(self.snp.trailing).inset(10)
}
enterButton.snp.makeConstraints { (make) in
make.top.equalTo(self.snp.centerY).multipliedBy(1.3)
make.leading.trailing.equalTo(0)
make.bottom.equalToSuperview().inset(50)
}
let stack2 = UIStackView(arrangedSubviews: [filterbutton,filterbutton2,filterbutton3,filterbutton4,filterbutton5])
stack2.axis = .vertical
stack2.distribution = .fillProportionally
stack2.spacing = 8
stack2.alignment = .leading
addSubview(stack2)
stack2.snp.makeConstraints { (make) in
make.top.equalTo(horizontalIndicator.snp.bottom).offset(10)
make.leading.equalTo(self.snp.leading).inset(50)
}
let stack3 = UIStackView(arrangedSubviews: [filterbutton6,filterbutton7,filterbutton8,filterbutton9])
stack3.axis = .vertical
stack3.distribution = .fillProportionally
stack3.spacing = 8
stack3.alignment = .leading
addSubview(stack3)
stack3.snp.makeConstraints { (make) in
make.top.equalTo(horizontalIndicator.snp.bottom).offset(10)
make.leading.equalTo(verticalIndicator.snp.leading).inset(50)
}
}
// 필터를 선택했을때
func selectChosenOrder(_ index: Int) {
let selectedButton = orderArrayButtons[index]
selectedButton.setTitleColor(.red, for: .normal)
selectedButton.setImage(UIImage(systemName: "circle.fill"), for: .normal)
selectedButton.imageView?.tintColor = .systemGray
}
func selectChosenPayment(_ index: Int) {
let selectedButton = paymentArrayButtons[index]
selectedButton.setTitleColor(.red, for: .normal)
selectedButton.setImage(UIImage(systemName: "circle.fill"), for: .normal)
selectedButton.imageView?.tintColor = .systemGray
}
func setFilterView(view: StoreFilterbigView) {
storeFilterBigView = view
}
// MARK: Selector
// 초기화 버튼 Action
@objc func setInitButtonClicked() {
for i in orderArrayButtons {
i.setTitleColor( .darkGray, for: .normal)
i.setImage(UIImage(systemName: "circle"), for: .normal)
i.tintColor = .darkGray
}
selectChosenOrder(0)
for i in paymentArrayButtons {
i.setTitleColor( .darkGray, for: .normal)
i.setImage(UIImage(systemName: "circle"), for: .normal)
i.tintColor = .darkGray
}
selectChosenPayment(0)
}
// 필터 닫기 버튼 Action
@objc func filtercloseButton() {
storeFilterBigView?.removeFromSuperview()
}
// 필터 적용버튼 Action
@objc func orderfilterButtontaped(_ sender: UIButton) {
let image = UIImage(systemName: "circle")
for i in orderArrayButtons {
i.setTitleColor( .darkGray, for: .normal)
i.setImage(image, for: .normal)
i.tintColor = UIColor.red
}
selectedOrder = sender.tag
selectChosenOrder(sender.tag)
}
// 초기화 컬러
//sender 컬러 따로주는 작업
@objc func paymentfilterButtontaped(_ sender: UIButton){
for i in paymentArrayButtons {
i.setTitleColor( .darkGray, for: .normal)
i.setImage(UIImage(systemName: "circle"), for: .normal)
i.tintColor = UIColor.red
}
selectedPayment = sender.tag
selectChosenPayment(sender.tag)
}
// 적용버튼 Action
@objc func enterButtontaped(_ sender: UIButton){
/* 이벤트 발생
리스너 : StoreVC의 카테고리 확인(StoreVC 의 Delegate) + FilterVC의 selected.tag를 확인!
이벤트 발생하면,
*/
self.filterViewDelegate?.presentStorefilterView(selectedOrder: selectedOrder, selectedPayment: selectedPayment)
storeFilterBigView?.removeFromSuperview()
}
}
| 37.722749 | 122 | 0.632263 |
e27741ca2cfee69eb6ae505a762ba8c2c23f5fab | 2,963 | import Foundation
import azureSwiftRuntime
public protocol ServiceVerifyHostingEnvironmentVnet {
var headerParameters: [String: String] { get set }
var subscriptionId : String { get set }
var apiVersion : String { get set }
var parameters : VnetParametersProtocol? { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (VnetValidationFailureDetailsProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.Service {
// VerifyHostingEnvironmentVnet verifies if this VNET is compatible with an App Service Environment by analyzing the
// Network Security Group rules.
internal class VerifyHostingEnvironmentVnetCommand : BaseCommand, ServiceVerifyHostingEnvironmentVnet {
public var subscriptionId : String
public var apiVersion = "2016-03-01"
public var parameters : VnetParametersProtocol?
public init(subscriptionId: String, parameters: VnetParametersProtocol) {
self.subscriptionId = subscriptionId
self.parameters = parameters
super.init()
self.method = "Post"
self.isLongRunningOperation = false
self.path = "/subscriptions/{subscriptionId}/providers/Microsoft.Web/verifyHostingEnvironmentVnet"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
self.body = parameters
}
public override func encodeBody() throws -> Data? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let encoder = try CoderFactory.encoder(for: mimeType)
let encodedValue = try encoder.encode(parameters as? VnetParametersData)
return encodedValue
}
throw DecodeError.unknownMimeType
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
let result = try decoder.decode(VnetValidationFailureDetailsData?.self, from: data)
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (VnetValidationFailureDetailsProtocol?, Error?) -> Void) -> Void {
client.executeAsync(command: self) {
(result: VnetValidationFailureDetailsData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 46.296875 | 117 | 0.643267 |
ffef611e681454fef566923919fbe3f4a8207440 | 6,390 | //
// TweetPresenter.swift
// MeetupTweet
//
// Created by Yoshinori Imajo on 2016/03/03.
// Copyright © 2016年 Yoshinori Imajo. All rights reserved.
//
import Foundation
import RxSwift
import AppKit
import OAuthSwift
import TwitterAPI
class NicoNicoCommentFlowWindowDataSource: FlowWindowDataSource {
var subscription: Disposable?
fileprivate let tweetSearchUseCase: TwitterStraemAPIUseCase
fileprivate let disposeBag = DisposeBag()
fileprivate var comments: [String: (comment: CommentType, view: CommentView)] = [:]
fileprivate var commentViews: [CommentView?] = []
fileprivate var window: NSWindow?
init(oauthClient: OAuthClient) {
self.tweetSearchUseCase = TwitterStraemAPIUseCase(oauthClient: oauthClient)
}
func search(_ search: String, screen: NSScreen) {
refreshComments()
window = makeTweetWindow(screen)
let tweetStream = tweetSearchUseCase.startStream(search)
.observeOn(MainScheduler.instance)
.startWith(Announce(search: search))
.filter { !$0.message.hasPrefix("RT") }
subscription = Observable.of(tweetStream, AnnounceUseCase.intervalTextStream(search))
.merge()
.subscribe(onNext: { [unowned self] comment in
self.addComment(comment)
})
subscription?.disposed(by: disposeBag)
}
func stop() {
window?.orderOut(nil)
refreshComments()
}
}
private extension NicoNicoCommentFlowWindowDataSource {
func refreshComments() {
tweetSearchUseCase.stopStream()
subscription?.dispose()
comments = [:]
commentViews = []
}
func addComment(_ comment: CommentType) {
guard let window = window else { return }
let view = makeCommentView(comment, from: window)
window.contentView?.addSubview(view)
comments[comment.identifier] = (comment: comment, view: view)
startAnimationComment(comment, view: view)
}
func removeComment(_ comment: CommentType) {
if let tweet = comments[comment.identifier] {
tweet.view.removeFromSuperview()
comments[comment.identifier] = nil
}
}
func startAnimationComment(_ comment: CommentType, view: CommentView) {
guard let window = window else { return }
// TextFieldの移動開始
let windowFrame = window.frame
let v: CGFloat = 200.0
let firstDuration = TimeInterval(view.frame.width / v)
let len = windowFrame.width
let secondDuration = TimeInterval(len / v)
NSAnimationContext.runAnimationGroup(
{ context in
context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
context.duration = firstDuration
view.animator().frame = view.frame.offsetBy(dx: -view.frame.width, dy: 0)
}, completionHandler: { [weak self] in
guard let `self` = self else { return }
for (index, v) in self.commentViews.enumerated() {
if v == view {
self.commentViews[index] = nil
break;
}
}
NSAnimationContext.runAnimationGroup({ context in
context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
context.duration = secondDuration
view.animator().frame = view.frame.offsetBy(dx: -len, dy: 0)
}, completionHandler: { [weak self] in
self?.removeComment(comment)
})
}
)
}
func makeCommentView(_ comment: CommentType, from window: NSWindow) -> CommentView {
let commentView: CommentView
switch comment.type {
case .tweet:
commentView = CommentView.newCommentView(comment.message)
if let url = comment.imageURL {
URLSession.shared.rx.data(request: URLRequest(url: url))
.subscribe(onNext: { data in
DispatchQueue.main.async {
commentView.imageView.image = NSImage(data: data)
}
})
.disposed(by: disposeBag)
}
case .announce:
commentView = CommentView.newCommentView(comment.message, fontColor: NSColor.red)
commentView.imageView.image = NSApp.applicationIconImage
}
var space = 0
if commentViews.count == 0 {
commentViews.append(commentView)
} else {
var add = false
for (index, view) in commentViews.enumerated() {
if view == nil {
commentViews[index] = commentView
space = index
add = true
break
}
}
if !add {
commentViews.append(commentView)
space = commentViews.count
}
}
commentView.layoutSubtreeIfNeeded()
let windowFrame = window.frame
let y = (windowFrame.height - commentView.frame.height) - (CGFloat(space) * commentView.frame.height)
commentView.frame.origin = CGPoint(x: windowFrame.width, y: y)
return commentView
}
func makeTweetWindow(_ screen: NSScreen) -> NSWindow {
let menuHeight: CGFloat = 23.0
let size = CGSize(width: screen.frame.size.width, height: screen.frame.size.height - menuHeight)
let frame = NSRect(origin: CGPoint.zero, size: size)
let window = NSWindow(contentRect: frame, styleMask: .resizable, backing: .buffered, defer: false, screen: screen)
window.isOpaque = false
window.hasShadow = false
window.isMovable = true
window.isMovableByWindowBackground = true
window.isReleasedWhenClosed = false
window.backgroundColor = NSColor.clear
window.level = NSWindow.Level(Int(CGWindowLevelForKey(.maximumWindow)))
window.makeKeyAndOrderFront(nil)
return window
}
}
| 33.28125 | 122 | 0.578717 |
9bfb7a30a6eaeb671f6f4ba69386ad488e14b033 | 773 | //
// File.swift
//
//
// Created by Tibor Bodecs on 2020. 11. 21..
//
public extension Request {
/// invokes the first hook function with a given name and inserts the app & req pointers as arguments
func invoke<ReturnType>(_ name: String, args: HookArguments = [:]) -> ReturnType? {
let ctxArgs = args.merging(["req": self]) { (_, new) in new }
return application.invoke(name, args: ctxArgs)
}
/// invokes all the available hook functions with a given name and inserts the app & req pointers as arguments
func invokeAll<ReturnType>(_ name: String, args: HookArguments = [:]) -> [ReturnType] {
let ctxArgs = args.merging(["req": self]) { (_, new) in new }
return application.invokeAll(name, args: ctxArgs)
}
}
| 35.136364 | 114 | 0.645537 |
0889cc83bb3bb930764cbc388f580520b8c63d58 | 1,282 | //
// stellarsdkTests_HostUITests.swift
// stellarsdkTests-HostUITests
//
// Created by Razvan Chelemen on 29/01/2018.
// Copyright © 2018 Soneso. All rights reserved.
//
import XCTest
class stellarsdkTests_HostUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.648649 | 182 | 0.672387 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.