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
|
---|---|---|---|---|---|
23efdb474c1c541e9d00501e9690bcdaad867c08 | 2,401 | //
// Tweet.swift
// Tweeter
//
// Created by Bianca Curutan on 10/27/16.
// Copyright © 2016 Bianca Curutan. All rights reserved.
//
import UIKit
enum TimelineType: Int {
case home = 0, mentions
}
final class Tweet: NSObject {
var tweets: [Tweet]!
var timelineType: TimelineType!
var favorited = false
var favoritesCount: Int = 0
var id: NSNumber = 0
var retweetCount: Int = 0
var retweeted = false
var text: String?
var timestamp: String! = ""
var user: User?
override init() {
super.init()
}
init(dictionary: NSDictionary) {
favorited = (dictionary["favorited"] as? Bool)!
favoritesCount = (dictionary["favorite_count"] as? Int) ?? 0
id = (dictionary["id"] as? NSNumber) ?? 0
retweetCount = (dictionary["retweet_count"] as? Int) ?? 0
retweeted = (dictionary["retweeted"] as? Bool)!
text = dictionary["text"] as? String
let timestampString = dictionary["created_at"] as? String
if let timestampString = timestampString {
let now = Date()
timestamp = now.offsetFrom(dateString: timestampString)
}
if let userDictionary = dictionary["user"] {
user = User(dictionary: userDictionary as! NSDictionary)
}
}
class func tweetsWithArray(dictionaries: [NSDictionary]) -> [Tweet] {
var tweets: [Tweet] = []
for dictionary in dictionaries {
let tweet = Tweet(dictionary: dictionary)
tweets.append(tweet)
}
return tweets
}
func refreshTimeline() {
if timelineType == .home {
TwitterClient.sharedInstance.homeTimeline(
success: { (tweets: [Tweet]) -> () in
self.tweets = tweets
}, failure: { (error: Error) -> () in
print("error: \(error.localizedDescription)")
}
)
} else if timelineType == .mentions {
TwitterClient.sharedInstance.mentionsTimeline(
success: { (tweets: [Tweet]) -> () in
self.tweets = tweets
}, failure: { (error: Error) -> () in
print("error: \(error.localizedDescription)")
}
)
}
}
}
| 28.247059 | 73 | 0.533111 |
f4c97346a6cba2a09ce2adca93ea7c65d95567e5 | 2,451 | // RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/one-way-external-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Handled main.swift
// CHECK-FIRST: Handled other.swift
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND-NOT: Handled
// RUN: touch -t 201401240005 %t/*
// RUN: touch -t 201401240006 %t/*.o
// RUN: touch -t 201401240004 %t/*-external
// RUN: rm %t/other1-external
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s
// CHECK-THIRD-DAG: Handled other.swift
// CHECK-THIRD-DAG: Handled main.swift
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/one-way-external-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// RUN: touch -t 201401240005 %t/*
// RUN: touch -t 201401240006 %t/*.o
// RUN: touch -t 201401240004 %t/*-external
// RUN: rm %t/main1-external
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s
// CHECK-FOURTH-NOT: Handled other.swift
// CHECK-FOURTH: Handled main.swift
// CHECK-FOURTH-NOT: Handled other.swift
| 58.357143 | 318 | 0.71685 |
e87d2a4259f50e3e7cac9985577f60cdad99fef6 | 823 | //
// HomeViewController.swift
// FlashCard African Flags
//
// Created by ishmael on 6/27/17.
// Copyright © 2017 ishmael.mthombeni. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
@IBOutlet weak var homeImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
homeImage.layer.cornerRadius = 10
homeImage.layer.borderWidth = 1
homeImage.layer.borderColor = UIColor.green.cgColor
homeImage.clipsToBounds = true
}
override func viewDidDisappear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = false
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = true
}
}
| 21.102564 | 60 | 0.646416 |
3a8fda24160279a0bbd8c6962c704d8adae84d3c | 924 | //
// Tip_CalculatorTests.swift
// Tip_CalculatorTests
//
// Created by Stewart Powell on 11/18/20.
//
import XCTest
@testable import Tip_Calculator
class Tip_CalculatorTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.176471 | 111 | 0.67316 |
c14ba47e423aab4dcc21f4089cbf316d280ef846 | 407 | //
// ResendPhoneNumberVerificationCode.swift
// tl2swift
//
// Generated automatically. Any changes will be lost!
// Based on TDLib 1.8.0-fa8feefe
// https://github.com/tdlib/td/tree/fa8feefe
//
import Foundation
/// Re-sends the code to verify a phone number to be added to a user's Telegram Passport
public struct ResendPhoneNumberVerificationCode: Codable, Equatable {
public init() {}
}
| 20.35 | 88 | 0.732187 |
48463929a2a8ddf05dfd3b571815c52a8ea50815 | 6,322 | //
// APIWrappersViewController.swift
// RxExample
//
// Created by Carlos García on 8/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
import CoreLocation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
extension UILabel {
public override var accessibilityValue: String! {
get {
return self.text
}
set {
self.text = newValue
self.accessibilityValue = newValue
}
}
}
class APIWrappersViewController: ViewController {
@IBOutlet weak var debugLabel: UILabel!
@IBOutlet weak var openActionSheet: UIButton!
@IBOutlet weak var openAlertView: UIButton!
@IBOutlet weak var bbitem: UIBarButtonItem!
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var switcher: UISwitch!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var mypan: UIPanGestureRecognizer!
@IBOutlet weak var textView: UITextView!
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
datePicker.date = NSDate(timeIntervalSince1970: 0)
let ash = UIActionSheet(title: "Title", delegate: nil, cancelButtonTitle: "Cancel", destructiveButtonTitle: "OK")
let av = UIAlertView(title: "Title", message: "The message", delegate: nil, cancelButtonTitle: "Cancel", otherButtonTitles: "OK", "Two", "Three", "Four", "Five")
openActionSheet.rx_tap
.subscribeNext { [weak self] x in
if let view = self?.view {
ash.showInView(view)
}
}
.addDisposableTo(disposeBag)
openAlertView.rx_tap
.subscribeNext { x in
av.show()
}
.addDisposableTo(disposeBag)
// MARK: UIActionSheet
ash.rx_clickedButtonAtIndex
.subscribeNext { [weak self] x in
self?.debug("UIActionSheet clickedButtonAtIndex \(x)")
}
.addDisposableTo(disposeBag)
ash.rx_willDismissWithButtonIndex
.subscribeNext { [weak self] x in
self?.debug("UIActionSheet willDismissWithButtonIndex \(x)")
}
.addDisposableTo(disposeBag)
ash.rx_didDismissWithButtonIndex
.subscribeNext { [weak self] x in
self?.debug("UIActionSheet didDismissWithButtonIndex \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UIAlertView
av.rx_clickedButtonAtIndex
.subscribeNext { [weak self] x in
self?.debug("UIAlertView clickedButtonAtIndex \(x)")
}
.addDisposableTo(disposeBag)
av.rx_willDismissWithButtonIndex
.subscribeNext { [weak self] x in
self?.debug("UIAlertView willDismissWithButtonIndex \(x)")
}
.addDisposableTo(disposeBag)
av.rx_didDismissWithButtonIndex
.subscribeNext { [weak self] x in
self?.debug("UIAlertView didDismissWithButtonIndex \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UIBarButtonItem
bbitem.rx_tap
.subscribeNext { [weak self] x in
self?.debug("UIBarButtonItem Tapped")
}
.addDisposableTo(disposeBag)
// MARK: UISegmentedControl
segmentedControl.rx_value
.subscribeNext { [weak self] x in
self?.debug("UISegmentedControl value \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UISwitch
switcher.rx_value
.subscribeNext { [weak self] x in
self?.debug("UISwitch value \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UIActivityIndicatorView
switcher.rx_value
.bindTo(activityIndicator.rx_animating)
.addDisposableTo(disposeBag)
// MARK: UIButton
button.rx_tap
.subscribeNext { [weak self] x in
self?.debug("UIButton Tapped")
}
.addDisposableTo(disposeBag)
// MARK: UISlider
slider.rx_value
.subscribeNext { [weak self] x in
self?.debug("UISlider value \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UIDatePicker
datePicker.rx_date
.subscribeNext { [weak self] x in
self?.debug("UIDatePicker date \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UITextField
textField.rx_text
.subscribeNext { [weak self] x in
self?.debug("UITextField text \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UIGestureRecognizer
mypan.rx_event
.subscribeNext { [weak self] x in
self?.debug("UIGestureRecognizer event \(x.state)")
}
.addDisposableTo(disposeBag)
// MARK: UITextView
textView.rx_text
.subscribeNext { [weak self] x in
self?.debug("UITextView event \(x)")
}
.addDisposableTo(disposeBag)
// MARK: CLLocationManager
#if !RX_NO_MODULE
manager.requestWhenInUseAuthorization()
#endif
manager.rx_didUpdateLocations
.subscribeNext { [weak self] x in
self?.debug("rx_didUpdateLocations \(x)")
}
.addDisposableTo(disposeBag)
_ = manager.rx_didFailWithError
.subscribeNext { [weak self] x in
self?.debug("rx_didFailWithError \(x)")
}
manager.rx_didChangeAuthorizationStatus
.subscribeNext { status in
print("Authorization status \(status)")
}
.addDisposableTo(disposeBag)
manager.startUpdatingLocation()
}
func debug(string: String) {
print(string)
debugLabel.text = string
}
}
| 25.595142 | 169 | 0.572287 |
1a65370c073699043dc09db5499edce6f276ca96 | 230 | import SwiftUI
public extension EnvironmentValues {
var gridStyle: GridStyle {
get {
return self[GridStyleKey.self]
}
set {
self[GridStyleKey.self] = newValue
}
}
}
| 17.692308 | 46 | 0.547826 |
feec72e05f1720926ecfbc042313e10d709a51ae | 1,798 | //
// ViewController.swift
// PresentingDemo
//
// Created by Nicholas Outram on 14/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import UIKit
class ViewController: UIViewController, ModalViewController1Protocol {
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ModalViewController1 {
vc.delegate = self
switch (segue.identifier) {
case "DEMO1"?:
vc.titleText = "DEMO 1"
case "DEMO2"?:
vc.titleText = "DEMO 2"
default:
break
} //end switch
} //end if
}
@IBAction func doDemo2(_ sender: AnyObject) {
self.performSegue(withIdentifier: "DEMO2", sender: self)
}
@IBAction func doDemo3(_ sender: AnyObject) {
let sb = UIStoryboard(name: "ModalStoryboard", bundle: nil)
if let vc = sb.instantiateViewController(withIdentifier: "DEMO3") as? ModalViewController1 {
vc.delegate = self
vc.titleText = "DEMO 3"
self.present(vc, animated: true, completion: { })
}
}
//Call back
func dismissWithStringData(_ str: String) {
self.dismiss(animated: true) {
self.resultLabel.text = str
}
}
}
| 25.323944 | 97 | 0.564516 |
d7098b8f23101d07cdcf89ca91c31136061ddcc0 | 4,519 | //
// SimplePagingView.swift
// WWDC21 Swift Student Challenge
//
// Created by Diego Henrique Silva Oliveira on 19/04/21.
//
import SwiftUI
import PlaygroundSupport
public struct SimplePagingView: View {
public init(){}
var technique: MemoryManagmentTechniques = .simplepaging
var apps: [Application] = Application.simplePagingApps
@State var memory: Memory = .simplePagingMemory
@State var firstRun : Bool = true
@State var isAnimating = false
@State private var memRects: [String: CGRect] = [:]
@State private var baseAppRects: [String: CGRect] = [:]
@State private var appToMem: [String: String] = [:]
@State private var appNotFitInMemory: [String : Int] = [:]
@State private var framesUsed: [String : [Int]] = [:]
public var body: some View {
ZStack {
LayoutView(technique: technique)
VStack {
VStack (spacing: 70) {
HStack (alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 15) {
ForEach(apps) { app in
AppIconView(appToMem: $appToMem, appNotFitInMemory: $appNotFitInMemory, technique: technique, app : app)
}
}
.padding(.top, 1580.0)
.padding()
.onPreferenceChange(AppItemPreferenceKey.self) { appItemRects in
for appItemData in appItemRects {
baseAppRects[appItemData.appId] = appItemData.rect
}
}
HStack (alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 25) {
ForEach(apps) { app in
AppButtonView(technique: technique, firstRun: $firstRun, memory: $memory, appToMem: $appToMem, appNotFitInMemory: $appNotFitInMemory, framesUsed: $framesUsed, app: app)
}
}
.padding(.top, -210)
VStack {
ForEach(memory.items) { memItem in
MemoryView(technique: technique, memItem: memItem, appToMem: $appToMem, framesUsed: $framesUsed)
}
}
.padding(.top, -1005)
.onPreferenceChange(MemoryItemPreferenceKey.self) { memItemRects in
for memItemData in memItemRects {
memRects[memItemData.memoryId] = memItemData.rect
}
}
}
.padding(.top, 100)
Button(action: {
PlaygroundPage.current.navigateTo(page: .pageReference(reference: "Credits"))
}) {
Text("Continue")
.frame(width: 170.0, height: 78.0)
.font(.system(size: 26, weight: .semibold, design: Font.Design.monospaced))
.shadow(color: /*@START_MENU_TOKEN@*/.black/*@END_MENU_TOKEN@*/, radius: 5, x: 10)
.foregroundColor(.white)
.overlay(
RoundedRectangle(cornerRadius: .infinity)
.stroke(Color.white, lineWidth: 1.5)
).background(RoundedRectangle(cornerRadius: .infinity).fill(Color.black))
.padding(.bottom, 300)
.padding(.leading, 750.0)
.scaleEffect(self.isAnimating ? 1: 0)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
withAnimation(Animation.spring()) {
self.isAnimating = true
}
}
}
}
.contentShape(Rectangle())
}
.padding(.bottom, 400.0)
Group {
ForEach(apps) { app in
AppIconResizeView(memory: $memory, appToMem: $appToMem, memRects: $memRects, baseAppRects: $baseAppRects, appNotFitInMemory: $appNotFitInMemory, framesUsed: $framesUsed, technique: technique, app: app)
}
}
}
.coordinateSpace(name: "ContentViewCS")
}
}
| 45.19 | 221 | 0.485506 |
62eeba259e349dcb67ed0933b2dff8ff87d8ffe7 | 610 | //
// SketchEnum.swift
// SGSketchTool
//
// Created by 吴小星 on 16/8/8.
// Copyright © 2016年 crash. All rights reserved.
//
import UIKit
/**
图记类型
- Point: 点
- FoldLine: 折线
- Curve: 曲线
- Surfaces: 曲面
- Polygon: 多边行
*/
public enum SketchType :String {
case Point ,FoldLine ,Curve ,Surfaces ,Polygon
public var describe: String{
switch self {
case .Point: return "点"
case .FoldLine: return "折线"
case .Curve: return "曲线"
case .Surfaces: return "曲面"
case .Polygon: return "多边形"
}
}
} | 17.428571 | 50 | 0.537705 |
56126654f7749fc0184f076f60babb4a8f217d16 | 7,374 |
// RUN: %target-swift-frontend -module-name mangling -Xllvm -sil-full-demangle -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
// Test mangling of Unicode identifiers.
// These examples are from RFC 3492, which defines the Punycode encoding used
// by name mangling.
// CHECK-LABEL: sil hidden @$s8mangling0022egbpdajGbuEbxfgehfvwxnyyF
func ليهمابتكلموشعربي؟() { }
// CHECK-LABEL: sil hidden @$s8mangling0024ihqwcrbEcvIaIdqgAFGpqjyeyyF
func 他们为什么不说中文() { }
// CHECK-LABEL: sil hidden @$s8mangling0027ihqwctvzcJBfGFJdrssDxIboAybyyF
func 他們爲什麽不說中文() { }
// CHECK-LABEL: sil hidden @$s8mangling0030Proprostnemluvesky_uybCEdmaEBayyF
func Pročprostěnemluvíčesky() { }
// <rdar://problem/13757744> Variadic tuples need a different mangling from
// non-variadic tuples.
// CHECK-LABEL: sil hidden @$s8mangling9r137577441xySaySiG_tF
func r13757744(x: [Int]) {}
// CHECK-LABEL: sil hidden @$s8mangling9r137577441xySid_tF
func r13757744(x: Int...) {}
// <rdar://problem/13757750> Prefix, postfix, and infix operators need
// distinct manglings.
prefix operator +-
postfix operator +-
infix operator +-
// CHECK-LABEL: sil hidden @$s8mangling2psopyyxlF
prefix func +- <T>(a: T) {}
// CHECK-LABEL: sil hidden @$s8mangling2psoPyyxlF
postfix func +- <T>(a: T) {}
// CHECK-LABEL: sil hidden @$s8mangling2psoiyyx_xtlF
func +- <T>(a: T, b: T) {}
// CHECK-LABEL: sil hidden @$s8mangling2psopyyx1a_x1bt_tlF
prefix func +- <T>(_: (a: T, b: T)) {}
// CHECK-LABEL: sil hidden @$s8mangling2psoPyyx1a_x1bt_tlF
postfix func +- <T>(_: (a: T, b: T)) {}
infix operator «+»
// CHECK-LABEL: sil hidden @$s8mangling007p_qcaDcoiyS2i_SitF
func «+»(a: Int, b: Int) -> Int { return a + b }
protocol Foo {}
protocol Bar {}
// Ensure protocol list manglings are '_' terminated regardless of length
// CHECK-LABEL: sil hidden @$s8mangling12any_protocolyyypF
func any_protocol(_: Any) {}
// CHECK-LABEL: sil hidden @$s8mangling12one_protocolyyAA3Foo_pF
func one_protocol(_: Foo) {}
// CHECK-LABEL: sil hidden @$s8mangling18one_protocol_twiceyyAA3Foo_p_AaC_ptF
func one_protocol_twice(_: Foo, _: Foo) {}
// CHECK-LABEL: sil hidden @$s8mangling12two_protocolyyAA3Bar_AA3FoopF
func two_protocol(_: Foo & Bar) {}
// Ensure archetype depths are mangled correctly.
class Zim<T> {
// CHECK-LABEL: sil hidden @$s8mangling3ZimC4zangyyx_qd__tlF
func zang<U>(_: T, _: U) {}
// CHECK-LABEL: sil hidden @$s8mangling3ZimC4zungyyqd___xtlF
func zung<U>(_: U, _: T) {}
}
// Clang-imported classes and protocols get mangled into a magic 'So' context
// to make collisions into link errors. <rdar://problem/14221244>
// CHECK-LABEL: sil hidden @$s8mangling28uses_objc_class_and_protocol1o1p2p2ySo8NSObjectC_So8NSAnsing_pSo14NSBetterAnsing_ptF
func uses_objc_class_and_protocol(o: NSObject, p: NSAnsing, p2: BetterAnsing) {}
// Clang-imported structs get mangled using their Clang module name.
// FIXME: Temporarily mangles everything into the virtual module __C__
// <rdar://problem/14221244>
// CHECK-LABEL: sil hidden @$s8mangling17uses_clang_struct1rySo6NSRectV_tF
func uses_clang_struct(r: NSRect) {}
// CHECK-LABEL: sil hidden @$s8mangling14uses_optionals1xs7UnicodeO6ScalarVSgSiSg_tF
func uses_optionals(x: Int?) -> UnicodeScalar? { return nil }
enum GenericUnion<T> {
// CHECK-LABEL: sil shared [transparent] @$s8mangling12GenericUnionO3FooyACyxGSicAEmlF
case Foo(Int)
}
func instantiateGenericUnionConstructor<T>(_ t: T) {
_ = GenericUnion<T>.Foo
}
struct HasVarInit {
static var state = true && false
}
// CHECK-LABEL: // function_ref implicit closure #1 : @autoclosure () throws -> Swift.Bool in variable initialization expression of static mangling.HasVarInit.state : Swift.Bool
// CHECK-NEXT: function_ref @$s8mangling10HasVarInitV5stateSbvpZfiSbyKXKfu_
// auto_closures should not collide with the equivalent non-auto_closure
// function type.
// CHECK-LABEL: sil hidden @$s8mangling19autoClosureOverload1fySiyXK_tF : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> () {
func autoClosureOverload(f: @autoclosure () -> Int) {}
// CHECK-LABEL: sil hidden @$s8mangling19autoClosureOverload1fySiyXE_tF : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> () {
func autoClosureOverload(f: () -> Int) {}
// CHECK-LABEL: sil hidden @$s8mangling24autoClosureOverloadCallsyyF : $@convention(thin) () -> () {
func autoClosureOverloadCalls() {
// CHECK: function_ref @$s8mangling19autoClosureOverload1fySiyXK_tF
autoClosureOverload(f: 1)
// CHECK: function_ref @$s8mangling19autoClosureOverload1fySiyXE_tF
autoClosureOverload {1}
}
// <rdar://problem/16079822> Associated type requirements need to appear in the
// mangling.
protocol AssocReqt {}
protocol HasAssocType {
associatedtype Assoc
}
// CHECK-LABEL: sil hidden @$s8mangling4fooAyyxAA12HasAssocTypeRzlF : $@convention(thin) <T where T : HasAssocType> (@in_guaranteed T) -> ()
func fooA<T: HasAssocType>(_: T) {}
// CHECK-LABEL: sil hidden @$s8mangling4fooByyxAA12HasAssocTypeRzAA0D4Reqt0D0RpzlF : $@convention(thin) <T where T : HasAssocType, T.Assoc : AssocReqt> (@in_guaranteed T) -> ()
func fooB<T: HasAssocType>(_: T) where T.Assoc: AssocReqt {}
// CHECK-LABEL: sil hidden @$s8mangling2qqoiyySi_SitF
func ??(x: Int, y: Int) {}
struct InstanceAndClassProperty {
var property: Int {
// CHECK-LABEL: sil hidden @$s8mangling24InstanceAndClassPropertyV8propertySivg
get { return 0 }
// CHECK-LABEL: sil hidden @$s8mangling24InstanceAndClassPropertyV8propertySivs
set {}
}
static var property: Int {
// CHECK-LABEL: sil hidden @$s8mangling24InstanceAndClassPropertyV8propertySivgZ
get { return 0 }
// CHECK-LABEL: sil hidden @$s8mangling24InstanceAndClassPropertyV8propertySivsZ
set {}
}
}
// CHECK-LABEL: sil hidden @$s8mangling6curry1yyF : $@convention(thin) () -> ()
func curry1() {
}
// CHECK-LABEL: sil hidden @$s8mangling3barSiyKF : $@convention(thin) () -> (Int, @error Error)
func bar() throws -> Int { return 0 }
// CHECK-LABEL: sil hidden @$s8mangling12curry1ThrowsyyKF : $@convention(thin) () -> @error Error
func curry1Throws() throws {
}
// CHECK-LABEL: sil hidden @$s8mangling12curry2ThrowsyycyKF : $@convention(thin) () -> (@owned @callee_guaranteed () -> (), @error Error)
func curry2Throws() throws -> () -> () {
return curry1
}
// CHECK-LABEL: sil hidden @$s8mangling6curry3yyKcyF : $@convention(thin) () -> @owned @callee_guaranteed () -> @error Error
func curry3() -> () throws -> () {
return curry1Throws
}
// CHECK-LABEL: sil hidden @$s8mangling12curry3ThrowsyyKcyKF : $@convention(thin) () -> (@owned @callee_guaranteed () -> @error Error, @error Error)
func curry3Throws() throws -> () throws -> () {
return curry1Throws
}
// CHECK-LABEL: sil hidden @$s8mangling14varargsVsArray3arr1nySid_SStF : $@convention(thin) (@guaranteed Array<Int>, @guaranteed String) -> ()
func varargsVsArray(arr: Int..., n: String) { }
// CHECK-LABEL: sil hidden @$s8mangling14varargsVsArray3arr1nySaySiG_SStF : $@convention(thin) (@guaranteed Array<Int>, @guaranteed String) -> ()
func varargsVsArray(arr: [Int], n: String) { }
// CHECK-LABEL: sil hidden @$s8mangling14varargsVsArray3arr1nySaySiGd_SStF : $@convention(thin) (@guaranteed Array<Array<Int>>, @guaranteed String) -> ()
func varargsVsArray(arr: [Int]..., n: String) { }
| 39.223404 | 182 | 0.7361 |
e2864ebc482094635fac47ce5f03bdb8b58872be | 2,308 | import Foundation
protocol APIKeyProviderInterface {
var apiKey: String {get}
}
enum AuthorizedServiceError: Error, Equatable {
case unauthorized
case networkError(Error)
static func == (lhs: AuthorizedServiceError, rhs: AuthorizedServiceError) -> Bool {
switch (lhs, rhs) {
case (.unauthorized, .unauthorized):
return true
case (.networkError(let lhsError), .networkError(let rhsError)):
return lhsError.localizedDescription == rhsError.localizedDescription
default:
return false
}
}
}
typealias AuthorizedResult = Result<(data: Data?, response: URLResponse?), AuthorizedServiceError>
typealias AuthorizedServiceCompletion = (AuthorizedResult) -> ()
protocol AuthorizedServiceInterface {
func fetch(request: URLRequest, completion: @escaping AuthorizedServiceCompletion)
}
final class AuthorizedService {
private let service: NetworkServiceInterface
private let tokenProvider: APIKeyProviderInterface
init(service: NetworkServiceInterface, tokenProvider: APIKeyProviderInterface) {
self.service = service
self.tokenProvider = tokenProvider
}
}
extension AuthorizedService: AuthorizedServiceInterface {
func fetch(request: URLRequest, completion: @escaping AuthorizedServiceCompletion) {
var request = request
request.addValue(tokenProvider.apiKey, forHTTPHeaderField: "X-API-KEY")
fetchAuth(request: request) { result in
switch result {
case .success(let tuple):
guard
let urlResponse = tuple.response as? HTTPURLResponse,
urlResponse.statusCode != 401 else {
return completion(.failure(.unauthorized))
}
completion(.success(tuple))
case .failure(let error):
completion(.failure(.networkError(error)))
}
}
}
}
private extension AuthorizedService {
func fetchAuth(request: URLRequest, completion: @escaping NetworkServiceCompletion) {
service.fetch(request: request, completion: completion)
}
}
struct APIKeyProvider: APIKeyProviderInterface {
var apiKey: String {
return "DD6E5FD7D0-E7FD-4622-8A19-9EBC602C9D0D"
}
}
| 32.055556 | 98 | 0.67201 |
ebaf8a6ce24abf0c443de8cba84deb1c79345db5 | 3,531 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
import SQLite
import XCTest
@testable import Amplify
@testable import AmplifyTestCommon
@testable import AWSDataStoreCategoryPlugin
class StorageEngineTestsHasOne: StorageEngineTestsBase {
override func setUp() {
super.setUp()
Amplify.Logging.logLevel = .warn
let validAPIPluginKey = "MockAPICategoryPlugin"
let validAuthPluginKey = "MockAuthCategoryPlugin"
do {
connection = try Connection(.inMemory)
storageAdapter = try SQLiteStorageEngineAdapter(connection: connection)
try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas)
syncEngine = MockRemoteSyncEngine()
storageEngine = StorageEngine(storageAdapter: storageAdapter,
dataStoreConfiguration: .default,
syncEngine: syncEngine,
validAPIPluginKey: validAPIPluginKey,
validAuthPluginKey: validAuthPluginKey)
ModelRegistry.register(modelType: Team.self)
ModelRegistry.register(modelType: Project.self)
do {
try storageEngine.setUp(modelSchemas: [Team.schema])
try storageEngine.setUp(modelSchemas: [Project.schema])
} catch {
XCTFail("Failed to setup storage engine")
}
} catch {
XCTFail(String(describing: error))
return
}
}
func testBelongsToRelationshipWithoutOwner() {
let teamA = Team(name: "A-Team")
let projectA = Project(name: "ProjectA", team: teamA)
let teamB = Team(name: "B-Team")
let projectB = Project(name: "ProjectB", team: teamB)
let teamC = Team(name: "C-Team")
let projectC = Project(name: "ProjectC", team: teamC)
guard case .success = saveModelSynchronous(model: teamA),
case .success = saveModelSynchronous(model: projectA),
case .success = saveModelSynchronous(model: teamB),
case .success = saveModelSynchronous(model: projectB),
case .success = saveModelSynchronous(model: teamC),
case .success = saveModelSynchronous(model: projectC) else {
XCTFail("Failed to save hierachy")
return
}
guard case .success =
querySingleModelSynchronous(modelType: Project.self, predicate: Project.keys.id == projectA.id) else {
XCTFail("Failed to query ProjectA")
return
}
guard case .success =
querySingleModelSynchronous(modelType: Team.self, predicate: Project.keys.id == teamA.id) else {
XCTFail("Failed to query TeamA")
return
}
let mutationEventOnProject = expectation(description: "Mutation Events submitted to sync engine")
syncEngine.setCallbackOnSubmit(callback: { _ in
mutationEventOnProject.fulfill()
})
guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Project.self,
withId: projectA.id) else {
XCTFail("Failed to delete projectA")
return
}
wait(for: [mutationEventOnProject], timeout: defaultTimeout)
}
}
| 37.967742 | 114 | 0.599547 |
b9df55abd41578c10be9837133d21abec0f3005c | 2,499 | //
// RetryControl.swift
// iONess
//
// Created by Nayanda Haberty (ID) on 21/10/20.
//
import Foundation
/// Retry control decision
public enum RetryControlDecision {
case noRetry
case retryAfter(TimeInterval)
case retry
}
/// Retry control protocol
public protocol RetryControl {
/// Decide request shoudl retry or not
/// - Parameters:
/// - request: request that failed
/// - response: response of request
/// - error: error occurs on request
/// - didHaveDecision: closure to capture the decision
func shouldRetry(
for request: URLRequest,
response: URLResponse?,
error: Error,
didHaveDecision: @escaping (RetryControlDecision) -> Void) -> Void
}
/// Retry control based on time request retried
public final class CounterRetryControl: RetryControl, LockRunner {
var maxRetryCount: Int
/// time interval before do a retry
public var timeIntervalBeforeTryToRetry: TimeInterval?
/// Default init
/// - Parameters:
/// - maxRetryCount: maximum retry count
/// - timeIntervalBeforeTryToRetry: time interval before do a retry
public init(maxRetryCount: Int, timeIntervalBeforeTryToRetry: TimeInterval? = nil) {
self.maxRetryCount = maxRetryCount
self.timeIntervalBeforeTryToRetry = timeIntervalBeforeTryToRetry
}
let lock: NSLock = .init()
var retriedRequests: [URLRequest: Int] = [:]
/// Decide request shoudl retry or not. It will always retry until retry count is match with maxRetryCount
/// - Parameters:
/// - request: request that failed
/// - response: response of request
/// - error: error occurs on request
/// - didHaveDecision: closure to capture the decision
public func shouldRetry(for request: URLRequest, response: URLResponse?, error: Error, didHaveDecision: @escaping (RetryControlDecision) -> Void) {
let counter = lockedRun {
retriedRequests[request] ?? 0
}
guard counter < maxRetryCount else {
lockedRun {
retriedRequests.removeValue(forKey: request)
}
didHaveDecision(.noRetry)
return
}
lockedRun {
retriedRequests[request] = counter + 1
}
guard let timeInterval = timeIntervalBeforeTryToRetry else {
didHaveDecision(.retry)
return
}
didHaveDecision(.retryAfter(timeInterval))
}
}
| 32.038462 | 151 | 0.645458 |
8a8fb5d584e356593b95f37dc0c0332a1a2929ee | 1,083 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "Login",
platforms: [
.iOS(.v9),
],
products: [
.library(
name: "Login",
targets: ["Login"]),
],
dependencies: [
.package(path: "../ACMESecureStore"),
.package(path: "../Architecture"),
.package(path: "../Entities"),
.package(path: "../NetworkingCommon"),
.package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.1.0"),
.package(url: "https://github.com/facile-it/FunctionalKit.git", from: "0.22.0"),
],
targets: [
.target(
name: "Login",
dependencies: ["FunctionalKit", "RxSwift"]),
.testTarget(
name: "LoginTests",
dependencies: [
"Entities",
"Login",
"RxSwift",
"Architecture",
"ACMESecureStore",
"NetworkingCommon",
.product(name: "RxBlocking", package: "RxSwift")
]),
]
)
| 27.075 | 88 | 0.480148 |
d66465e3f60cf30851366e1f7cc3d36038763e3b | 2,296 | //
// SceneDelegate.swift
// SSPagerExample
//
// Created by Eido Goya on 2021/09/11.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.320755 | 147 | 0.713415 |
61b81b29a6cdb0612fa747ca64402b065608f768 | 437 | //
// NetworkConstants.swift
// IGTest
//
// Created by Enrique Melgarejo on 09/01/22.
//
import Foundation
enum NetworkConstants {
// Request default values
static let timeoutInterval: TimeInterval = 60
// HTTP Headers keys
static let contentTypeKey = "Content-Type"
// Response
static let successResponseRange = 200...299
// Content Type Value
static let contentTypeValue = "application/json"
}
| 19 | 52 | 0.691076 |
e9875a425e46c85d6795a4b07b66193c6d1d6f45 | 991 | //
// BroadcastStarterTests.swift
// BroadcastStarterTests
//
// Created by 李玉峰 on 2018/4/24.
// Copyright © 2018年 cai. All rights reserved.
//
import XCTest
@testable import BroadcastStarter
class BroadcastStarterTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.783784 | 111 | 0.641776 |
fe5775777d54e666ee6fea162bb35facbcfd1ff0 | 12,585 | //
// GQLJsonToHtml.swift
// ContentstackUtilsTests
//
// Created by Uttam Ukkoji on 19/07/21.
//
import XCTest
@testable import ContentstackUtils
class GQLJsonToHtml: XCTestCase {
func testEmpty_Node_Returns_Empty_String() {
guard let json = GQLJsonRTE(node: kBlankDocument) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, "")
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [""])
}
}
func testPlainText_Document_Return_HtmlString_Result() {
guard let json = GQLJsonRTE(node: kPlainTextJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kPlainTextHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kPlainTextHtml])
}
}
func testAsset_Reference_Document() {
guard let json = GQLJsonRTE(node: kAssetReferenceJson, items: kGQLAssetEmbed) else { return }
let expected = "<img src=\"svg-logo-text.png\" alt=\"svg-logo-text.png\" />"
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, expected)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [expected])
}
}
func testEntryBlock_Reference_Document() {
guard let json = GQLJsonRTE(node: kEntryReferenceBlockJson, items: kGQLEntryblock) else { return }
let expected = "<div><p>Update this title</p><p>Content type: <span>GQL</span></p></div>"
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, expected)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [expected])
}
}
func testEntryLink_Reference_Document() {
guard let json = GQLJsonRTE(node: kEntryReferenceLinkJson, items: kGQLEntryLink) else { return }
let expected = "<a href=\"bltemmbedEntryuid\">/copy-of-entry-final-02</a>"
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, expected)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [expected])
}
}
func testEntryInline_Reference_Document() {
guard let json = GQLJsonRTE(node: kEntryReferenceInlineJson, items: kGQLEntryInline) else { return }
let expected = "<span>updated title</span>"
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, expected)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [expected])
}
}
func testParagraph_Document() {
guard let json = GQLJsonRTE(node: kParagraphJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kParagraphHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kParagraphHtml])
}
}
func testLink_Document() {
guard let json = GQLJsonRTE(node: kLinkInPJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kLinkInPHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kLinkInPHtml])
}
}
func testImage_Document() {
guard let json = GQLJsonRTE(node: kImgJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kImgHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kImgHtml])
}
}
func testEmbed_Document() {
guard let json = GQLJsonRTE(node: kEmbedJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kEmbedHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kEmbedHtml])
}
}
func testH1_Document() {
guard let json = GQLJsonRTE(node: kH1Json) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kH1Html)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kH1Html])
}
}
func testH2_Document() {
guard let json = GQLJsonRTE(node: kH2Json) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kH2Html)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kH2Html])
}
}
func testH3_Document() {
guard let json = GQLJsonRTE(node: kH3Json) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kH3Html)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kH3Html])
}
}
func testH4_Document() {
guard let json = GQLJsonRTE(node: kH4Json) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kH4Html)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kH4Html])
}
}
func testH5_Document() {
guard let json = GQLJsonRTE(node: kH5Json) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kH5Html)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kH5Html])
}
}
func testH6_Document() {
guard let json = GQLJsonRTE(node: kH6Json) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kH6Html)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kH6Html])
}
}
func testOrderList_Document() {
guard let json = GQLJsonRTE(node: kOrderListJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kOrderListHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kOrderListHtml])
}
}
func testUnorderList_Document() {
guard let json = GQLJsonRTE(node: kUnorderListJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kIUnorderListHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kIUnorderListHtml])
}
}
func testTable_Document() {
guard let json = GQLJsonRTE(node: kTableJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kTableHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kTableHtml])
}
}
func testBlockquote_Document() {
guard let json = GQLJsonRTE(node: kBlockquoteJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kBlockquoteHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kBlockquoteHtml])
}
}
func testCode_Document() {
guard let json = GQLJsonRTE(node: kCodeJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, kCodeHtml)
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, [kCodeHtml])
}
}
func testHR_Document() {
guard let json = GQLJsonRTE(node: kHRJson) else { return }
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["single_rte"] as! [String : Any?]) as? String {
XCTAssertEqual(result, "<hr>")
}
if let result = try? ContentstackUtils.GQL.jsonToHtml(rte: json["multiple_rte"] as! [String : Any?]) as? [String] {
XCTAssertEqual(result, ["<hr>"])
}
}
static var allTests = [
("testEmpty_Node_Returns_Empty_String", testEmpty_Node_Returns_Empty_String),
("testPlainText_Document_Return_HtmlString_Result", testPlainText_Document_Return_HtmlString_Result),
("testAsset_Reference_Document", testAsset_Reference_Document),
("testEntryBlock_Reference_Document", testEntryBlock_Reference_Document),
("testEntryLink_Reference_Document", testEntryLink_Reference_Document),
("testEntryInline_Reference_Document", testEntryInline_Reference_Document),
("testParagraph_Document", testParagraph_Document),
("testLink_Document", testLink_Document),
("testImage_Document", testImage_Document),
("testEmbed_Document", testEmbed_Document),
("testH1_Document", testH1_Document),
("testH2_Document", testH2_Document),
("testH3_Document", testH3_Document),
("testH4_Document", testH4_Document),
("testH5_Document", testH5_Document),
("testH6_Document", testH6_Document),
("testOrderList_Document", testOrderList_Document),
("testUnorderList_Document", testUnorderList_Document),
("testHR_Document", testHR_Document),
("testTable_Document", testTable_Document),
("testBlockquote_Document", testBlockquote_Document),
("testCode_Document", testCode_Document),
]
}
| 41.262295 | 123 | 0.627573 |
f9306a3573d6fda0416a37c9d5a22514a3172865 | 6,146 | //
// TopAddSecutityVC.swift
// Geeklink
//
// Created by YANGFEIFEI on 2018/3/28.
// Copyright © 2018年 Geeklink. All rights reserved.
//
import UIKit
protocol TopAddAutoRuleVCDelegate : class {
func addAutoRuleVCReturnAutoRuleInfo(_ autoRuleInfo: TopAutoRuleInfo) -> Bool;
}
class TopAddAutoRuleVC: TopSuperVC ,UITableViewDelegate, UITableViewDataSource, TopTypeSelectedVCDelegate{
weak var delegate : TopAddAutoRuleVCDelegate?
var _autoRuleInfo: TopAutoRuleInfo?
var autoRuleInfo: TopAutoRuleInfo?{
set{
_autoRuleInfo = newValue as TopAutoRuleInfo?
}
get{
if _autoRuleInfo == nil{
_autoRuleInfo = TopAutoRuleInfo()
_autoRuleInfo?.mode = .leave
}
return _autoRuleInfo
}
}
@IBOutlet weak var tableView: UITableView!
var itemList = [TopItem]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("Add rule", comment: "")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(saveItemDidClicked))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetItem()
}
@objc func saveItemDidClicked() -> Void {
if delegate?.addAutoRuleVCReturnAutoRuleInfo(self.autoRuleInfo!) == false {
return
}
self.navigationController?.popViewController(animated: true)
}
func resetItem() -> Void {
itemList.removeAll()
let timeItem: TopItem = TopItem()
timeItem.text = NSLocalizedString("Timing setting", comment: "")
timeItem.detailedText = (autoRuleInfo?.timeMode.timerStr)!+"\n"+(autoRuleInfo?.timeMode.weekDayStr)!
weak var weakSelf = self
timeItem.block = { (vc: UIViewController) in
let sb = UIStoryboard(name: "Macro", bundle: nil)
let timerVC: TopTimerVC = sb.instantiateViewController(withIdentifier: "TopTimerVC") as! TopTimerVC
timerVC.type = .TopTimerVCTypeTimeSet
timerVC.timerModel = weakSelf?.autoRuleInfo?.timeMode
vc.show(timerVC, sender: nil)
}
timeItem.accessoryType = .disclosureIndicator
itemList.append(timeItem)
let securityItem: TopItem = TopItem()
securityItem.text = NSLocalizedString("Security selecting", comment: "")
securityItem.detailedText = (autoRuleInfo?.name)!
securityItem.block = { (vc: UIViewController) in
weakSelf?.showTypeSelectView()
}
securityItem.accessoryType = .disclosureIndicator
itemList.append(securityItem)
self.tableView.reloadData()
}
func showTypeSelectView(){
var safeList = Array<TopSafe>()
let goOutSafe: TopSafe = TopSafe()
goOutSafe.mode = .leave
safeList.append(goOutSafe)
TopDataManager.shared.safe = goOutSafe
let atHomeSafe: TopSafe = TopSafe()
atHomeSafe.mode = .home
safeList.append(atHomeSafe)
let nightSafe: TopSafe = TopSafe()
nightSafe.mode = .night
safeList.append(nightSafe)
let disarm: TopSafe = TopSafe()
disarm.mode = .disarm
safeList.append(disarm)
var itemList = [TopItem]()
for safe in safeList {
let icon: String = safe.selectIcon
let title: String = safe.name
let iconItem = TopItem()
iconItem.text = title
iconItem.icon = icon
iconItem.accessoryType = .selectedBtn
itemList.append(iconItem)
}
var selectRow: Int = 0
switch autoRuleInfo?.mode {
case .leave?:
selectRow = 0
case .home?:
selectRow = 1
case .night?:
selectRow = 2
case .disarm?:
selectRow = 3
default:
break
}
let sb = UIStoryboard(name: "Security", bundle: nil)
let typeSelectedVC: TopTypeSelectedVC = sb.instantiateViewController(withIdentifier: "TopTypeSelectedVC") as! TopTypeSelectedVC
typeSelectedVC.selectedRow = selectRow
typeSelectedVC.itemList = itemList
typeSelectedVC.delegate = self
show(typeSelectedVC, sender: nil)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemList.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item: TopItem = itemList[indexPath.row]
let cell: TopSuperCell = TopSuperCell(style: UITableViewCell.CellStyle.value1, reuseIdentifier: "TopSuperCell")
cell.detailTextLabel?.font = UIFont.systemFont(ofSize: 13)
cell.item = item;
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item: TopItem = itemList[indexPath.row]
weak var weakSelf = self
item.block(weakSelf!)
}
func typeSelectedVCDidSelectMode(_ mode: GLSecurityModeType) {
self.autoRuleInfo?.mode = mode
}
}
| 28.192661 | 145 | 0.590791 |
753becdd1e18fc9cd5b97454d8c33d9c8d0bf5a1 | 2,802 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// DNSChecker.swift
//
// Created by Joshua Liebowitz on 12/20/21.
import Foundation
protocol DNSCheckerType {
static func isBlockedAPIError(_ error: Error?) -> Bool
static func errorWithBlockedHostFromError(_ error: Error?) -> DNSError?
static func isBlockedURL(_ url: URL) -> Bool
static func resolvedHost(fromURL url: URL) -> String?
}
enum DNSError: Error, DescribableError, Equatable {
case blocked(failedURL: URL, resolvedHost: String?)
public var description: String {
switch self {
case .blocked(let failedURL, let resolvedHost):
return NetworkStrings.blocked_network(url: failedURL, newHost: resolvedHost).description
}
}
}
enum DNSChecker: DNSCheckerType {
static let invalidHosts = Set(["0.0.0.0", "127.0.0.1"])
static func isBlockedAPIError(_ error: Error?) -> Bool {
guard let error = error else {
return false
}
let nsError = error as NSError
guard nsError.domain == NSURLErrorDomain,
nsError.code == NSURLErrorCannotConnectToHost else {
return false
}
guard let failedURL = nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL else {
return false
}
return isBlockedURL(failedURL)
}
static func errorWithBlockedHostFromError(_ error: Error?) -> DNSError? {
guard isBlockedAPIError(error),
let nsError = error as NSError?,
let failedURL = nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL else {
return nil
}
let host = resolvedHost(fromURL: failedURL)
let blockedError = DNSError.blocked(failedURL: failedURL, resolvedHost: host)
return blockedError
}
static func isBlockedURL(_ url: URL) -> Bool {
guard let resolvedHostName = resolvedHost(fromURL: url) else {
return false
}
return self.invalidHosts.contains(resolvedHostName)
}
static func resolvedHost(fromURL url: URL) -> String? {
guard let name = url.host,
let host = name.withCString({gethostbyname($0)}),
host.pointee.h_length > 0 else {
return nil
}
var addr = in_addr()
memcpy(&addr.s_addr, host.pointee.h_addr_list[0], Int(host.pointee.h_length))
guard let remoteIPAsC = inet_ntoa(addr) else {
return nil
}
let hostIP = String(cString: remoteIPAsC)
return hostIP
}
}
| 29.1875 | 100 | 0.631692 |
1a812cb29d351e633943ca9a169427ae1778858a | 9,773 | import Foundation
public final class Declaration {
public enum Kind: String, RawRepresentable, CaseIterable {
case `associatedtype` = "associatedtype"
case `class` = "class"
case `enum` = "enum"
case enumelement = "enumelement"
case `extension` = "extension"
case extensionClass = "extension.class"
case extensionEnum = "extension.enum"
case extensionProtocol = "extension.protocol"
case extensionStruct = "extension.struct"
case functionAccessorAddress = "function.accessor.address"
case functionAccessorDidset = "function.accessor.didset"
case functionAccessorGetter = "function.accessor.getter"
case functionAccessorMutableaddress = "function.accessor.mutableaddress"
case functionAccessorSetter = "function.accessor.setter"
case functionAccessorWillset = "function.accessor.willset"
case functionConstructor = "function.constructor"
case functionDestructor = "function.destructor"
case functionFree = "function.free"
case functionMethodClass = "function.method.class"
case functionMethodInstance = "function.method.instance"
case functionMethodStatic = "function.method.static"
case functionOperator = "function.operator"
case functionOperatorInfix = "function.operator.infix"
case functionOperatorPostfix = "function.operator.postfix"
case functionOperatorPrefix = "function.operator.prefix"
case functionSubscript = "function.subscript"
case genericTypeParam = "generic_type_param"
case module = "module"
case precedenceGroup = "precedencegroup"
case `protocol` = "protocol"
case `struct` = "struct"
case `typealias` = "typealias"
case varClass = "var.class"
case varGlobal = "var.global"
case varInstance = "var.instance"
case varLocal = "var.local"
case varParameter = "var.parameter"
case varStatic = "var.static"
public static var functionKinds: Set<Kind> {
Set(Kind.allCases.filter { $0.isFunctionKind })
}
var isFunctionKind: Bool {
rawValue.hasPrefix("function")
}
var isAccessibilityModifiableFunctionKind: Bool {
rawValue.hasPrefix("function.method")
|| rawValue.hasPrefix("function.operator")
|| rawValue == "function.subscript"
|| rawValue == "function.free"
|| rawValue == "function.constructor"
}
static var variableKinds: Set<Kind> {
Set(Kind.allCases.filter { $0.isVariableKind })
}
var isVariableKind: Bool {
rawValue.hasPrefix("var")
}
var isAccessibilityModifiableVariableKind: Bool {
isVariableKind
}
static var globalKinds: Set<Kind> = [
.class,
.protocol,
.enum,
.struct,
.typealias,
.functionFree,
.extensionClass,
.extensionStruct,
.extensionProtocol,
.varGlobal
]
static var extensionKinds: Set<Kind> {
Set(Kind.allCases.filter { $0.isExtensionKind })
}
var extendedKind: Kind? {
switch self {
case .extensionClass:
return .class
case .extensionStruct:
return .struct
case .extensionEnum:
return .enum
case .extensionProtocol:
return .protocol
default:
return nil
}
}
var isExtensionKind: Bool {
rawValue.hasPrefix("extension")
}
var isConformableKind: Bool {
isDiscreteConformableKind || isExtensionKind
}
var isDiscreteConformableKind: Bool {
Self.discreteConformableKinds.contains(self)
}
static var discreteConformableKinds: Set<Kind> {
return [.class, .struct, .enum]
}
static var accessorKinds: Set<Kind> {
Set(Kind.allCases.filter { $0.isAccessorKind })
}
static var accessibleKinds: Set<Kind> {
functionKinds.union(variableKinds).union(globalKinds)
}
public var isAccessorKind: Bool {
rawValue.hasPrefix("function.accessor")
}
public var displayName: String? {
switch self {
case .class:
return "class"
case .protocol:
return "protocol"
case .struct:
return "struct"
case .enum:
return "enum"
case .enumelement:
return "enum case"
case .typealias:
return "typealias"
case .associatedtype:
return "associatedtype"
case .functionConstructor:
return "initializer"
case .extension, .extensionEnum, .extensionClass, .extensionStruct, .extensionProtocol:
return "extension"
case .functionMethodClass, .functionMethodStatic, .functionMethodInstance, .functionFree, .functionOperator, .functionSubscript:
return "function"
case .varStatic, .varInstance, .varClass, .varGlobal, .varLocal:
return "property"
case .varParameter:
return "parameter"
case .genericTypeParam:
return "generic type parameter"
default:
return nil
}
}
var referenceEquivalent: Reference.Kind? {
Reference.Kind(rawValue: rawValue)
}
}
public let location: SourceLocation
public var attributes: Set<String> = []
public var modifiers: Set<String> = []
public var accessibility: DeclarationAccessibility = .init(value: .internal, isExplicit: false)
public let kind: Kind
public var name: String?
public let usrs: Set<String>
public var unusedParameters: Set<Declaration> = []
public var declarations: Set<Declaration> = []
public var commentCommands: Set<CommentCommand> = []
public var references: Set<Reference> = []
public var declaredType: String?
public var parent: Declaration?
var related: Set<Reference> = []
var isImplicit: Bool = false
var isObjcAccessible: Bool = false
var ancestralDeclarations: Set<Declaration> {
var maybeParent = parent
var declarations: Set<Declaration> = []
while let thisParent = maybeParent {
declarations.insert(thisParent)
maybeParent = thisParent.parent
}
return declarations
}
public var descendentDeclarations: Set<Declaration> {
Set(declarations.flatMap { $0.descendentDeclarations }).union(declarations).union(unusedParameters)
}
var immediateInheritedTypeReferences: Set<Reference> {
let superclassReferences = related.filter { [.class, .struct, .protocol].contains($0.kind) }
// Innherited typealiases are References instead of a Related.
let typealiasReferences = references.filter { $0.kind == .typealias }
return superclassReferences.union(typealiasReferences)
}
var isComplexProperty: Bool {
return declarations.contains {
if [.functionAccessorWillset,
.functionAccessorDidset].contains($0.kind) {
return true
}
if $0.kind.isAccessorKind && !$0.references.isEmpty {
return true
}
return false
}
}
init(kind: Kind, usrs: Set<String>, location: SourceLocation) {
self.kind = kind
self.usrs = usrs
self.location = location
}
func isDeclaredInExtension(kind: Declaration.Kind) -> Bool {
guard let parent = parent else { return false }
return parent.kind == kind
}
}
extension Declaration: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(usrs)
}
}
extension Declaration: Equatable {
public static func == (lhs: Declaration, rhs: Declaration) -> Bool {
lhs.usrs == rhs.usrs
}
}
extension Declaration: CustomStringConvertible {
public var description: String {
"Declaration(\(descriptionParts.joined(separator: ", ")))"
}
private var descriptionParts: [String] {
let formattedName = name != nil ? "'\(name!)'" : "nil"
let formattedAttributes = "[" + attributes.sorted().joined(separator: ", ") + "]"
let formattedModifiers = "[" + modifiers.sorted().joined(separator: ", ") + "]"
let formattedCommentCommands = "[" + commentCommands.map { $0.description }.sorted().joined(separator: ", ") + "]"
let formattedUsrs = "[" + usrs.sorted().joined(separator: ", ") + "]"
let implicitOrExplicit = isImplicit ? "implicit" : "explicit"
return [kind.rawValue,
formattedName,
implicitOrExplicit,
accessibility.value.rawValue,
formattedModifiers,
formattedAttributes,
formattedCommentCommands,
formattedUsrs,
location.shortDescription]
}
}
extension Declaration: Comparable {
public static func < (lhs: Declaration, rhs: Declaration) -> Bool {
lhs.location < rhs.location
}
}
public struct DeclarationAccessibility {
public let value: Accessibility
public let isExplicit: Bool
public func isExplicitly(_ testValue: Accessibility) -> Bool {
isExplicit && value == testValue
}
}
| 33.816609 | 140 | 0.597565 |
39eb820d416b8884049b1fc783b7e7c1e262faac | 14,860 | import Foundation
import JSONUtilities
import XcodeProj
import Version
public struct LegacyTarget: Equatable {
public static let passSettingsDefault = false
public var toolPath: String
public var arguments: String?
public var passSettings: Bool
public var workingDirectory: String?
public init(
toolPath: String,
passSettings: Bool = passSettingsDefault,
arguments: String? = nil,
workingDirectory: String? = nil
) {
self.toolPath = toolPath
self.arguments = arguments
self.passSettings = passSettings
self.workingDirectory = workingDirectory
}
}
extension LegacyTarget: PathContainer {
static var pathProperties: [PathProperty] {
[
.string("workingDirectory"),
]
}
}
public struct Target: ProjectTarget {
public var name: String
public var type: PBXProductType
public var platform: Platform
public var settings: Settings
public var sources: [TargetSource]
public var dependencies: [Dependency]
public var info: Plist?
public var entitlements: Plist?
public var transitivelyLinkDependencies: Bool?
public var directlyEmbedCarthageDependencies: Bool?
public var requiresObjCLinking: Bool?
public var preBuildScripts: [BuildScript]
public var postCompileScripts: [BuildScript]
public var postBuildScripts: [BuildScript]
public var buildRules: [BuildRule]
public var configFiles: [String: String]
public var scheme: TargetScheme?
public var legacy: LegacyTarget?
public var deploymentTarget: Version?
public var attributes: [String: Any]
public var productName: String
public var onlyCopyFilesOnInstall: Bool
public var isLegacy: Bool {
legacy != nil
}
public var filename: String {
var filename = productName
if let fileExtension = type.fileExtension {
filename += ".\(fileExtension)"
}
if type == .staticLibrary {
filename = "lib\(filename)"
}
return filename
}
public init(
name: String,
type: PBXProductType,
platform: Platform,
productName: String? = nil,
deploymentTarget: Version? = nil,
settings: Settings = .empty,
configFiles: [String: String] = [:],
sources: [TargetSource] = [],
dependencies: [Dependency] = [],
info: Plist? = nil,
entitlements: Plist? = nil,
transitivelyLinkDependencies: Bool? = nil,
directlyEmbedCarthageDependencies: Bool? = nil,
requiresObjCLinking: Bool? = nil,
preBuildScripts: [BuildScript] = [],
postCompileScripts: [BuildScript] = [],
postBuildScripts: [BuildScript] = [],
buildRules: [BuildRule] = [],
scheme: TargetScheme? = nil,
legacy: LegacyTarget? = nil,
attributes: [String: Any] = [:],
onlyCopyFilesOnInstall: Bool = false
) {
self.name = name
self.type = type
self.platform = platform
self.deploymentTarget = deploymentTarget
self.productName = productName ?? name
self.settings = settings
self.configFiles = configFiles
self.sources = sources
self.dependencies = dependencies
self.info = info
self.entitlements = entitlements
self.transitivelyLinkDependencies = transitivelyLinkDependencies
self.directlyEmbedCarthageDependencies = directlyEmbedCarthageDependencies
self.requiresObjCLinking = requiresObjCLinking
self.preBuildScripts = preBuildScripts
self.postCompileScripts = postCompileScripts
self.postBuildScripts = postBuildScripts
self.buildRules = buildRules
self.scheme = scheme
self.legacy = legacy
self.attributes = attributes
self.onlyCopyFilesOnInstall = onlyCopyFilesOnInstall
}
}
extension Target: CustomStringConvertible {
public var description: String {
"\(name): \(platform.rawValue) \(type)"
}
}
extension Target: PathContainer {
static var pathProperties: [PathProperty] {
[
.dictionary([
.string("sources"),
.object("sources", TargetSource.pathProperties),
.string("configFiles"),
.object("dependencies", Dependency.pathProperties),
.object("info", Plist.pathProperties),
.object("entitlements", Plist.pathProperties),
.object("preBuildScripts", BuildScript.pathProperties),
.object("prebuildScripts", BuildScript.pathProperties),
.object("postCompileScripts", BuildScript.pathProperties),
.object("postBuildScripts", BuildScript.pathProperties),
.object("legacy", LegacyTarget.pathProperties),
]),
]
}
}
extension Target {
static func resolveMultiplatformTargets(jsonDictionary: JSONDictionary) -> JSONDictionary {
guard let targetsDictionary: [String: JSONDictionary] = jsonDictionary["targets"] as? [String: JSONDictionary] else {
return jsonDictionary
}
var crossPlatformTargets: [String: JSONDictionary] = [:]
for (targetName, target) in targetsDictionary {
if let platforms = target["platform"] as? [String] {
for platform in platforms {
var platformTarget = target
platformTarget = platformTarget.expand(variables: ["platform": platform])
platformTarget["platform"] = platform
let platformSuffix = platformTarget["platformSuffix"] as? String ?? "_\(platform)"
let platformPrefix = platformTarget["platformPrefix"] as? String ?? ""
let newTargetName = platformPrefix + targetName + platformSuffix
var settings = platformTarget["settings"] as? JSONDictionary ?? [:]
var newProductName: String?
if settings["configs"] != nil || settings["groups"] != nil || settings["base"] != nil {
var base = settings["base"] as? JSONDictionary ?? [:]
if let baseProductName = base["PRODUCT_NAME"] as? String {
newProductName = baseProductName
} else {
base["PRODUCT_NAME"] = targetName
}
settings["base"] = base
} else {
if let productName = settings["PRODUCT_NAME"] as? String {
newProductName = productName
} else {
settings["PRODUCT_NAME"] = targetName
}
}
platformTarget["productName"] = ((platformTarget["productNameFromSettings"] as? Bool == true) ? newProductName : nil) ?? targetName
platformTarget["settings"] = settings
if let deploymentTargets = target["deploymentTarget"] as? [String: Any] {
platformTarget["deploymentTarget"] = deploymentTargets[platform]
}
crossPlatformTargets[newTargetName] = platformTarget
}
} else {
crossPlatformTargets[targetName] = target
}
}
var merged = jsonDictionary
merged["targets"] = crossPlatformTargets
return merged
}
}
extension Target: Equatable {
public static func == (lhs: Target, rhs: Target) -> Bool {
lhs.name == rhs.name &&
lhs.type == rhs.type &&
lhs.platform == rhs.platform &&
lhs.deploymentTarget == rhs.deploymentTarget &&
lhs.transitivelyLinkDependencies == rhs.transitivelyLinkDependencies &&
lhs.requiresObjCLinking == rhs.requiresObjCLinking &&
lhs.directlyEmbedCarthageDependencies == rhs.directlyEmbedCarthageDependencies &&
lhs.settings == rhs.settings &&
lhs.configFiles == rhs.configFiles &&
lhs.sources == rhs.sources &&
lhs.info == rhs.info &&
lhs.entitlements == rhs.entitlements &&
lhs.dependencies == rhs.dependencies &&
lhs.preBuildScripts == rhs.preBuildScripts &&
lhs.postCompileScripts == rhs.postCompileScripts &&
lhs.postBuildScripts == rhs.postBuildScripts &&
lhs.buildRules == rhs.buildRules &&
lhs.scheme == rhs.scheme &&
lhs.legacy == rhs.legacy &&
NSDictionary(dictionary: lhs.attributes).isEqual(to: rhs.attributes)
}
}
extension LegacyTarget: JSONObjectConvertible {
public init(jsonDictionary: JSONDictionary) throws {
toolPath = try jsonDictionary.json(atKeyPath: "toolPath")
arguments = jsonDictionary.json(atKeyPath: "arguments")
passSettings = jsonDictionary.json(atKeyPath: "passSettings") ?? LegacyTarget.passSettingsDefault
workingDirectory = jsonDictionary.json(atKeyPath: "workingDirectory")
}
}
extension LegacyTarget: JSONEncodable {
public func toJSONValue() -> Any {
var dict: [String: Any?] = [
"toolPath": toolPath,
"arguments": arguments,
"workingDirectory": workingDirectory,
]
if passSettings != LegacyTarget.passSettingsDefault {
dict["passSettings"] = passSettings
}
return dict
}
}
extension Target: NamedJSONDictionaryConvertible {
public init(name: String, jsonDictionary: JSONDictionary) throws {
let resolvedName: String = jsonDictionary.json(atKeyPath: "name") ?? name
self.name = resolvedName
productName = jsonDictionary.json(atKeyPath: "productName") ?? resolvedName
let typeString: String = try jsonDictionary.json(atKeyPath: "type")
if let type = PBXProductType(string: typeString) {
self.type = type
} else {
throw SpecParsingError.unknownTargetType(typeString)
}
let platformString: String = try jsonDictionary.json(atKeyPath: "platform")
if let platform = Platform(rawValue: platformString) {
self.platform = platform
} else {
throw SpecParsingError.unknownTargetPlatform(platformString)
}
if let string: String = jsonDictionary.json(atKeyPath: "deploymentTarget") {
deploymentTarget = try Version.parse(string)
} else if let double: Double = jsonDictionary.json(atKeyPath: "deploymentTarget") {
deploymentTarget = try Version.parse(String(double))
} else {
deploymentTarget = nil
}
settings = jsonDictionary.json(atKeyPath: "settings") ?? .empty
configFiles = jsonDictionary.json(atKeyPath: "configFiles") ?? [:]
if let source: String = jsonDictionary.json(atKeyPath: "sources") {
sources = [TargetSource(path: source)]
} else if let array = jsonDictionary["sources"] as? [Any] {
sources = try array.compactMap { source in
if let string = source as? String {
return TargetSource(path: string)
} else if let dictionary = source as? [String: Any] {
return try TargetSource(jsonDictionary: dictionary)
} else {
return nil
}
}
} else {
sources = []
}
if jsonDictionary["dependencies"] == nil {
dependencies = []
} else {
let dependencies: [Dependency] = try jsonDictionary.json(atKeyPath: "dependencies", invalidItemBehaviour: .fail)
self.dependencies = dependencies.filter { [platform] dependency -> Bool in
// If unspecified, all platforms are supported
guard let platforms = dependency.platforms else { return true }
return platforms.contains(platform)
}
}
if jsonDictionary["info"] != nil {
info = try jsonDictionary.json(atKeyPath: "info") as Plist
}
if jsonDictionary["entitlements"] != nil {
entitlements = try jsonDictionary.json(atKeyPath: "entitlements") as Plist
}
transitivelyLinkDependencies = jsonDictionary.json(atKeyPath: "transitivelyLinkDependencies")
directlyEmbedCarthageDependencies = jsonDictionary.json(atKeyPath: "directlyEmbedCarthageDependencies")
requiresObjCLinking = jsonDictionary.json(atKeyPath: "requiresObjCLinking")
preBuildScripts = jsonDictionary.json(atKeyPath: "preBuildScripts") ?? jsonDictionary.json(atKeyPath: "prebuildScripts") ?? []
postCompileScripts = jsonDictionary.json(atKeyPath: "postCompileScripts") ?? []
postBuildScripts = jsonDictionary.json(atKeyPath: "postBuildScripts") ?? jsonDictionary.json(atKeyPath: "postbuildScripts") ?? []
buildRules = jsonDictionary.json(atKeyPath: "buildRules") ?? []
scheme = jsonDictionary.json(atKeyPath: "scheme")
legacy = jsonDictionary.json(atKeyPath: "legacy")
attributes = jsonDictionary.json(atKeyPath: "attributes") ?? [:]
onlyCopyFilesOnInstall = jsonDictionary.json(atKeyPath: "onlyCopyFilesOnInstall") ?? false
}
}
extension Target: JSONEncodable {
public func toJSONValue() -> Any {
var dict: [String: Any?] = [
"type": type.name,
"platform": platform.rawValue,
"settings": settings.toJSONValue(),
"configFiles": configFiles,
"attributes": attributes,
"sources": sources.map { $0.toJSONValue() },
"dependencies": dependencies.map { $0.toJSONValue() },
"postCompileScripts": postCompileScripts.map { $0.toJSONValue() },
"prebuildScripts": preBuildScripts.map { $0.toJSONValue() },
"postbuildScripts": postBuildScripts.map { $0.toJSONValue() },
"buildRules": buildRules.map { $0.toJSONValue() },
"deploymentTarget": deploymentTarget?.deploymentTarget,
"info": info?.toJSONValue(),
"entitlements": entitlements?.toJSONValue(),
"transitivelyLinkDependencies": transitivelyLinkDependencies,
"directlyEmbedCarthageDependencies": directlyEmbedCarthageDependencies,
"requiresObjCLinking": requiresObjCLinking,
"scheme": scheme?.toJSONValue(),
"legacy": legacy?.toJSONValue(),
]
if productName != name {
dict["productName"] = productName
}
if onlyCopyFilesOnInstall {
dict["onlyCopyFilesOnInstall"] = true
}
return dict
}
}
| 39.73262 | 151 | 0.610027 |
28ba95b8995f207dc47473b791daf6397876c07b | 7,020 | //
// DownloadManager.swift
// EMHenTai
//
// Created by yuman on 2022/1/14.
//
import Foundation
import Alamofire
final class DownloadManager {
enum DownloadState {
case before
case ing
case suspend
case finish
}
static let shared = DownloadManager()
static let DownloadPageSuccessNotification = NSNotification.Name(rawValue: "EMHenTai.DownloadManager.DownloadPageSuccessNotification")
static let DownloadStateChangedNotification = NSNotification.Name(rawValue: "EMHenTai.DownloadManager.DownloadStateChangedNotification")
private init() {}
private let taskMap = TaskMap()
private let groupTotalImgNum = 40
private let maxConcurrentDownloadCount = 8
func download(book: Book) {
Task {
let state = await downloadState(of: book)
if state == .ing || state == .finish {
return
}
try? FileManager.default.createDirectory(at: URL(fileURLWithPath: book.folderPath), withIntermediateDirectories: true, attributes: nil)
await taskMap.set(Task {
await p_download(of: book)
await taskMap.remove(book.gid)
if book.downloadedFileCount == book.fileCountNum {
NotificationCenter.default.post(name: DownloadManager.DownloadStateChangedNotification, object: book.gid, userInfo: nil)
}
}, for: book.gid)
NotificationCenter.default.post(name: DownloadManager.DownloadStateChangedNotification, object: book.gid, userInfo: nil)
}
}
func suspend(book: Book) {
Task {
await taskMap.remove(book.gid)
NotificationCenter.default.post(name: DownloadManager.DownloadStateChangedNotification, object: book.gid, userInfo: nil)
}
}
func remove(book: Book) {
Task {
await taskMap.remove(book.gid)
try? FileManager.default.removeItem(atPath: book.folderPath)
NotificationCenter.default.post(name: DownloadManager.DownloadStateChangedNotification, object: book.gid, userInfo: nil)
}
}
func downloadState(of book: Book) async -> DownloadState {
if book.downloadedFileCount == book.fileCountNum {
return .finish
} else if await taskMap.isContain(book.gid) {
return .ing
} else {
return book.downloadedFileCount == 0 ? .before : .suspend
}
}
private func p_download(of book: Book) async {
let urlStream = AsyncStream<String> { continuation in
Task {
await withTaskGroup(of: Void.self, body: { group in
let groupNum = book.fileCountNum / groupTotalImgNum + (book.fileCountNum % groupTotalImgNum == 0 ? 0 : 1)
for groupIndex in 0..<groupNum {
guard checkGroupNeedRequest(of: book, groupIndex: groupIndex) else { continue }
group.addTask {
let url = book.currentWebURLString + (groupIndex > 0 ? "?p=\(groupIndex)" : "") + "/?nw=session"
guard let value = try? await AF.request(url, interceptor: RetryPolicy()).serializingString(automaticallyCancelling: true).value else { return }
let baseURL = SearchInfo.currentSource.rawValue + "s/"
value.allSubStringOf(target: baseURL, endCharater: "\"").forEach { continuation.yield(baseURL + $0) }
}
await group.waitForAll()
}
})
continuation.finish()
}
}
await withTaskGroup(of: Void.self, body: { group in
var count = 0
for await url in urlStream {
let imgIndex = (url.split(separator: "-").last.flatMap({ Int("\($0)") }) ?? 1) - 1
let imgKey = url.split(separator: "/").count > 1 ? url.split(separator: "/").reversed()[1] : ""
guard !FileManager.default.fileExists(atPath: book.imagePath(at: imgIndex)) else { continue }
guard !imgKey.isEmpty else { continue }
count += 1
if count > maxConcurrentDownloadCount {
await group.next()
}
group.addTask {
guard let value = try? await AF.request(url, interceptor: RetryPolicy()).serializingString(automaticallyCancelling: true).value else { return }
guard let showKey = value.allSubStringOf(target: "showkey=\"", endCharater: "\"").first else { return }
guard let source = try? await AF.request(
SearchInfo.currentSource.rawValue + "api.php",
method: .post,
parameters: [
"method": "showpage",
"gid": book.gid,
"page": imgIndex + 1,
"imgkey": imgKey,
"showkey": showKey],
encoding: JSONEncoding.default
).serializingDecodable(GroupModel.self, automaticallyCancelling: true).value.i3 else { return }
guard let imgURL = source.allSubStringOf(target: "src=\"", endCharater: "\"").first else { return }
guard let p = try? await AF
.download(imgURL, interceptor: RetryPolicy(), to: { _, _ in (URL(fileURLWithPath: book.imagePath(at: imgIndex)), []) })
.serializingDownload(using: URLResponseSerializer(), automaticallyCancelling: true)
.value, FileManager.default.fileExists(atPath: p.path) else { return }
NotificationCenter.default.post(name: DownloadManager.DownloadPageSuccessNotification, object: (book.gid, imgIndex), userInfo: nil)
}
}
})
}
private func checkGroupNeedRequest(of book: Book, groupIndex: Int) -> Bool {
for index in 0..<groupTotalImgNum {
let realIndex = groupIndex * groupTotalImgNum + index
guard realIndex < book.fileCountNum else { break }
if !FileManager.default.fileExists(atPath: book.imagePath(at: realIndex)) {
return true
}
}
return false
}
}
final private actor TaskMap {
private var map = [Int: Task<Void, Never>]()
func set(_ task: Task<Void, Never>, for gid: Int) {
map[gid] = task
}
func remove(_ gid: Int) {
map.removeValue(forKey: gid)?.cancel()
}
func isContain(_ gid: Int) -> Bool {
map[gid] != nil
}
}
private struct GroupModel: Codable {
let i3: String
}
| 42.035928 | 171 | 0.553419 |
14d2580d69fe16f70915c382238411d5300da777 | 11,517 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: unittest_swift_enum.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Protocol Buffers - Google's data interchange format
// Copyright 2015 Apple, Inc. All Rights Reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct ProtobufUnittest_SwiftEnumTest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var values1: [ProtobufUnittest_SwiftEnumTest.EnumTest1] = []
var values2: [ProtobufUnittest_SwiftEnumTest.EnumTest2] = []
var values3: [ProtobufUnittest_SwiftEnumTest.EnumTestNoStem] = []
var values4: [ProtobufUnittest_SwiftEnumTest.EnumTestReservedWord] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
enum EnumTest1: SwiftProtobuf.Enum {
typealias RawValue = Int
case firstValue // = 1
case secondValue // = 2
init() {
self = .firstValue
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .firstValue
case 2: self = .secondValue
default: return nil
}
}
var rawValue: Int {
switch self {
case .firstValue: return 1
case .secondValue: return 2
}
}
}
enum EnumTest2: SwiftProtobuf.Enum {
typealias RawValue = Int
case firstValue // = 1
case secondValue // = 2
init() {
self = .firstValue
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .firstValue
case 2: self = .secondValue
default: return nil
}
}
var rawValue: Int {
switch self {
case .firstValue: return 1
case .secondValue: return 2
}
}
}
enum EnumTestNoStem: SwiftProtobuf.Enum {
typealias RawValue = Int
case enumTestNoStem1 // = 1
case enumTestNoStem2 // = 2
init() {
self = .enumTestNoStem1
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .enumTestNoStem1
case 2: self = .enumTestNoStem2
default: return nil
}
}
var rawValue: Int {
switch self {
case .enumTestNoStem1: return 1
case .enumTestNoStem2: return 2
}
}
}
enum EnumTestReservedWord: SwiftProtobuf.Enum {
typealias RawValue = Int
case `var` // = 1
case notReserved // = 2
init() {
self = .var
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .var
case 2: self = .notReserved
default: return nil
}
}
var rawValue: Int {
switch self {
case .var: return 1
case .notReserved: return 2
}
}
}
init() {}
}
#if swift(>=4.2)
extension ProtobufUnittest_SwiftEnumTest.EnumTest1: CaseIterable {
// Support synthesized by the compiler.
}
extension ProtobufUnittest_SwiftEnumTest.EnumTest2: CaseIterable {
// Support synthesized by the compiler.
}
extension ProtobufUnittest_SwiftEnumTest.EnumTestNoStem: CaseIterable {
// Support synthesized by the compiler.
}
extension ProtobufUnittest_SwiftEnumTest.EnumTestReservedWord: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
struct ProtobufUnittest_SwiftEnumWithAliasTest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var values: [ProtobufUnittest_SwiftEnumWithAliasTest.EnumWithAlias] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
enum EnumWithAlias: SwiftProtobuf.Enum {
typealias RawValue = Int
case foo1 // = 1
static let foo2 = foo1
/// out of value order to test allCases
case baz1 // = 3
case bar1 // = 2
static let bar2 = bar1
init() {
self = .foo1
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .foo1
case 2: self = .bar1
case 3: self = .baz1
default: return nil
}
}
var rawValue: Int {
switch self {
case .foo1: return 1
case .bar1: return 2
case .baz1: return 3
}
}
}
init() {}
}
#if swift(>=4.2)
extension ProtobufUnittest_SwiftEnumWithAliasTest.EnumWithAlias: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest"
extension ProtobufUnittest_SwiftEnumTest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SwiftEnumTest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "values1"),
2: .same(proto: "values2"),
3: .same(proto: "values3"),
4: .same(proto: "values4"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedEnumField(value: &self.values1) }()
case 2: try { try decoder.decodeRepeatedEnumField(value: &self.values2) }()
case 3: try { try decoder.decodeRepeatedEnumField(value: &self.values3) }()
case 4: try { try decoder.decodeRepeatedEnumField(value: &self.values4) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.values1.isEmpty {
try visitor.visitRepeatedEnumField(value: self.values1, fieldNumber: 1)
}
if !self.values2.isEmpty {
try visitor.visitRepeatedEnumField(value: self.values2, fieldNumber: 2)
}
if !self.values3.isEmpty {
try visitor.visitRepeatedEnumField(value: self.values3, fieldNumber: 3)
}
if !self.values4.isEmpty {
try visitor.visitRepeatedEnumField(value: self.values4, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_SwiftEnumTest, rhs: ProtobufUnittest_SwiftEnumTest) -> Bool {
if lhs.values1 != rhs.values1 {return false}
if lhs.values2 != rhs.values2 {return false}
if lhs.values3 != rhs.values3 {return false}
if lhs.values4 != rhs.values4 {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_SwiftEnumTest.EnumTest1: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ENUM_TEST_1_FIRST_VALUE"),
2: .same(proto: "ENUM_TEST_1_SECOND_VALUE"),
]
}
extension ProtobufUnittest_SwiftEnumTest.EnumTest2: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ENUM_TEST_2_FIRST_VALUE"),
2: .same(proto: "SECOND_VALUE"),
]
}
extension ProtobufUnittest_SwiftEnumTest.EnumTestNoStem: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ENUM_TEST_NO_STEM_1"),
2: .same(proto: "ENUM_TEST_NO_STEM_2"),
]
}
extension ProtobufUnittest_SwiftEnumTest.EnumTestReservedWord: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ENUM_TEST_RESERVED_WORD_VAR"),
2: .same(proto: "ENUM_TEST_RESERVED_WORD_NOT_RESERVED"),
]
}
extension ProtobufUnittest_SwiftEnumWithAliasTest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SwiftEnumWithAliasTest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "values"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedEnumField(value: &self.values) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.values.isEmpty {
try visitor.visitPackedEnumField(value: self.values, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_SwiftEnumWithAliasTest, rhs: ProtobufUnittest_SwiftEnumWithAliasTest) -> Bool {
if lhs.values != rhs.values {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_SwiftEnumWithAliasTest.EnumWithAlias: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .aliased(proto: "FOO1", aliases: ["FOO2"]),
2: .aliased(proto: "BAR1", aliases: ["BAR2"]),
3: .same(proto: "BAZ1"),
]
}
| 31.211382 | 151 | 0.705739 |
d977e80d8b3bdc8161fb294181beb9e68ff7a0b7 | 1,114 | //
// ActivityIndicatorView.swift
// EsoftUIKit
//
// Copyright © 2019 E-SOFT. All rights reserved.
//
import UIKit
import YogaKit
import BaseUI
public final class ActivityIndicatorView: View {
public private(set) var activity: ActivityIndicator = ActivityIndicator()
override public var intrinsicContentSize: CGSize {
let sideSize = activity.spinnerSize * 2 + activity.strokeWidth
return CGSize(width: sideSize, height: sideSize)
}
override public init() {
super.init()
createUI()
configureUI()
}
private func createUI() {
addSubview(activity)
}
private func configureUI() {}
override public func layoutSubviews() {
super.layoutSubviews()
configureLayout { layout in
layout.isEnabled = true
layout.width = 100%
layout.height = 100%
layout.alignItems = .center
layout.justifyContent = .center
}
activity.configureLayout { layout in
layout.isEnabled = true
layout.width = YGValue.base
layout.height = YGValue.base
}
yoga.applyLayout(preservingOrigin: true)
}
}
| 21.018868 | 75 | 0.669659 |
4b138048713ccbada8698118bcc633fe0b464be7 | 2,634 | // Copyright (c) 2020-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import Foundation
struct ErrorMessage {
struct Info {
static let nilPointOfInterestZeroOffset =
"[INFO] The point of interest is nil, offset will be zero."
static let nilPointOfInterestCenterAlignment =
"[INFO] The point of interest is nil, alignment will fall back to .center."
static let skipViewNoSuperviewNotShown =
"[INFO] skipView has no superview and won't be shown."
static let skipViewNoSuperviewNotUpdated =
"[INFO] skipView has no superview and won't be updated."
}
struct Warning {
static let unsupportedWindowLevel =
"[WARNING] Displaying Instructions over the status bar is unsupported in iOS 13+."
static let nilDataSource =
"[WARNING] dataSource is nil."
static let noCoachMarks =
"[WARNING] dataSource.numberOfCoachMarks(for:) returned 0."
static let noParent =
"[WARNING] View has no parent, cannot define constraints."
static let frameWithNoWidth =
"[WARNING] frame has no width, alignment will fall back to .center."
static let negativeNumberOfCoachMarksToSkip =
"[WARNING] numberToSkip is negative, ignoring."
}
struct Error {
static let couldNotBeAttached =
"""
[ERROR] Instructions could not be properly attached to the window \
did you call `start(in:)` inside `viewDidLoad` instead of `viewDidAppear`?
"""
static let notAChild =
"""
[WARNING] `coachMarkView` is not a child of `parentView`. \
The array of constraints will be empty.
"""
static let updateWentWrong =
"""
[ERROR] Something went wrong, did you call \
`updateCurrentCoachMark()` without pausing the controller first?
"""
static let overlayEmptyBounds =
"""
[ERROR] The overlay view added to the window has empty bounds, \
Instructions will stop.
"""
}
struct Fatal {
static let negativeNumberOfCoachMarks =
"dataSource.numberOfCoachMarks(for:) returned a negative number."
static let windowContextNotAvailableInAppExtensions =
"PresentationContext.newWindow(above:) is not available in App Extensions."
static let doesNotSupportNSCoding =
"This class does not support NSCoding."
}
}
| 33.769231 | 94 | 0.621109 |
14387798c89167f253db599c8bae607422c96e66 | 4,011 | //
// PhoneVC.swift
// Ribbit
//
// Created by Adnan Asghar on 3/16/21.
// MARK: - Take the phone number of a user
import SSSpinnerButton
import TweeTextField
import UIKit
class PhoneVC: BaseVC {
// MARK: - IB-Outlets
@IBOutlet var txtPhone: TweeAttributedTextField!
@IBOutlet var btnCont: SSSpinnerButton!
// MARK: - Variables
private var phoneVM: PhoneViewModel!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setDataOnView()
}
// MARK: - IBActions
@IBAction func continuePressed(_ sender: SSSpinnerButton) {
// reset error
txtPhone.showInfo("")
let num = txtPhone.text?.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "-", with: "")
.replacingOccurrences(of: "(", with: "")
.replacingOccurrences(of: ")", with: "") ?? ""
// validate text field
let validator = Validator()
if let errorMsg = validator.validate(text: num, with: [.notEmpty, .validatePhone]) {
txtPhone.showInfo(errorMsg)
return
}
sender.startAnimate(spinnerType: SpinnerType.circleStrokeSpin, spinnercolor: UIColor.white, spinnerSize: 20, complete: {
self.updateProfile(sender: sender)
})
}
// MARK: - Helpers
private func updateProfile(sender: SSSpinnerButton) {
let num = txtPhone.text?.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "-", with: "")
.replacingOccurrences(of: "(", with: "")
.replacingOccurrences(of: ")", with: "") ?? ""
phoneVM = PhoneViewModel(phone: num)
phoneVM.sender = sender
phoneVM.bindViewModelToController = {
sender.stopAnimate {
self.openDOB()
}
}
}
private func openDOB() {
let router = PhoneRouter()
router.route(to: DOBVC.identifier, from: self, parameters: nil, animated: true)
}
private func setDataOnView() {
txtPhone.delegate = self
if let phone = USER.shared.details?.user?.mobile, phone != "" {
txtPhone.text = phone.replacingOccurrences(of: "+1", with: "").applyPatternOnNumbers(pattern: "(###) ###-####", replacementCharacter: "#")
btnCont.setBackground(enable: true)
}
}
}
extension PhoneVC: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return false }
let charsLimit = 14
let startingLength = text.count
let lengthToAdd = string.count
let lengthToReplace = range.length
let newLength = startingLength + lengthToAdd - lengthToReplace
let flag = newLength <= charsLimit
if flag {
txtPhone.showInfo("")
textField.text = text.applyPatternOnNumbers(pattern: "(###) ###-####", replacementCharacter: "#")
}
let currentText = textField.text ?? ""
guard let stringRange = Range(range, in: currentText) else { return false }
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
let num = updatedText.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "-", with: "")
.replacingOccurrences(of: "(", with: "")
.replacingOccurrences(of: ")", with: "")
// validate text field
let validator = Validator()
if let errorMsg = validator.validate(text: num, with: [.notEmpty, .validatePhone]) {
txtPhone.showInfo(errorMsg)
btnCont.setBackground(enable: false)
} else {
txtPhone.showInfo("")
btnCont.setBackground(enable: true)
}
return flag
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 34.878261 | 150 | 0.602593 |
48d192bc976868f55a9f8e392d36ac8a14b825e6 | 1,193 | //
// ProductItemView.swift
// Touchdown
//
// Created by Jorge Martinez on 08/10/21.
//
import SwiftUI
struct ProductItemView: View {
// MARK: - Properties
var product: Product
// MARK: - Body
var body: some View {
VStack(alignment: .leading, spacing: 6) {
// PHOTO
ZStack {
Image(product.image)
.resizable()
.scaledToFit()
.padding(10)
} //: ZStack
.background(product.colorComponent)
.cornerRadius(12)
// NAME
Text(product.name)
.font(.title3)
.fontWeight(.black)
// PRICE
Text(product.formattedPrice)
.fontWeight(.semibold)
.foregroundColor(.gray)
} //: VStack
}
}
// MARK: - Preview
struct ProductItemView_Previews: PreviewProvider {
static var previews: some View {
ProductItemView(product: products[0])
.previewLayout(.fixed(width: 200, height: 300))
.padding()
.background(colorBackground)
}
}
| 23.392157 | 59 | 0.49036 |
72da428f884fef839a5701eac953381295ac93e9 | 1,975 | //
// DraggableDismissInteractionController.swift
// PresentationController
//
// Created by Emre on 11.09.2018.
// Copyright © 2018 Emre. All rights reserved.
//
import UIKit
class BottomPopupDismissInteractionController: UIPercentDrivenInteractiveTransition {
private let kMinPercentOfVisiblePartToCompleteAnimation = CGFloat(0.25)
private weak var presentedViewController: BottomPopupViewController?
private var currentPercent: CGFloat = 0
private weak var transitioningDelegate: BottomPopupTransitionHandler?
init(presentedViewController: BottomPopupViewController?) {
self.presentedViewController = presentedViewController
self.transitioningDelegate = presentedViewController?.transitioningDelegate as? BottomPopupTransitionHandler
super.init()
preparePanGesture(in: presentedViewController?.view)
}
private func finishAnimation() {
if currentPercent > kMinPercentOfVisiblePartToCompleteAnimation {
finish()
} else {
cancel()
}
}
private func preparePanGesture(in view: UIView?) {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
presentedViewController?.view?.addGestureRecognizer(panGesture)
}
@objc private func handlePanGesture(_ pan: UIPanGestureRecognizer) {
let translationY = pan.translation(in: presentedViewController?.view).y
currentPercent = min(max(translationY/(presentedViewController?.view.frame.size.height ?? 0), 0), 1)
switch pan.state {
case .began:
transitioningDelegate?.isInteractiveDismissStarted = true
presentedViewController?.dismiss(animated: true, completion: nil)
case .changed:
update(currentPercent)
default:
transitioningDelegate?.isInteractiveDismissStarted = false
finishAnimation()
}
}
}
| 36.574074 | 116 | 0.704304 |
7913ac933860afe16e1494173eca9ae0bc07c1c5 | 25,156 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
`LevelScene` is an `SKScene` representing a playable level in the game. `WorldLayer` is an enumeration that represents the different z-indexed layers of a `LevelScene`.
*/
import SpriteKit
import GameplayKit
/// The names and z-positions of each layer in a level's world.
enum WorldLayer: CGFloat {
// The zPosition offset to use per character (`PlayerBot` or `TaskBot`).
static let zSpacePerCharacter: CGFloat = 100
// Specifying `AboveCharacters` as 1000 gives room for 9 enemies on a level.
case Board = -100, Debug = -75, Shadows = -50, Obstacles = -25, Characters = 0, AboveCharacters = 1000, Top = 1100
// The expected name for this node in the scene file.
var nodeName: String {
switch self {
case .Board: return "board"
case .Debug: return "debug"
case .Shadows: return "shadows"
case .Obstacles: return "obstacles"
case .Characters: return "characters"
case .AboveCharacters: return "above_characters"
case .Top: return "top"
}
}
// The full path to this node, for use with `childNodeWithName(_:)`.
var nodePath: String {
return "/world/\(nodeName)"
}
static var allLayers = [Board, Debug, Shadows, Obstacles, Characters, AboveCharacters, Top]
}
class LevelScene: BaseScene, SKPhysicsContactDelegate {
// MARK: Properties
/// Stores a reference to the root nodes for each world layer in the scene.
var worldLayerNodes = [WorldLayer: SKNode]()
let playerBot = PlayerBot()
var entities = Set<GKEntity>()
var lastUpdateTimeInterval: NSTimeInterval = 0
let maximumUpdateDeltaTime: NSTimeInterval = 1.0 / 60.0
var levelConfiguration: LevelConfiguration!
lazy var stateMachine: GKStateMachine = GKStateMachine(states: [
LevelSceneActiveState(levelScene: self),
LevelScenePauseState(levelScene: self),
LevelSceneSuccessState(levelScene: self),
LevelSceneFailState(levelScene: self)
])
let timerNode = SKLabelNode(text: "--:--")
// MARK: Pathfinding
lazy var graph: GKObstacleGraph = GKObstacleGraph(obstacles: self.polygonObstacles, bufferRadius: GameplayConfiguration.TaskBot.pathfindingGraphBufferRadius)
lazy var obstacleSpriteNodes: [SKSpriteNode] = self["world/obstacles/*"] as! [SKSpriteNode]
lazy var polygonObstacles: [GKPolygonObstacle] = SKNode.obstaclesFromNodePhysicsBodies(self.obstacleSpriteNodes)
// MARK: Pathfinding Debug
var debugDrawingEnabled = false {
didSet {
debugDrawingEnabledDidChange()
}
}
var graphLayer = SKNode()
var debugObstacleLayer = SKNode()
// MARK: Rule State
var levelStateSnapshot: LevelStateSnapshot?
func entitySnapshotForEntity(entity: GKEntity) -> EntitySnapshot? {
// Create a snapshot of the level's state if one does not already exist for this update cycle.
if levelStateSnapshot == nil {
levelStateSnapshot = LevelStateSnapshot(scene: self)
}
// Find and return the entity snapshot for this entity.
return levelStateSnapshot!.entitySnapshots[entity]
}
// MARK: Component Systems
lazy var componentSystems: [GKComponentSystem] = {
let agentSystem = GKComponentSystem(componentClass: TaskBotAgent.self)
let animationSystem = GKComponentSystem(componentClass: AnimationComponent.self)
let chargeSystem = GKComponentSystem(componentClass: ChargeComponent.self)
let intelligenceSystem = GKComponentSystem(componentClass: IntelligenceComponent.self)
let movementSystem = GKComponentSystem(componentClass: MovementComponent.self)
let beamSystem = GKComponentSystem(componentClass: BeamComponent.self)
let rulesSystem = GKComponentSystem(componentClass: RulesComponent.self)
// The systems will be updated in order. This order is explicitly defined to match assumptions made within components.
return [rulesSystem, intelligenceSystem, movementSystem, agentSystem, chargeSystem, beamSystem, animationSystem]
}()
// MARK: Scene Life Cycle
override func didMoveToView(view: SKView) {
// Load the level's configuration from the level data file.
levelConfiguration = LevelConfiguration(fileName: sceneManager.currentSceneMetadata!.fileName)
// Create references to the base nodes that define the different layers of the scene.
loadWorldLayers()
// Add a `PlayerBot` for the player.
beamInPlayerBot()
// Gravity will be in the negative z direction; there is no x or y component.
physicsWorld.gravity = CGVector.zeroVector
// The scene will handle physics contacts itself.
physicsWorld.contactDelegate = self
// Move to the active state, starting the level timer.
stateMachine.enterState(LevelSceneActiveState.self)
// Create a background queue on which to perform the level's setup, to avoid blocking the main queue.
let backgroundQueue = dispatch_queue_create("com.example.apple-samplecode.demobots.levelscene", DISPATCH_QUEUE_SERIAL)
// Move the remainder of the level setup onto the background queue.
dispatch_async(backgroundQueue) {
self.addNode(self.graphLayer, toWorldLayer: .Debug)
self.addNode(self.debugObstacleLayer, toWorldLayer: .Debug)
// Configure the `timerNode` and add it to the camera node.
self.timerNode.zPosition = WorldLayer.AboveCharacters.rawValue
self.timerNode.fontColor = SKColor.whiteColor()
self.timerNode.fontName = GameplayConfiguration.Timer.fontName
self.scaleTimerNode()
self.camera!.addChild(self.timerNode)
// Iterate over the `TaskBot` configurations for this level, and create each `TaskBot`.
for taskBotConfiguration in self.levelConfiguration.taskBotConfigurations {
// A convenience function to find node locations given a set of node names.
func nodePointsFromNodeNames(nodeNames: [String]) -> [CGPoint] {
let charactersNode = self.childNodeWithName(WorldLayer.Characters.nodePath)!
return nodeNames.map {
charactersNode[$0].first!.position
}
}
let taskBot: TaskBot
// Find the locations of the nodes that define the `TaskBot`'s "good" and "bad" patrol paths.
let goodPathPoints = nodePointsFromNodeNames(taskBotConfiguration.goodPathNodeNames)
let badPathPoints = nodePointsFromNodeNames(taskBotConfiguration.badPathNodeNames)
// Create the appropriate type `TaskBot` (ground or flying).
switch taskBotConfiguration.locomotion {
case .Flying:
taskBot = FlyingBot(isGood: !taskBotConfiguration.startsBad, goodPathPoints: goodPathPoints, badPathPoints: badPathPoints)
case .Ground:
taskBot = GroundBot(isGood: !taskBotConfiguration.startsBad, goodPathPoints: goodPathPoints, badPathPoints: badPathPoints)
}
// Set the `TaskBot`'s initial orientation so that it is facing the correct way.
guard let orientationComponent = taskBot.componentForClass(OrientationComponent.self) else {
fatalError("A task bot must have an orientation component to be able to be added to a level")
}
orientationComponent.compassDirection = taskBotConfiguration.initialOrientation
// Set the `TaskBot`'s initial position.
let taskBotNode = taskBot.renderComponent.node
taskBotNode.position = taskBot.isGood ? goodPathPoints.first! : badPathPoints.first!
taskBot.updateAgentPositionToMatchNodePosition()
// Add the `TaskBot` to the scene and the component systems.
self.addEntity(taskBot)
// Add the `TaskBot`'s debug drawing node beneath all characters.
self.addNode(taskBot.debugNode, toWorldLayer: .Debug)
}
self.gameSession.startSession()
#if os(iOS)
// Start screen recording. See `LevelScene+ScreenRecording` for implementaion.
self.startScreenRecording()
#endif
}
}
override func didChangeSize(oldSize: CGSize) {
super.didChangeSize(oldSize)
/*
A `LevelScene` needs to update its camera constraints to match the new
aspect ratio of the window when the window size changes.
*/
setCameraConstraints()
// As the scene may now have a different height, scale and position the timer node appropriately.
scaleTimerNode()
}
// MARK: SKScene Processing
/// Called before each frame is rendered.
override func update(currentTime: NSTimeInterval) {
// Calculate the amount of time since `update` was last called.
var deltaTime = currentTime - lastUpdateTimeInterval
// If more than `maximumUpdateDeltaTime` has passed, clamp to the maximum; otherwise use `deltaTime`.
deltaTime = deltaTime > maximumUpdateDeltaTime ? maximumUpdateDeltaTime : deltaTime
// The current time will be used as the last update time in the next execution of the method.
lastUpdateTimeInterval = currentTime
// Get rid of the now-stale `LevelStateSnapshot` if it exists. It will be regenerated when next needed.
levelStateSnapshot = nil
// Don't evaluate any updates if the scene is paused.
if paused { return }
// Update the level's state machine.
stateMachine.updateWithDeltaTime(deltaTime)
/*
Update each component system.
The order of systems in `componentSystems` is important
and was determined when the `componentSystems` array was instantiated.
*/
for componentSystem in componentSystems {
componentSystem.updateWithDeltaTime(deltaTime)
}
}
override func didFinishUpdate() {
// Check if the `playerBot` has been added to this scene.
if let playerBotNode = playerBot.componentForClass(RenderComponent.self)?.node where playerBotNode.scene == self {
/*
Update the `PlayerBot`'s agent position to match its node position.
This makes sure that the agent is in a valid location in the SpriteKit
physics world at the start of its next update cycle.
*/
playerBot.updateAgentPositionToMatchNodePosition()
}
// Sort the entities in the scene by ascending y-position.
let ySortedEntities = entities.sort {
let nodeA = $0.0.componentForClass(RenderComponent.self)!.node
let nodeB = $0.1.componentForClass(RenderComponent.self)!.node
return nodeA.position.y > nodeB.position.y
}
// Set the `zPosition` of each entity so that entities with a higher y-position are rendered above those with a lower y-position.
var characterZPosition = WorldLayer.zSpacePerCharacter
for entity in ySortedEntities {
let node = entity.componentForClass(RenderComponent.self)!.node
node.zPosition = characterZPosition
// Use a large enough z-position increment to leave space for emitter effects.
characterZPosition += WorldLayer.zSpacePerCharacter
}
}
// MARK: SKPhysicsContactDelegate
func didBeginContact(contact: SKPhysicsContact) {
handleContact(contact) { (ContactNotifiableType: ContactNotifiableType, otherEntity: GKEntity) in
ContactNotifiableType.contactWithEntityDidBegin(otherEntity)
}
}
func didEndContact(contact: SKPhysicsContact) {
handleContact(contact) { (ContactNotifiableType: ContactNotifiableType, otherEntity: GKEntity) in
ContactNotifiableType.contactWithEntityDidEnd(otherEntity)
}
}
// MARK: SKPhysicsContactDelegate convenience
private func handleContact(contact: SKPhysicsContact, contactCallback: (ContactNotifiableType, GKEntity) -> Void) {
// Get the `ColliderType` for each contacted body.
let colliderTypeA = ColliderType(rawValue: contact.bodyA.categoryBitMask)
let colliderTypeB = ColliderType(rawValue: contact.bodyB.categoryBitMask)
// Determine which `ColliderType` should be notified of the contact.
let aWantsCallback = colliderTypeA.notifyOnContactWithColliderType(colliderTypeB)
let bWantsCallback = colliderTypeB.notifyOnContactWithColliderType(colliderTypeA)
// Make sure that at least one of the entities wants to handle this contact.
assert(aWantsCallback || bWantsCallback, "Unhandled physics contact - A = \(colliderTypeA), B = \(colliderTypeB)")
let entityA = (contact.bodyA.node as? EntityNode)?.entity
let entityB = (contact.bodyB.node as? EntityNode)?.entity
/*
If `entityA` is a notifiable type and `colliderTypeA` specifies that it should be notified
of contact with `colliderTypeB`, call the callback on `entityA`.
*/
if let notifiableEntity = entityA as? ContactNotifiableType, otherEntity = entityB where aWantsCallback {
contactCallback(notifiableEntity, otherEntity)
}
/*
If `entityB` is a notifiable type and `colliderTypeB` specifies that it should be notified
of contact with `colliderTypeA`, call the callback on `entityB`.
*/
if let notifiableEntity = entityB as? ContactNotifiableType, otherEntity = entityA where bWantsCallback {
contactCallback(notifiableEntity, otherEntity)
}
}
// MARK: Level Construction
func loadWorldLayers() {
for worldLayer in WorldLayer.allLayers {
// Try to find a matching node for this world layer's node name.
let foundNodes = self["world/\(worldLayer.nodeName)"]
// Make sure it was possible to find a node with this name.
precondition(!foundNodes.isEmpty, "Could not find a world layer node for \(worldLayer.nodeName)")
// Retrieve the actual node.
let layerNode = foundNodes.first!
// Make sure that the node's `zPosition` is correct relative to the other world layers.
layerNode.zPosition = worldLayer.rawValue
// Store a reference to the retrieved node.
worldLayerNodes[worldLayer] = layerNode
}
}
func addEntity(entity: GKEntity) {
entities.insert(entity)
for componentSystem in self.componentSystems {
componentSystem.addComponentWithEntity(entity)
}
// If the entity has a `RenderComponent`, add its node to the scene.
if let renderNode = entity.componentForClass(RenderComponent.self)?.node {
addNode(renderNode, toWorldLayer: .Characters)
/*
If the entity has a `ShadowComponent`, add its shadow node to the scene.
Constrain the `ShadowComponent`'s node to the `RenderComponent`'s node.
*/
if let shadowNode = entity.componentForClass(ShadowComponent.self)?.node {
addNode(shadowNode, toWorldLayer: .Shadows)
// Constrain the shadow node's position to the render node.
let xRange = SKRange(constantValue: shadowNode.position.x)
let yRange = SKRange(constantValue: shadowNode.position.y)
let constraint = SKConstraint.positionX(xRange, y: yRange)
constraint.referenceNode = renderNode
shadowNode.constraints = [constraint]
}
/*
If the entity has a `ChargeComponent` with a `ChargeBar`, add the `ChargeBar`
to the scene. Constrain the `ChargeBar` to the `RenderComponent`'s node.
*/
if let chargeBar = entity.componentForClass(ChargeComponent.self)?.chargeBar {
addNode(chargeBar, toWorldLayer: .AboveCharacters)
// Constrain the `ChargeBar`'s node position to the render node.
let xRange = SKRange(constantValue: GameplayConfiguration.PlayerBot.chargeBarOffset.x)
let yRange = SKRange(constantValue: GameplayConfiguration.PlayerBot.chargeBarOffset.y)
let constraint = SKConstraint.positionX(xRange, y: yRange)
constraint.referenceNode = renderNode
chargeBar.constraints = [constraint]
}
}
// If the entity has an `IntelligenceComponent`, enter its initial state.
if let intelligenceComponent = entity.componentForClass(IntelligenceComponent.self) {
intelligenceComponent.enterInitialState()
}
}
func addNode(node: SKNode, toWorldLayer worldLayer: WorldLayer) {
let worldLayerNode = worldLayerNodes[worldLayer]!
worldLayerNode.addChild(node)
}
// MARK: GameSessionDelegate
override func gameSessionDidUpdateControlInputSources(gameSession: GameSession) {
super.gameSessionDidUpdateControlInputSources(gameSession)
/*
Update the player's `controlInputSources` to delegate input
to the playerBot's `InputComponent`.
*/
for controlInputSource in gameSession.player.controlInputSources {
controlInputSource.delegate = playerBot.componentForClass(InputComponent.self)
}
#if os(iOS)
// When a game controller is connected, hide the thumb stick controls.
let isGameControllerConnected = (gameSession.player.secondaryControlInputSource != nil)
touchControlInputSource.hideThumbStickControls = isGameControllerConnected
#endif
}
// MARK: ControlInputSourceGameStateDelegate
override func controlInputSourceDidTogglePauseState(controlInputSource: ControlInputSourceType) {
if stateMachine.currentState is LevelSceneActiveState {
stateMachine.enterState(LevelScenePauseState.self)
}
else {
stateMachine.enterState(LevelSceneActiveState.self)
}
}
#if DEBUG
override func controlInputSourceDidToggleDebugInfo(controlInputSource: ControlInputSourceType) {
debugDrawingEnabled = !debugDrawingEnabled
if let view = view {
view.showsPhysics = debugDrawingEnabled
view.showsFPS = debugDrawingEnabled
view.showsNodeCount = debugDrawingEnabled
view.showsDrawCount = debugDrawingEnabled
}
}
override func controlInputSourceDidTriggerLevelSuccess(controlInputSource: ControlInputSourceType) {
if stateMachine.currentState is LevelSceneActiveState {
stateMachine.enterState(LevelSceneSuccessState.self)
}
}
override func controlInputSourceDidTriggerLevelFailure(controlInputSource: ControlInputSourceType) {
if stateMachine.currentState is LevelSceneActiveState {
stateMachine.enterState(LevelSceneFailState.self)
}
}
#endif
// MARK: Convenience
/// Constrains the camera to follow the PlayerBot without approaching the scene edges.
private func setCameraConstraints() {
// Don't try to set up camera constraints if we don't yet have a camera.
guard let camera = camera else { return }
// Constrain the camera to stay a constant distance of 0 points from the player node.
let zeroRange = SKRange(constantValue: 0.0)
let playerNode = playerBot.renderComponent.node
let playerBotLocationConstraint = SKConstraint.distance(zeroRange, toNode: playerNode)
/*
Also constrain the camera to avoid it moving to the very edges of the scene.
First, work out the scaled size of the scene. Its scaled height will always be
the original height of the scene, but its scaled width will vary based on
the window's current aspect ratio.
*/
let scaledSize = CGSize(width: size.width * camera.xScale, height: size.height * camera.yScale)
/*
Find the root "board" node in the scene (the container node for
the level's background tiles).
*/
let boardNode = childNodeWithName(WorldLayer.Board.nodePath)!
/*
Calculate the accumulated frame of this node.
The accumulated frame of a node is the outer bounds of all of the node's
child nodes, i.e. the total size of the entire contents of the node.
This gives us the bounding rectangle for the level's environment.
*/
let boardContentRect = boardNode.calculateAccumulatedFrame()
/*
Work out how far within this rectangle to constrain the camera.
We want to stop the camera when we get within 100pts of the edge of the screen,
unless the level is so small that this inset would be outside of the level.
*/
let xInset = min((scaledSize.width / 2) - 100.0, boardContentRect.width / 2)
let yInset = min((scaledSize.height / 2) - 100.0, boardContentRect.height / 2)
// Use these insets to create a smaller inset rectangle within which the camera must stay.
let insetContentRect = boardContentRect.rectByInsetting(dx: xInset, dy: yInset)
// Define an `SKRange` for each of the x and y axes to stay within the inset rectangle.
let xRange = SKRange(lowerLimit: insetContentRect.minX, upperLimit: insetContentRect.maxX)
let yRange = SKRange(lowerLimit: insetContentRect.minY, upperLimit: insetContentRect.maxY)
// Constrain the camera within the inset rectangle.
let levelEdgeConstraint = SKConstraint.positionX(xRange, y: yRange)
levelEdgeConstraint.referenceNode = boardNode
/*
Add both constraints to the camera. The scene edge constraint is added
second, so that it takes precedence over following the `PlayerBot`.
The result is that the camera will follow the player, unless this would mean
moving too close to the edge of the level.
*/
camera.constraints = [playerBotLocationConstraint, levelEdgeConstraint]
}
/// Scales and positions the timer node to fit the scene's current height.
private func scaleTimerNode() {
// Update the font size of the timer node based on the height of the scene.
timerNode.fontSize = size.height * GameplayConfiguration.Timer.fontSize
// Make sure the timer node is positioned at the top of the scene.
timerNode.position.y = (size.height / 2.0) - timerNode.frame.size.height
// Add padding between the top of scene and the top of the timer node.
timerNode.position.y -= timerNode.fontSize * GameplayConfiguration.Timer.paddingSize
}
private func beamInPlayerBot() {
// Find the location of the player's initial position.
let charactersNode = childNodeWithName(WorldLayer.Characters.nodePath)!
let transporterCoordinate = charactersNode.childNodeWithName("transporter_coordinate")!
// Set the initial orientation.
guard let orientationComponent = playerBot.componentForClass(OrientationComponent.self) else {
fatalError("A player bot must have an orientation component to be able to be added to a level")
}
orientationComponent.compassDirection = levelConfiguration.initialPlayerBotOrientation
// Set up the `PlayerBot` position in the scene.
let playerNode = playerBot.renderComponent.node
playerNode.position = transporterCoordinate.position
playerBot.updateAgentPositionToMatchNodePosition()
// Constrain the camera to the `PlayerBot` position and the level edges.
setCameraConstraints()
// Add the `PlayerBot` to the scene and component systems.
addEntity(playerBot)
}
}
| 45.082437 | 172 | 0.653522 |
4bc491e6a69bd5829a4437b2ba3d3f107cd91b04 | 2,913 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for OpsWorksCM
public struct OpsWorksCMErrorType: AWSErrorType {
enum Code: String {
case invalidNextTokenException = "InvalidNextTokenException"
case invalidStateException = "InvalidStateException"
case limitExceededException = "LimitExceededException"
case resourceAlreadyExistsException = "ResourceAlreadyExistsException"
case resourceNotFoundException = "ResourceNotFoundException"
case validationException = "ValidationException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize OpsWorksCM
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// This occurs when the provided nextToken is not valid.
public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) }
/// The resource is in a state that does not allow you to perform a specified action.
public static var invalidStateException: Self { .init(.invalidStateException) }
/// The limit of servers or backups has been reached.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// The requested resource cannot be created because it already exists.
public static var resourceAlreadyExistsException: Self { .init(.resourceAlreadyExistsException) }
/// The requested resource does not exist, or access was denied.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// One or more of the provided request parameters are not valid.
public static var validationException: Self { .init(.validationException) }
}
extension OpsWorksCMErrorType: Equatable {
public static func == (lhs: OpsWorksCMErrorType, rhs: OpsWorksCMErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension OpsWorksCMErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 39.90411 | 117 | 0.682458 |
1cb5a5fd3f86b5f290483c04e2d935811d4db78c | 847 | //:## Core ML
import PlaygroundSupport
// Enable support for asynchronous completion handlers
PlaygroundPage.current.needsIndefiniteExecution = true
import VisualRecognitionV3
let visualRecognition = setupVisualRecognitionV3()
var classifierID = WatsonCredentials.VisualRecognitionV3ClassifierID
//:### Retrieve a Core ML model of a classifier
visualRecognition.getCoreMLModel(classifierID: classifierID) {
response, error in
guard let coreMLData = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
let modelFile = URL(fileURLWithPath: NSTemporaryDirectory() + "\(classifierID).mlmodel")
do {
try coreMLData.write(to: modelFile)
print("ML model saved to \(modelFile.lastPathComponent)")
} catch {
print("Error writing: \(error)")
}
}
| 27.322581 | 92 | 0.726092 |
fefa3c62b57df7c67fc5d8b529afb72bdfa18459 | 9,633 | import Foundation
import LLVM_C
import LLVM
import Parse
import AST
import protocol MIR.Statement
import SemanticAnalysis
import IRGen
#if os(Linux)
typealias Process = Task
#endif
open class Driver {
public var outputStream: TextOutputStream
public let typeChecker: TypeChecker
public let irGenerator: IRGenerator
public var emitInLLVMFormat: Bool
private let targetMachine: LLVM.TargetMachine
public var module: LLVM.Module!
public init(outputStream: TextOutputStream = Stdout(), allowRedefinitions: Bool = false,
using irGenerator: IRGenerator = IRGenerator()) {
LLVMInitializeNativeTarget()
LLVMInitializeNativeAsmPrinter()
LLVMInitializeNativeAsmParser()
self.outputStream = outputStream
self.typeChecker = TypeChecker(allowRedefinitions: allowRedefinitions)
self.irGenerator = irGenerator
self.emitInLLVMFormat = false
let target = try! LLVM.Target(fromTriple: LLVM.defaultTargetTriple)
targetMachine = LLVM.TargetMachine(target: target, targetTriple: LLVM.defaultTargetTriple,
cpu: "generic", features: "", optLevel: LLVMCodeGenLevelNone)
}
public func compileAndExecute(inputFile: String, stdoutPipe: Pipe? = nil) throws -> Int32? {
return try compileAndExecute(inputFiles: [inputFile], stdoutPipe: stdoutPipe)
}
/// Returns the exit status of the executed program on successful completion, or `nil` if
/// the compiled program was not executed, e.g. because the compilation didn't succeed.
public func compileAndExecute(inputFiles: [String], stdoutPipe: Pipe? = nil) throws -> Int32? {
if !compile(inputFiles: inputFiles) { return nil }
let moduleName = determineModuleName(for: inputFiles)
let linkProcess = Process()
linkProcess.launchPath = "/usr/bin/env"
linkProcess.arguments = ["cc", moduleName + ".o", "-o", moduleName + ".out"]
linkProcess.launch()
linkProcess.waitUntilExit()
if linkProcess.terminationStatus != 0 { return nil }
try FileManager.default.removeItem(atPath: moduleName + ".o")
let executeProcess = Process()
executeProcess.launchPath = moduleName + ".out"
if stdoutPipe != nil { executeProcess.standardOutput = stdoutPipe }
executeProcess.launch()
executeProcess.waitUntilExit()
try FileManager.default.removeItem(atPath: moduleName + ".out")
return executeProcess.terminationStatus
}
private func determineModuleName(for inputFiles: [String]) -> String {
if inputFiles.count == 1 { return inputFiles[0] }
let commonPathPrefix = inputFiles.reduce(inputFiles[0]) { $0.commonPrefix(with: $1) }
let parentDirectoryName = commonPathPrefix.components(separatedBy: "/").dropLast().last!
return parentDirectoryName
}
private func determineCompilationOrder(of inputFiles: [String]) -> [String] {
guard let mainFileIndex = inputFiles.index(where: {
$0.components(separatedBy: "/").last!.caseInsensitiveCompare("main.gaia") == .orderedSame
}) else {
return inputFiles
}
var orderedInputFiles = inputFiles
orderedInputFiles.append(orderedInputFiles.remove(at: mainFileIndex)) // Move main.gaia last.
return orderedInputFiles
}
/// Returns whether the compilation completed successfully.
public func compile(inputFiles: [String]) -> Bool {
if inputFiles.isEmpty {
outputStream.write("error: no input files\n")
exit(1)
}
return compile(files: determineCompilationOrder(of: inputFiles))
}
/// Returns whether the compilation completed successfully.
private func compile(files inputFileNames: [String]) -> Bool {
initModule(moduleName: determineModuleName(for: inputFileNames))
initFunctionPassManager(for: module)
compileCoreLibrary()
for inputFileName in inputFileNames {
if !compileFile(inputFileName) { return false }
}
emitModule(as: LLVMObjectFile, toPath: determineModuleName(for: inputFileNames))
return true
}
/// Returns whether the compilation completed successfully.
fileprivate func compileFile(_ inputFileName: String) -> Bool {
guard let inputFile = try? SourceFile(atPath: inputFileName) else {
outputStream.write("error reading input file \(inputFileName), aborting\n")
return false
}
do {
let parser = Parser(readingFrom: inputFile)
while try handleNextToken(parser: parser) { }
return true
} catch {
emitError(error, file: inputFileName)
return false
}
}
/// Returns whether there are still tokens to be handled.
public func handleNextToken(parser: Parser) throws -> Bool {
switch try parser.nextToken() {
case .eof: return false
case .newline: break
case .keyword(.function): try handleFunctionDefinition(parser: parser)
case .keyword(.extern): try handleExternFunctionDeclaration(parser: parser)
default: try handleToplevelExpression(parser: parser)
}
return true
}
private func emitError(_ error: Error, file: String) {
let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
guard #available(macOS 10.11, *) else {
fatalError("This program requires macOS 10.11 or greater.")
}
let relativeFileURL = URL(fileURLWithPath: file, relativeTo: currentDirectoryURL)
if let sourceCodeError = error as? SourceCodeError {
if let location = sourceCodeError.location, let fileContents = try? String(contentsOfFile: file) {
outputStream.write("\(relativeFileURL.relativePath):\(location): error: \(sourceCodeError)\n")
let line = fileContents.components(separatedBy: .newlines)[location.line - 1]
outputStream.write("\(line)\n\(String(repeating: " ", count: location.column - 1))^\n")
} else {
outputStream.write("\(relativeFileURL.relativePath): error: \(sourceCodeError)\n")
}
} else {
outputStream.write("\(error)")
}
}
private func emitModule(as codeGenFileType: LLVMCodeGenFileType, toPath outputFilePath: String) {
irGenerator.appendImplicitZeroReturnToMainFunction()
if emitInLLVMFormat {
if codeGenFileType == LLVMObjectFile {
if (outputFilePath + ".bc").withCString({ LLVMWriteBitcodeToFile(irGenerator.module.ref, $0) }) != 0 {
fatalError("LLVMWriteBitcodeToFile failed")
}
}
if codeGenFileType == LLVMAssemblyFile {
fatalError("LLVM IR emit to file not implemented")
}
} else {
try! targetMachine.emitToFile(module, atPath: outputFilePath + ".o", fileType: codeGenFileType)
}
}
public func handleFunctionDefinition(parser: Parser) throws {
let function = try parser.parseFunctionDefinition()
_ = try function.acceptVisitor(typeChecker)
}
public func handleExternFunctionDeclaration(parser: Parser) throws {
let prototype = try parser.parseExternFunctionDeclaration()
_ = try prototype.acceptVisitor(typeChecker)
}
open func handleToplevelExpression(parser: Parser) throws {
// Add top-level statements into main function.
let statement = try parser.parseStatement()
irGenerator.appendToMainFunction(try statement.acceptVisitor(typeChecker) as! Statement)
}
public func initModule(moduleName: String) {
module = LLVM.Module(name: moduleName)
module.dataLayout = targetMachine.dataLayout.string
module.target = LLVM.defaultTargetTriple
irGenerator.module = module
}
public func initFunctionPassManager(for module: LLVM.Module) {
let functionPassManager = LLVM.FunctionPassManager(for: module)
// Promote allocas to registers.
functionPassManager.addPromoteMemoryToRegisterPass()
// Do simple "peephole" and bit-twiddling optimizations.
functionPassManager.addInstructionCombiningPass()
// Reassociate expressions.
functionPassManager.addReassociatePass()
// Eliminate common subexpressions.
functionPassManager.addGVNPass()
// Simplify the control flow graph (deleting unreachable blocks, etc.).
functionPassManager.addCFGSimplificationPass()
functionPassManager.initialize()
irGenerator.functionPassManager = functionPassManager
}
public func compileCoreLibrary() {
let onError = { print("Core library compilation failed.") }
guard let coreLibraryFiles = try? findCoreLibraryFiles() else { return onError() }
for file in coreLibraryFiles {
if !compileFile(file) { return onError() }
}
}
}
private func findCoreLibraryFiles() throws -> [String] {
guard let gaiaHome = ProcessInfo.processInfo.environment["GAIA_HOME"] else {
fatalError("GAIA_HOME not defined")
}
let coreLibPath = gaiaHome + "/Core/"
return try FileManager.default.contentsOfDirectory(atPath: coreLibPath).map { coreLibPath + $0 }
}
public final class Stdout: TextOutputStream {
public init() { }
public func write(_ string: String) {
print(string, terminator: "")
}
}
| 41.166667 | 118 | 0.666044 |
56df89701c98f049b367cae9ca3a038e4522729a | 221 | //
// ChartsApp.swift
// Charts
//
// Created by Jannik Arndt on 29.08.21.
//
import SwiftUI
@main
struct ChartsApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.277778 | 40 | 0.547511 |
67e92efd1b697a0f421a8733cf7559b02e5bc6c9 | 5,819 | // web3swift
//
// Created by Alex Vlasov.
// Copyright © 2018 Alex Vlasov. All rights reserved.
//
import Foundation
public extension Data {
init<T>(fromArray values: [T]) {
self = values.withUnsafeBytes { Data($0) }
}
func toArray<T>(type: T.Type) -> [T] where T: ExpressibleByIntegerLiteral {
var array = Array<T>(repeating: 0, count: self.count/MemoryLayout<T>.stride)
_ = array.withUnsafeMutableBytes { copyBytes(to: $0) }
return array
}
// func toArray<T>(type: T.Type) throws -> [T] {
// return try self.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
// if let bodyAddress = body.baseAddress, body.count > 0 {
// let pointer = bodyAddress.assumingMemoryBound(to: T.self)
// return [T](UnsafeBufferPointer(start: pointer, count: self.count/MemoryLayout<T>.stride))
// } else {
// throw Web3Error.dataError
// }
// }
// }
func constantTimeComparisonTo(_ other:Data?) -> Bool {
guard let rhs = other else {return false}
guard self.count == rhs.count else {return false}
var difference = UInt8(0x00)
for i in 0..<self.count { // compare full length
difference |= self[i] ^ rhs[i] //constant time
}
return difference == UInt8(0x00)
}
static func zero(_ data: inout Data) {
let count = data.count
data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in
body.baseAddress?.assumingMemoryBound(to: UInt8.self).initialize(repeating: 0, count: count)
}
}
// static func zero(_ data: inout Data) {
// let count = data.count
// data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in
// body.baseAddress?.assumingMemoryBound(to: UInt8.self).initialize(repeating: 0, count: count)
// }
// }
static func randomBytes(length: Int) -> Data? {
for _ in 0...1024 {
var data = Data(repeating: 0, count: length)
let result = data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) -> Int32? in
if let bodyAddress = body.baseAddress, body.count > 0 {
let pointer = bodyAddress.assumingMemoryBound(to: UInt8.self)
return SecRandomCopyBytes(kSecRandomDefault, 32, pointer)
} else {
return nil
}
}
if let notNilResult = result, notNilResult == errSecSuccess {
return data
}
}
return nil
}
// static func randomBytes(length: Int) -> Data? {
// for _ in 0...1024 {
// var data = Data(repeating: 0, count: length)
// let result = data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) -> Int32? in
// if let bodyAddress = body.baseAddress, body.count > 0 {
// let pointer = bodyAddress.assumingMemoryBound(to: UInt8.self)
// return SecRandomCopyBytes(kSecRandomDefault, 32, pointer)
// } else {
// return nil
// }
// }
// if let notNilResult = result, notNilResult == errSecSuccess {
// return data
// }
// }
// return nil
// }
static func fromHex(_ hex: String) -> Data? {
let string = hex.lowercased().stripHexPrefix()
let array = Array<UInt8>(hex: string)
if (array.count == 0) {
if (hex == "0x" || hex == "") {
return Data()
} else {
return nil
}
}
return Data(array)
}
func bitsInRange(_ startingBit:Int, _ length:Int) -> UInt64? { //return max of 8 bytes for simplicity, non-public
if startingBit + length / 8 > self.count, length > 64, startingBit > 0, length >= 1 {return nil}
let bytes = self[(startingBit/8) ..< (startingBit+length+7)/8]
let padding = Data(repeating: 0, count: 8 - bytes.count)
let padded = bytes + padding
guard padded.count == 8 else {return nil}
let pointee = padded.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
body.baseAddress?.assumingMemoryBound(to: UInt64.self).pointee
}
guard let ptee = pointee else {return nil}
var uintRepresentation = UInt64(bigEndian: ptee)
uintRepresentation = uintRepresentation << (startingBit % 8)
uintRepresentation = uintRepresentation >> UInt64(64 - length)
return uintRepresentation
}
// func bitsInRange(_ startingBit:Int, _ length:Int) -> UInt64? { //return max of 8 bytes for simplicity, non-public
// if startingBit + length / 8 > self.count, length > 64, startingBit > 0, length >= 1 {return nil}
// let bytes = self[(startingBit/8) ..< (startingBit+length+7)/8]
// let padding = Data(repeating: 0, count: 8 - bytes.count)
// let padded = bytes + padding
// guard padded.count == 8 else {return nil}
// let pointee = padded.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
// body.baseAddress?.assumingMemoryBound(to: UInt64.self).pointee
// }
// guard let ptee = pointee else {return nil}
// var uintRepresentation = UInt64(bigEndian: ptee)
// uintRepresentation = uintRepresentation << (startingBit % 8)
// uintRepresentation = uintRepresentation >> UInt64(64 - length)
// return uintRepresentation
// }
}
| 42.474453 | 123 | 0.559031 |
144abc7d46551b980fe0ca5b4c7e21d0b589b404 | 689 | //
// Refeicao.swift
// eggplant-brownie
//
// Created by Alura on 16/03/19.
// Copyright © 2019 Alura. All rights reserved.
//
import UIKit
class Refeicao: NSObject {
// MARK: - Atributos
let nome: String
let felicidade: Int
var itens: Array<Item> = []
// MARK: - Init
init(nome: String, felicidade: Int, itens: [Item] = []) {
self.nome = nome
self.felicidade = felicidade
self.itens = itens
}
// MARK: - Metodos
func totalDeCalorias() -> Double {
var total = 0.0
for item in itens {
total += item.calorias
}
return total
}
}
| 17.666667 | 61 | 0.519594 |
e9cabd7b3661082fb5ec116e256d415a079069f0 | 345 |
import UIKit;
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
*
* @created 2020-01-22
* @description
* @augments
* @example
*
*/
// Double represents a 64-bit floating-point number.
// Float represents a 32-bit floating-point number.
let pi: Double = 3.1415926535897932384626433
// 3.14 15926 5358 9793
let π = 3.141
| 14.375 | 52 | 0.675362 |
5b2dc82f92482ac661677ab3883dcbfd35995bbf | 1,152 | //
// HandlerWithTimer.swift
// Atem
//
// Created by Damiaan on 20/05/18.
//
import NIO
let sendInterval = TimeAmount.milliseconds(20)
class HandlerWithTimer: ChannelInboundHandler {
typealias InboundIn = AddressedEnvelope<ByteBuffer>
typealias OutboundOut = AddressedEnvelope<ByteBuffer>
var nextKeepAliveTask: Scheduled<Void>?
func channelActive(context: ChannelHandlerContext) {
startLoop(in: context)
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {}
func channelInactive(context: ChannelHandlerContext) {
nextKeepAliveTask?.cancel()
}
final func startLoop(in context: ChannelHandlerContext) {
nextKeepAliveTask = context.eventLoop.scheduleTask(in: sendInterval) {
self.executeTimerTask(context: context)
self.startLoop(in: context)
}
}
func executeTimerTask(context: ChannelHandlerContext) {}
final func encode(bytes: [UInt8], for client: SocketAddress, in context: ChannelHandlerContext) -> NIOAny {
var buffer = context.channel.allocator.buffer(capacity: bytes.count)
buffer.writeBytes(bytes)
return wrapOutboundOut(AddressedEnvelope(remoteAddress: client, data: buffer))
}
}
| 26.790698 | 108 | 0.770833 |
8911a2c4dc7e1b1a15f2b0aba4dbb1aa2a7ba3b4 | 7,831 | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
/// Routes for the file_requests namespace
open class FileRequestsRoutes {
public let client: DropboxTransportClient
init(client: DropboxTransportClient) {
self.client = client
}
/// Returns the total number of file requests owned by this user. Includes both open and closed file requests.
///
///
/// - returns: Through the response callback, the caller will receive a `FileRequests.CountFileRequestsResult`
/// object on success or a `FileRequests.CountFileRequestsError` object on failure.
@discardableResult open func count() -> RpcRequest<FileRequests.CountFileRequestsResultSerializer, FileRequests.CountFileRequestsErrorSerializer> {
let route = FileRequests.count
return client.request(route)
}
/// Creates a file request for this user.
///
/// - parameter title: The title of the file request. Must not be empty.
/// - parameter destination: The path of the folder in the Dropbox where uploaded files will be sent. For apps with
/// the app folder permission, this will be relative to the app folder.
/// - parameter deadline: The deadline for the file request. Deadlines can only be set by Professional and Business
/// accounts.
/// - parameter open: Whether or not the file request should be open. If the file request is closed, it will not
/// accept any file submissions, but it can be opened later.
///
/// - returns: Through the response callback, the caller will receive a `FileRequests.FileRequest` object on
/// success or a `FileRequests.CreateFileRequestError` object on failure.
@discardableResult open func create(title: String, destination: String, deadline: FileRequests.FileRequestDeadline? = nil, open: Bool = true) -> RpcRequest<FileRequests.FileRequestSerializer, FileRequests.CreateFileRequestErrorSerializer> {
let route = FileRequests.create
let serverArgs = FileRequests.CreateFileRequestArgs(title: title, destination: destination, deadline: deadline, open: open)
return client.request(route, serverArgs: serverArgs)
}
/// Delete a batch of closed file requests.
///
/// - parameter ids: List IDs of the file requests to delete.
///
/// - returns: Through the response callback, the caller will receive a `FileRequests.DeleteFileRequestsResult`
/// object on success or a `FileRequests.DeleteFileRequestError` object on failure.
@discardableResult open func delete(ids: Array<String>) -> RpcRequest<FileRequests.DeleteFileRequestsResultSerializer, FileRequests.DeleteFileRequestErrorSerializer> {
let route = FileRequests.delete
let serverArgs = FileRequests.DeleteFileRequestArgs(ids: ids)
return client.request(route, serverArgs: serverArgs)
}
/// Delete all closed file requests owned by this user.
///
///
/// - returns: Through the response callback, the caller will receive a
/// `FileRequests.DeleteAllClosedFileRequestsResult` object on success or a
/// `FileRequests.DeleteAllClosedFileRequestsError` object on failure.
@discardableResult open func deleteAllClosed() -> RpcRequest<FileRequests.DeleteAllClosedFileRequestsResultSerializer, FileRequests.DeleteAllClosedFileRequestsErrorSerializer> {
let route = FileRequests.deleteAllClosed
return client.request(route)
}
/// Returns the specified file request.
///
/// - parameter id: The ID of the file request to retrieve.
///
/// - returns: Through the response callback, the caller will receive a `FileRequests.FileRequest` object on
/// success or a `FileRequests.GetFileRequestError` object on failure.
@discardableResult open func get(id: String) -> RpcRequest<FileRequests.FileRequestSerializer, FileRequests.GetFileRequestErrorSerializer> {
let route = FileRequests.get
let serverArgs = FileRequests.GetFileRequestArgs(id: id)
return client.request(route, serverArgs: serverArgs)
}
/// Returns a list of file requests owned by this user. For apps with the app folder permission, this will only
/// return file requests with destinations in the app folder.
///
/// - parameter limit: The maximum number of file requests that should be returned per request.
///
/// - returns: Through the response callback, the caller will receive a `FileRequests.ListFileRequestsV2Result`
/// object on success or a `FileRequests.ListFileRequestsError` object on failure.
@discardableResult open func listV2(limit: UInt64 = 1000) -> RpcRequest<FileRequests.ListFileRequestsV2ResultSerializer, FileRequests.ListFileRequestsErrorSerializer> {
let route = FileRequests.listV2
let serverArgs = FileRequests.ListFileRequestsArg(limit: limit)
return client.request(route, serverArgs: serverArgs)
}
/// Returns a list of file requests owned by this user. For apps with the app folder permission, this will only
/// return file requests with destinations in the app folder.
///
///
/// - returns: Through the response callback, the caller will receive a `FileRequests.ListFileRequestsResult`
/// object on success or a `FileRequests.ListFileRequestsError` object on failure.
@discardableResult open func list_() -> RpcRequest<FileRequests.ListFileRequestsResultSerializer, FileRequests.ListFileRequestsErrorSerializer> {
let route = FileRequests.list_
return client.request(route)
}
/// Once a cursor has been retrieved from listV2, use this to paginate through all file requests. The cursor must
/// come from a previous call to listV2 or listContinue.
///
/// - parameter cursor: The cursor returned by the previous API call specified in the endpoint description.
///
/// - returns: Through the response callback, the caller will receive a `FileRequests.ListFileRequestsV2Result`
/// object on success or a `FileRequests.ListFileRequestsContinueError` object on failure.
@discardableResult open func listContinue(cursor: String) -> RpcRequest<FileRequests.ListFileRequestsV2ResultSerializer, FileRequests.ListFileRequestsContinueErrorSerializer> {
let route = FileRequests.listContinue
let serverArgs = FileRequests.ListFileRequestsContinueArg(cursor: cursor)
return client.request(route, serverArgs: serverArgs)
}
/// Update a file request.
///
/// - parameter id: The ID of the file request to update.
/// - parameter title: The new title of the file request. Must not be empty.
/// - parameter destination: The new path of the folder in the Dropbox where uploaded files will be sent. For apps
/// with the app folder permission, this will be relative to the app folder.
/// - parameter deadline: The new deadline for the file request. Deadlines can only be set by Professional and
/// Business accounts.
/// - parameter open: Whether to set this file request as open or closed.
///
/// - returns: Through the response callback, the caller will receive a `FileRequests.FileRequest` object on
/// success or a `FileRequests.UpdateFileRequestError` object on failure.
@discardableResult open func update(id: String, title: String? = nil, destination: String? = nil, deadline: FileRequests.UpdateFileRequestDeadline = .noUpdate, open: Bool? = nil) -> RpcRequest<FileRequests.FileRequestSerializer, FileRequests.UpdateFileRequestErrorSerializer> {
let route = FileRequests.update
let serverArgs = FileRequests.UpdateFileRequestArgs(id: id, title: title, destination: destination, deadline: deadline, open: open)
return client.request(route, serverArgs: serverArgs)
}
}
| 58.879699 | 281 | 0.730941 |
e44dd2c9dea650bbcb6ee7086b8ffb476e4c29f9 | 385 | //
// RepositoryCell.swift
// Top Repos
//
// Created by Ben Scheirman on 10/11/17.
// Copyright © 2017 NSScreencast. All rights reserved.
//
import UIKit
class RepositoryCell : UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var starsLabel: UILabel!
@IBOutlet weak var forksLabel: UILabel!
}
| 22.647059 | 55 | 0.716883 |
5601460acadffb5e9c391bfd9ec1a33334235719 | 2,389 | //
// GKFile.swift
// Pods
//
// Created by Jelle Vandebeeck on 15/03/16.
//
//
import Foundation
import AEXML
/**
The root element in the XML file.
*/
public class File {
/// You must include the name or URL of the software that created your GPX document. This allows others to inform the creator of a GPX instance document that fails to validate.
public var creator: String?
/// The name of the GPX file.
public var name: String?
/// A description of the contents of the GPX file.
public var description: String?
/// The person or organization who created the GPX file.
public var author: Person?
/// Copyright and license information governing use of the file.
public var copyrightNotice: CopyrightNotice?
/// URLs associated with the location described in the file.
public var link: Link?
/// The creation date of the file.
public var time: NSDate?
/// Keywords associated with the file. Search engines or databases can use this information to classify the data.
public var keywords: [String]?
/// Minimum and maximum coordinates which describe the extent of the coordinates in the file.
public var bounds: Bounds?
/// A list of waypoints.
public var waypoints: [Point]?
/// A list of routes.
public var routes: [Route]?
/// A list of tracks.
public var tracks: [Track]?
}
extension File {
convenience init?(fromElement element: AEXMLElement) {
// When the element is an error, don't create the instance.
if element.attributes["version"] != "1.1" {
return nil
}
self.init()
// Fetch the creator from the root element.
creator = element.attributes["creator"]
// Fetch the metadata from the metadata element.
let metadata = element["metadata"]
name <~ metadata["name"]
description <~ metadata["desc"]
author <~ metadata["author"]
copyrightNotice <~ metadata["copyright"]
link <~ metadata["link"]
time <~ metadata["time"]
keywords <~ metadata["keywords"]
bounds <~ metadata["bounds"]
waypoints <~ element["wpt"].all
routes <~ element["rte"].all
tracks <~ element["trk"].all
}
}
| 29.134146 | 180 | 0.60946 |
ccbc6ee2732963625869cad7eaed8b2882264b5c | 3,039 | //
// DBService+AppUser.swift
// Hype Post App
//
// Created by C4Q on 2/5/18.
// Copyright © 2018 C4Q. All rights reserved.
//
import Foundation
import FirebaseDatabase
extension DBService {
public func addAppUser(_ appUser: AppUser) {
let ref = usersRef.child(appUser.uID)
ref.setValue(["email": appUser.email,
"uID": appUser.uID,
"userName": appUser.userName,
"firstName": appUser.firstName,
"lastName": appUser.lastName as Any,
"flags": appUser.flags,
"bio": appUser.bio ?? ""])
}
func getAppUser(with uID: String, completion: @escaping (_ user: AppUser) -> Void) {
let userRef = usersRef.child(uID)
userRef.observeSingleEvent(of: .value) { (snapshot) in
guard let email = snapshot.childSnapshot(forPath: "email").value as? String else {return}
guard let userName = snapshot.childSnapshot(forPath: "userName").value as? String else {return}
guard let firstName = snapshot.childSnapshot(forPath: "firstName").value as? String else {return}
guard let lastName = snapshot.childSnapshot(forPath: "lastName").value as? String else {return}
guard let flags = snapshot.childSnapshot(forPath: "flags").value as? UInt else {return}
let imageURL = snapshot.childSnapshot(forPath: "imageURL").value as? String
let bio = snapshot.childSnapshot(forPath: "bio").value as? String
let currentAppUser = AppUser(email: email, userName: userName, uID: uID, firstName: firstName, lastName: lastName, imageURL: imageURL, bio: bio, flags: flags)
completion(currentAppUser)
}
}
public func addImageToAppUser(with url: String, uID: String) {
addImage(url: url, ref: usersRef, id: uID)
}
public func flagUser(flaggedUID: String, userFlaggedById uID: String) {
let ref = usersRef.child(flaggedUID)
ref.runTransactionBlock { (mutableData) -> TransactionResult in
if var userObject = mutableData.value as? [String: Any] {
var flaggedDict = userObject["flaggedBy"] as? [String:Any] ?? ["no":"data"]
var flags = userObject["flags"] as? UInt ?? 0
if flaggedDict[uID] != nil {
//self.delegate?.didFlagUser?(self)
print("user flagged already")
} else {
flaggedDict[uID] = true
flags += 1
self.delegate?.didFlagUser?(self)
}
userObject["flaggedBy"] = flaggedDict
userObject["flags"] = flags
mutableData.value = userObject
return TransactionResult.success(withValue: mutableData)
}
return TransactionResult.success(withValue: mutableData)
}
}
}
| 41.067568 | 170 | 0.571899 |
696607f439f0f14bbb245860722af60f4138df75 | 3,716 | protocol P1 {
func foo()
func foo1()
}
class C1 : P1 {
func foo1() {}
}
class C2 : P1 {
func foo() {}
}
class C3 : P1 {}
protocol P2 {
associatedtype T1
associatedtype T2
func foo1()
}
class C4 : P2 {}
class C5 : P2 {
typealias T1 = Int
func foo1() {}
}
class C6 : P2 {
typealias T1 = Int
typealias T2 = Int
}
class C7 : P2 {
typealias T2 = Int
func foo1() {}
}
class C8 : P2 {
typealias T1 = Int
typealias T2 = Int
func foo1() {}
}
class C9 {}
extension C9 : P1 {}
extension C9 : P2 {}
class C10 {}
extension C10 : P1 {
func foo() {}
func foo1() {}
}
extension C10 : P2 {
typealias T1 = Int
typealias T2 = Int
func foo1() {}
}
class C11 {}
extension C11 : P1 {
func foo() {}
}
extension C11 : P2 {
typealias T1 = Int
typealias T2 = Int
}
class C12 {}
extension C12 : P1 {
func foo1() {}
}
extension C12 : P2 {
typealias T1 = Int
func foo1() {}
}
class C13 {}
extension C13 : P1 {
func foo() {}
func foo1() {}
}
extension C13 : P2 {
typealias T1 = Int
func foo1() {}
}
class C14 {}
extension C14 : P1 {
func foo() {}
}
extension C14 : P2 {
typealias T1 = Int
typealias T2 = Int
func foo1() {}
}
protocol P3 {
func foo3()
func foo4()
}
extension C14: P3 {
func foo3()
}
// RUN: rm -rf %t.result && mkdir -p %t.result
// RUN: %refactor -fill-stub -source-filename %s -pos=5:8 >> %t.result/P5-8.swift
// RUN: diff -u %S/Outputs/basic/P5-8.swift.expected %t.result/P5-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=8:8 >> %t.result/P8-8.swift
// RUN: diff -u %S/Outputs/basic/P8-8.swift.expected %t.result/P8-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=11:8 >> %t.result/P11-8.swift
// RUN: diff -u %S/Outputs/basic/P11-8.swift.expected %t.result/P11-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=18:8 >> %t.result/P18-8.swift
// RUN: diff -u %S/Outputs/basic/P18-8.swift.expected %t.result/P18-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=19:8 >> %t.result/P19-8.swift
// RUN: diff -u %S/Outputs/basic/P19-8.swift.expected %t.result/P19-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=23:8 >> %t.result/P23-8.swift
// RUN: diff -u %S/Outputs/basic/P23-8.swift.expected %t.result/P23-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=27:8 >> %t.result/P27-8.swift
// RUN: diff -u %S/Outputs/basic/P27-8.swift.expected %t.result/P27-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=38:12 >> %t.result/P38-12.swift
// RUN: diff -u %S/Outputs/basic/P38-12.swift.expected %t.result/P38-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=39:12 >> %t.result/P39-12.swift
// RUN: diff -u %S/Outputs/basic/P39-12.swift.expected %t.result/P39-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=51:12 >> %t.result/P51-12.swift
// RUN: diff -u %S/Outputs/basic/P51-12.swift.expected %t.result/P51-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=54:12 >> %t.result/P54-12.swift
// RUN: diff -u %S/Outputs/basic/P54-12.swift.expected %t.result/P54-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=59:12 >> %t.result/P59-12.swift
// RUN: diff -u %S/Outputs/basic/P59-12.swift.expected %t.result/P59-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=62:12 >> %t.result/P62-12.swift
// RUN: diff -u %S/Outputs/basic/P62-12.swift.expected %t.result/P62-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=71:12 >> %t.result/P71-12.swift
// RUN: diff -u %S/Outputs/basic/P71-12.swift.expected %t.result/P71-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=88:12 >> %t.result/P88-12.swift
// RUN: diff -u %S/Outputs/basic/P88-12.swift.expected %t.result/P88-12.swift
| 30.211382 | 85 | 0.653391 |
5bf6050015e7130edbfe54e8a40692b6cdd83601 | 6,422 | import XCTest
import SwiftAST
import KnownType
import GlobalsProviders
import TypeSystem
let cInt = SwiftType.typeName("CInt")
let cFloat = SwiftType.typeName("CFloat")
let cDouble = SwiftType.typeName("CDouble")
class BaseGlobalsProviderTestCase: XCTestCase {
var sut: GlobalsProvider!
var globals: DefinitionsSource!
var types: KnownTypeProvider!
var typealiases: TypealiasProvider!
override func setUp() {
super.setUp()
types = nil
typealiases = nil
}
func assertDefined(typealiasFrom typealiasName: String,
to type: SwiftType,
file: StaticString = #filePath, line: UInt = #line) {
guard let actual = typealiases.unalias(typealiasName) else {
XCTFail("Expected to find typealias with name \(typealiasName)",
file: file, line: line)
return
}
if actual != type {
XCTFail("Expected typealias to be of type \(type), but found \(actual) instead.",
file: file, line: line)
}
}
func assertDefined(variable: String,
type: SwiftType,
file: StaticString = #filePath, line: UInt = #line) {
guard let definition = globals.firstDefinition(named: variable) else {
XCTFail("Expected to find definition \(variable)",
file: file, line: line)
return
}
guard case let .variable(_, storage) = definition.kind else {
XCTFail("Expected to find a variable defined, but found \(definition.kind) instead",
file: file, line: line)
return
}
if storage.type != type {
XCTFail("Expected variable to be of type \(type), but found \(storage.type) instead.",
file: file, line: line)
}
}
func assertDefined(function: String,
paramTypes: [SwiftType],
returnType: SwiftType,
file: StaticString = #filePath, line: UInt = #line) {
let asSignature =
FunctionSignature(
name: function,
parameters: paramTypes.map { ParameterSignature(label: nil, name: "v", type: $0) },
returnType: returnType)
assertDefined(functionSignature: TypeFormatter.asString(signature: asSignature, includeName: true),
file: file,
line: line)
}
func assertDefined(functionSignature: String,
file: StaticString = #filePath, line: UInt = #line) {
let asSignature = try! FunctionSignature(signatureString: functionSignature)
let signatures: [FunctionSignature] =
globals
.functionDefinitions(matching: asSignature.asIdentifier)
.compactMap {
guard case let .function(signature) = $0.kind else {
return nil
}
return signature
}
guard !signatures.isEmpty else {
XCTFail("Expected to find definition for \(functionSignature)",
file: file, line: line)
return
}
if !signatures.contains(where: { asSignature.asIdentifier == $0.asIdentifier }) {
XCTFail(
"""
Failed to find function definition \(functionSignature).
Function signatures found:
\(signatures.map { TypeFormatter.asString(signature: $0, includeName: true) }.joined(separator: "\n -"))
""",
file: file, line: line)
}
}
func assertDefined(typeName: String, supertype: String? = nil, file: StaticString = #filePath, line: UInt = #line) {
guard let type = types.knownType(withName: typeName) else {
XCTFail("Expected to find type \(typeName)",
file: file, line: line)
return
}
if let supertype = supertype, type.supertype?.asTypeName != supertype {
XCTFail("Expected supertype \(supertype), but found \(type.supertype?.asTypeName ?? "<nil>")",
file: file,
line: line)
}
}
func assertDefined(typeName: String,
supertype: String? = nil,
signature: String,
file: StaticString = #filePath, line: UInt = #line) {
guard let type = types.knownType(withName: typeName) else {
XCTFail("Expected to find type \(typeName)",
file: file, line: line)
return
}
if let supertype = supertype, type.supertype?.asTypeName != supertype {
XCTFail("Expected supertype \(supertype), but found \(type.supertype?.asTypeName ?? "<nil>")",
file: file, line: line)
}
let typeString = TypeFormatter.asString(knownType: type)
if typeString != signature {
XCTFail("""
Expected type signature of type \(typeName) to match
\(signature)
but found signature
\(typeString.makeDifferenceMarkString(against: signature))
""",
file: file, line: line)
}
}
func assertDefined(canonicalTypeName: String,
forNonCanon nonCanon: String,
file: StaticString = #filePath, line: UInt = #line) {
guard let canonName = types.canonicalName(for: nonCanon) else {
XCTFail("Expected to find canonical type mapping for \(nonCanon)",
file: file, line: line)
return
}
if canonName != canonicalTypeName {
XCTFail(
"""
Expected canonical type '\(nonCanon)' to map to \(canonicalTypeName), \
but it maps to \(canonName)
""",
file: file, line: line)
}
}
}
| 35.677778 | 120 | 0.511367 |
64b9544abb521c78665d7c64029b458e89f1c79e | 295 | // RUN: not --crash %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
for c where
{{{
s{
{}
b {
h}}}class S<T{func a<h{func b<T where h.g=a{c
| 22.692308 | 87 | 0.701695 |
690e55ee8bf03ae9e531603b24dccc520d3f11ff | 2,993 | //
// GFZMonthFactParser.swift
// Solario
//
// Created by Hermann Wagenleitner on 03/07/2017.
// Copyright © 2017 Hermann Wagenleitner. All rights reserved.
//
import Foundation
class GFZMonthFactParser: RawDataParserProtocol {
private let longWhitespacesRegex = try! NSRegularExpression(pattern: "[ ]+", options: [])
private let dateFormat = "yyMMdd"
private lazy var dateFormatter: DateFormatter = self.dateFormatter(format: self.dateFormat)
private let valueStep: Float = 1 / 3
// MARK: - RawDataParserProtocol
var rawDataFile: RawDataFile?
var issueDate: Date?
func items(setPriority priority: DataItemPriority) throws -> [DataItem] {
guard let lines = rawDataFile?.lines else {
throw ParserError.noDataFile
}
var items: [DataItem] = []
for line in lines {
var preparedLine = removeLongWhitespaces(fromText: line)
preparedLine = preparedLine.trimmingCharacters(in: .whitespaces)
let lineComps = preparedLine.split(separator: " ")
guard lineComps.count > 1 else {
continue
}
let dateString = String(lineComps.first!)
guard let date = dateFormatter.date(from: dateString) else {
continue
}
let eightsCount = min(9, lineComps.count) - 1
for eighth in 1...eightsCount {
let rawValue = String(lineComps[eighth])
guard let value = value(fromRaw: rawValue) else {
throw ParserError.unrecognizedFormat
}
if let dateInterval = dateInterval(from: date, eighth: eighth) {
let item = DataItem(value: value, dateInterval: dateInterval, isForecast: false, priority: priority)
items.append(item)
}
}
}
return items
}
// MARK: -
private func removeLongWhitespaces(fromText text: String) -> String {
let range = NSMakeRange(0, text.count)
return longWhitespacesRegex.stringByReplacingMatches(in: text,
options: [],
range: range,
withTemplate: " ")
}
private func dateFormatter(format: String) -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter
}
private func value(fromRaw raw: String) -> Float? {
guard
raw.count == 2,
let integerValue = Int(String(raw.first!)) else {
return nil
}
var value = Float(integerValue)
let half = raw.last!
if half == "+" {
value += valueStep
} else if half == "-" {
value -= valueStep
}
return value
}
}
| 28.504762 | 120 | 0.551286 |
fc80f90dd583262f6adabb6cc4da9942d666e291 | 400 | import XCTest
@testable import Views
final class ViewsTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(Views().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
| 25 | 87 | 0.64 |
e83f9fc68cde0f5af8873581e51fb2acfad964de | 7,804 | // MVCarouselCollectionView.swift
//
// Copyright (c) 2015 Andrea Bizzotto ([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 UIKit
import Foundation
/*
* TODO: Would be nice to support spacing between pages. The link below explains how to do this but
* the code sample needs to be converted to Auto Layout
* http://stackoverflow.com/questions/13228600/uicollectionview-align-logic-missing-in-horizontal-paging-scrollview
*/
@objc public protocol MVCarouselCollectionViewDelegate {
// method to provide a custom loader for a cell
@objc optional func imageLoaderForCell(atIndexPath indexPath: NSIndexPath, imagePath: String) -> MVImageLoaderClosure
func carousel(carousel: MVCarouselCollectionView, didSelectCellAtIndexPath indexPath: NSIndexPath)
func carousel(carousel: MVCarouselCollectionView, didScrollToCellAtIndex cellIndex : NSInteger)
}
public class MVCarouselCollectionView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private let reuseID = "SomeReuseID"
// MARK: Variables
public var imagePaths : [String] = []
public var selectDelegate : MVCarouselCollectionViewDelegate?
public var currentPageIndex : Int = 0
public var maximumZoom : Double = 0.0
// Default clousure used to load images
public var commonImageLoader: MVImageLoaderClosure?
// Trick to avoid updating the page index more than necessary
private var clientDidRequestScroll : Bool = false
// MARK: Initialisation
override public func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
self.dataSource = self
// Loading bundle from class, see: http://stackoverflow.com/questions/25138989/uicollectionview-nib-from-a-framework-target-registered-as-a-cell-fails-at-runt
let bundle = Bundle(for: MVCarouselCell.self)
let nib = UINib(nibName : "MVCarouselCell", bundle: bundle)
self.register(nib, forCellWithReuseIdentifier: self.reuseID)
}
// MARK: UICollectionViewDataSource
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imagePaths.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// Should be set at this point
assert(commonImageLoader != nil)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseID, for: indexPath) as! MVCarouselCell
cell.cellSize = self.bounds.size
// Pass the closure to the cell
let imagePath = self.imagePaths[indexPath.row]
let loader = self.selectDelegate?.imageLoaderForCell?(atIndexPath: indexPath as NSIndexPath, imagePath: imagePath)
cell.imageLoader = loader != nil ? loader : self.commonImageLoader
// Set image path, which will call closure
cell.imagePath = imagePath
cell.maximumZoom = maximumZoom
// http://stackoverflow.com/questions/16960556/how-to-zoom-a-uiscrollview-inside-of-a-uicollectionviewcell
if let gestureRecognizer = cell.scrollView.pinchGestureRecognizer {
self.addGestureRecognizer(gestureRecognizer)
}
if let gestureRecognizer = cell.scrollView?.panGestureRecognizer {
self.addGestureRecognizer(gestureRecognizer)
}
return cell
}
public func collectionView(_ collectionView : UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? MVCarouselCell {
// http://stackoverflow.com/questions/16960556/how-to-zoom-a-uiscrollview-inside-of-a-uicollectionviewcell
if let gestureRecognizer = cell.scrollView?.pinchGestureRecognizer {
self.removeGestureRecognizer(gestureRecognizer)
}
if let gestureRecognizer = cell.scrollView?.panGestureRecognizer {
self.removeGestureRecognizer(gestureRecognizer)
}
}
}
// MARK: UICollectionViewDelegateFlowLayout
public func collectionView(_ collectionView : UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.superview!.bounds.size
}
public func collectionView(_ collectionView : UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectDelegate?.carousel(carousel: self, didSelectCellAtIndexPath: indexPath as NSIndexPath)
//self.selectDelegate?.carousel(self, didSelectCellAtIndexPath: indexPath)
}
// MARK: UIScrollViewDelegate
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self {
if !self.clientDidRequestScroll {
self.updatePageIndex()
}
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == self {
self.clientDidRequestScroll = false
self.updatePageIndex()
}
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if scrollView == self {
self.clientDidRequestScroll = false
self.updatePageIndex()
}
}
public func updatePageIndex() {
let pageIndex = self.getPageNumber()
if currentPageIndex != pageIndex {
// println("old page: \(currentPageIndex), new page: \(pageIndex)")
currentPageIndex = pageIndex
self.selectDelegate?.carousel(carousel: self, didScrollToCellAtIndex: pageIndex)
///self.selectDelegate?.carousel(self, didScrollToCellAtIndex: pageIndex)
}
}
public func getPageNumber() -> NSInteger {
// http://stackoverflow.com/questions/4132993/getting-the-current-page
let width : CGFloat = self.frame.size.width
var page : NSInteger = NSInteger((self.contentOffset.x + (CGFloat(0.5) * width)) / width)
let numPages = self.numberOfItems(inSection: 0)
if page < 0 {
page = 0
}
else if page >= numPages {
page = numPages - 1
}
return page
}
public func setCurrentPageIndex(pageIndex: Int, animated: Bool) {
self.currentPageIndex = pageIndex
self.clientDidRequestScroll = true;
let indexPath = NSIndexPath(row: currentPageIndex, section: 0)
self.scrollToItem(at: indexPath as IndexPath, at:UICollectionView.ScrollPosition.centeredHorizontally, animated: animated)
}
public func resetZoom() {
for cell in self.visibleCells as! [MVCarouselCell] {
cell.resetZoom()
}
}
}
| 41.510638 | 168 | 0.704895 |
460d8d051a24cac36cd73bbc5a6531aba6d8fca0 | 3,361 | // Andrey Vysher 2016
// Swift Algorithms and data structures
// https://github.com/zerocool0686/swift-algorithms-and-data-structures
import UIKit
class DLLCell<T: Equatable> {
var key: T
var next: DLLCell<T>?
var prev: DLLCell<T>?
init(value: T) {
key = value
}
}
class DoublyLinkedList<T: Equatable> {
var head: DLLCell<T>?
var size: Int {
get {
return 0
}
}
// Add methods:
func addCellHead(cell: DLLCell<T>) {
if head == nil {
head = cell
} else {
cell.next = head
head = cell
cell.next?.prev = head
}
}
func addCellTail(cell: DLLCell<T>) {
if head == nil {
head = cell
} else {
var nextCell = head
while nextCell?.next != nil {
nextCell = nextCell?.next
}
nextCell?.next = cell
cell.prev = nextCell
}
}
func addCell(newCell: DLLCell<T>, isBefore: Bool, key: T) {
if (head?.key == key && isBefore) {
addCellHead(newCell)
return
}
if let cell = findByKey(key, isBefore: isBefore) {
cell.next?.prev = newCell
newCell.next = cell.next
newCell.prev = cell
cell.next = newCell
}
}
// Remove methods:
func removeHead() {
if head?.next == nil {
head = nil
return
}
head = head?.next
head?.prev = nil
}
func removeTail() {
if head?.next == nil {
head = nil
return
}
var last = head
while last?.next != nil {
last = last?.next
}
last?.prev?.next = nil
}
// Find method:
func findByKey(key: T, isBefore: Bool) -> DLLCell<T>? {
if head != nil {
var nextCell = head
var prevCell = head
while nextCell != nil {
if nextCell?.key == key {
return isBefore ? prevCell : nextCell
}
prevCell = nextCell!
nextCell = nextCell?.next
}
}
return nil
}
// Print method:
func printAllCells() {
var nextCell = head
while nextCell != nil {
print("[\(nextCell?.key)]\n")
nextCell = nextCell?.next
}
}
}
///////////////
// TEST AREA //
///////////////
let dLinkedList = DoublyLinkedList<Int>()
dLinkedList.addCellHead(DLLCell<Int>(value: 5))
dLinkedList.addCellHead(DLLCell<Int>(value: 55))
dLinkedList.addCellHead(DLLCell<Int>(value: 45))
dLinkedList.addCellHead(DLLCell<Int>(value: 35))
dLinkedList.addCellHead(DLLCell<Int>(value: 25))
dLinkedList.addCellTail(DLLCell<Int>(value: 87))
dLinkedList.removeTail()
dLinkedList.removeTail()
dLinkedList.removeHead()
print(dLinkedList.findByKey(45, isBefore: true)?.key)
dLinkedList.addCell(DLLCell<Int>(value: 13), isBefore: false, key: 35)
print(dLinkedList.findByKey(45, isBefore: true)?.key)
dLinkedList.printAllCells()
| 21.407643 | 71 | 0.487057 |
22faeef12ae969df6666e2f5c09be08f3c620100 | 1,126 | //
// VimeoReachability.swift
// Vimeo
//
// Created by King, Gavin on 9/22/16.
// Copyright © 2016 Vimeo. All rights reserved.
//
import UIKit
public class VimeoReachability {
private static var LastKnownReachabilityStatus = AFNetworkReachabilityStatus.unknown
internal static func beginPostingReachabilityChangeNotifications() {
AFNetworkReachabilityManager.shared().setReachabilityStatusChange { (status) in
if LastKnownReachabilityStatus != status {
LastKnownReachabilityStatus = status
NetworkingNotification.reachabilityDidChange.post(object: nil)
}
}
AFNetworkReachabilityManager.shared().startMonitoring()
}
public static func reachable() -> Bool {
return AFNetworkReachabilityManager.shared().isReachable
}
public static func reachableViaCellular() -> Bool {
return AFNetworkReachabilityManager.shared().isReachableViaWWAN
}
public static func reachableViaWiFi() -> Bool {
return AFNetworkReachabilityManager.shared().isReachableViaWiFi
}
}
| 29.631579 | 88 | 0.690941 |
4606952734e55efb469d68994843cc40ca8bc6cc | 4,771 | //===---- EmitSupportedFeatures.swift - Swift Compiler Features Info Job ----===//
//
// 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 TSCBasic
import SwiftOptions
import Foundation
/// Describes information about the compiler's supported arguments and features
@_spi(Testing) public struct SupportedCompilerFeatures: Codable {
var SupportedArguments: [String]
var SupportedFeatures: [String]
}
extension Toolchain {
func emitSupportedCompilerFeaturesJob(requiresInPlaceExecution: Bool = false,
swiftCompilerPrefixArgs: [String]) throws -> Job {
var commandLine: [Job.ArgTemplate] = swiftCompilerPrefixArgs.map { Job.ArgTemplate.flag($0) }
var inputs: [TypedVirtualPath] = []
commandLine.append(contentsOf: [.flag("-frontend"),
.flag("-emit-supported-features")])
// This action does not require any input files, but all frontend actions require
// at least one so we fake it.
// FIXME: Teach -emit-supported-features to not expect any inputs, like -print-target-info does.
let dummyInputPath =
VirtualPath.createUniqueTemporaryFileWithKnownContents(.init("dummyInput.swift"),
"".data(using: .utf8)!)
commandLine.appendPath(dummyInputPath)
inputs.append(TypedVirtualPath(file: dummyInputPath.intern(), type: .swift))
return Job(
moduleName: "",
kind: .emitSupportedFeatures,
tool: try resolvedTool(.swiftCompiler),
commandLine: commandLine,
displayInputs: [],
inputs: inputs,
primaryInputs: [],
outputs: [.init(file: .standardOutput, type: .jsonCompilerFeatures)],
requiresInPlaceExecution: requiresInPlaceExecution
)
}
}
extension Driver {
static func computeSupportedCompilerArgs(of toolchain: Toolchain, hostTriple: Triple,
parsedOptions: inout ParsedOptions,
diagnosticsEngine: DiagnosticsEngine,
fileSystem: FileSystem,
executor: DriverExecutor, env: [String: String])
throws -> Set<String> {
// TODO: Once we are sure libSwiftScan is deployed across supported platforms and architectures
// we should deploy it here.
// let swiftScanLibPath = try Self.getScanLibPath(of: toolchain,
// hostTriple: hostTriple,
// env: env)
//
// if fileSystem.exists(swiftScanLibPath) {
// let libSwiftScanInstance = try SwiftScan(dylib: swiftScanLibPath)
// if libSwiftScanInstance.canQuerySupportedArguments() {
// return try libSwiftScanInstance.querySupportedArguments()
// }
// }
// Invoke `swift-frontend -emit-supported-features`
let frontendOverride = try FrontendOverride(&parsedOptions, diagnosticsEngine)
frontendOverride.setUpForTargetInfo(toolchain)
defer { frontendOverride.setUpForCompilation(toolchain) }
let frontendFeaturesJob =
try toolchain.emitSupportedCompilerFeaturesJob(swiftCompilerPrefixArgs:
frontendOverride.prefixArgsForTargetInfo)
let decodedSupportedFlagList = try executor.execute(
job: frontendFeaturesJob,
capturingJSONOutputAs: SupportedCompilerFeatures.self,
forceResponseFiles: false,
recordedInputModificationDates: [:]).SupportedArguments
return Set(decodedSupportedFlagList)
}
static func computeSupportedCompilerFeatures(of toolchain: Toolchain,
env: [String: String]) throws -> Set<String> {
struct FeatureInfo: Codable {
var name: String
}
struct FeatureList: Codable {
var features: [FeatureInfo]
}
let jsonPath = try getRootPath(of: toolchain, env: env)
.appending(component: "share")
.appending(component: "swift")
.appending(component: "features.json")
guard localFileSystem.exists(jsonPath) else {
return Set<String>()
}
let content = try localFileSystem.readFileContents(jsonPath)
let result = try JSONDecoder().decode(FeatureList.self, from: Data(content.contents))
return Set(result.features.map {$0.name})
}
}
| 43.770642 | 100 | 0.640537 |
1ac2518f631ca44aa5a52ef1d00dccd3bf8d971a | 5,436 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/main/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
@_exported import AWSSDKSwiftCore
/*
Client object for interacting with AWS SSO service.
AWS Single Sign-On Portal is a web service that makes it easy for you to assign user access to AWS SSO resources such as the user portal. Users can get AWS account applications and roles assigned to them and get federated into the application. For general information about AWS SSO, see What is AWS Single Sign-On? in the AWS SSO User Guide. This API reference guide describes the AWS SSO Portal operations that you can call programatically and includes detailed information on data types and errors. AWS provides SDKs that consist of libraries and sample code for various programming languages and platforms, such as Java, Ruby, .Net, iOS, or Android. The SDKs provide a convenient way to create programmatic access to AWS SSO and other AWS services. For more information about the AWS SDKs, including how to download and install them, see Tools for Amazon Web Services.
*/
public struct SSO: AWSService {
// MARK: Member variables
public let client: AWSClient
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the SSO client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: AWSSDKSwiftCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
service: "portal.sso",
signingName: "awsssoportal",
serviceProtocol: .restjson,
apiVersion: "2019-06-10",
endpoint: endpoint,
serviceEndpoints: ["ap-southeast-1": "portal.sso.ap-southeast-1.amazonaws.com", "ap-southeast-2": "portal.sso.ap-southeast-2.amazonaws.com", "ca-central-1": "portal.sso.ca-central-1.amazonaws.com", "eu-central-1": "portal.sso.eu-central-1.amazonaws.com", "eu-west-1": "portal.sso.eu-west-1.amazonaws.com", "eu-west-2": "portal.sso.eu-west-2.amazonaws.com", "us-east-1": "portal.sso.us-east-1.amazonaws.com", "us-east-2": "portal.sso.us-east-2.amazonaws.com", "us-west-2": "portal.sso.us-west-2.amazonaws.com"],
possibleErrorTypes: [SSOErrorType.self],
timeout: timeout
)
}
// MARK: API Calls
/// Returns the STS short-term credentials for a given role name that is assigned to the user.
public func getRoleCredentials(_ input: GetRoleCredentialsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetRoleCredentialsResponse> {
return self.client.execute(operation: "GetRoleCredentials", path: "/federation/credentials", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger)
}
/// Lists all roles that are assigned to the user for a given AWS account.
public func listAccountRoles(_ input: ListAccountRolesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListAccountRolesResponse> {
return self.client.execute(operation: "ListAccountRoles", path: "/assignment/roles", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger)
}
/// Lists all AWS accounts assigned to the user. These AWS accounts are assigned by the administrator of the account. For more information, see Assign User Access in the AWS SSO User Guide. This operation returns a paginated response.
public func listAccounts(_ input: ListAccountsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListAccountsResponse> {
return self.client.execute(operation: "ListAccounts", path: "/assignment/accounts", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger)
}
/// Removes the client- and server-side session that is associated with the user.
@discardableResult public func logout(_ input: LogoutRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<Void> {
return self.client.execute(operation: "Logout", path: "/logout", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger)
}
}
| 64.714286 | 873 | 0.69702 |
38ff37db93bfb860118afa7941a7e9fdad0cf03b | 940 |
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
extension ApplicationDelegate {
//····················································································································
@IBAction func updateLibrary (_ inSender : AnyObject) {
if let logTextView = g_Preferences?.mLibraryUpdateLogTextView {
let optionKey : Bool = NSApp.currentEvent?.modifierFlags.contains (.option) ?? false
if optionKey {
startLibraryRevisionListOperation (logTextView)
}else{
startLibraryUpdateOperation (showProgressWindow: true, logTextView)
}
}
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 36.153846 | 120 | 0.340426 |
e5d008cd9ad95b3438e2c206d5b71515e086b08d | 529 | // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "WebMIDIKit",
products: [
.library(
name: "WebMIDIKit",
targets: ["WebMIDIKit"]),
],
dependencies: [
],
targets: [
.target(
name: "WebMIDIKit",
dependencies: []),
.testTarget(
name: "WebMIDIKitTests",
dependencies: []),
]
)
| 22.041667 | 96 | 0.548204 |
79453e3b90ecabe0da8139a4ad4b838c5bfb395e | 1,348 | public enum CircleRotationDirection {
/// Item rotate in clockwise direction.
case clockwise
/// Item rotate in anticlockwise direction.
case anticlockwise
}
public protocol CircleRotationAnimatable: ScaleAnimatable, UIAppearanceAnimatable {
/// The radius of the circle. The default value is 100.
@discardableResult func radius(_ radius: CGFloat) -> CircleRotationAnimatable
/// The direction of rotation. The default value is `CircleRotationDirection.clockwise`.
@discardableResult func rotateDirection(_ direction: CircleRotationDirection) -> CircleRotationAnimatable
/// A Boolean value indicating whether the item rotates or not.
@discardableResult func itemRotationEnabled(_ isEnabled: Bool) -> CircleRotationAnimatable
}
extension GeminiAnimationModel: CircleRotationAnimatable {
@discardableResult
public func radius(_ radius: CGFloat) -> CircleRotationAnimatable {
circleRadius = radius
return self
}
@discardableResult
public func rotateDirection(_ direction: CircleRotationDirection) -> CircleRotationAnimatable {
rotateDirection = direction
return self
}
@discardableResult
public func itemRotationEnabled(_ isEnabled: Bool) -> CircleRotationAnimatable {
isItemRotationEnabled = isEnabled
return self
}
}
| 34.564103 | 109 | 0.747033 |
8ac8ed9e6d0135374288bc21187941aac214cab1 | 4,412 | //
// DictionaryDocument.swift
// AzureData
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
/// Represents a document in the Azure Cosmos DB service.
///
/// - Remark:
/// A document is a structured JSON document. There is no set schema for the JSON documents,
/// and a document may contain any number of custom properties as well as an optional list of attachments.
/// Document is an application resource and can be authorized using the master key or resource keys.
public class DictionaryDocument : Document {
let sysKeys = ["id", "_rid", "_self", "_etag", "_ts", "_attachments"]
public private(set) var data: CodableDictionary?
public override init () { super.init() }
public override init (_ id: String) { super.init(id) }
internal init(data: CodableDictionary) {
super.init()
self.data = data
}
public subscript (key: String) -> Any? {
get { return data?[key] }
set {
assert(Swift.type(of: self) == DictionaryDocument.self, "Error: Subscript cannot be used on children of DictionaryDocument\n")
assert(!sysKeys.contains(key), "Error: Subscript cannot be used to set the following system generated properties: \(sysKeys.joined(separator: ", "))\n")
if data == nil { data = CodableDictionary() }
data![key] = newValue
}
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
if Swift.type(of: self) == DictionaryDocument.self {
let userContainer = try decoder.container(keyedBy: UserCodingKeys.self)
data = CodableDictionary()
let userKeys = userContainer.allKeys.filter { !sysKeys.contains($0.stringValue) }
for key in userKeys {
data![key.stringValue] = (try? userContainer.decode(CodableDictionaryValueType.self, forKey: key))?.value
}
}
}
public override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
if Swift.type(of: self) == DictionaryDocument.self {
var userContainer = encoder.container(keyedBy: UserCodingKeys.self)
if let data = data {
for (k, v) in data {
let key = UserCodingKeys(stringValue: k)!
switch v {
case .uuid(let value): try userContainer.encode(value, forKey: key)
case .bool(let value): try userContainer.encode(value, forKey: key)
case .int(let value): try userContainer.encode(value, forKey: key)
case .double(let value): try userContainer.encode(value, forKey: key)
case .float(let value): try userContainer.encode(value, forKey: key)
case .date(let value): try userContainer.encode(value, forKey: key)
case .string(let value): try userContainer.encode(value, forKey: key)
case .dictionary(let value): try userContainer.encode(value, forKey: key)
case .array(let value): try userContainer.encode(value, forKey: key)
default: break
}
}
}
}
}
private struct UserCodingKeys : CodingKey {
let key: String
var stringValue: String {
return key
}
init?(stringValue: String) {
key = stringValue
}
var intValue: Int? { return nil }
init?(intValue: Int) { return nil }
}
public override var debugDescription: String {
return "DictionaryDocument :\n\tid : \(self.id)\n\tresourceId : \(self.resourceId)\n\tselfLink : \(self.selfLink.valueOrNilString)\n\tetag : \(self.etag.valueOrNilString)\n\ttimestamp : \(self.timestamp.valueOrNilString)\n\taltLink : \(self.altLink.valueOrNilString)\n\tattachmentsLink : \(self.attachmentsLink.valueOrNilString)\n\t\(self.data?.dictionary.map { "\($0) : \($1 ?? "nil")" }.joined(separator: "\n\t") ?? "nil")\n--"
}
}
| 37.709402 | 437 | 0.57117 |
d566b48c0867bfa3565ee0aa97b3f487ec4b369b | 317 | //
// SecretAPIKeys.swift
// WeatherApp
//
// Created by Eric Widjaja on 10/13/19.
// Copyright © 2019 Eric Widjaja. All rights reserved.
//
import Foundation
struct SecretAPIKeys {
static let darkSkyKey = "37a2b0ef5d9c00fc93693af5d6fb5ebd"
static let pixaBayKey = "13797079-1da769e52f4691c85dcbdcd6b"
}
| 22.642857 | 64 | 0.741325 |
8f238ac8e013dbe950f9d576d2ac73ae3e816147 | 3,419 | //
// UIImageView+kf.swift
// SwiftX
//
// Created by wangcong on 2019/2/16.
//
import UIKit
import Kingfisher
public extension UIImageView {
public func kf_cancelImageRequest() {
self.kf.cancelDownloadTask()
}
public func kf_setImageWithRoundCorner(
urlString: String,
placeholder: UIImage?,
cornerRadius: CGFloat? = nil,
size: CGSize? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) {
let s = size ?? bounds.size
let radius = cornerRadius ?? min(s.width, s.height) / 2
let url = URL(string: urlString)
kf_setImageWithRoundCorner(url: url, placeholder: placeholder, cornerRadius: radius, size: s, progressBlock: progressBlock, completionHandler: completionHandler)
}
public func kf_setImageWithRoundCorner(
url: URL?,
placeholder: UIImage?,
cornerRadius: CGFloat? = nil,
size: CGSize? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) {
let s = size ?? bounds.size
guard s.width != 0 && s.height != 0 else { // bug fix: 当size为0,导致kingfiser获取绘制图片上下文失败,crash
return
}
let radius = cornerRadius ?? min(s.width, s.height) / 2
let scale = UIScreen.main.scale
let roundProcessor = RoundCornerImageProcessor(cornerRadius: radius * scale, targetSize: CGSize(width: s.width * scale, height: s.height * scale))
kf_setImage(url: url, placeholder: placeholder, size: s, options: [.processor(roundProcessor), .cacheSerializer(RoundCornerImageCacheSerializer.default)], progressBlock: progressBlock, completionHandler: completionHandler)
}
public func kf_setImage(
urlString: String?,
placeholder: UIImage?,
size: CGSize? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) {
let s = size ?? CGSize(width: min(bounds.size.width, 1242), height: min(bounds.size.height, 2208))
let url = URL(string: urlString ?? "")
kf_setImage(url: url, placeholder: placeholder, size: s, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
public func kf_setImage(
url: URL?,
placeholder: UIImage?,
size: CGSize? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) {
let s = size ?? CGSize(width: min(bounds.size.width, 1242), height: min(bounds.size.height, 2208))
kf.setImage(with: url, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
}
private struct RoundCornerImageCacheSerializer: CacheSerializer {
static let `default` = RoundCornerImageCacheSerializer()
private init() {}
func data(with image: Image, original: Data?) -> Data? {
return image.kf.pngRepresentation()
}
func image(with data: Data, options: KingfisherParsedOptionsInfo) -> Image? {
let options = options
let image = Image(data: data, scale: options.scaleFactor)
return image
}
}
| 36.763441 | 230 | 0.649898 |
e8102a565990671c78448a38dfae7ec40c6f3ba5 | 1,451 | //
// String+color.swift
// Shared
//
// Created by Stephan Vanterpool on 9/15/18.
// Copyright © 2018 Robbie Trencheny. All rights reserved.
//
import Foundation
extension String {
func dictionary() -> [String: Any]? {
if let data = self.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
func colorWithHexValue(alpha: CGFloat? = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(String.intFromHexString(self))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
let alpha = alpha!
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
private static func intFromHexString(_ hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: Scanner = Scanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
// Scan hex value
scanner.scanHexInt32(&hexInt)
return hexInt
}
}
| 29.612245 | 98 | 0.583735 |
030546f71230540d38d2bf8969009644a6d01779 | 4,370 | //
// DetailViewController.swift
// BackingTrackPlayer
//
// Created by Nick Malbraaten on 6/2/18.
// Copyright © 2018 Nick Malbraaten. All rights reserved.
//
import UIKit
import AVFoundation
class DetailViewController: UIViewController, TrackPlayerDelegate {
@IBOutlet weak var detailDescriptionLabel: UILabel!
@IBOutlet weak var trackName: UILabel!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var rewindButton: UIButton!
@IBOutlet weak var skipButton: UIButton!
var trackPlayer: TrackPlayer?
func configureView() {
// Update the user interface for the detail item.
if let detail = detailItem {
if let label = detailDescriptionLabel {
label.text = detail.description
}
}
playButton.setTitle("", for: .normal)
let playImage = UIImage(systemName: "play.fill")
playImage?.accessibilityIdentifier = "play"
playButton.setImage(playImage, for: .normal)
rewindButton.setTitle("", for: .normal)
let rewindImage = UIImage(systemName: "backward.end.fill")
rewindImage?.accessibilityIdentifier = "rewind"
rewindButton.setImage(rewindImage, for: .normal)
skipButton.setTitle("", for: .normal)
let skipImage = UIImage(systemName: "forward.end.fill")
skipImage?.accessibilityIdentifier = "skip"
skipButton.setImage(skipImage, for: .normal)
}
func configureTrackPlayer() {
self.trackPlayer = TrackPlayer(tracks: self.getTracks())
self.trackPlayer?.delegate = self
updateTitleLabel()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configureTrackPlayer()
configureView()
}
// This will need to be rewritten when we're not hardcoding track titles/locations
// (e.g. getting them from the device's music library, etc.)
func getTracks() -> Array<Track> {
let trackTitles = [
"Sense Control_BT",
"When Morning Came_BT",
"In The Pines_BT",
"Blind_BT",
"Legacy_BT"
]
let trackRootPath = "Backing Tracks/"
let trackFileType = "wav"
var tracks: Array<Track> = []
for title in trackTitles {
tracks.append(Track(title: title, filePath: trackRootPath + title, fileType: trackFileType))
}
return tracks
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var detailItem: NSDate? {
didSet {
// Update the view.
configureView()
}
}
@IBAction func playSong(_ sender: UIButton) {
if (trackPlayer != nil) {
if (trackPlayer!.isPlaying()) {
trackPlayer!.stop()
} else {
trackPlayer!.play()
}
togglePlayButtonLabel()
}
}
@IBAction func skipToNextSong(_ sender: Any) {
if (trackPlayer != nil) {
if (trackPlayer!.isPlaying()) {
togglePlayButtonLabel()
}
trackPlayer!.fastForward()
updateTitleLabel()
}
}
@IBAction func rewindSong(_ sender: Any) {
if (trackPlayer != nil) {
if (trackPlayer!.isPlaying()) {
togglePlayButtonLabel()
}
trackPlayer!.rewind()
}
}
func trackPlayerDidFinishPlaying() {
updateTitleLabel()
}
func updateTitleLabel() {
trackName.text = trackPlayer?.currentTrack.title
}
func togglePlayButtonLabel() {
let buttonMode = playButton.image(for: .normal)?.accessibilityIdentifier;
if (buttonMode == "play") {
let playImage = UIImage(systemName: "pause.circle.fill")
playImage?.accessibilityIdentifier = "pause"
playButton.setImage(playImage, for: .normal)
} else {
let playImage = UIImage(systemName: "play.fill")
playImage?.accessibilityIdentifier = "play"
playButton.setImage(playImage, for: .normal)
}
}
}
| 30.137931 | 104 | 0.584897 |
f486e9e62142b8f6eeb258d64f11321bbd1de277 | 971 | import SwiftUI
extension AddCarbs {
class ViewModel<Provider>: BaseViewModel<Provider>, ObservableObject where Provider: AddCarbsProvider {
@Injected() var carbsStorage: CarbsStorage!
@Injected() var settingsManager: SettingsManager!
@Injected() var apsManager: APSManager!
@Published var carbs: Decimal = 0
@Published var date = Date()
override func subscribe() {}
func add() {
guard carbs > 0 else {
showModal(for: nil)
return
}
carbsStorage.storeCarbs([
CarbsEntry(createdAt: date, carbs: carbs, enteredBy: CarbsEntry.manual)
])
if settingsManager.settings.skipBolusScreenAfterCarbs ?? false {
apsManager.determineBasalSync()
showModal(for: nil)
} else {
showModal(for: .bolus(waitForDuggestion: true))
}
}
}
}
| 30.34375 | 107 | 0.570546 |
fca541a3e46db7b3525fc34108c188ea01166b69 | 1,041 | //
// Corona-Warn-App
//
// SAP SE and all other contributors
// copyright owners license this file to you under the Apache
// License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
import Foundation
import UIKit
class SubmitCollectionViewCell: HomeCardCollectionViewCell {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var bodyLabel: UILabel!
@IBOutlet var imageView: UIImageView!
@IBOutlet var contactButton: UIButton!
weak var delegate: HomeCardCellButtonDelegate?
@IBAction func submitButtonTapped(_: UIButton) {
delegate?.buttonTapped(cell: self)
}
}
| 30.617647 | 62 | 0.760807 |
f82c0b8cf73d24d2f3202cba7979400477cd66d6 | 3,374 | // Copyright © 2020 ShawnJames. All rights reserved.
// Created by Shawn James
// AutoCompleteTableView.swift
import CoreData
import UIKit
protocol AutoCompleteTableViewMyDelegate {
func replaceTextFieldText(with text: String)
}
class AutoCompleteTableView: UITableView, UITableViewDelegate, UITextFieldDelegate {
typealias SuggestionsData = UITableViewDiffableDataSource<Int, NSAttributedString>
typealias SuggestionsSnapshot = NSDiffableDataSourceSnapshot<Int, NSAttributedString>
// MARK: - Model
private var autoCompleteModel = ExercisePermanentRecordController()
private var fetchedResultsController: NSFetchedResultsController<ExercisePermanentRecord>?
// MARK: - Properties
private var suggestionsDataSource: SuggestionsData!
var myDelegate: AutoCompleteTableViewMyDelegate?
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: contentSize.width, height: contentSize.height)
}
// MARK: - Lifecycle
/// Storyboard init
required init?(coder: NSCoder) {
super.init(coder: coder)
isHidden = true
delegate = self
isScrollEnabled = false
separatorStyle = .none
backgroundColor = .clear
cellForRowAt()
}
// MARK: - Public Methods
func showDropDown() {
isHidden = false; alpha = 1
}
func hideDropDown() {
isHidden = true; alpha = 0
}
// MARK: - TableView
func cellForRowAt() {
suggestionsDataSource = SuggestionsData(tableView: self, cellProvider: { (tableView, indexPath, autoCompleteSuggestion) -> UITableViewCell? in
let cell: AutoCompleteCell = tableView.dequeueReusableCell(for: indexPath)
cell.autoCompleteSuggestion = autoCompleteSuggestion
return cell
})
}
func updateTableView() {
snapshotView(afterScreenUpdates: true)
var update = SuggestionsSnapshot()
update.appendSections([0])
update.appendItems(autoCompleteModel.autoCompleteResults)
DispatchQueue.main.async { [weak self] in
self?.suggestionsDataSource.apply(update, animatingDifferences: false)
self?.visibleCells.first?.setSelected(true, animated: false)
self?.autoCompleteModel.autoCompleteResults.isEmpty ?? true ? self?.hideDropDown() : self?.showDropDown()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let autofill = suggestionsDataSource.itemIdentifier(for: indexPath) else { return }
myDelegate?.replaceTextFieldText(with: autofill.string)
}
// MARK: - Textfield
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if let firstCell = visibleCells.first, let indexPath = indexPath(for: firstCell) {
tableView(self, didSelectRowAt: indexPath)
}
return true
}
func textFieldDidChangeSelection(_ textField: UITextField) {
autoCompleteModel.fetchAutoCompleteSuggestions(quantity: 8, for: textField.text?.lowercased()) // FIXME: - Need to be saved as lowercase as well? remove lowercase
updateTableView()
}
}
| 30.125 | 170 | 0.688797 |
1eff229891da74c06b6da4cbf7d242e39ce6a4a0 | 756 | //
// Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.
// The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
//
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and limitations under the License.
//
import Foundation
class Weak<T: AnyObject> {
weak var object : T?
init (object: T) {
self.object = object
}
}
| 36 | 120 | 0.724868 |
abc646610d2462da4172255e4703976fc3cd374b | 1,506 | //
// ReadViewCell.swift
//
//
//
import UIKit
class ReadViewCell: UITableViewCell {
/// 阅读视图
private var readView = ReadView()
var pageModel:ReadPageModel?{
didSet{
readView.pagingModel = pageModel
setNeedsLayout()
}
}
class func cell(_ tableView:UITableView) ->ReadViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "ReadViewCell")
if cell == nil {
cell = ReadViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "ReadViewCell")
}
return cell as! ReadViewCell
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
backgroundColor = UIColor.clear
// 阅读视图
contentView.addSubview(readView)
}
override func layoutSubviews() {
super.layoutSubviews()
// 分页顶部高度
let y = pageModel?.headTypeHeight ?? SPACE_MIN_HEIGHT
// 内容高度
let h = pageModel?.contentSize.height ?? SPACE_MIN_HEIGHT
readView.frame = CGRect(x: 0, y: y, width: READ_VIEW_RECT.width, height: h)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 22.147059 | 106 | 0.558433 |
202ecce7aff1adcbd9fd55b457ffed86d33e051c | 5,061 | //
// SwiftUIView.swift
//
//
// Created by Tomas Green on 2021-09-17.
//
import SwiftUI
/// AppSettings extension used by the AppSettingsExplorer view
extension AppSettings {
/// ConfigContainer representing the default plist file
var defaultConfigContianer:AppSettingsExplorer.ConfigContainer? {
guard let c = self.defaultConfig else {
return nil
}
return AppSettingsExplorer.ConfigContainer(title: "Standard", config: c)
}
/// ConfigContainer representing the MDM App Config
var managedConfigContianer:AppSettingsExplorer.ConfigContainer? {
guard let c = self.managedConfig else {
return nil
}
return AppSettingsExplorer.ConfigContainer(title: "Managed", config: c)
}
/// ConfigContainer representing the current config, could be either managed, default or mixed.
var currentConfigContinaer:AppSettingsExplorer.ConfigContainer? {
guard let c = self.config else {
return nil
}
return AppSettingsExplorer.ConfigContainer(title: "Current", config: c)
}
/// Array that holds all containers, ie. defaultConfigContianer, managedConfigContianer and currentConfigContinaer
var containers:[AppSettingsExplorer.ConfigContainer] {
var arr = [AppSettingsExplorer.ConfigContainer]()
if let c = currentConfigContinaer {
arr.append(c)
}
if let c = managedConfigContianer {
arr.append(c)
}
if let c = defaultConfigContianer {
arr.append(c)
}
return arr
}
/// App Settings explorer view
public struct AppSettingsExplorer: View {
/// Container object holding the config and a title.
public struct ConfigContainer {
/// The config title or name, localizable
public let title:LocalizedStringKey
/// The config file
public let config:Config
/// Initializes a new ConfigContainer
/// - Parameters:
/// - title: The config title or name, localizable
/// - config: The config file
public init(title:LocalizedStringKey, config:Config) {
self.title = title
self.config = config
}
}
/// List configs
var configs:[ConfigContainer]
/// Overlay used in case the list is empty
var overlay:some View {
Group {
if configs.count != 0 {
EmptyView()
} else {
Text(LocalizedStringKey("Missing configuration"))
}
}
}
/// View body
public var body: some View {
Form {
ForEach(0..<configs.count) { i in
let container = configs[i]
Section(header:Text(container.title)) {
ForEach(container.config.keyValueRepresentation.sorted(by: >), id: \.key) { key, value in
VStack(alignment:.leading) {
Text(key).font(.headline)
Text(value).font(.body)
}
}
}
}
}
.overlay(overlay)
.listStyle(GroupedListStyle())
.navigationBarTitle(LocalizedStringKey("App Config"))
}
}
/// Explorer view that represents the AppSettings instance configuration
public var explorer: AppSettingsExplorer {
return AppSettingsExplorer(configs: containers)
}
}
struct PreviewAppConfig : AppSettingsConfig {
func combine(deafult config: PreviewAppConfig?) -> PreviewAppConfig {
return self
}
var keyValueRepresentation: [String : String] {
var dict = [String:String]()
if let stringValue = stringValue {
dict["String"] = "\(stringValue)"
}
if let secretStringValue = secretStringValue {
dict["Secret string"] = String.mask(secretStringValue,percentage: 50)
}
if let intValue = intValue {
dict["Integer"] = "\(intValue)"
}
if let boolValue = boolValue {
dict["Bool"] = "\(boolValue)"
}
if let doubleValue = doubleValue {
dict["Double"] = "\(doubleValue)"
}
return dict
}
var stringValue:String?
var secretStringValue:String?
var intValue:Int?
var boolValue:Bool?
var doubleValue:Double?
}
struct AppSettingsExplorer_Previews: PreviewProvider {
static var settings:AppSettings<PreviewAppConfig> {
let c = AppSettings<PreviewAppConfig>()
c.set(config: PreviewAppConfig(
stringValue: "A string",
secretStringValue: "My secret string",
intValue: 1,
boolValue: false,
doubleValue: 2.2)
)
return c
}
static var previews: some View {
settings.explorer
}
}
| 34.195946 | 118 | 0.572021 |
d7e3b3ae602ca201c30300760e48f02ad5d74739 | 198 | //
// MyClass.swift
// Pods
//
// Created by Uy Nguyen Long on 3/1/17.
//
//
import UIKit
class MyClass: NSObject {
public func hello() -> String
{
return "Hello world"
}
}
| 11.647059 | 40 | 0.560606 |
39fb1e0d63ca21d4b043a13ba14698056c06cff7 | 2,563 | //
// Utility.swift
// N Clip Board
//
// Created by nuc_mac on 2019/10/11.
// Copyright © 2019 branson. All rights reserved.
//
import Cocoa
final class Utility {
static func registerUserDefaults() {
var preferenceDict = Dictionary<String, Any>.init()
preferenceDict[Constants.Userdefaults.LaunchOnStartUp] = false
preferenceDict[Constants.Userdefaults.ShowCleanUpMenuItem] = false
preferenceDict[Constants.Userdefaults.KeepClipBoardItemUntil] = 30
preferenceDict[Constants.Userdefaults.PollingInterval] = 0.4
preferenceDict[Constants.Userdefaults.ShowPollingIntervalLabel] = false
preferenceDict[Constants.Userdefaults.ExcludedAppDict] = [String: Bool]()
// default using command+shift+v
preferenceDict[Constants.Userdefaults.ActivationHotKeyDict] = Constants.defaultActivationHotKey
UserDefaults.standard.register(defaults: preferenceDict)
}
// referenced from https://stackoverflow.com/questions/26971240/how-do-i-run-an-terminal-command-in-a-swift-script-e-g-xcodebuild
@discardableResult
static func shell(_ args: String...) -> Int32 {
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
static func findAppIcon(by bundleIdentifier: String) -> NSImage? {
guard let bundlePath = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: bundleIdentifier) else { return nil }
return NSWorkspace.shared.icon(forFile: bundlePath)
}
static func getAppLocalizedName(by bundleIdentifier: String) -> String? {
guard let bundlePath = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: bundleIdentifier) else {
LoggingService.shared.warn("Fail to find bundle \(bundleIdentifier)")
return nil
}
return FileManager.default.displayName(atPath: bundlePath)
}
static func hexColor(color: NSColor) -> String {
let red = Int(round(color.redComponent * 0xff))
let blue = Int(round(color.blueComponent * 0xff))
let green = Int(round(color.greenComponent * 0xff))
return String(format: "#%02X%02X%02X", red, green, blue)
}
}
func warningBox(title: String, message: String) {
let alert = NSAlert()
alert.alertStyle = .warning
alert.messageText = title
alert.informativeText = message
alert.runModal()
}
| 36.614286 | 136 | 0.685915 |
ace609f221afead0da844faff3f8971cdb91cc92 | 2,540 | //
// Logs.swift
// OysterKit
//
// Created on 18/06/2018.
//
import Foundation
#if canImport(NaturalLanguage)
import os
@available(OSX 10.14, *)
public enum Log {
case parsing, decoding
public static let _parsingLog = OSLog(subsystem: "com.swift-studies.OysterKit", category: "parsing")
public static let _decodingLog = OSLog(subsystem: "com.swift-studies.OysterKit", category: "decoding")
public static var parsingLog : OSLog = .disabled
public static var decodingLog : OSLog = _decodingLog
public func enable(){
switch self {
case .parsing:
Log.parsingLog = Log._parsingLog
Log.signPostIdStack.removeAll(keepingCapacity: true)
case .decoding:
Log.decodingLog = Log._decodingLog
}
}
public func disable(){
switch self {
case .parsing: Log.parsingLog = .disabled
case .decoding: Log.decodingLog = .disabled
}
}
private static var signPostIdStack = [OSSignpostID]()
static func decodingError(_ error:DecodingError){
guard decodingLog.isEnabled(type: .default) else{
return
}
os_log("%{public}@", Log.formatted(decodingError: error))
}
private static func describe(rule:Rule)->String{
return rule.shortDescription
}
static func beginRule(rule:Rule){
guard parsingLog.signpostsEnabled else {
return
}
let newId = OSSignpostID(log: parsingLog)
signPostIdStack.append(newId)
os_signpost(.begin, log: parsingLog, name: "matches", signpostID: newId, "%{public}@", "\(describe(rule: rule))" as NSString)
}
static func endRule(rule:Rule, result:MatchResult){
guard parsingLog.signpostsEnabled else {
return
}
let oldId = signPostIdStack.removeLast()
let resultDescription : String
switch result {
case .success( _):
resultDescription = "✅" + (result.matchedString != nil ? "='" + result.matchedString! + "'" : "")
case .consume( _):
resultDescription = "👄"
case .ignoreFailure( _):
resultDescription = "❌"
case .failure( _):
resultDescription = "☠️"
}
os_signpost(.end, log: parsingLog, name: "matches", signpostID: oldId, "%{public}@ %{public}@", "\(describe(rule: rule))" as NSString, resultDescription as NSString)
}
}
#endif
| 29.534884 | 173 | 0.594488 |
2927572ab3dbe5a50bd7e88f7f47f04d85ff8aa9 | 2,696 | //
// FundsRequestListEmptyView.swift
// MyMonero
//
// Created by Paul Shapiro on 6/15/17.
// Copyright (c) 2014-2018, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
import UIKit
class FundsRequestListEmptyView: UIView
{
var emptyStateView: UICommonComponents.EmptyStateView!
//
init()
{
super.init(frame: .zero)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup()
{
do {
let view = UICommonComponents.EmptyStateView(
emoji: "🤑",
message: NSLocalizedString("You haven't made any\nrequests yet.", comment: "")
)
self.emptyStateView = view
self.addSubview(view)
}
}
//
// Imperatives - Overrides
override func layoutSubviews()
{
super.layoutSubviews()
//
let margin_h = UICommonComponents.EmptyStateView.default__margin_h
let emptyStateView_margin_top: CGFloat = 0
let emptyStateView_margin_bottom: CGFloat = 16
self.emptyStateView.frame = CGRect(
x: margin_h,
y: emptyStateView_margin_top,
width: self.frame.size.width - 2*margin_h,
height: self.frame.size.height - emptyStateView_margin_top - emptyStateView_margin_bottom
).integral
}
}
| 35.012987 | 92 | 0.748145 |
4b6ce756eae0e939d45afd81002c54238c3a5851 | 1,013 | //
// FavIcon
// Copyright © 2016 Leon Breedt
//
// 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.
//
/// Checks whether a URL exists, and returns `URLResult.Success` as the result if it does.
final class CheckURLExistsOperation: URLRequestOperation {
override func prepareRequest() {
urlRequest.httpMethod = "HEAD"
}
override func processResult(_ data: Data?, response: HTTPURLResponse, completion: @escaping (URLResult) -> Void) {
completion(.success(url: response.url!))
}
}
| 36.178571 | 118 | 0.725568 |
9b0c1605b337473dc0c977361f979987e63c655c | 3,442 | //
// Created by Tom Baranes on 25/06/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
@IBDesignable
open class AnimatableSlider: UISlider, SliderImagesDesignable, BorderDesignable, RotationDesignable, ShadowDesignable, Animatable {
// MARK: - SliderImagesDesignable
@IBInspectable open var thumbImage: UIImage? {
didSet {
configureThumbImage()
}
}
@IBInspectable open var thumbHighlightedImage: UIImage? {
didSet {
configureThumbImage()
}
}
@IBInspectable open var minimumTrackImage: UIImage? {
didSet {
configureMinimumTrackImage()
}
}
@IBInspectable open var minimumTrackHighlightedImage: UIImage? {
didSet {
configureMinimumTrackImage()
}
}
@IBInspectable open var maximumTrackImage: UIImage? {
didSet {
configureMaximumTrackImage()
}
}
@IBInspectable open var maximumTrackHighlightedImage: UIImage? {
didSet {
configureMaximumTrackImage()
}
}
// MARK: - BorderDesignable
open var borderType: BorderType = .solid {
didSet {
configureBorder()
}
}
@IBInspectable var _borderType: String? {
didSet {
borderType = BorderType(string: _borderType)
}
}
@IBInspectable open var borderColor: UIColor? {
didSet {
configureBorder()
}
}
@IBInspectable open var borderWidth: CGFloat = CGFloat.nan {
didSet {
configureBorder()
}
}
open var borderSides: BorderSides = .AllSides {
didSet {
configureBorder()
}
}
@IBInspectable var _borderSides: String? {
didSet {
borderSides = BorderSides(rawValue: _borderSides)
}
}
// MARK: - RotationDesignable
@IBInspectable open var rotate: CGFloat = CGFloat.nan {
didSet {
configureRotate()
}
}
// MARK: - ShadowDesignable
@IBInspectable open var shadowColor: UIColor? {
didSet {
configureShadowColor()
}
}
@IBInspectable open var shadowRadius: CGFloat = CGFloat.nan {
didSet {
configureShadowRadius()
}
}
@IBInspectable open var shadowOpacity: CGFloat = CGFloat.nan {
didSet {
configureShadowOpacity()
}
}
@IBInspectable open var shadowOffset: CGPoint = CGPoint(x: CGFloat.nan, y: CGFloat.nan) {
didSet {
configureShadowOffset()
}
}
// MARK: - Animatable
open var animationType: AnimationType = .none
@IBInspectable var _animationType: String? {
didSet {
animationType = AnimationType(string: _animationType)
}
}
@IBInspectable open var autoRun: Bool = true
@IBInspectable open var duration: Double = Double.nan
@IBInspectable open var delay: Double = Double.nan
@IBInspectable open var damping: CGFloat = CGFloat.nan
@IBInspectable open var velocity: CGFloat = CGFloat.nan
@IBInspectable open var force: CGFloat = CGFloat.nan
// MARK: - Lifecycle
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configureInspectableProperties()
}
open override func awakeFromNib() {
super.awakeFromNib()
configureInspectableProperties()
}
open override func layoutSubviews() {
super.layoutSubviews()
configureAfterLayoutSubviews()
autoRunAnimation()
}
// MARK: - Private
fileprivate func configureInspectableProperties() {
configureAnimatableProperties()
}
fileprivate func configureAfterLayoutSubviews() {
configureBorder()
}
}
| 21.923567 | 131 | 0.68129 |
01410b8d63b9174ddc35d4518a581d235f5af7d1 | 2,290 | //
// SceneDelegate.swift
// Prework
//
// Created by Cherrie Chang on 1/30/22.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.207547 | 147 | 0.712664 |
bfa2d7906eae3cd5848108ceff04e4a57b872e0e | 748 | //
// Mediator+Login.swift
// God
//
// Created by Limon on 27/02/2017.
// Copyright © 2017 Limon.F. All rights reserved.
//
import UIKit
import Mediator
extension Mediator {
public func loginViewController(with color: UIColor, callbackAction: @escaping (([String: Any]) -> Void)) -> UIViewController? {
let deliverParams: [String: Any] = ["color": color, "callbackAction": callbackAction]
return performTarget("Login", action: "LoginViewController", params: deliverParams, shouldCacheTarget: false) as? UIViewController
}
public func didLogin() -> Bool {
let result = performTarget("Login", action: "DidLogin", params: [:]) as? [String: Any]
return (result?["result"] as? Bool) ?? false
}
}
| 31.166667 | 138 | 0.667112 |
cc66a84bcadec204071db0331fc6bd64f4ca79f2 | 5,951 | //
// NSEntityDescription+DynamicModel.swift
// CoreStore
//
// Copyright © 2017 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import CoreData
import Foundation
// MARK: - NSEntityDescription
internal extension NSEntityDescription {
@nonobjc
internal var dynamicObjectType: DynamicObject.Type? {
guard let userInfo = self.userInfo,
let typeName = userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] as! String? else {
return nil
}
return (NSClassFromString(typeName) as! DynamicObject.Type)
}
@nonobjc
internal var coreStoreEntity: DynamicEntity? {
get {
guard let userInfo = self.userInfo,
let typeName = userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] as! String?,
let entityName = userInfo[UserInfoKey.CoreStoreManagedObjectEntityName] as! String?,
let isAbstract = userInfo[UserInfoKey.CoreStoreManagedObjectIsAbstract] as! Bool? else {
return nil
}
return DynamicEntity(
type: NSClassFromString(typeName) as! CoreStoreObject.Type,
entityName: entityName,
isAbstract: isAbstract,
versionHashModifier: userInfo[UserInfoKey.CoreStoreManagedObjectVersionHashModifier] as! String?
)
}
set {
if let newValue = newValue {
cs_setUserInfo { (userInfo) in
userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] = NSStringFromClass(newValue.type)
userInfo[UserInfoKey.CoreStoreManagedObjectEntityName] = newValue.entityName
userInfo[UserInfoKey.CoreStoreManagedObjectIsAbstract] = newValue.isAbstract
userInfo[UserInfoKey.CoreStoreManagedObjectVersionHashModifier] = newValue.versionHashModifier
}
}
else {
cs_setUserInfo { (userInfo) in
userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] = nil
userInfo[UserInfoKey.CoreStoreManagedObjectEntityName] = nil
userInfo[UserInfoKey.CoreStoreManagedObjectIsAbstract] = nil
userInfo[UserInfoKey.CoreStoreManagedObjectVersionHashModifier] = nil
}
}
}
}
@nonobjc
internal var keyPathsByAffectedKeyPaths: [KeyPathString: Set<KeyPathString>] {
get {
if let userInfo = self.userInfo,
let value = userInfo[UserInfoKey.CoreStoreManagedObjectKeyPathsByAffectedKeyPaths] {
return value as! [KeyPathString: Set<KeyPathString>]
}
return [:]
}
set {
cs_setUserInfo { (userInfo) in
userInfo[UserInfoKey.CoreStoreManagedObjectKeyPathsByAffectedKeyPaths] = newValue
}
}
}
@nonobjc
internal var customGetterSetterByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter] {
get {
if let userInfo = self.userInfo,
let value = userInfo[UserInfoKey.CoreStoreManagedObjectCustomGetterSetterByKeyPaths] {
return value as! [KeyPathString: CoreStoreManagedObject.CustomGetterSetter]
}
return [:]
}
set {
cs_setUserInfo { (userInfo) in
userInfo[UserInfoKey.CoreStoreManagedObjectCustomGetterSetterByKeyPaths] = newValue
}
}
}
// MARK: Private
// MARK: - UserInfoKey
private enum UserInfoKey {
fileprivate static let CoreStoreManagedObjectTypeName = "CoreStoreManagedObjectTypeName"
fileprivate static let CoreStoreManagedObjectEntityName = "CoreStoreManagedObjectEntityName"
fileprivate static let CoreStoreManagedObjectIsAbstract = "CoreStoreManagedObjectIsAbstract"
fileprivate static let CoreStoreManagedObjectVersionHashModifier = "CoreStoreManagedObjectVersionHashModifier"
fileprivate static let CoreStoreManagedObjectKeyPathsByAffectedKeyPaths = "CoreStoreManagedObjectKeyPathsByAffectedKeyPaths"
fileprivate static let CoreStoreManagedObjectCustomGetterSetterByKeyPaths = "CoreStoreManagedObjectCustomGetterSetterByKeyPaths"
}
private func cs_setUserInfo(_ closure: (_ userInfo: inout [AnyHashable: Any]) -> Void) {
var userInfo = self.userInfo ?? [:]
closure(&userInfo)
self.userInfo = userInfo
}
}
| 38.393548 | 136 | 0.632331 |
76ab28ee73fd92d2ec0238a979a0a4a64753ed58 | 2,604 | //
// SceneDelegate.swift
// POEPlus
//
// Created by Алексей Филатов on 29.09.2021.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
window?.frame = UIScreen.main.bounds
let mainVC = Builder.buildPassiveTreeView()
let navVC = UINavigationController(rootViewController: mainVC)
window?.rootViewController = navVC
window?.makeKeyAndVisible()
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 44.135593 | 147 | 0.711982 |
019500535c3e1b1e589ad7f85646638cdeb30475 | 1,211 | //
// KeccakExtensionsTests.swift
// web3sTests
//
// Created by Matt Marshall on 13/03/2018.
// Copyright © 2018 Argent Labs Limited. All rights reserved.
//
import XCTest
@testable import web3swift
class KeccakExtensionsTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testKeccak256Hash() {
let string = "hello world"
let hash = string.keccak256
let hexStringHash = hash.hexString
XCTAssertEqual(hexStringHash, "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad")
}
func testDataKeccak256HashHex() {
let string = "0x68656c6c6f20776f726c64"
let data = Data(hex: string)!
let keccak = data.keccak256
XCTAssertEqual(keccak.hexString, "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad")
}
func testDataKeccak256HashStr() {
let string = "hello world"
let data = string.data(using: .utf8)!
let keccak = data.keccak256
XCTAssertEqual(keccak.hexString, "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad")
}
}
| 26.911111 | 110 | 0.674649 |
e5729eb1bcf6f0f90a3a243940d09daad7693be5 | 4,122 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import Foundation
public enum GraphQLOperationType: String {
case mutation
case query
case subscription
}
public typealias GraphQLParameterName = String
/// Represents a single directive GraphQL document. Concrete types that conform to this protocol must
/// define a valid GraphQL operation document.
///
/// This type aims to provide a representation of a simple GraphQL document with its components that can be easily
/// decorated to extend the document. The components can then derive the standardized form of a GraphQL document
/// containing the query string and variables.
public protocol SingleDirectiveGraphQLDocument {
/// The `GraphQLOperationType` a concrete implementation represents the
/// GraphQL operation of the document
var operationType: GraphQLOperationType { get set }
/// The name of the document. This is useful to inspect the response, since it will
/// contain the name of the document as the key to the response value.
var name: String { get set }
/// Input parameters and its values on the GraphQL document
var inputs: [GraphQLParameterName: GraphQLDocumentInput] { get set }
/// The selection set of the document, used to specify the response data returned by the service.
var selectionSet: SelectionSet? { get set }
/// Simple constructor to be implemented by the concrete types, used by the `copy` method.
init(operationType: GraphQLOperationType,
name: String,
inputs: [GraphQLParameterName: GraphQLDocumentInput],
selectionSet: SelectionSet?)
}
// Provides default implementation
extension SingleDirectiveGraphQLDocument {
/// Method to create a deep copy of the document, useful for `ModelBasedGraphQLDocumentDecorator` decorators
/// when decorating a document and returning a new document.
public func copy(operationType: GraphQLOperationType? = nil,
name: String? = nil,
inputs: [GraphQLParameterName: GraphQLDocumentInput]? = nil,
selectionSet: SelectionSet? = nil) -> Self {
return Self.init(operationType: operationType ?? self.operationType,
name: name ?? self.name,
inputs: inputs ?? self.inputs,
selectionSet: selectionSet ?? self.selectionSet)
}
/// Returns nil when there are no `inputs`. Otherwise, consolidates the `inputs`
/// into a single object that can be used for the GraphQL request.
public var variables: [String: Any]? {
if inputs.isEmpty {
return nil
}
var variables = [String: Any]()
inputs.forEach { input in
switch input.value.value {
case .object(let values):
variables.updateValue(values, forKey: input.key)
case .scalar(let value):
variables.updateValue(value, forKey: input.key)
}
}
return variables
}
/// Provides default construction of the graphQL document based on the components of the document.
public var stringValue: String {
var selectionSetString = ""
if let selectionSet = selectionSet {
selectionSetString = selectionSet.stringValue()
}
guard !inputs.isEmpty else {
return """
\(operationType.rawValue) \(name.pascalCased()) {
\(name) {
\(selectionSetString)
}
}
"""
}
let sortedInputs = inputs.sorted { $0.0 < $1.0 }
let inputTypes = sortedInputs.map { "$\($0.key): \($0.value.type)" }.joined(separator: ", ")
let inputParameters = sortedInputs.map { "\($0.key): $\($0.key)" }.joined(separator: ", ")
return """
\(operationType.rawValue) \(name.pascalCased())(\(inputTypes)) {
\(name)(\(inputParameters)) {
\(selectionSetString)
}
}
"""
}
}
| 36.157895 | 114 | 0.635856 |
2359d77d639817a838b841619eb7882e40fefc06 | 1,034 | //
// ContentView.swift
// CameraApp
//
// Created by Tuomas Käyhty on 07/02/2020.
// Copyright © 2020 Tuomas Käyhty. All rights reserved.
//
import SwiftUI
struct CameraButtonView: View {
@Binding var showActionSheet:Bool
var body: some View {
Button(action: {
self.showActionSheet.toggle()
}) {
RoundedRectangle(cornerRadius: 30)
.frame(width: 38, height: 38, alignment: .center)
.foregroundColor(.white)
.overlay(
RoundedRectangle(cornerRadius: 30)
.frame(width: 36, height: 36, alignment: .center)
.foregroundColor(Color.init(red: 232/255, green: 233/255, blue: 231/255))
.overlay(
Image(systemName: "camera.fill")
.foregroundColor(.black))
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
CameraButtonView(showActionSheet: .constant(false))
.previewLayout(.sizeThatFits)
.padding()
}
}
| 25.85 | 85 | 0.602515 |
792ffae0002638810aa1503fa03e0cbe2faea539 | 4,388 | //
// The MIT License (MIT)
//
// Copyright (c) 2017 Tommaso Madonia
//
// 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
import UIKit
import SwiftSH
class CommandViewController: UIViewController, SSHViewController {
@IBOutlet var commandTextField: UITextField!
@IBOutlet var textView: UITextView!
var command: Command!
var authenticationChallenge: AuthenticationChallenge?
var semaphore: DispatchSemaphore!
var passwordTextField: UITextField?
var requiresAuthentication = false
var hostname: String!
var port: UInt16?
var username: String!
var password: String?
override func viewDidLoad() {
super.viewDidLoad()
if self.requiresAuthentication {
if let password = self.password {
self.authenticationChallenge = .byPassword(username: self.username, password: password)
} else {
self.authenticationChallenge = .byKeyboardInteractive(username: self.username) { [unowned self] challenge in
DispatchQueue.main.async {
self.askForPassword(challenge)
}
self.semaphore = DispatchSemaphore(value: 0)
_ = self.semaphore.wait(timeout: DispatchTime.distantFuture)
self.semaphore = nil
return self.password ?? ""
}
}
}
self.textView.text = ""
self.command = Command(host: self.hostname, port: self.port ?? 22)
}
@IBAction func disconnect() {
self.command?.disconnect { [unowned self] in
self.navigationController?.popViewController(animated: true)
}
}
func performCommand(_ command: String) {
self.commandTextField.resignFirstResponder()
self.command
.connect()
.authenticate(self.authenticationChallenge)
.execute(command) { [unowned self] (command, result: String?, error) in
if let result = result {
self.textView.text = result
} else {
self.textView.text = "ERROR: \(String(describing: error))"
}
}
}
func askForPassword(_ challenge: String) {
let alertController = UIAlertController(title: "Authetication challenge", message: challenge, preferredStyle: .alert)
alertController.addTextField { [unowned self] (textField) in
textField.placeholder = challenge
textField.isSecureTextEntry = true
self.passwordTextField = textField
}
alertController.addAction(UIAlertAction(title: "OK", style: .default) { [unowned self] _ in
self.password = self.passwordTextField?.text
if let semaphore = self.semaphore {
semaphore.signal()
}
})
self.present(alertController, animated: true, completion: nil)
}
}
extension CommandViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let command = textField.text, !command.isEmpty {
self.performCommand(command)
}
return true
}
}
| 36.264463 | 125 | 0.6299 |
1eb97d9f76bf892be3e04bad34fa48ee4afc4427 | 5,956 | //
// BKReportBatch.swift
// BoundlessKit
//
// Created by Akash Desai on 3/12/18.
//
import Foundation
internal class BKReportBatch : SynchronizedDictionary<String, SynchronizedArray<BKReinforcement>>, BKData, BoundlessAPISynchronizable {
static let registerWithNSKeyed: Void = {
NSKeyedUnarchiver.setClass(BKReportBatch.self, forClassName: "BKReportBatch")
NSKeyedArchiver.setClassName("BKReportBatch", for: BKReportBatch.self)
}()
var enabled = true
var desiredMaxTimeUntilSync: Int64
var desiredMaxCountUntilSync: Int
init(timeUntilSync: Int64 = 86400000,
sizeUntilSync: Int = 10,
dict: [String: [BKReinforcement]] = [:]) {
self.desiredMaxTimeUntilSync = timeUntilSync
self.desiredMaxCountUntilSync = sizeUntilSync
super.init(dict.mapValues({ (reinforcements) -> SynchronizedArray<BKReinforcement> in
return SynchronizedArray(reinforcements)
}))
}
var storage: BKDatabase.Storage?
class func initWith(database: BKDatabase, forKey key: String) -> BKReportBatch {
let batch: BKReportBatch
if let archived: BKReportBatch = database.unarchive(key) {
batch = archived
} else {
batch = BKReportBatch()
}
batch.storage = (database, key)
return batch
}
required convenience init?(coder aDecoder: NSCoder) {
guard let dictData = aDecoder.decodeObject(forKey: "dictValues") as? Data,
let dictValues = NSKeyedUnarchiver.unarchiveObject(with: dictData) as? [String: [BKReinforcement]] else {
return nil
}
let desiredMaxTimeUntilSync = aDecoder.decodeInt64(forKey: "desiredMaxTimeUntilSync")
let desiredMaxCountUntilSync = aDecoder.decodeInteger(forKey: "desiredMaxCountUntilSync")
self.init(timeUntilSync: desiredMaxTimeUntilSync,
sizeUntilSync: desiredMaxCountUntilSync,
dict: dictValues)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(NSKeyedArchiver.archivedData(withRootObject: self.valuesForKeys.mapValues({ (synchronizedArray) -> [BKReinforcement] in
return synchronizedArray.values
})), forKey: "dictValues")
aCoder.encode(desiredMaxTimeUntilSync, forKey: "desiredMaxTimeUntilSync")
aCoder.encode(desiredMaxCountUntilSync, forKey: "desiredMaxCountUntilSync")
}
let storeGroup = DispatchGroup()
func store(_ reinforcement: BKReinforcement) {
guard enabled else {
return
}
if self[reinforcement.actionID] == nil {
self[reinforcement.actionID] = SynchronizedArray()
}
self[reinforcement.actionID]?.append(reinforcement)
BKLog.debug(confirmed: "Report #<\(count)> actionID:<\(reinforcement.actionID)> with reinforcementID:<\(reinforcement.name)>")
storeGroup.enter()
self.storage?.0.archive(self, forKey: self.storage!.1)
}
func erase() {
self.valuesForKeys = [:]
self.storage?.0.archive(self, forKey: self.storage!.1)
}
var needsSync: Bool {
guard enabled else { return false }
if count >= desiredMaxCountUntilSync {
return true
}
let timeNow = Int64(1000*Date().timeIntervalSince1970)
for reports in values {
if let startTime = reports.first?.utc,
startTime + desiredMaxTimeUntilSync <= timeNow {
return true
}
}
return false
}
func synchronize(with apiClient: BoundlessAPIClient, successful: @escaping (Bool)->Void = {_ in}) {
guard enabled else {
successful(true)
return
}
storeGroup.wait()
let reportCopy = self.valuesForKeys
let reportCount = reportCopy.values.reduce(0, {$0 + $1.count})
guard reportCount > 0 else {
successful(true)
return
}
// BKLog.debug("Sending report batch with \(reportCount) actions...")
var reportEvents = [String: [String: [[String:Any]]]]()
for (actionID, events) in reportCopy {
if reportEvents[actionID] == nil { reportEvents[actionID] = [:] }
for reinforcement in events.values {
if reportEvents[actionID]?[reinforcement.cartridgeID] == nil { reportEvents[actionID]?[reinforcement.cartridgeID] = [] }
reportEvents[actionID]?[reinforcement.cartridgeID]?.append(reinforcement.toJSONType())
}
}
var payload = apiClient.credentials.json
payload["versionId"] = apiClient.version.name
payload["reports"] = reportEvents.reduce(into: [[[String: Any]]]()) { (result, args) in
let (key, value) = args
result.append(value.map{["actionName": key, "cartridgeId": $0.key, "events": $0.value]})
}.flatMap({$0})
apiClient.post(url: BoundlessAPIEndpoint.report.url, jsonObject: payload) { response in
var success = false
defer { successful(success) }
if let errors = response?["errors"] as? [String: Any] {
BKLog.debug(error: "Sending report batch failed with error type <\(errors["type"] ?? "nil")> message <\(errors["msg"] ?? "nil")>")
return
}
for (actionID, actions) in reportCopy {
self[actionID]?.removeFirst(actions.count)
}
self.storage?.0.archive(self, forKey: self.storage!.1)
BKLog.debug(confirmed: "Sent report batch!")
success = true
return
}.start()
}
override var count: Int {
var count = 0
queue.sync {
count = values.reduce(0, {$0 + $1.count})
}
return count
}
}
| 37.225 | 146 | 0.604097 |
ccbe45ceb15a02aaf0cb248ab04053430f7e2228 | 681 | //
// UIImage+Metal.swift
// GoldenTiler
//
// Created by Alexander Kolov on 10/6/15.
// Copyright © 2015 Alexander Kolov. All rights reserved.
//
import Metal
import UIKit
public extension UIImage {
public func imageByConvertingFromCIImage(device device: MTLDevice? = nil, context: CIContext? = nil) -> UIImage? {
if CGImage != nil {
return self
}
guard let image = self.CIImage else {
return nil
}
guard let device = device ?? MTLCreateSystemDefaultDevice() else {
return nil
}
let context = context ?? CIContext(MTLDevice: device)
return UIImage(CGImage: context.createCGImage(image, fromRect: image.extent))
}
}
| 21.28125 | 116 | 0.674009 |
9c2fbe9c2de8a7fd3475ce4ed7d3487397377a9d | 978 | import Foundation
/**
Configuration options for the Customer.io SDK.
See `CustomerIO.config()` to configurate the SDK.
*/
public struct SdkConfig {
/**
Base URL to use for the Customer.io track API. You will more then likely not modify this value.
If you override this value, `Region` set when initializing the SDK will be ignored.
*/
var trackingApiUrl: String = ""
/**
Automatic tracking of push events will automatically generate `opened` and `delivered` metrics
for push notifications sent by Customer.io
*/
public var autoTrackPushEvents: Bool = true
internal var httpBaseUrls: HttpBaseUrls {
HttpBaseUrls(trackingApi: trackingApiUrl)
}
}
public protocol SdkConfigStore: AutoMockable {
var config: SdkConfig { get set }
}
// sourcery: InjectRegister = "SdkConfigStore"
// sourcery: InjectSingleton
public class InMemorySdkConfigStore: SdkConfigStore {
@Atomic public var config = SdkConfig()
}
| 27.942857 | 100 | 0.716769 |
1e0ec431cd3a54e5b561ee6b6acf25fb2bff409d | 8,279 | //
// Cacheable.swift
// Longinus
//
// Created by Qitao Yang on 2020/5/11.
//
// Copyright (c) 2020 KittenYang <[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 UIKit
/*
Represents memory cache ablity.
*/
public protocol MemoryCacheable: CacheStandard {
mutating func save(value: Value?, for key: Key, cost: Int)
}
/*
Represents disk cache ablity.
*/
public protocol DiskCacheable: CacheStandard, CacheAsyncStandard {
init?(path: String, sizeThreshold threshold: Int32)
}
/*
Represents a cache which has both disk and memory cache ablity.
*/
public protocol Cacheable {
associatedtype M: CacheStandard
associatedtype D: CacheStandard & CacheAsyncStandard where M.Key == D.Key, M.Value == D.Value
init(memoryCache: M, diskCache: D)
}
/*
Represents synchronous cache ablity standard.
*/
public protocol CacheStandard {
associatedtype Value
associatedtype Key: Hashable
func containsObject(key: Key) -> Bool
mutating func query(key: Key) -> Value?
mutating func save(value: Value?, for key: Key)
mutating func save(_ dataWork: @escaping () -> (Value, Int)?, forKey key: Key)
mutating func remove(key: Key)
mutating func removeAll()
}
/*
Represents asynchronous cache ablity standard.
*/
public protocol CacheAsyncStandard {
associatedtype Value
associatedtype Key: Hashable
func containsObject(key: Key, _ result: @escaping ((_ key: Key, _ contain: Bool) -> Void))
mutating func query(key: Key, _ result: @escaping ((_ key: Key, _ value: Value?) -> Void))
mutating func save(value: Value?, for key: Key, _ result: @escaping (()->Void))
mutating func save(_ dataWork: @escaping () -> (Value, Int)?, forKey key: Key, result: @escaping (() -> Void))
mutating func remove(key: Key, _ result: @escaping ((_ key: Key) -> Void))
mutating func removeAll(_ result: @escaping (()->Void))
}
/*
Represents cache trimable ablity.
*/
protocol AutoTrimable: class {
var countLimit: Int32 { get }
var costLimit: Int32 { get }
var ageLimit: CacheAge { get }
var autoTrimInterval: TimeInterval { get }
var shouldAutoTrim: Bool { get set }
func trimToAge(_ age: CacheAge)
func trimToCost(_ cost: Int32)
func trimToCount(_ count: Int32)
}
/*
Default method for auto trim which runs in concurrent background queue. This method repeats every `autoTrimInterval` seconds.
*/
extension AutoTrimable {
func autoTrim() {
DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime.now() + autoTrimInterval) {
self.trimToAge(self.ageLimit)
self.trimToCost(self.costLimit)
self.trimToCount(self.countLimit)
if self.shouldAutoTrim { self.autoTrim() }
}
}
}
/*
Represents the expiration strategy used in storage.
- never: The item never expires.
- seconds: The item expires after a time duration of given seconds from now.
- minutes: The item expires after a time duration of given minutes from now.
- hours: The item expires after a time duration of given hours from now.
- days: The item expires after a time duration of given days from now.
- expired: Indicates the item is already expired. Use this to skip cache.
*/
public enum CacheAge {
/// The item never expires.
case never
/// The item expires after a time duration of given seconds from now.
case seconds(Int32)
/// The item expires after a time duration of given minutes from now.
case minutes(Int32)
/// The item expires after a time duration of given hours from now.
case hours(Int32)
/// The item expires after a time duration of given days from now.
case days(Int32)
/// Indicates the item is already expired. Use this to remove cache
case expired
var isExpired: Bool {
return timeInterval <= 0
}
var timeInterval: Int32 {
switch self {
case .never: return .max
case .seconds(let seconds): return seconds
case .minutes(let minutes): return Int32(TimeConstants.secondsInOneMinute) * minutes
case .hours(let hours): return Int32(TimeConstants.secondsInOneHour) * hours
case .days(let days): return Int32(TimeConstants.secondsInOneDay) * days
case .expired: return -(.max)
}
}
struct TimeConstants {
static let secondsInOneMinute = 60
static let secondsInOneHour = 3600
static let minutesInOneHour = 60
static let hoursInOneDay = 24
static let secondsInOneDay = 86_400
}
}
/*
Cache type of a cached image.
- none: The image is not cached yet when retrieving it.
- memory: The image is cached in memory.
- disk: The image is cached in disk.
- all: The image is cached both in disk and memory.
*/
public struct ImageCacheType: OptionSet {
public let rawValue: Int
/// The image is not cached yet when retrieving it.
public static let none = ImageCacheType([])
/// The image is cached in memory.
public static let memory = ImageCacheType(rawValue: 1 << 0)
/// The image is cached in disk.
public static let disk = ImageCacheType(rawValue: 1 << 1)
/// The image is cached both in disk and memory.
public static let all: ImageCacheType = [.memory, .disk]
public init(rawValue: Int) { self.rawValue = rawValue }
}
/*
Represents the cache query result type. Used in cache query methods completion.
Capturing associated values in some cases.
*/
public enum ImageCacheQueryCompletionResult {
/// No result
case none
/// Query cache hitted in memory. storing a `UIImage`.
case memory(image: UIImage)
/// Query cache hitted in disk. storing a `Data`.
case disk(data: Data)
/// Query cache hitted both in memory and disk. storing `UIImage` and `Data`.
case all(image: UIImage, data: Data)
}
/*
Represents a cache which can store/remove/query UIImage and UIImage Data.
*/
public protocol ImageCacheable: AnyObject {
/// Query image from `memory` or `disk` and return the `ImageCacheQueryCompletionResult` by the completion handler/
/// Typically, if memory cache hitted, the completion handler will called synchronous from current thread.
/// If disk cache hitted, the completion handler will called asynchronous from a background queue.
func image(forKey key: String, cacheType: ImageCacheType, completion: @escaping (ImageCacheQueryCompletionResult) -> Void)
func isCached(forKey key: String) -> (Bool, ImageCacheType)
/// Check whether disk cache exist datas by the `key`
func diskDataExists(forKey key: String, completion: ((Bool) -> Void)?)
/// Store image or data to the memory cache or disk cache
func store(_ image: UIImage?,
data: Data?,
forKey key: String,
cacheType: ImageCacheType,
completion: (() -> Void)?)
/// Remove image or data to the memory cache or disk cache by the specific key.
func removeImage(forKey key: String, cacheType: ImageCacheType, completion: ((_ key: String) -> Void)?)
/// Remove all images or datas to the memory cache or disk cache.
func remove(_ type: ImageCacheType, completion: (() -> Void)?)
}
| 36.959821 | 126 | 0.694649 |
d9408daa354a087a4fa24983ca44213399d42c60 | 17,057 | //
// ViewController.swift
// AAChartKit-Swift
//
// Created by An An on 17/4/18.
// Copyright © 2017年 An An . All rights reserved.
//*************** ...... SOURCE CODE ...... ***************
//***...................................................***
//*** https://github.com/AAChartModel/AAChartKit ***
//*** https://github.com/AAChartModel/AAChartKit-Swift ***
//***...................................................***
//*************** ...... SOURCE CODE ...... ***************
/*
*********************************************************************************
*
* 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔
*
* Please contact me on GitHub,if there are any problems encountered in use.
* GitHub Issues : https://github.com/AAChartModel/AAChartKit-Swift/issues
* -------------------------------------------------------------------------------
* And if you want to contribute for this project, please contact me as well
* GitHub : https://github.com/AAChartModel
* StackOverflow : https://stackoverflow.com/users/12302132/codeforu
* JianShu : https://www.jianshu.com/u/f1e6753d4254
* SegmentFault : https://segmentfault.com/u/huanghunbieguan
*
*********************************************************************************
*/
import UIKit
import AAInfographics
@available(macCatalyst 13.0, *)
class BasicChartVC: UIViewController {
public var chartType: AAChartType!
public var step: Bool?
private var aaChartModel: AAChartModel!
private var aaChartView: AAChartView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
navigationController?.navigationBar.barTintColor = kRGBColorFromHex(rgbValue: 0x22324c)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
navigationController?.navigationBar.barTintColor = .white
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = kRGBColorFromHex(rgbValue: 0x22324c)
title = chartType.map { $0.rawValue }
setUpTheSwitches()
setUpTheSegmentControls()
setUpAAChartView()
}
private func setUpAAChartView() {
aaChartView = AAChartView()
let chartViewWidth = view.frame.size.width
let chartViewHeight = view.frame.size.height - 220
aaChartView!.frame = CGRect(x: 0,
y: 60,
width: chartViewWidth,
height: chartViewHeight)
view.addSubview(aaChartView!)
aaChartView!.scrollEnabled = false//Disable chart content scrolling
aaChartView!.isClearBackgroundColor = true
aaChartView!.delegate = self as AAChartViewDelegate
aaChartModel = AAChartModel()
.chartType(chartType!)
.colorsTheme(["#1e90ff","#ef476f","#ffd066","#04d69f","#25547c",])//Colors theme
.xAxisLabelsStyle(AAStyle(color: AAColor.white))
.dataLabelsEnabled(false)
.tooltipValueSuffix("℃")
.animationType(.bounce)
.touchEventEnabled(true)
.series([
AASeriesElement()
.name("Tokyo")
.data([7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6])
,
AASeriesElement()
.name("New York")
.data([0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5])
,
AASeriesElement()
.name("Berlin")
.data([0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0])
,
AASeriesElement()
.name("London")
.data([3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8])
,
])
configureTheStyleForDifferentTypeChart()
aaChartView!.aa_drawChartWithChartModel(aaChartModel!)
}
private func configureTheStyleForDifferentTypeChart() {
if (chartType == .area && step == true)
|| (chartType == .line && step == true) {
configureStepAreaChartAndStepLineChartStyle()
} else if chartType == .column
|| chartType == .bar {
configureColumnChartAndBarChartStyle()
} else if chartType == .area
|| chartType == .areaspline {
configureAreaChartAndAreasplineChartStyle()
} else if chartType == .line
|| chartType == .spline {
configureLineChartAndSplineChartStyle()
}
}
private func configureStepAreaChartAndStepLineChartStyle() {
aaChartModel!.series([
AASeriesElement()
.name("Berlin")
.data([149.9, 171.5, 106.4, 129.2, 144.0, 176.0, 135.6, 188.5, 276.4, 214.1, 95.6, 54.4])
.step(true)//Set the polyline style to a histogram, and the connection point position is left by default
,
AASeriesElement()
.name("New York")
.data([83.6, 78.8, 188.5, 93.4, 106.0, 84.5, 105.0, 104.3, 131.2, 153.5, 226.6, 192.3])
.step(true)
,
AASeriesElement()
.name("Tokyo")
.data([48.9, 38.8, 19.3, 41.4, 47.0, 28.3, 59.0, 69.6, 52.4, 65.2, 53.3, 72.2])
.step(true)
,
])
}
private func configureColumnChartAndBarChartStyle() {
aaChartModel!
.categories(["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
.legendEnabled(true)
.colorsTheme(["#fe117c","#ffc069","#06caf4","#7dffc0"])
.animationType(.easeOutCubic)
.animationDuration(1200)
}
private func configureAreaChartAndAreasplineChartStyle() {
aaChartModel!
.animationType(.easeOutQuart)
.markerSymbolStyle(.innerBlank)//Set the polyline connection point style to: white inside
.markerRadius(5)
.markerSymbol(.circle)
.categories(["Java", "Swift", "Python", "Ruby", "PHP", "Go","C", "C#", "C++", "Perl", "R", "MATLAB", "SQL"])
.legendEnabled(true)
if chartType == .areaspline {
let gradientColorDic = AAGradientColor.linearGradient(
direction: .toBottomRight,
startColor: "rgba(138,43,226,1)",
endColor: "rgba(30,144,255,1)"//Color string settings support hexadecimal and rgba types
)
aaChartModel!
.animationType(.easeFrom)//Set chart rendering animation type to EaseFrom
.series([
AASeriesElement()
.name("Tokyo Hot")
.data([0.45, 0.43, 0.50, 0.55, 0.58, 0.62, 0.83, 0.39, 0.56, 0.67, 0.50, 0.34, 0.50, 0.67, 0.58, 0.29, 0.46, 0.23, 0.47, 0.46, 0.38, 0.56, 0.48, 0.36])
.color(gradientColorDic)
,
AASeriesElement()
.name("Berlin Hot")
.data([0.38, 0.31, 0.32, 0.32, 0.64, 0.66, 0.86, 0.47, 0.52, 0.75, 0.52, 0.56, 0.54, 0.60, 0.46, 0.63, 0.54, 0.51, 0.58, 0.64, 0.60, 0.45, 0.36, 0.67])
,
AASeriesElement()
.name("New York Hot")
.data([0.46, 0.32, 0.53, 0.58, 0.86, 0.68, 0.85, 0.73, 0.69, 0.71, 0.91, 0.74, 0.60, 0.50, 0.39, 0.67, 0.55, 0.49, 0.65, 0.45, 0.64, 0.47, 0.63, 0.64])
,
AASeriesElement()
.name("London Hot")
.data([0.60, 0.51, 0.52, 0.53, 0.64, 0.84, 0.65, 0.68, 0.63, 0.47, 0.72, 0.60, 0.65, 0.74, 0.66, 0.65, 0.71, 0.59, 0.65, 0.77, 0.52, 0.53, 0.58, 0.53])
,
])
}
}
private func configureLineChartAndSplineChartStyle() {
aaChartModel!
.markerSymbolStyle(.borderBlank)//Set the polyline connection point style to: white edge
.markerRadius(6)
.categories(["Java", "Swift", "Python", "Ruby", "PHP", "Go","C", "C#", "C++", "Perl", "R", "MATLAB", "SQL"])
if chartType == .spline {
aaChartModel!
.animationType(.swingFromTo)
.series([
AASeriesElement()
.name("Tokyo")
.data([50, 320, 230, 370, 230, 400,])
,
AASeriesElement()
.name("New York")
.data([80, 390, 210, 340, 240, 350,])
,
AASeriesElement()
.name("Berlin")
.data([100, 370, 180, 280, 260, 300,])
,
AASeriesElement()
.name("London")
.data([130, 350, 160, 310, 250, 268,])
,
])
}
}
private func setUpTheSegmentControls() {
let segmentedNamesArr:[[String]]
let typeLabelNamesArr:[String]
if chartType == .column
|| chartType == .bar {
segmentedNamesArr = [
["No stacking",
"Normal stacking",
"Percent stacking"],
["Square corners",
"Rounded corners",
"Wedge"]
]
typeLabelNamesArr = [
"Stacking Type Selection",
"Corners Style Type Selection"
]
} else {
segmentedNamesArr = [
["No stacking",
"Normal stacking",
"Percent stacking"],
["Circle",
"Square",
"Diamond",
"Triangle",
"Triangle-down"]
]
typeLabelNamesArr = [
"Stacking Type Selection",
"Chart Symbol Type Selection"
]
}
for i in 0 ..< segmentedNamesArr.count {
let segment = UISegmentedControl.init(items: segmentedNamesArr[i] as [Any])
segment.frame = CGRect(x: 20,
y: 40.0 * CGFloat(i) + (view.frame.size.height - 145),
width: view.frame.size.width - 40,
height: 20)
segment.tag = i
segment.tintColor = .red
segment.selectedSegmentIndex = 0
segment.addTarget(self,
action: #selector(segmentDidSelected(segmentedControl:)),
for:.valueChanged)
view.addSubview(segment)
let subLabel = UILabel()
subLabel.font = UIFont(name: "EuphemiaUCAS", size: 12.0)
subLabel.frame = CGRect(x: 20,
y: 40 * CGFloat(i) + (view.frame.size.height - 165),
width: view.frame.size.width - 40,
height: 20)
subLabel.text = typeLabelNamesArr[i] as String
subLabel.backgroundColor = .clear
subLabel.textColor = .lightGray
view.addSubview(subLabel)
}
}
@objc func segmentDidSelected(segmentedControl:UISegmentedControl) {
let selectedSegmentIndex = segmentedControl.selectedSegmentIndex
switch segmentedControl.tag {
case 0:
let stackingArr = [
AAChartStackingType.none,
.normal,
.percent
]
aaChartModel!.stacking(stackingArr[selectedSegmentIndex])
case 1:
if chartType == .column || chartType == .bar {
let borderRadiusArr: [Float] = [0,10,100]
aaChartModel!.borderRadius(borderRadiusArr[selectedSegmentIndex])
} else {
let symbolArr = [
AAChartSymbolType.circle,
.square,
.diamond,
.triangle,
.triangleDown
]
aaChartModel!.markerSymbol(symbolArr[selectedSegmentIndex])
}
default: break
}
aaChartView!.aa_refreshChartWholeContentWithChartModel(aaChartModel!)
}
private func setUpTheSwitches() {
let nameArr: [String]
let switchWidth: CGFloat
if chartType == .column || chartType == .bar {
nameArr = [
"xReversed",
"yReversed",
"xInverted",
"Polarization",
"DataShow"
]
switchWidth = (view.frame.size.width - 40) / 5
} else {
nameArr = [
"xReversed",
"yReversed",
"xInverted",
"Polarization",
"DataShow",
"HideMarker"
]
switchWidth = (view.frame.size.width - 40) / 6
}
for i in 0 ..< nameArr.count {
let uiSwitch = UISwitch()
uiSwitch.frame = CGRect(x: switchWidth * CGFloat(i) + 20,
y: view.frame.size.height - 70,
width: switchWidth,
height: 20)
uiSwitch.isOn = false
uiSwitch.tag = i
uiSwitch.onTintColor = .red
uiSwitch.addTarget(self,
action: #selector(switchDidChange(switchView:)),
for: .valueChanged)
view.addSubview(uiSwitch)
let subLabel = UILabel()
subLabel.font = UIFont(name: "EuphemiaUCAS", size: nameArr.count == 5 ? 10.0 : 9.0)
subLabel.frame = CGRect(x: switchWidth * CGFloat(i) + 20,
y: view.frame.size.height - 45,
width: switchWidth,
height: 35)
subLabel.text = nameArr[i] as String
subLabel.backgroundColor = .clear
subLabel.textColor = .lightGray
view.addSubview(subLabel)
}
}
@objc func switchDidChange(switchView:UISwitch) {
let isOn = switchView.isOn
switch switchView.tag {
case 0: aaChartModel!.xAxisReversed(isOn)
case 1: aaChartModel!.yAxisReversed(isOn)
case 2: aaChartModel!.inverted(isOn)
case 3: aaChartModel!.polar(isOn)
case 4: aaChartModel!.dataLabelsEnabled(isOn)
case 5: aaChartModel!.markerRadius(isOn ? 0 : 5)//Polyline connection point radius length.A value of 0 is equivalent to no polyline connection point.
default:
break
}
aaChartView!.aa_refreshChartWholeContentWithChartModel(aaChartModel!)
}
private func kRGBColorFromHex(rgbValue: Int) -> (UIColor) {
return UIColor(red: ((CGFloat)((rgbValue & 0xFF0000) >> 16)) / 255.0,
green: ((CGFloat)((rgbValue & 0xFF00) >> 8)) / 255.0,
blue: ((CGFloat)(rgbValue & 0xFF)) / 255.0,
alpha: 1.0)
}
}
@available(macCatalyst 13.0, *)
extension BasicChartVC: AAChartViewDelegate {
open func aaChartViewDidFinishLoad(_ aaChartView: AAChartView) {
print("🙂🙂🙂, AAChartView Did Finished Load!!!")
}
open func aaChartView(_ aaChartView: AAChartView, moveOverEventMessage: AAMoveOverEventMessageModel) {
print(
"""
selected point series element name: \(moveOverEventMessage.name ?? "")
🔥🔥🔥WARNING!!!!!!!!!!!!!!!!!!!! Touch Event Message !!!!!!!!!!!!!!!!!!!! WARNING🔥🔥🔥
==========================================================================================
------------------------------------------------------------------------------------------
user finger moved over!!!,get the move over event message: {
category = \(String(describing: moveOverEventMessage.category))
index = \(String(describing: moveOverEventMessage.index))
name = \(String(describing: moveOverEventMessage.name))
offset = \(String(describing: moveOverEventMessage.offset))
x = \(String(describing: moveOverEventMessage.x))
y = \(String(describing: moveOverEventMessage.y))
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
"""
)
}
}
| 39.946136 | 175 | 0.472768 |
e5a7450dd16cea6d82ce07a20be0940629735ee2 | 2,791 | //
// TreeTableViewSearchBar.swift
// LTXiOSUtils
//
// Created by CoderStar on 2020/2/1.
//
import Foundation
/// 协议
public protocol TreeTableViewSearchBarDelegate: AnyObject {
/// 输入框开始进行编辑
func treeTableViewSearchBarDidBeginEditing(searchBar: TreeTableViewSearchBar)
/// 点击键盘搜索键
func treeTableViewSearchBarShouldReturn(searchBar: TreeTableViewSearchBar)
/// 实时搜索
func treeTableViewSearchBarSearhing(searchBar: TreeTableViewSearchBar)
}
public class TreeTableViewSearchBar: UIView {
public lazy var searchTextField: UITextField = {
let searchTextField = UITextField()
searchTextField.layer.cornerRadius = 5
searchTextField.placeholder = "请输入关键字进行搜索"
searchTextField.clearButtonMode = .whileEditing
searchTextField.adjustsFontSizeToFitWidth = true
searchTextField.returnKeyType = .search
searchTextField.leftViewMode = .always
searchTextField.backgroundColor = .white
searchTextField.delegate = self
searchTextField.addTarget(self, action: #selector(search), for: .editingChanged)
return searchTextField
}()
public weak var delegate: TreeTableViewSearchBarDelegate?
public var text: String? {
return searchTextField.text
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
private func setupView() {
backgroundColor = UIColor(hexString: "#eeeeee")
addSubview(searchTextField)
searchTextField.frame = CGRect(x: 5, y: 5, width: frame.size.width - 10, height: frame.size.height - 10)
searchTextField.leftView = getLeftView(height: frame.size.height - 10)
}
private func getLeftView(height: CGFloat) -> UIView {
let button = UIButton(type: .custom)
button.isUserInteractionEnabled = false
button.frame = CGRect(x: 0, y: 0, width: height, height: height)
button.contentEdgeInsets = UIEdgeInsets(top: height / 4, left: height / 4, bottom: height / 4, right: height / 4)
button.setImage("TreeTableView_search".imageOfLTXiOSUtilsComponent, for: .normal)
return button
}
}
extension TreeTableViewSearchBar: UITextFieldDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
delegate?.treeTableViewSearchBarDidBeginEditing(searchBar: self)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
delegate?.treeTableViewSearchBarShouldReturn(searchBar: self)
textField.resignFirstResponder()
return true
}
@objc
private func search() {
delegate?.treeTableViewSearchBarSearhing(searchBar: self)
}
}
| 32.835294 | 121 | 0.698674 |
11284be57183f4227d32c95803019792a18c9af7 | 633 | //
// AppSymbolNameType.swift
// MNkSupportUtilities
//
// Created by Malith Nadeeshan on 7/23/20.
//
import Foundation
public struct AppSymbolNameType: RawRepresentable, Equatable, Hashable, Comparable {
public var rawValue: String
public var hashValue: Int {
return rawValue.hashValue
}
public static func < (lhs: AppSymbolNameType, rhs: AppSymbolNameType) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
}
public protocol AppSymbolNames {}
extension AppSymbolNameType: AppSymbolNames {}
| 21.1 | 85 | 0.674566 |
f422718c2cb98f5402ff6c487732b5b1688fed5d | 5,751 | //
// Copyright © FINN.no AS, Inc. All rights reserved.
//
import UIKit
public protocol MarketsGridViewDelegate: AnyObject {
func marketsGridView(_ marketsGridView: MarketsGridView, didSelectItemAtIndex index: Int)
}
public protocol MarketsGridViewDataSource: AnyObject {
func numberOfItems(inMarketsGridView marketsGridView: MarketsGridView) -> Int
func marketsGridView(_ marketsGridView: MarketsGridView, modelAtIndex index: Int) -> MarketsGridViewModel
}
public class MarketsGridView: UIView {
// MARK: - Internal properties
@objc private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: MarketsGridViewFlowLayout())
collectionView.delegate = self
collectionView.dataSource = self
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .clear
return collectionView
}()
private weak var delegate: MarketsGridViewDelegate?
private weak var dataSource: MarketsGridViewDataSource?
// MARK: - Setup
public init(frame: CGRect = .zero, delegate: MarketsGridViewDelegate, dataSource: MarketsGridViewDataSource) {
super.init(frame: frame)
self.delegate = delegate
self.dataSource = dataSource
setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
collectionView.register(MarketsGridViewCell.self)
addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: topAnchor),
collectionView.bottomAnchor.constraint(equalTo: bottomAnchor),
collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
// MARK: - Functionality
public func reloadData() {
collectionView.reloadData()
}
public func calculateSize(constrainedTo width: CGFloat) -> CGSize {
let size = itemSize(for: width)
let line = lineSpacing(for: width)
let inst = insets(for: width)
let rows = numberOfRows(for: width)
let height = (size.height * CGFloat(rows)) + (line * CGFloat(rows - 1)) + inst.top + inst.bottom
return CGSize(width: width, height: height)
}
// MARK: - Private
private func numberOfRows(for viewWidth: CGFloat) -> Int {
guard let modelsCount = dataSource?.numberOfItems(inMarketsGridView: self) else {
return 0
}
return Int(ceil(Double(modelsCount) / Double(MarketsGridViewLayoutConfiguration(width: viewWidth).itemsPerRow)))
}
private func itemSize(for viewWidth: CGFloat) -> CGSize {
let screenWidth = MarketsGridViewLayoutConfiguration(width: viewWidth)
let itemSize = CGSize(width: viewWidth / screenWidth.itemsPerRow - screenWidth.sideMargins - screenWidth.interimSpacing, height: screenWidth.itemHeight)
return itemSize
}
private func insets(for viewWidth: CGFloat) -> UIEdgeInsets {
let screenWidth = MarketsGridViewLayoutConfiguration(width: viewWidth)
return screenWidth.edgeInsets
}
private func lineSpacing(for viewWidth: CGFloat) -> CGFloat {
let screenWidth = MarketsGridViewLayoutConfiguration(width: viewWidth)
return screenWidth.lineSpacing
}
private func interimSpacing(for viewWidth: CGFloat) -> CGFloat {
let screenWidth = MarketsGridViewLayoutConfiguration(width: viewWidth)
return screenWidth.interimSpacing
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension MarketsGridView: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return itemSize(for: bounds.width)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return insets(for: bounds.width)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return lineSpacing(for: bounds.width)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return interimSpacing(for: bounds.width)
}
}
// MARK: - UICollectionViewDataSource
extension MarketsGridView: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource?.numberOfItems(inMarketsGridView: self) ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeue(MarketsGridViewCell.self, for: indexPath)
if let model = dataSource?.marketsGridView(self, modelAtIndex: indexPath.row) {
cell.model = model
}
return cell
}
}
// MARK: - UICollectionViewDelegate
extension MarketsGridView: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.marketsGridView(self, didSelectItemAtIndex: indexPath.row)
}
}
| 36.398734 | 182 | 0.721092 |
0a1affb209977e9641de0e6c485b11738e22be1a | 2,601 | //
// TextTweakTableViewCell
// Copyright (c) 2016 Just Eat Holding Ltd. All rights reserved.
//
import UIKit
class TextTweakTableViewCell: UITableViewCell, TweakViewControllerCell, UITextFieldDelegate {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var title: String? {
get {
return textLabel?.text
}
set {
textLabel?.text = newValue
}
}
var desc: String? {
get {
return detailTextLabel?.text
}
set {
detailTextLabel?.text = newValue
}
}
var value: TweakValue = "" {
didSet {
textField.text = value.description
textField.sizeToFit()
if textField.bounds.width > bounds.width / 2.0 {
textField.bounds.size = CGSize(width: bounds.width / 2.0,
height: textField.bounds.size.height)
}
}
}
weak var delegate: TweakViewControllerCellDelegate?
var keyboardType: UIKeyboardType {
get {
return .default
}
}
lazy var textField: UITextField! = {
let textField = UITextField()
textField.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
textField.addTarget(self, action: #selector(textEditingDidEnd), for: .editingDidEnd)
textField.textColor = UIColor.darkGray
textField.keyboardType = self.keyboardType
textField.returnKeyType = .done
textField.textAlignment = .right
textField.borderStyle = .none
textField.delegate = self
self.accessoryView = textField
self.selectionStyle = .none
return textField
}()
@objc func textDidChange() {
guard let text = textField.text else { return }
if let int = Int(text) {
value = int
}
else if let double = Double(text) {
value = double
}
else if let float = Float(text) {
value = float
}
else {
value = text
}
}
@objc func textEditingDidEnd() {
delegate?.tweakConfigurationCellDidChangeValue(self)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(true)
return true
}
}
| 27.378947 | 93 | 0.571319 |
d964c66fbe267ab9db12a700452ff0985f50de7a | 3,930 | // Copyright (c) 2020 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Fluent
import FluentSQL
struct CreateBuild: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
if let sql = database as? SQLDatabase {
return sql.raw("""
CREATE TABLE builds (
id text,
day date NOT NULL,
project_name text NOT NULL,
machine_name text NOT NULL,
schema text NOT NULL,
build_status text NOT NULL,
start_timestamp timestamp with time zone NOT NULL,
end_timestamp timestamp with time zone NOT NULL,
compilation_end_timestamp timestamp with time zone NOT NULL,
start_timestamp_microseconds double precision NOT NULL,
end_timestamp_microseconds double precision NOT NULL,
compilation_end_timestamp_microseconds double precision NOT NULL,
duration double precision NOT NULL,
compilation_duration double precision NOT NULL,
warning_count integer NOT NULL,
error_count integer NOT NULL,
tag text NOT NULL,
is_ci boolean NOT NULL,
user_id text NOT NULL,
user_id_256 text NOT NULL,
category text NOT NULL,
compiled_count integer NOT NULL,
was_suspended boolean NOT NULL,
PRIMARY KEY (id, day)
) PARTITION BY LIST (day);
""").run()
}
return database.schema("builds")
.field("id", .string, .identifier(auto: false))
.field("project_name", .string, .required)
.field("machine_name", .string, .required)
.field("schema", .string, .required)
.field("build_status", .string, .required)
.field("start_timestamp", .datetime, .required)
.field("end_timestamp", .datetime, .required)
.field("compilation_end_timestamp", .datetime, .required)
.field("start_timestamp_microseconds", .double, .required)
.field("end_timestamp_microseconds", .double, .required)
.field("compilation_end_timestamp_microseconds", .double, .required)
.field("duration", .double, .required)
.field("compilation_duration", .double, .required)
.field("warning_count", .int32, .required)
.field("error_count", .int32, .required)
.field("tag", .string, .required)
.field("is_ci", .bool, .required)
.field("user_id", .string, .required)
.field("user_id_256", .string, .required)
.field("category", .string, .required)
.field("compiled_count", .int32, .required)
.field("was_suspended", .bool, .required)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema("builds").delete()
}
}
| 46.235294 | 85 | 0.594911 |
010c754911e07b0c5b72eb461a3eea21f8951cb0 | 2,294 | //
// Copyright 2021 Adobe. All rights reserved.
// This file is licensed to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
// OF ANY KIND, either express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
import AEPAssurance
import AEPCore
import AEPEdgeIdentity
import AEPServices
import Compression
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate {
// TODO: Set up the Environment File ID from your Launch property for the preferred environment
private let LAUNCH_ENVIRONMENT_FILE_ID = ""
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
MobileCore.setLogLevel(.trace)
MobileCore.configureWith(appId: LAUNCH_ENVIRONMENT_FILE_ID)
MobileCore.registerExtensions([Identity.self, Assurance.self])
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 48.808511 | 179 | 0.763731 |
6429ef99ebebbf68a6c66c91ad717a7584b4584c | 2,631 | //
// Token.swift
// Mapper
//
// Created by LZephyr on 2017/9/23.
// Copyright © 2017年 LZephyr. All rights reserved.
//
import Foundation
// MARK: - 词法单元类型
enum TokenType {
case unknown // 未知类型
case endOfFile // 文件结束
case ocProtocol // @protocol
case interface // @interface
case implementation // @implementation
case end // @end
case statical // 静态声明关键字: static
case name // 名称 (包括变量、类名、方法等所有名称)
case leftParen // 左圆括号: (
case rightParen // 右圆括号: )
case leftSquare // 左方括号: [
case rightSquare // 右方括号: ]
case leftBrace // 左大括号: {
case rightBrace // 右大括号: }
case leftAngle // 左尖括号: <
case rightAngle // 右尖括号: >
case colon // 冒号: :
case comma // 逗号: ,
case semicolon // 分号: ;
case equal // 等号: =
case underline // 下划线: _
case plus // 加号: +
case minus // 减号: -
case asterisk // 星号: *
case doubleQuote // 双引号: "
case backslash // 反斜线: \
case caret // 脱字符: ^
case dot // 点号: .
case at // @
case rightArrow // 箭头: ->
// MARK: swift特有符号
case cls // swift的class关键字
case proto // swift的protocol关键字
case exten // swift的extension关键字
case structure // swift的struct关键字
case function // swift的func关键字
case autoclosure // @autoclosure
case escaping // @escaping
case `init` // init
case `inout` // inout
case `throw` // throws、rethrows
case accessControl // 访问控制符: open、public、internal, fileprivate、private
}
// MARK: - 词法单元
struct Token {
var type: TokenType // 词法单元类型
var text: String // 词法单元的值
init(type: TokenType, text: String) {
self.type = type
self.text = text
}
}
extension Token: Equatable {
static func ==(lhs: Token, rhs: Token) -> Bool {
if lhs.type == .name && rhs.type == .name {
return lhs.text == rhs.text
} else {
return lhs.type == rhs.type
}
}
}
extension Token: CustomStringConvertible {
var description: String {
return "\(text)"
}
}
extension Array where Element == Token {
/// 将Token数组中每一个Token的text连接起来
func joinedText(separator: String) -> String {
let texts = self.map { $0.text }
return texts.joined(separator: separator)
}
}
| 27.694737 | 77 | 0.510072 |
e5a749802d5bd3e51211796871d91f64a66ccd50 | 368 | //
// UIStackView+Utils.swift
// CIFilter.io
//
// Created by Noah Gilmore on 12/2/18.
// Copyright © 2018 Noah Gilmore. All rights reserved.
//
import UIKit
extension UIStackView {
func removeAllArrangedSubviews() {
for view in self.arrangedSubviews {
removeArrangedSubview(view)
view.removeFromSuperview()
}
}
}
| 19.368421 | 55 | 0.641304 |
fc647c4374bcf3742f1174de3f7eccb0cc39a3ae | 522 | //
// SaintService.swift
// Ichthys Calendar
//
// Created by Viktor on 11.11.2020.
//
import Foundation
import Combine
protocol SaintService {
var apiSession: APIService { get }
func getCertainSaintData(from certainSaint: Int) -> AnyPublisher<Saint, APIError>
}
extension SaintService {
func getCertainSaintData(from certainSaint: Int) -> AnyPublisher<Saint, APIError> {
return apiSession.request(with: CalendarEndpoint.certainSaint(id: certainSaint))
.eraseToAnyPublisher()
}
}
| 23.727273 | 88 | 0.718391 |
7a9db29d6a08d7082730a144b0fb586e28b3ede6 | 7,125 | //
// AddIngredientViewController.swift
// Food-Doods-Prototype
//
// Created by Wren Liang on 2020-04-07.
// Copyright © 2020 Wren Liang. All rights reserved.
//
import Foundation
import UIKit
class AddIngredientViewController: UIViewController {
var myView: UIView!
var nameTextField: UITextField!
var amountTextField: UITextField!
var expiryPicker: UIPickerView!
var locationPicker: UIPickerView!
var expiryController: ExpiryPickerController!
var locationController: LocationPickerController!
var addDelegate: AddIngredientDelegate?
// MARK: Pls use this Alan
func scheduleNotification(for seconds: Int, item: Item) {
let content = UNMutableNotificationContent()
content.title = "\(item.name) is expiring today!"
content.body = "Be sure to eat your \(Int(item.amount))g of \(item.name) today!"
content.sound = UNNotificationSound.default
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(seconds), repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let newView = AddIngredientView()
newView.addButton.addTarget(self, action: #selector(addPressed), for: .touchUpInside)
newView.dismissButton.addTarget(self, action: #selector(dismissPressed), for: .touchUpInside)
nameTextField = newView.ingredientNameTextField
amountTextField = newView.amountTextField
// MARK: ExpiryPicker Delegation Setup
let expiryNums = ["1", "2" , "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"]
let expiryVals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
let expiryUnits = ["week(s)", "day(s)", "sec (DEMO)"]
let expiryUnitVals = [1*60*24*7, 1*60*24, 1]
let expiryNumController = ExpiryPickerController(numDisplay: expiryNums, numVal: expiryVals, unitDisplay: expiryUnits, unitVal: expiryUnitVals)
newView.expiryNumPicker.delegate = expiryNumController
newView.expiryNumPicker.dataSource = expiryNumController
newView.expiryNumPicker.reloadAllComponents()
// MARK: LocationPicker Delegation Setup
let locations = [ "Pantry", "Fridge", "Freeze"]
let locVals = [FoodLocation.pantry, FoodLocation.fridge, FoodLocation.freeze]
let locationPickerController = LocationPickerController(display: locations, val: locVals)
newView.locationPicker.delegate = locationPickerController
newView.locationPicker.dataSource = locationPickerController
newView.locationPicker.reloadAllComponents()
addChild(expiryNumController)
addChild(locationPickerController)
expiryController = expiryNumController
locationController = locationPickerController
expiryPicker = newView.expiryNumPicker
locationPicker = newView.locationPicker
self.view = newView
myView = newView
}
@objc func addPressed() {
guard let name = nameTextField.text, let amountText = amountTextField.text else { return }
guard let amount = Int(amountText) else { return }
let location = locationController.locValue[locationPicker.selectedRow(inComponent: 0)]
let expiryVal = expiryController.numVal[expiryPicker.selectedRow(inComponent: 0)]
let expiryMultiple = expiryController.unitVal[expiryPicker.selectedRow(inComponent: 1)]
var expires = 0
var shelfLife = 1
if expiryMultiple == 1 {
// seconds, leave at 0 days
} else if expiryMultiple == 1*60*24 {
//days
expires = expiryVal
shelfLife = expiryVal
} else {
//weeks
expires = expiryVal * 7
shelfLife = expiryVal * 7
}
let image = UIImage(named: name.lowercased()) ?? UIImage(named: "groceries")
let newItem = Item(name: name, image: image, location: location, amount: Double(amount), expires: expires, shelfLife: shelfLife)
if let delegate = addDelegate {
delegate.addNewLocalIngredient(item: newItem)
scheduleNotification(for: expiryVal * expiryMultiple, item: newItem)
dismiss(animated: true, completion: {})
}
}
@objc func dismissPressed() {
dismiss(animated: true, completion: {})
}
}
// MARK: - Picker View Delegate
class ExpiryPickerController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
var numDisplay: [String]
var numVal: [Int]
var unitDisplay: [String]
var unitVal: [Int]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return numDisplay.count
} else {
return unitDisplay.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return numDisplay[row]
} else {
return unitDisplay[row]
}
}
// MARK: - UIViewController Init Stuff
init(numDisplay: [String], numVal: [Int], unitDisplay: [String], unitVal: [Int]) {
self.numDisplay = numDisplay
self.numVal = numVal
self.unitDisplay = unitDisplay
self.unitVal = unitVal
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class LocationPickerController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
var locDisplay: [String]
var locValue: [FoodLocation]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return locDisplay.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return locDisplay[row]
}
// MARK: - UIViewController Init Stuff
init(display: [String], val: [FoodLocation]) {
self.locDisplay = display
self.locValue = val
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.450704 | 151 | 0.627368 |
485ba8c53a33ce5e064038b49640a1f41ba0bd8d | 1,283 | import UIKit
/// Can perform spring animations with different options
public struct SpringAnimator {
// MARK: Public properties
public let duration: TimeInterval
public let delay: TimeInterval
public let springDamping: CGFloat
public let initialSpringVelocity: CGFloat
public let options: UIView.AnimationOptions
// MARK: Initializers
public init(duration: TimeInterval = 0.5,
delay: TimeInterval = 0,
springDamping: CGFloat = 0.66,
initialSpringVelocity: CGFloat = 0.5,
options: UIView.AnimationOptions = []) {
self.duration = duration
self.delay = delay
self.springDamping = springDamping
self.initialSpringVelocity = initialSpringVelocity
self.options = options
}
}
extension SpringAnimator: CanAnimate {
public func animate(_ animations: @escaping () -> (), completion: (() -> ())?) {
UIView.animate(withDuration: duration,
delay: delay,
usingSpringWithDamping: springDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: animations) { _ in
completion?()
}
}
}
| 32.897436 | 84 | 0.611068 |
696b5cb169b510b0eb376f35e70f7a442217b5fb | 974 | //
// TabPageViewTests.swift
// TabPageViewTests
//
// Created by apple on 2018/7/3.
// Copyright © 2018年 apple. All rights reserved.
//
import XCTest
@testable import TabPageView
class TabPageViewTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.324324 | 111 | 0.635524 |
8f2a997988c46f0a450d35c80f4f597a6b26e995 | 2,824 | import Foundation
public struct StateTransition<State> {
let currentStateMatches: (State) -> Bool
let nextState: State
fileprivate init(currentStateCondition: @escaping (State) -> Bool, nextState: State) {
self.currentStateMatches = currentStateCondition
self.nextState = nextState
}
}
public struct TypedStateTransition<T, State> {
let stateTransition: StateTransition<State>
let inputId: String
fileprivate init(_ input: BaseInput<T>, transition: StateTransition<State>) {
self.inputId = input.id
self.stateTransition = transition
}
var typeErasedTransition: TypeErasedStateTransition<State> {
return TypeErasedStateTransition(inputId, transition: stateTransition)
}
}
public struct TypeErasedStateTransition<State> {
let stateTransition: StateTransition<State>
let inputId: String
func initialStateMatches(_ state: State) -> Bool {
return stateTransition.currentStateMatches(state)
}
fileprivate init(_ inputId: String, transition: StateTransition<State>) {
self.inputId = inputId
self.stateTransition = transition
}
}
public struct MappedStateTransition<State> {
let erasedTransition: TypeErasedStateTransition<State>
let effectWithArguments: (Any, StateMachine<State>) throws -> (() -> Void)
fileprivate init(erasedTransition: TypeErasedStateTransition<State>,
effectWithArguments: @escaping (Any, StateMachine<State>) throws -> (() -> Void)) {
self.erasedTransition = erasedTransition
self.effectWithArguments = effectWithArguments
}
}
infix operator => : MultiplicationPrecedence
infix operator | : AdditionPrecedence
public func => <State: Equatable>(state: State, nextState: State) -> StateTransition<State> {
return { $0 == state } => nextState
}
public func => <State>(condition: @escaping (State) -> Bool, nextState: State) -> StateTransition<State> {
return StateTransition(currentStateCondition: condition, nextState: nextState)
}
public func |<T, State: Equatable>(input: BaseInput<T>, transition: StateTransition<State>) -> TypedStateTransition<T, State> {
return TypedStateTransition(input, transition: transition)
}
public func |<T, State: Equatable>(typedTransition: TypedStateTransition<T, State>, effect: EffectWrapper<T, State>) -> MappedStateTransition<State> {
let typeErasedTransition = typedTransition.typeErasedTransition
let effectWithArguments: (Any, StateMachine<State>) throws -> (() -> Void) = { arg, sm in
guard let arg = arg as? T else { throw MappingError.invalidArgumentType }
return {
effect.effect?(arg, sm)
}
}
return MappedStateTransition(erasedTransition: typeErasedTransition, effectWithArguments: effectWithArguments)
}
| 36.205128 | 150 | 0.71813 |
14d03534dfc2a9ef73032e07ec03ad14f93ff135 | 9,038 | //
// Numeric+Extensions.swift
// FoundationExtensions
//
// Created by Luiz Barbosa on 11.10.18.
// Copyright © 2018 Lautsprecher Teufel GmbH. All rights reserved.
//
import Foundation
// MARK: - Interpolation & Progress for Floating Points
extension BinaryFloatingPoint {
/// Linear Interpolation between two floating-point numbers of same type
/// (https://en.wikipedia.org/wiki/Linear_interpolation)
/// Usage:
/// assert(Double.linearInterpolation(minimum: 0.0, maximum: 10.0, percentage: 0.5) == 5.0)
/// assert(Double.linearInterpolation(minimum: 1.0, maximum: 2.0, percentage: 0.5) == 1.5)
/// assert(Double.linearInterpolation(minimum: 1.0, maximum: 3.0, percentage: 0.2) == 1.4)
///
/// - Parameters:
/// - minimum: lower number
/// - maximum: greater number
/// - percentage: point in interpolation where the result should be, from 0.0 to 1.0
/// - Returns: the normalized number between maximum and minimum, given the percentage progress
public static func linearInterpolation(minimum: Self, maximum: Self, percentage: Self) -> Self {
(percentage * (maximum - minimum)) + minimum
}
/// Linear Progress between two floating-point numbers of same type
/// It's the dual of Linear Interpolation, for a value we want the percentage, not the opposite.
/// Usage:
/// assert(Double.linearProgress(minimum: 0.0, maximum: 10.0, current: 5.0) == 0.5)
/// assert(Double.linearProgress(minimum: 1.0, maximum: 2.0, current: 1.5) == 0.5)
/// assert(Double.linearProgress(minimum: 1.0, maximum: 3.0, current: 1.4) == 0.2)
/// assert(Double.linearProgress(minimum: 1.0, maximum: 3.0, current: 3.5) == 1.0)
/// assert(Double.linearProgress(minimum: 1.0, maximum: 3.0, current: 3.5, constrainedToValidPercentage: false) == 1.25)
///
/// - Parameters:
/// - minimum: lower number
/// - maximum: greater number
/// - current: point in interpolation where the result should be, from minimum to maximum
/// - constrainedToValidPercentage: constrains the result between 0% and 100%
/// - Returns: the percentage representing the progress that `current` value travelled from `minimum` to `maximum`
public static func linearProgress(minimum: Self, maximum: Self, current: Self, constrainedToValidPercentage: Bool = true) -> Self {
assert(maximum > minimum, "On function linearProgress, maximum value \(maximum) should be greater than minimum value \(minimum)")
let value = constrainedToValidPercentage
? current.clamped(to: minimum...maximum)
: current
return (value - minimum) / (maximum - minimum)
}
/// Combined operation of `linearProgress` and `linearInterpolation`.
///
/// First gets the progress of `current` between `minimum` and `maximum`, optionally
/// `constrainedToValidPercentage`, then interpolates this onto the bracket defined by
/// `lowerBound` and `upperBound`.
/// - Parameters:
/// - minimum: Absolute minimum value for the progress calculation.
/// - maximum: Absolute maximum value for the progress calculation.
/// - current: Absolute current value for the progress calculation.
/// - constrainedToValidPercentage: Determines if percentage is clamped to `0...1`.
/// - lowerBound: Absolute lower bound of the interpolation bracket.
/// - upperBound: Absolute upper bound of the interpolation bracket.
/// - Returns: The absolute value returned by using the calculated percentage as `current` for
/// `linearInterpolation`.
public static func interpolateProgress(
minimum: Self,
maximum: Self,
current: Self,
constrainedToValidPercentage: Bool = true,
ontoBracketWith lowerBound: Self,
upperBound: Self) -> Self {
let percentage = linearProgress(
minimum: minimum,
maximum: maximum,
current: current,
constrainedToValidPercentage: constrainedToValidPercentage)
let interpolation = linearInterpolation(
minimum: lowerBound,
maximum: upperBound,
percentage: percentage)
return interpolation
}
}
// MARK: - Interpolation & Progress for Integers
extension BinaryInteger {
/// Linear Interpolation between two integer numbers of same type
/// (https://en.wikipedia.org/wiki/Linear_interpolation)
/// Usage:
/// assert(Int.linearInterpolation(minimum: 0, maximum: 10, percentage: 0.5) == 5.0)
/// assert(Int.linearInterpolation(minimum: 1, maximum: 2, percentage: 0.5) == 1.5)
/// assert(Int.linearInterpolation(minimum: 1, maximum: 3, percentage: 0.2) == 1.4)
///
/// - Parameters:
/// - minimum: lower number
/// - maximum: greater number
/// - percentage: point in interpolation where the result should be, from 0.0 to 1.0
/// - Returns: the normalized number between maximum and minimum, given the percentage progress
public static func linearInterpolation(minimum: Self, maximum: Self, percentage: Double) -> Double {
Double.linearInterpolation(minimum: Double(minimum),
maximum: Double(maximum),
percentage: percentage)
}
/// Linear Progress between two integer numbers of same type
/// It's the dual of Linear Interpolation, for a value we want the percentage, not the opposite.
/// Usage:
/// assert(Int.linearProgress(minimum: 0, maximum: 10, current: 5) == 0.5)
/// assert(Int.linearProgress(minimum: 1, maximum: 2, current: 1) == 0.5)
/// assert(Int.linearProgress(minimum: 1, maximum: 3, current: 1) == 0.333)
/// assert(Int.linearProgress(minimum: 1, maximum: 3, current: 4) == 1.0)
/// assert(Int.linearProgress(minimum: 1, maximum: 3, current: 6, constrainedToValidPercentage: false) == 2.0)
///
/// - Parameters:
/// - minimum: lower number
/// - maximum: greater number
/// - current: point in interpolation where the result should be, from minimum to maximum
/// - constrainedToValidPercentage: constrains the result between 0% and 100%
/// - Returns: the percentage representing the progress that `current` value travelled from `minimum` to `maximum`
public static func linearProgress(minimum: Self, maximum: Self, current: Self, constrainedToValidPercentage: Bool = true) -> Double {
Double.linearProgress(minimum: Double(minimum),
maximum: Double(maximum),
current: Double(current),
constrainedToValidPercentage: constrainedToValidPercentage)
}
/// Combined operation of `linearProgress` and `linearInterpolation`.
///
/// First gets the progress of `current` between `minimum` and `maximum`, optionally
/// `constrainedToValidPercentage`, then interpolates this onto the bracket defined by
/// `lowerBound` and `upperBound`.
/// - Parameters:
/// - minimum: Absolute minimum value for the progress calculation.
/// - maximum: Absolute maximum value for the progress calculation.
/// - current: Absolute current value for the progress calculation.
/// - constrainedToValidPercentage: Determines if percentage is clamped to `0...1`.
/// - lowerBound: Absolute lower bound of the interpolation bracket.
/// - upperBound: Absolute upper bound of the interpolation bracket.
/// - Returns: The absolute value returned by using the calculated percentage as `current` for
/// `linearInterpolation`.
public static func interpolateProgress(
minimum: Self,
maximum: Self,
current: Self,
constrainedToValidPercentage: Bool = true,
ontoBracketWith lowerBound: Double,
upperBound: Double) -> Double {
Double.interpolateProgress(minimum: Double(minimum),
maximum: Double(maximum),
current: Double(current),
constrainedToValidPercentage: constrainedToValidPercentage,
ontoBracketWith: Double(lowerBound),
upperBound: upperBound)
}
}
extension Double {
/// Logistic Function
/// (https://en.wikipedia.org/wiki/Logistic_function)
/// It's a sigmoid curve (S shaped) with the equation
/// `f(x) = L / (1 + pow(Euler, -k * (x - x0)))`
/// - Parameters:
/// - `x`: value on X-axis
/// - `l`: the maximum value of Y-axis
/// - `k`: the logistic growth rate (steepness of the curve)
/// - `x₀`: the value of `x` when `y` is at 50% (midpoint of the curve)
/// - Returns: the value of `y` for the given `x` in this logistic function
public static func logistic(x: Double, L: Double, k: Double, x₀: Double) -> Double { // swiftlint:disable:this identifier_name
L / (1.0 + pow(M_E, -k * (x - x₀)))
}
}
| 51.352273 | 137 | 0.645718 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.