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
|
---|---|---|---|---|---|
50b279957c87187327a7f47902551f0c155c88ab | 4,376 | //
// SettingViewControllerViewController.swift
// XavBotFramework
//
// Created by Ajeet Sharma on 19/10/20.
// Copyright © 2020 Ajeet Sharma. All rights reserved.
//
import UIKit
class SettingViewControllerViewController: UIViewController {
@IBOutlet weak var channelContainer: UIView!
@IBOutlet weak var languageContainer: UIView!
@IBOutlet weak var languagelabel: UILabel!
@IBOutlet weak var channellabel: UILabel!
var languageArray = [Language]()
var languageSelected = ""
var channelSelected = ""
var NavTitleImg:UIImage = UIImage(named: "user1")!
var navTitleImgView:UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
// self.navigationItem.title = "Settings"
self.addNavTitleImage()
self.channelContainer.roundedShadowView(cornerRadius: 5, borderWidth: 1, borderColor: .darkGray)
self.languageContainer.roundedShadowView(cornerRadius: 5, borderWidth: 1, borderColor: .darkGray)
// Do any additional setup after loading the view.
}
func addNavTitleImage() {
let navHeight = self.navigationController!.navigationBar.frame.size.height - 30
let navWidth = self.navigationController!.navigationBar.frame.size.width - 50
navTitleImgView = UIImageView(frame: CGRect(x: 0, y: 0, width: navWidth, height: navHeight))
navTitleImgView?.contentMode = .scaleAspectFit
navTitleImgView?.image = self.NavTitleImg
navigationItem.titleView = navTitleImgView
}
@IBAction func channelBtnClicked(_ sender: UIButton) {
self.presentListingPopover(forChannel: true, sender: sender)
}
@IBAction func languageBtnClicked(_ sender: UIButton) {
self.presentListingPopover(forChannel: false, sender: sender)
}
func presentListingPopover(forChannel:Bool, sender: UIButton) {
// if let button = sender as? UIBarButtonItem {
let storyboard: UIStoryboard = UIStoryboard(name: "VirtualAssistantMain", bundle: nil)
let popoverContentController = storyboard.instantiateViewController(withIdentifier: "ListingPopoverViewController") as! ListingPopoverViewController
popoverContentController.modalPresentationStyle = .popover
popoverContentController.preferredContentSize = CGSize(width: 300, height: forChannel ? 100: (self.languageArray.count * 30 + 20 ))
popoverContentController.delegate = self
print(self.languageArray)
popoverContentController.languageArray = self.languageArray
popoverContentController.isChannelSelected = forChannel
if let popoverPresentationController = popoverContentController.popoverPresentationController {
popoverPresentationController.permittedArrowDirections = .up
popoverPresentationController.backgroundColor = UIColor.black.withAlphaComponent(0.65)
popoverPresentationController.sourceView = sender
// popoverPresentationController.barButtonItem = button
popoverPresentationController.delegate = self
present(popoverContentController, animated: true, completion: nil)
}
// }
}
}
extension SettingViewControllerViewController: ListingPopoverVCDelegate, UIPopoverPresentationControllerDelegate {
func didSelectectlanguage(index: Int, language: Language) {
print(language.displayName)
self.languageSelected = language.lang ?? ""
self.languagelabel.text = language.displayName
dismiss(animated: true, completion: nil)
}
func didSelectectWeb(index: Int, webName: String) {
print(webName)
self.channellabel.text = webName
self.channelSelected = webName
dismiss(animated: true, completion: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
//UIPopoverPresentationControllerDelegate
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
}
func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
return true
}
}
| 40.897196 | 160 | 0.707495 |
16d9667d96013879aaa1a6ef6f78e23c9574e431 | 4,399 | //
// AuthErrorTests.swift
// FRAuthTests
//
// Copyright (c) 2020 ForgeRock. All rights reserved.
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
import XCTest
@testable import FRAuth
class AuthErrorTests: FRAuthBaseTest {
func test_01_domain() {
XCTAssertEqual(AuthError.errorDomain, "com.forgerock.ios.frauth.authentication")
}
func test_02_invalid_token_response() {
let error = AuthError.invalidTokenResponse([:])
XCTAssertEqual(error.code, 1000006)
XCTAssertEqual(error.errorCode, 1000006)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertTrue(error.localizedDescription.hasPrefix("Invalid token response: access_token, token_type, expires_in and scope are required, but missing in the response."))
}
func test_03_invalid_callback_response() {
let error = AuthError.invalidCallbackResponse("")
XCTAssertEqual(error.code, 1000007)
XCTAssertEqual(error.errorCode, 1000007)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "Invalid callback response: ")
}
func test_04_unsupported_callback() {
let error = AuthError.unsupportedCallback("")
XCTAssertEqual(error.code, 1000008)
XCTAssertEqual(error.errorCode, 1000008)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "Unsupported callback: ")
}
func test_05_invalid_auth_service_response() {
let error = AuthError.invalidAuthServiceResponse("")
XCTAssertEqual(error.code, 1000009)
XCTAssertEqual(error.errorCode, 1000009)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "Invalid AuthService response: ")
}
func test_06_invalid_oauth2_client() {
let error = AuthError.invalidOAuth2Client
XCTAssertEqual(error.code, 1000010)
XCTAssertEqual(error.errorCode, 1000010)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "Invalid OAuth2Client: no OAuth2Client object was found")
}
func test_07_invalid_generic_type() {
let error = AuthError.invalidGenericType
XCTAssertEqual(error.code, 1000011)
XCTAssertEqual(error.errorCode, 1000011)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "Invalid generic type: Only Token, AccessToken, and FRUser are allowed")
}
func test_08_invalid_generic_type() {
var error = AuthError.userAlreadyAuthenticated(true)
XCTAssertEqual(error.code, 1000020)
XCTAssertEqual(error.errorCode, 1000020)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "User is already authenticated")
error = AuthError.userAlreadyAuthenticated(false)
XCTAssertEqual(error.code, 1000020)
XCTAssertEqual(error.errorCode, 1000020)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "User is already authenticated and has Session Token; use FRUser.currentUser.getAccessToken to obtian OAuth2 tokens")
}
func test_08_authentication_cancelled() {
let error = AuthError.authenticationCancelled
XCTAssertEqual(error.code, 1000030)
XCTAssertEqual(error.errorCode, 1000030)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "Authentication is cancelled")
}
func test_09_invalid_resume_uri() {
let error = AuthError.authenticationCancelled
XCTAssertEqual(error.code, 1000030)
XCTAssertEqual(error.errorCode, 1000030)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "Authentication is cancelled")
}
func test_10_user_authentication_required() {
let error = AuthError.userAuthenticationRequired
XCTAssertEqual(error.code, 1000035)
XCTAssertEqual(error.errorCode, 1000035)
XCTAssertNotNil(error.errorUserInfo)
XCTAssertEqual(error.localizedDescription, "All user credentials are expired or invalid; user authentication is required")
}
}
| 37.598291 | 176 | 0.709479 |
f99b09af5b0ea06977da03479b8b98f39ebf611e | 97 | @testable import NetServiceTests
import XCTest
XCTMain([
testCase(BrowserTests.allTests),
])
| 13.857143 | 35 | 0.783505 |
2169abc59e4c1cb5ceba737fa23b3ee043aa3c58 | 1,261 | //
// MailContentController.swift
// Nexmail 1.0 (28-jun-2017)
//
// Created by Alumno on 06/07/2017.
// Copyright © 2017 Alumno. All rights reserved.
//
import UIKit
class MailContentController: UIViewController {
@IBOutlet var mailContentImage: UIImageView!
@IBOutlet var mailContentTitle: UILabel!
@IBOutlet var mailContentSender: UILabel!
@IBOutlet var mailContentText: UITextView!
//OJO En lugar de copiar los arrays, mejor hacer un Siingletton (mirar los apuntes)
let mailList = ["¡Vente al Corte Inglés!", "Su seguro más barato", "Hola, soy Marta ¿Me quieres conocer?", "Trabajo final (versión definitiva 8)", "Rebaja semanal Game", "Su préstamo en 24h"]
let senderList = ["El Corte Inglés", "Axa seguros", "Chicas calientes", "Clara (Clase)", "Game", "Evo Bank"]
let senderImages = ["El Corte Inglés - logo.jpg", "Axa - logo.jpg", "Chica sexy - logo.jpg", "Persona - logo.jpg", "Game - logo.png", "Evo Bank - Logo.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
self.mailContentImage.image = UIImage.init(named:senderImages[0])
self.mailContentTitle.text = ""
self.mailContentSender.text = ""
self.mailContentTitle.text = ""
}
}
| 37.088235 | 195 | 0.666138 |
6947feb3ad751a3a1e384f56f2823af8b8d1c1ad | 4,305 | //
// MainViewController.swift
// WBPractice
//
// Created by xjc on 16/8/16.
// Copyright © 2016年 xjc. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
//tabBar.tintColor = UIColor.orangeColor()
//添加所有子控制器
addChildViewControllers()
}
//IOS后不推荐在viewDidLoad设置frame
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//添加加号按钮
setupCompseBtn()
}
/**
监听加号按钮点击
监听按钮点击的方法不能是私有方法
按钮点击事件的调用是由 运行循环 监听并且以消息机制传递的,因此,按钮监听函数不能设置为 private
*/
func composeBtnClick() {
print(__FUNCTION__)
}
//添加加号按钮
private func setupCompseBtn() {
//添加加号按钮
tabBar.addSubview(composeBtn)
//调整加号按钮的位置
let width = UIScreen.mainScreen().bounds.size.width / CGFloat(viewControllers!.count)
let rect = CGRect(x: 0, y: 0, width: width, height: 48)
//第一个参数:frame的大小
//第二个参数:x方向偏移量的大小
//第三个参数:y方向偏移量的大小
composeBtn.frame = CGRectOffset(rect, 2 * width, 0)
}
//MARK: - 添加所有子控制器
func addChildViewControllers() {
//获取json文件路径(可以通过服务器更改控制器数据)
let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)
//通过文件路径创建NSData
if let jsonPath = path {
let jsonData = NSData(contentsOfFile: jsonPath)
do {
//序列化json数据 --> Array
let dictArr = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers)
//遍历数组,动态创建控制器和设置数据
for dict in dictArr as! [[String: String]]{
addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
}
}catch{
//如果json文件动态加载控制器出错,则默认为本地创建
addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home")
addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center")
//添加一个占位控制器
addChildViewController("NullViewController", title: "", imageName: "")
addChildViewController("DiscoverTableViewController", title: "广场", imageName: "tabbar_discover")
addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile")
}
}
}
/**
初始化子控制器
- parameter childController: 需要初始化的子控制器
- parameter title: 子控制器的标题
- parameter imageName: 子控制器的图片
*/
private func addChildViewController(childControllerName: String, title: String, imageName: String) {
//动态获取命名空间
let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
//将字符串转换为类
let cls:AnyClass? = NSClassFromString(ns + "." + childControllerName)
//通过类创建对象
let vcCls = cls as! UIViewController.Type
//通过class创建对象
let vc = vcCls.init()
vc.tabBarItem.image = UIImage(named: imageName)
vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
vc.title = title
let nav = UINavigationController()
nav.addChildViewController(vc)
addChildViewController(nav)
}
//MARK: - 懒加载
private lazy var composeBtn:UIButton = {
let btn = UIButton()
//添加前景图片
btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
//添加背景图片
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
btn.addTarget(self, action: "composeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
}
| 33.372093 | 132 | 0.605807 |
8a8b4ce1e4192ab83a54cc658eba06bf729f6efd | 401 | import Foundation
import HTTP
class VersioningMiddleware: Middleware {
let version: String
init(version: String) {
self.version = version
}
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
let response = try next.respond(to: request)
response.headers["Version"] = "HelloWorld API \(version)"
return response
}
}
| 23.588235 | 86 | 0.663342 |
cc8365d9d877f33c66e9798ffcfea6b81d1477b6 | 5,985 | //
// BottomDrawerView.swift
// BottomDrawerView
//
// Created by Quentin on 2019/8/8.
// Copyright © 2019 Quentin. All rights reserved.
//
import SwiftUI
struct DrawerView<Content: View>: View {
@Binding var isShow: Bool
@State private var translation = CGSize.zero
// The default color of back layer
var backLayerColor = Color.black
// The default opacity of back layer when the drawer is pulled out
var backLayerOpacity = 0.5
// Use the default animation of back layer
var backLayerAnimation = Animation.default
// The default orientation of drawer
var drawerOrientation = Axis.Set.vertical
// The default height of drawer
// Will be used when orientation set to be VERTICAL
var drawerHeight: CGFloat?
private var computedDrawerHeight: CGFloat {
if let height = drawerHeight {
return height
}
return UIScreen.main.bounds.height / 2
}
// The default width of drawer
// Will be used when orientation set to be HORIZANTAL
var drawerWidth: CGFloat?
private var computedDrawerWidth: CGFloat {
if let width = drawerWidth {
return width
}
return UIScreen.main.bounds.width / 2
}
// The default value of corner radius of drawer view
var drawerCornerRadius: CGFloat = 20
// The default color of the background of drawer view
var drawerBackgroundColor = Color.blue
// The default animation of opening up drawer view
var drawerOutAnimation = Animation.interpolatingSpring(mass: 0.5, stiffness: 45, damping: 45, initialVelocity: 15)
var isDrawerShadowEnable = true
var drawerShadowRadius: CGFloat = 20
var content: Content
private var xOffset: CGFloat {
if drawerOrientation == Axis.Set.horizontal {
let origOffset = isShow ? -(UIScreen.main.bounds.width - computedDrawerWidth) / 2 : -(UIScreen.main.bounds.width + computedDrawerWidth) / 2
return origOffset - translation.width
}
return 0
}
private var initYOffset: CGFloat? {
if drawerOrientation == Axis.Set.vertical {
return isShow ? (UIScreen.main.bounds.height - computedDrawerHeight ) / 2 : (UIScreen.main.bounds.height + computedDrawerHeight ) / 2
}
return nil
}
private var yOffset: CGFloat {
if let y = initYOffset {
return y + translation.height
}
return 0
}
var body: some View {
ZStack {
// Implement the darken background
if isShow {
Rectangle()
.foregroundColor(backLayerColor)
.opacity(backLayerOpacity)
.animation(backLayerAnimation)
.onTapGesture {
// The default behavior of tapping on
// the back layer is dismissing the drawer
self.isShow.toggle()
}
}
VStack {
// The inner content of the drawer
// Be creative!
VStack {
Text("This is a draggable area")
}
.frame(minWidth: 0, maxWidth: .infinity)
.frame(height: 40)
.background(
RoundedRectangle(cornerRadius: drawerCornerRadius)
.stroke(lineWidth: 1)
)
.gesture(
DragGesture()
.onChanged { (value) in
self.translation = value.translation
}
.onEnded { (value) in
switch self.drawerOrientation {
case Axis.Set.vertical:
if value.translation.height > 20 {
self.isShow.toggle()
}
case Axis.Set.horizontal:
if value.translation.width < -20 {
self.isShow.toggle()
}
default:
break
}
self.translation = CGSize.zero
}
)
content
}
.frame(
width: drawerOrientation == Axis.Set.horizontal
? computedDrawerWidth
: UIScreen.main.bounds.width,
height: drawerOrientation == Axis.Set.vertical
? computedDrawerHeight
: UIScreen.main.bounds.height)
.background(drawerBackgroundColor)
.cornerRadius(drawerCornerRadius)
.shadow(radius: isDrawerShadowEnable ? drawerShadowRadius : 0)
.offset(x: xOffset, y: yOffset)
.animation(drawerOutAnimation)
}
.edgesIgnoringSafeArea(.all)
}
}
#if DEBUG
struct BottomDrawerView_Previews: PreviewProvider {
static var previews: some View {
Group {
DrawerView(isShow: .constant(false), content: SampleDrawerInnerView())
.previewDisplayName("Drawer is Closed, Vertical")
DrawerView(isShow: .constant(true), content: SampleDrawerInnerView())
.previewDisplayName("Drawer is Opened, Vertical")
// DrawerView(isShow: .constant(false), drawerOrientation: Axis.Set.horizontal)
// .previewDisplayName("Drawer is Closed, Horizontal")
//
// DrawerView(isShow: .constant(true), drawerOrientation: Axis.Set.horizontal)
// .previewDisplayName("Drawer is Opened, Horizontal")
}
}
}
#endif
| 34.2 | 151 | 0.529657 |
712500a85e8df293ecf6f75a8c327129889cf3d4 | 2,679 | //
// 🦠 Corona-Warn-App
//
import UIKit
class DeltaOnboardingV15ViewController: DynamicTableViewController, DeltaOnboardingViewControllerProtocol, ENANavigationControllerWithFooterChild, UIAdaptivePresentationControllerDelegate {
// MARK: - Attributes
var finished: (() -> Void)?
// MARK: - Initializers
init(
supportedCountries: [Country]
) {
self.viewModel = DeltaOnboardingV15ViewModel(supportedCountries: supportedCountries)
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.presentationController?.delegate = self
setupView()
setupRightBarButtonItem()
}
// MARK: - Protocol UIAdaptivePresentationControllerDelegate
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
finished?()
}
// MARK: - Protocol ENANavigationControllerWithFooterChild
func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapPrimaryButton button: UIButton) {
finished?()
}
// MARK: - Private API
private let viewModel: DeltaOnboardingV15ViewModel
private func setupRightBarButtonItem() {
let closeButton = UIButton(type: .custom)
closeButton.setImage(UIImage(named: "Icons - Close"), for: .normal)
closeButton.setImage(UIImage(named: "Icons - Close - Tap"), for: .highlighted)
closeButton.addTarget(self, action: #selector(close), for: .primaryActionTriggered)
let barButtonItem = UIBarButtonItem(customView: closeButton)
barButtonItem.accessibilityLabel = AppStrings.AccessibilityLabel.close
barButtonItem.accessibilityIdentifier = AccessibilityIdentifiers.AccessibilityLabel.close
navigationItem.rightBarButtonItem = barButtonItem
}
private func setupView() {
navigationFooterItem?.primaryButtonTitle = AppStrings.DeltaOnboarding.primaryButton
footerView?.primaryButton?.accessibilityIdentifier = AccessibilityIdentifiers.DeltaOnboarding.primaryButton
setupTableView()
}
private func setupTableView() {
view.backgroundColor = .enaColor(for: .background)
tableView.separatorStyle = .none
tableView.register(
DynamicTableViewRoundedCell.self,
forCellReuseIdentifier: CustomCellReuseIdentifiers.roundedCell.rawValue
)
dynamicTableViewModel = viewModel.dynamicTableViewModel
}
@objc
func close() {
finished?()
}
}
// MARK: - Cell reuse identifiers.
extension DeltaOnboardingV15ViewController {
enum CustomCellReuseIdentifiers: String, TableViewCellReuseIdentifiers {
case roundedCell
}
}
| 27.060606 | 189 | 0.786487 |
dbb86f8342133601df9b1c10b14f67357d3adfe6 | 9,341 | //
// Pantry.swift
// Pantry
//
// Created by Nick O'Neill on 10/29/15.
// Copyright © 2015 That Thing in Swift. All rights reserved.
//
import Foundation
/**
# Pantry
Pantry is a lightweight way to persist structs containing user data,
cached content or other relevant objects for later retrieval.
### Storage sample
```swift
let someCustomStruct = SomeCustomStruct(...)
Pantry.pack(someCustomStruct, "user_data")
```
### Retrieval sample
```swift
if let unpackedCustomStruct: SomeCustomStruct = Pantry.unpack("user_data") {
eprint("got my data out", unpackedCustomStruct)
} else {
print("there was no struct data to get")
}
```
*/
open class Pantry {
// Set to a string identifier to enable in memory mode with no persistent caching. Useful for unit testing.
public static var enableInMemoryModeWithIdentifier: String?
// MARK: pack generics
/**
Packs a generic struct that conforms to the `Storable` protocol
- parameter object: Generic object that will be stored
- parameter key: The object's key
- parameter expires: The storage expiration. Defaults to `Never`
- parameter storageType: The storage type. Defaults to `.permanent`
*/
public static func pack<T: Storable>(_ object: T, key: String, expires: StorageExpiry = .never, storageType: StorageType = .permanent) {
let warehouse = getWarehouse(key, storageType: storageType)
warehouse.write(object.toDictionary() as Any, expires: expires)
}
/**
Packs a generic collection of structs that conform to the `Storable` protocol
- parameter objects: Generic collection of objects that will be stored
- parameter key: The objects' key
- parameter storageType: The storage type. Defaults to `.permanent`
*/
public static func pack<T: Storable>(_ objects: [T], key: String, expires: StorageExpiry = .never, storageType: StorageType = .permanent) {
let warehouse = getWarehouse(key, storageType: storageType)
var result = [Any]()
for object in objects {
result.append(object.toDictionary() as Any)
}
warehouse.write(result as Any, expires: expires)
}
/**
Packs a default storage type.
- parameter object: Default object that will be stored
- parameter key: The object's key
- parameter expires: The storage expiration. Defaults to `Never`
- parameter storageType: The storage type. Defaults to `.permanent`
- SeeAlso: `StorableDefaultType`
*/
public static func pack<T: StorableDefaultType>(_ object: T, key: String, expires: StorageExpiry = .never, storageType: StorageType = .permanent) {
let warehouse = getWarehouse(key, storageType: storageType)
warehouse.write(object as Any, expires: expires)
}
/**
Packs a collection of default storage types.
- parameter objects: Collection of objects that will be stored
- parameter key: The object's key
- parameter expires: The storage expiration. Defaults to `Never`
- parameter storageType: The storage type. Defaults to `.permanent`
- SeeAlso: `StorableDefaultType`
*/
public static func pack<T: StorableDefaultType>(_ objects: [T], key: String, expires: StorageExpiry = .never, storageType: StorageType = .permanent) {
let warehouse = getWarehouse(key, storageType: storageType)
var result = [Any]()
for object in objects {
result.append(object as Any)
}
warehouse.write(result as Any, expires: expires)
}
/**
Packs a collection of optional default storage types.
- parameter objects: Collection of optional objects that will be stored
- parameter key: The object's key
- parameter expires: The storage expiration. Defaults to `Never`
- parameter storageType: The storage type. Defaults to `.permanent`
- SeeAlso: `StorableDefaultType`
*/
public static func pack<T: StorableDefaultType>(_ objects: [T?], key: String, expires: StorageExpiry = .never, storageType: StorageType = .permanent) {
let warehouse = getWarehouse(key, storageType: storageType)
var result = [Any]()
for object in objects {
result.append(object as Any)
}
warehouse.write(result as Any, expires: expires)
}
// MARK: unpack generics
/**
Unpacks a generic struct that conforms to the `Storable` protocol
- parameter key: The object's key
- parameter storageType: The storage type. Defaults to `.permanent`
- returns: T?
*/
public static func unpack<T: Storable>(_ key: String, storageType: StorageType = .permanent) -> T? {
let warehouse = getWarehouse(key, storageType: storageType)
if warehouse.cacheExists() {
return T(warehouse: warehouse)
}
return nil
}
/**
Unpacks a generic collection of structs that conform to the `Storable` protocol
- parameter key: The objects' key
- parameter storageType: The storage type. Defaults to `.permanent`
- returns: [T]?
*/
public static func unpack<T: Storable>(_ key: String, storageType: StorageType = .permanent) -> [T]? {
let warehouse = getWarehouse(key, storageType: storageType)
guard warehouse.cacheExists(),
let cache = warehouse.loadCache() as? Array<Any> else {
return nil
}
var unpackedItems = [T]()
for case let item as [String: Any] in cache {
if let unpackedItem: T = unpack(item) {
unpackedItems.append(unpackedItem)
}
}
return unpackedItems
}
/**
Unpacks a collection of default storage types.
- parameter key: The object's key
- parameter storageType: The storage type. Defaults to `.permanent`
- returns: [T]?
- SeeAlso: `StorableDefaultType`
*/
public static func unpack<T: StorableDefaultType>(_ key: String, storageType: StorageType = .permanent) -> [T]? {
let warehouse = getWarehouse(key, storageType: storageType)
guard warehouse.cacheExists(),
let cache = warehouse.loadCache() as? Array<Any> else {
return nil
}
var unpackedItems = [T]()
for case let item as T in cache {
unpackedItems.append(item)
}
return unpackedItems
}
/**
Unacks a default storage type.
- parameter key: The object's key
- parameter storageType: The storage type. Defaults to `.permanent`
- SeeAlso: `StorableDefaultType`
*/
public static func unpack<T: StorableDefaultType>(_ key: String, storageType: StorageType = .permanent) -> T? {
let warehouse = getWarehouse(key, storageType: storageType)
guard warehouse.cacheExists(),
let cache = warehouse.loadCache() as? T else {
return nil
}
return cache
}
/**
Expire a given object
- parameter key: The object's key
- parameter storageType: The storage type. Defaults to `.permanent`
*/
public static func expire(_ key: String, storageType: StorageType = .permanent) {
let warehouse = getWarehouse(key, storageType: storageType)
warehouse.removeCache()
}
/**
Deletes all the cache
- parameter storageType: The storage type. Defaults to `.permanent`
- Note: This will clear in-memory as well as JSON cache
*/
public static func removeAllCache(for storageType: StorageType = .permanent) {
///Blindly remove all the data!
MemoryWarehouse.removeAllCache(for: storageType)
JSONWarehouse.removeAllCache(for: storageType)
}
/**
Checks if an item exists for a given key
- parameter key: The object's key
- parameter storageType: The storage type. Defaults to `.permanent`
- Note: This will clear in-memory as well as JSON cache
*/
public static func itemExistsForKey(_ key: String, storageType: StorageType = .permanent) -> Bool {
let warehouse = getWarehouse(key, storageType: storageType)
return warehouse.cacheExists()
}
static func unpack<T: Storable>(_ dictionary: [String: Any], storageType: StorageType = .permanent) -> T? {
let warehouse = getWarehouse(dictionary as Any, storageType: storageType)
return T(warehouse: warehouse)
}
static func getWarehouse(_ forKey: String, storageType: StorageType) -> Warehouseable & WarehouseCacheable {
if let inMemoryIdentifier = Pantry.enableInMemoryModeWithIdentifier {
return MemoryWarehouse(key: forKey, inMemoryIdentifier: inMemoryIdentifier)
} else {
return JSONWarehouse(storageType: storageType, key: forKey)
}
}
static func getWarehouse(_ forContext: Any, storageType: StorageType) -> Warehouseable {
if let inMemoryIdentifier = Pantry.enableInMemoryModeWithIdentifier {
return MemoryWarehouse(context: forContext, inMemoryIdentifier: inMemoryIdentifier)
} else {
return JSONWarehouse(storageType: storageType, context: forContext)
}
}
}
| 35.249057 | 155 | 0.648646 |
fcbbf2678ea0c7323d238f32b918e9fb29d1b950 | 958 | //
// ManageActiveSleep.swift
// Rise
//
// Created by Vladimir Korolev on 06.12.2021.
// Copyright © 2021 VladimirBrejcha. All rights reserved.
//
import Foundation
/*
* Provides start and end dates for active sleep (if exists)
* Provides method to end sleep and therefore invalidates sleep dates
*/
protocol ManageActiveSleep: AnyObject {
var sleepStartedAt: Date? { get set }
var alarmAt: Date? { get set }
func endSleep()
}
final class ManageActiveSleepImpl: ManageActiveSleep {
private let userData: UserData
var sleepStartedAt: Date? {
get { userData.activeSleepStartDate }
set { userData.activeSleepStartDate = newValue }
}
var alarmAt: Date? {
get { userData.activeSleepEndDate }
set { userData.activeSleepEndDate = newValue }
}
init(_ userData: UserData) {
self.userData = userData
}
func endSleep() {
userData.invalidateActiveSleep()
}
}
| 22.809524 | 69 | 0.672234 |
906b02dd9409d193d6db86cec380ab60e78edb1f | 6,789 | //
// HomeViewController.swift
// PartnerUp
//
// Created by Joshua Chuang on 1/3/21.
//
import UIKit
import FirebaseAuth
class HomeViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating {
// MARK: Outlet variables
@IBOutlet weak var shapeTableView: UITableView!
// MARK: Other Variables
let searchController = UISearchController()
var shapeList = [Shape]()
var filteredShapes = [Shape]()
var placeholderText = "Graduated from Lorem Ipsum high school. Specialties include dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. Achievements include incididunt ut labore award, President of dolore magna club."
// MARK: Loading function
override func viewDidLoad() {
super.viewDidLoad()
validateAuth()
shapeList = initList()
let nib = UINib(nibName: "HomeTableViewCell", bundle: nil)
shapeTableView.register(nib, forCellReuseIdentifier: "HomeTableViewCell")
shapeTableView.delegate = self
shapeTableView.dataSource = self
initSearchController()
}
// MARK: Action functions
/// Customizes the Search Bar
func initSearchController() {
searchController.loadViewIfNeeded()
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.enablesReturnKeyAutomatically = false
searchController.searchBar.returnKeyType = UIReturnKeyType.done
definesPresentationContext = true
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchController.searchBar.scopeButtonTitles = ["All", "Computer Science", "Engineering", "Business", "Biology"]
searchController.searchBar.delegate = self
}
/// Creates a fixed list of users that shows up in the Home Page
func initList() -> [Shape] {
var tempList: [Shape] = []
let josh = Shape(name: "Joshua Chuang", imageName: "joshImage", major: "Computer Science", city: "Cypress", bio: placeholderText)
tempList.append(josh)
let frank = Shape(name: "Frank Deeprompt", imageName: "joshImage", major: "Engineering", city: "Cypress", bio: placeholderText)
tempList.append(frank)
let david = Shape(name: "David Lee", imageName: "joshImage", major: "Business", city: "Cypress", bio: placeholderText)
tempList.append(david)
let moses = Shape(name: "Moses Kao", imageName: "joshImage", major: "Biology", city: "Cypress", bio: placeholderText)
tempList.append(moses)
let meisen = Shape(name: "Meisen Wang", imageName: "joshImage", major: "Computer Science", city: "Cypress", bio: placeholderText)
tempList.append(meisen)
let emma = Shape(name: "Emma Lee", imageName: "joshImage", major: "Computer Science", city: "Cypress", bio: placeholderText)
tempList.append(emma)
let lydia = Shape(name: "Lydia Lee", imageName: "joshImage", major: "Business", city: "Cypress", bio: placeholderText)
tempList.append(lydia)
return tempList
}
// MARK: Helper functions
// Checks if there is a current user.
// If yes, automatically loads home page.
// If not, loads the login/signup screen
func validateAuth(){
if Auth.auth().currentUser == nil{
let viewController = self.storyboard?.instantiateViewController(withIdentifier: Constants.Storyboard.viewController) as! ViewController
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = viewController
}
}
/// Updates the results of the search in realtime
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
let selectedScopeButton = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
let searchText = searchBar.text!
filterForSearchTextAndScopeButton(searchText: searchText, selectedScopeButton: selectedScopeButton)
}
/// Filters the search by certain categories
func filterForSearchTextAndScopeButton(searchText: String, selectedScopeButton: String = "All"){
filteredShapes = shapeList.filter{
shape in
let scopeMatch = (selectedScopeButton == "All" || shape.major.lowercased().contains(selectedScopeButton.lowercased()))
if(searchController.searchBar.text != ""){
let searchTextMatch = shape.major.lowercased().contains(searchText.lowercased())
return scopeMatch && searchTextMatch
}
else{
return scopeMatch
}
}
shapeTableView.reloadData()
}
}
extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
// MARK: TableView components
// Protocol stubs to set up the tableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchController.isActive){
return filteredShapes.count
}
return shapeList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell
let thisShape: Shape!
if(searchController.isActive){
thisShape = filteredShapes[indexPath.row]
}
else{
thisShape = shapeList[indexPath.row]
}
tableViewCell.setShape(shape: thisShape)
return tableViewCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "detailSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "detailSegue") {
let indexPath = self.shapeTableView.indexPathForSelectedRow!
let tableViewDetail = segue.destination as? HomeDetailViewController
let selectedShape: Shape!
if(searchController.isActive){
selectedShape = filteredShapes[indexPath.row]
}
else{
selectedShape = shapeList[indexPath.row]
}
tableViewDetail?.selectedShape = selectedShape
self.shapeTableView.deselectRow(at: indexPath, animated: true)
}
}
}
| 39.017241 | 236 | 0.653705 |
111f2eca463ecc7a029071f3b5ba75a1a2d296d1 | 830 | //
// ViewController.swift
// SwiftComboBox
//
// Created by yigitserin on 01/15/2019.
// Copyright (c) 2019 yigitserin. All rights reserved.
//
import UIKit
import SwiftComboBox
class ViewController: UIViewController {
@IBOutlet weak var swiftComboBox: SwiftComboBox!
override func viewDidLoad() {
super.viewDidLoad()
swiftComboBox.dataSource = ["Apple", "Samsung", "Microsoft", "Google", "Intel", "IBM", "Facebook", "Tencent", "Oracle"]
swiftComboBox.didSelectRow = { (index: Int, item: String) in
print(item)
}
// 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.
}
}
| 25.151515 | 127 | 0.648193 |
bb4df8498a565507b701d7eb31042e5fa397173b | 1,400 | //
// Verify.swift
// cert-wallet
//
// Created by Chris Downie on 8/9/16.
// Copyright © 2016 Digital Certificates Project.
//
import Foundation
/// Representing any data needed to verify a certificate.
public struct Verify {
/// URI where issuer's public key is presented, or the public key itself. One of these will be present
public let signer : URL?
public let publicKey : BlockchainAddress?
/// Name of the attribute in the json that is signed by the issuer's private key. Default is `"uid"`, referring to the uid attribute.
public let signedAttribute : String?
/// Name of the signing method. Default is `"ECDSA(secp256k1)"`, referring to the Bitcoin method of signing messages with the issuer's private key.
public let type : String
public init(signer: URL?, publicKey: BlockchainAddress?, signedAttribute: String?, type: String) {
self.signer = signer
self.publicKey = publicKey
self.signedAttribute = signedAttribute
self.type = type
}
public init(signer: URL?, publicKeyValue: String?, signedAttribute: String?, type: String) {
var key: BlockchainAddress? = nil
if let keyValue = publicKeyValue {
key = BlockchainAddress(string: keyValue)
}
self.init(signer: signer, publicKey: key, signedAttribute: signedAttribute, type: type)
}
}
| 35 | 151 | 0.674286 |
9001077d7586e4e26d98f0876de74fc0065a8b12 | 781 | //
// UIShadowView.swift
// SmartLife-App
//
// Created by Hoang Nguyen on 3/5/18.
// Copyright © 2018 thanhlt. All rights reserved.
//
import UIKit
class UIShadowView: UIView {
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
layer.masksToBounds = false
layer.shadowColor = UIColor.lightGray.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
layer.shadowRadius = 0.0
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
}
| 26.931034 | 78 | 0.658131 |
e0d809ae2d28abd6d1be141003e2a7c45b7729e9 | 412 | //
// FirstSwiftLib.swift
// FirstSwiftLib
//
// Created by Антон Сафронов on 11.07.2021.
//
import Foundation
import SecondSwiftLib
open class FirstSwiftLib {
public func printSomethingOne() {
print("Something One")
}
public func printSomethingFromSecondLib() {
let secondLib = SecondSwiftLib()
secondLib.printSomethingTwo()
}
public init() { }
}
| 17.166667 | 47 | 0.640777 |
f489c6f4f2fa8e00ed28b3930504a4c83b237eb3 | 9,944 | //
// LoginViewController.swift
// SyncedLists
//
// Created by Kevin Largo on 11/5/17.
// Copyright © 2017 Kevin Largo. All rights reserved.
//
import FirebaseAuth
import FirebaseDatabase
import UIKit
class LoginViewController: UIViewController {
var handle: AuthStateDidChangeListenerHandle?
// MARK: - IBOutlets
@IBOutlet var buttons: [UIButton]!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
// MARK: - IBActions
@IBAction func unwindToLogin(segue:UIStoryboardSegue) { }
@IBAction func login(_ sender: Any) {
Utility.showActivityIndicator(in: self.view);
var loginCredentials = self.emailTextField.text!;
let password = self.passwordTextField.text!
if(loginCredentials.isAlphanumeric) { // Is a username due to lack of "@" character
let usernamesRef = Database.database().reference(withPath: "usernames");
usernamesRef.child(loginCredentials).observeSingleEvent(of: .value) { snapshot in
if(!(snapshot.value is NSNull)) {
let userID = snapshot.value as! String;
let usersRef = Database.database().reference(withPath: "users");
usersRef.child(userID).child("email").observeSingleEvent(of: .value) { snapshot in
loginCredentials = snapshot.value as! String;
self.signIn(with: loginCredentials, password: password);
}
} else {
Utility.presentErrorAlert(message: "The username \"\(loginCredentials)\" does not exist.", from: self);
}
}
} else {
self.signIn(with: loginCredentials, password: password);
}
}
func signIn(with loginCredentials: String, password: String) {
Auth.auth().signIn(withEmail: loginCredentials, password: password, completion: { (user, error) in
let defaults = UserDefaults.standard;
if let error = error { // Attempt login if account already exists
defaults.setValue(nil, forKey: "lastLoggedInEmail");
Utility.presentErrorAlert(message: error.localizedDescription, from: self);
} else {
defaults.setValue(self.emailTextField.text!, forKey: "lastLoggedInEmail");
self.performSegue(withIdentifier: "loginSegue", sender: nil);
}
Utility.hideActivityIndicator();
});
}
@IBAction func signUp(_ sender: Any) {
let alert = UIAlertController(title: "Register", message: "", preferredStyle: .alert);
let saveAction = UIAlertAction(title: "Sign Up", style: .default) { action in
let displayName = alert.textFields![0].text!;
let username = alert.textFields![1].text!;
let email = alert.textFields![2].text!;
let password = alert.textFields![3].text!;
let confirmPassword = alert.textFields![4].text!;
// Passwords must match
if(password != confirmPassword) {
Utility.presentErrorAlert(message: "Your passwords don't match.", from: self);
return;
}
// Username must be unique
let usernamesRef = Database.database().reference(withPath: "usernames");
let usernameRef = usernamesRef.child(username);
usernameRef.observeSingleEvent(of: .value) { snapshot in
if(!(snapshot.value is NSNull)) {
Utility.presentErrorAlert(message: "The username \"\(username)\" is already taken.", from: self);
return;
}
}
// Username should be alphanumeric
if(!username.isAlphanumeric) {
Utility.presentErrorAlert(message: "The username \"\(username)\" is invalid; usernames can only contain letters and numbers.", from: self);
return;
}
Utility.showActivityIndicator(in: self.view);
self.signUpUser(displayName: displayName, username: username, email: email, password: password);
}
saveAction.isEnabled = false;
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel);
alert.addTextField { displayNameTextField in
displayNameTextField.autocapitalizationType = .words;
displayNameTextField.delegate = self;
displayNameTextField.placeholder = "Display Name";
displayNameTextField.tag = 1;
}
alert.addTextField { usernameTextField in
usernameTextField.delegate = self;
usernameTextField.placeholder = "Username";
usernameTextField.tag = 1;
}
alert.addTextField { emailTextField in
emailTextField.keyboardType = .emailAddress;
emailTextField.placeholder = "Email";
}
alert.addTextField { passwordTextField in
passwordTextField.isSecureTextEntry = true;
passwordTextField.placeholder = "Password";
}
alert.addTextField(configurationHandler: { confirmPasswordTextField in
confirmPasswordTextField.isSecureTextEntry = true;
confirmPasswordTextField.placeholder = "Confirm Password";
})
alert.setupTextFields();
alert.addAction(cancelAction);
alert.addAction(saveAction);
present(alert, animated: true, completion: nil);
}
func signUpUser(displayName: String, username: String, email: String, password: String) {
Auth.auth().createUser(withEmail: email, password: password) { user, error in
if(error == nil) {
// Login and add user metadata to database
Auth.auth().signIn(withEmail: email, password: password);
let currentUser = Auth.auth().currentUser!
let changeRequest = currentUser.createProfileChangeRequest();
changeRequest.displayName = displayName;
changeRequest.commitChanges(completion: { error in
if(error == nil) {
// Add user to USERS
let usersRef = Database.database().reference(withPath: "users");
let newUserRef = usersRef.child(currentUser.uid);
newUserRef.child("name").setValue(currentUser.displayName);
newUserRef.child("email").setValue(currentUser.email);
newUserRef.child("username").setValue(username);
// Add user to EMAILS
let emailsRef = Database.database().reference(withPath: "emails");
emailsRef.child(User.emailToID(currentUser.email!)).setValue(currentUser.uid);
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if let error = error {
Utility.presentErrorAlert(message: error.localizedDescription, from: self);
} else {
self.performSegue(withIdentifier: "loginSegue", sender: nil);
Utility.hideActivityIndicator();
}
});
} else {
Utility.presentErrorAlert(message: error!.localizedDescription, from: self);
}
});
} else {
Utility.presentErrorAlert(message: error!.localizedDescription, from: self);
}
}
}
// MARK: - Overridden Methods
override func viewDidLoad() {
super.viewDidLoad()
for button in buttons {
button.layer.cornerRadius = 5;
}
// Setup textfields
let defaults = UserDefaults.standard;
let lastLoggedInEmail = defaults.value(forKey: "lastLoggedInEmail") as? String;
emailTextField.clearButtonMode = .whileEditing;
emailTextField.delegate = self;
emailTextField.text = lastLoggedInEmail;
passwordTextField.clearButtonMode = .whileEditing;
passwordTextField.delegate = self;
let dismissKeyboardGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard));
self.view.addGestureRecognizer(dismissKeyboardGesture);
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
passwordTextField.text?.removeAll();
handle = Auth.auth().addStateDidChangeListener { (auth, user) in
guard let _ = Auth.auth().currentUser else { return; }
self.performSegue(withIdentifier: "loginSegue", sender: nil);
}
}
}
extension LoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch (textField) {
case emailTextField:
passwordTextField.becomeFirstResponder();
case passwordTextField:
login(self);
default:
return true;
}
return true;
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Allow deletions
if(string == "") {
return true;
}
if(textField.tag == 1 &&
textField.text!.count > 10) {
return false;
}
return true;
}
@objc func dismissKeyboard() {
view.endEditing(true);
}
}
| 40.921811 | 155 | 0.576126 |
bfee468e2f701f69d0931047ae02c55dfc464e8b | 1,950 | //
// ContentView.swift
// TabbarDemo
//
// Created by pgq on 2020/3/30.
// Copyright © 2020 pq. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var currentIndex: Int = 0
@State private var isPopover = false
var body: some View {
ZStack {
TabView(selection: $currentIndex) {
HomeView()
.tabItem {
homeImage
Text("主页")
}
.tag(0)
AddView(vm: AddViewVM(phoneNum: "", code: ""))
.tabItem {
Text("")
.disabled(true)
}.tag(1)
MineView()
.tabItem {
mineImage
Text("我的")
}
.tag(2)
}
.accentColor(.orange)
GeometryReader { geo in
Image("add_fill")
.resizable()
.scaledToFill()
.frame(width: 50, height: 50)
.position(x: (geo.size.width) * 0.5, y: geo.size.height - 35)
.onTapGesture {
// self.currentIndex = 1
self.isPopover = true
}
}
}
.sheet(isPresented: $isPopover) {
AddView(vm: AddViewVM(phoneNum: "", code: ""))
}
}
private var mineImage: some View {
let name = currentIndex == 1 ? "person.fill" : "person"
return Image(systemName: name)
}
private var homeImage: some View {
let name = currentIndex == 0 ? "house.fill" : "house"
return Image(systemName: name)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 26.351351 | 81 | 0.424615 |
7957658f3c803372834c5f5ece49e02fdac6d351 | 166 | func getBit(bit: Int) -> Int {
var a = 1
if bit > 1 {
for i in 1 ... bit {
a = a * 10
}
}
return a
}
show(getBit(bit: 3))
| 15.090909 | 30 | 0.391566 |
f4bb4299c197e8ec70dbed873f77b1fbdf910546 | 1,256 | //
// Codepath_TumblrUITests.swift
// Codepath_TumblrUITests
//
// Created by Bhavesh on 9/5/18.
// Copyright © 2018 Bhavesh. All rights reserved.
//
import XCTest
class Codepath_TumblrUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.945946 | 182 | 0.667197 |
756568ca352af93a342b1bbf689207aa4cf4aff2 | 11,649 | //
// VisionPrescription.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/VisionPrescription) on 2019-05-21.
// 2019, SMART Health IT.
//
import Foundation
/**
Prescription for vision correction products for a patient.
An authorization for the provision of glasses and/or contact lenses to a patient.
*/
open class VisionPrescription: DomainResource {
override open class var resourceType: String {
get { return "VisionPrescription" }
}
/// Response creation date.
public var created: DateTime?
/// When prescription was authorized.
public var dateWritten: DateTime?
/// Created during encounter / admission / stay.
public var encounter: Reference?
/// Business Identifier for vision prescription.
public var identifier: [Identifier]?
/// Vision lens authorization.
public var lensSpecification: [VisionPrescriptionLensSpecification]?
/// Who prescription is for.
public var patient: Reference?
/// Who authorized the vision prescription.
public var prescriber: Reference?
/// The status of the resource instance.
public var status: FinancialResourceStatusCodes?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(created: DateTime, dateWritten: DateTime, lensSpecification: [VisionPrescriptionLensSpecification], patient: Reference, prescriber: Reference, status: FinancialResourceStatusCodes) {
self.init()
self.created = created
self.dateWritten = dateWritten
self.lensSpecification = lensSpecification
self.patient = patient
self.prescriber = prescriber
self.status = status
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
created = createInstance(type: DateTime.self, for: "created", in: json, context: &instCtx, owner: self) ?? created
if nil == created && !instCtx.containsKey("created") {
instCtx.addError(FHIRValidationError(missing: "created"))
}
dateWritten = createInstance(type: DateTime.self, for: "dateWritten", in: json, context: &instCtx, owner: self) ?? dateWritten
if nil == dateWritten && !instCtx.containsKey("dateWritten") {
instCtx.addError(FHIRValidationError(missing: "dateWritten"))
}
encounter = createInstance(type: Reference.self, for: "encounter", in: json, context: &instCtx, owner: self) ?? encounter
identifier = createInstances(of: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
lensSpecification = createInstances(of: VisionPrescriptionLensSpecification.self, for: "lensSpecification", in: json, context: &instCtx, owner: self) ?? lensSpecification
if (nil == lensSpecification || lensSpecification!.isEmpty) && !instCtx.containsKey("lensSpecification") {
instCtx.addError(FHIRValidationError(missing: "lensSpecification"))
}
patient = createInstance(type: Reference.self, for: "patient", in: json, context: &instCtx, owner: self) ?? patient
if nil == patient && !instCtx.containsKey("patient") {
instCtx.addError(FHIRValidationError(missing: "patient"))
}
prescriber = createInstance(type: Reference.self, for: "prescriber", in: json, context: &instCtx, owner: self) ?? prescriber
if nil == prescriber && !instCtx.containsKey("prescriber") {
instCtx.addError(FHIRValidationError(missing: "prescriber"))
}
status = createEnum(type: FinancialResourceStatusCodes.self, for: "status", in: json, context: &instCtx) ?? status
if nil == status && !instCtx.containsKey("status") {
instCtx.addError(FHIRValidationError(missing: "status"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.created?.decorate(json: &json, withKey: "created", errors: &errors)
if nil == self.created {
errors.append(FHIRValidationError(missing: "created"))
}
self.dateWritten?.decorate(json: &json, withKey: "dateWritten", errors: &errors)
if nil == self.dateWritten {
errors.append(FHIRValidationError(missing: "dateWritten"))
}
self.encounter?.decorate(json: &json, withKey: "encounter", errors: &errors)
arrayDecorate(json: &json, withKey: "identifier", using: self.identifier, errors: &errors)
arrayDecorate(json: &json, withKey: "lensSpecification", using: self.lensSpecification, errors: &errors)
if nil == lensSpecification || self.lensSpecification!.isEmpty {
errors.append(FHIRValidationError(missing: "lensSpecification"))
}
self.patient?.decorate(json: &json, withKey: "patient", errors: &errors)
if nil == self.patient {
errors.append(FHIRValidationError(missing: "patient"))
}
self.prescriber?.decorate(json: &json, withKey: "prescriber", errors: &errors)
if nil == self.prescriber {
errors.append(FHIRValidationError(missing: "prescriber"))
}
self.status?.decorate(json: &json, withKey: "status", errors: &errors)
if nil == self.status {
errors.append(FHIRValidationError(missing: "status"))
}
}
}
/**
Vision lens authorization.
Contain the details of the individual lens specifications and serves as the authorization for the fullfillment by
certified professionals.
*/
open class VisionPrescriptionLensSpecification: BackboneElement {
override open class var resourceType: String {
get { return "VisionPrescriptionLensSpecification" }
}
/// Added power for multifocal levels.
public var add: FHIRDecimal?
/// Lens meridian which contain no power for astigmatism.
public var axis: FHIRInteger?
/// Contact lens back curvature.
public var backCurve: FHIRDecimal?
/// Brand required.
public var brand: FHIRString?
/// Color required.
public var color: FHIRString?
/// Lens power for astigmatism.
public var cylinder: FHIRDecimal?
/// Contact lens diameter.
public var diameter: FHIRDecimal?
/// Lens wear duration.
public var duration: Quantity?
/// The eye for which the lens specification applies.
public var eye: VisionEyes?
/// Notes for coatings.
public var note: [Annotation]?
/// Contact lens power.
public var power: FHIRDecimal?
/// Eye alignment compensation.
public var prism: [VisionPrescriptionLensSpecificationPrism]?
/// Product to be supplied.
public var product: CodeableConcept?
/// Power of the lens.
public var sphere: FHIRDecimal?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(eye: VisionEyes, product: CodeableConcept) {
self.init()
self.eye = eye
self.product = product
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
add = createInstance(type: FHIRDecimal.self, for: "add", in: json, context: &instCtx, owner: self) ?? add
axis = createInstance(type: FHIRInteger.self, for: "axis", in: json, context: &instCtx, owner: self) ?? axis
backCurve = createInstance(type: FHIRDecimal.self, for: "backCurve", in: json, context: &instCtx, owner: self) ?? backCurve
brand = createInstance(type: FHIRString.self, for: "brand", in: json, context: &instCtx, owner: self) ?? brand
color = createInstance(type: FHIRString.self, for: "color", in: json, context: &instCtx, owner: self) ?? color
cylinder = createInstance(type: FHIRDecimal.self, for: "cylinder", in: json, context: &instCtx, owner: self) ?? cylinder
diameter = createInstance(type: FHIRDecimal.self, for: "diameter", in: json, context: &instCtx, owner: self) ?? diameter
duration = createInstance(type: Quantity.self, for: "duration", in: json, context: &instCtx, owner: self) ?? duration
eye = createEnum(type: VisionEyes.self, for: "eye", in: json, context: &instCtx) ?? eye
if nil == eye && !instCtx.containsKey("eye") {
instCtx.addError(FHIRValidationError(missing: "eye"))
}
note = createInstances(of: Annotation.self, for: "note", in: json, context: &instCtx, owner: self) ?? note
power = createInstance(type: FHIRDecimal.self, for: "power", in: json, context: &instCtx, owner: self) ?? power
prism = createInstances(of: VisionPrescriptionLensSpecificationPrism.self, for: "prism", in: json, context: &instCtx, owner: self) ?? prism
product = createInstance(type: CodeableConcept.self, for: "product", in: json, context: &instCtx, owner: self) ?? product
if nil == product && !instCtx.containsKey("product") {
instCtx.addError(FHIRValidationError(missing: "product"))
}
sphere = createInstance(type: FHIRDecimal.self, for: "sphere", in: json, context: &instCtx, owner: self) ?? sphere
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.add?.decorate(json: &json, withKey: "add", errors: &errors)
self.axis?.decorate(json: &json, withKey: "axis", errors: &errors)
self.backCurve?.decorate(json: &json, withKey: "backCurve", errors: &errors)
self.brand?.decorate(json: &json, withKey: "brand", errors: &errors)
self.color?.decorate(json: &json, withKey: "color", errors: &errors)
self.cylinder?.decorate(json: &json, withKey: "cylinder", errors: &errors)
self.diameter?.decorate(json: &json, withKey: "diameter", errors: &errors)
self.duration?.decorate(json: &json, withKey: "duration", errors: &errors)
self.eye?.decorate(json: &json, withKey: "eye", errors: &errors)
if nil == self.eye {
errors.append(FHIRValidationError(missing: "eye"))
}
arrayDecorate(json: &json, withKey: "note", using: self.note, errors: &errors)
self.power?.decorate(json: &json, withKey: "power", errors: &errors)
arrayDecorate(json: &json, withKey: "prism", using: self.prism, errors: &errors)
self.product?.decorate(json: &json, withKey: "product", errors: &errors)
if nil == self.product {
errors.append(FHIRValidationError(missing: "product"))
}
self.sphere?.decorate(json: &json, withKey: "sphere", errors: &errors)
}
}
/**
Eye alignment compensation.
Allows for adjustment on two axis.
*/
open class VisionPrescriptionLensSpecificationPrism: BackboneElement {
override open class var resourceType: String {
get { return "VisionPrescriptionLensSpecificationPrism" }
}
/// Amount of adjustment.
public var amount: FHIRDecimal?
/// The relative base, or reference lens edge, for the prism.
public var base: VisionBase?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(amount: FHIRDecimal, base: VisionBase) {
self.init()
self.amount = amount
self.base = base
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
amount = createInstance(type: FHIRDecimal.self, for: "amount", in: json, context: &instCtx, owner: self) ?? amount
if nil == amount && !instCtx.containsKey("amount") {
instCtx.addError(FHIRValidationError(missing: "amount"))
}
base = createEnum(type: VisionBase.self, for: "base", in: json, context: &instCtx) ?? base
if nil == base && !instCtx.containsKey("base") {
instCtx.addError(FHIRValidationError(missing: "base"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.amount?.decorate(json: &json, withKey: "amount", errors: &errors)
if nil == self.amount {
errors.append(FHIRValidationError(missing: "amount"))
}
self.base?.decorate(json: &json, withKey: "base", errors: &errors)
if nil == self.base {
errors.append(FHIRValidationError(missing: "base"))
}
}
}
| 40.307958 | 207 | 0.725298 |
f74a5dc47e69e6c94d4c4594b218579815f81a59 | 582 | //: Playground - noun: a place where people can play
import Cocoa
class Settings {
static var sharedInstance = Settings()
var volumeLevel: Float = 50
private init() {
print("Settings is loaded")
}
func resetSettings() {
print("Reset to default settings...")
Settings.sharedInstance = Settings()
}
}
print(Settings.sharedInstance.volumeLevel)
Settings.sharedInstance.volumeLevel = 24
print(Settings.sharedInstance.volumeLevel)
Settings.sharedInstance.resetSettings()
print(Settings.sharedInstance.volumeLevel)
| 20.785714 | 52 | 0.694158 |
e9e3f766426e23ea709f152b6036157b9964e9f2 | 588 | // Copyright Keefer Taylor, 2018
import TezosKit
//
// GetAddressManagerKeyRPCTest.swift
// TezosKitTests
//
// Created by Keefer Taylor on 10/26/18.
// Copyright © 2018 Keefer Taylor. All rights reserved.
//
import XCTest
class GetAddressManagerKeyRPCTest: XCTestCase {
public func testGetAddressManagerKeyRPC() {
let address = "abc123"
let rpc = GetAddressManagerKeyRPC(address: address)
XCTAssertEqual(rpc.endpoint, "/chains/main/blocks/head/context/contracts/" + address + "/manager_key")
XCTAssertNil(rpc.payload)
XCTAssertFalse(rpc.isPOSTRequest)
}
}
| 25.565217 | 106 | 0.741497 |
56c3dda6430d3796cebbec21e366fd9242642406 | 1,372 | //
// main.swift
// Bootstrapping
//
// Created by Hoon H. on 10/12/14.
// Copyright (c) 2014 Eonil. All rights reserved.
//
import AppKit
final class ExampleApplicationController: NSObject, NSApplicationDelegate {
/// Seems fine to create AppKit UI classes before `NSApplication` object
/// to be created starting OSX 10.10. (it was an error in OSX 10.9)
let window1 = NSWindow()
func applicationDidFinishLaunching(_ aNotification: Notification) {
window1.setFrame(CGRect(x: 0, y: 0, width: 800, height: 500), display: true)
window1.makeKeyAndOrderFront(self)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
/// When compared to Objective-C example, an `autoreleasepool`
/// is not required because Swift expected to install one automatically.
/// Anyway you can install one if you want to be defensive.
autoreleasepool { () -> () in
let app1 = NSApplication.shared() //< You need to retain the application object in stack. Otherwise it will be killed immediately.
let con1 = ExampleApplicationController() //< So do this too...
app1.delegate = con1
app1.run()
/// DO NOT call `NSApplicationMain`. It will be handled by `NSApplication.run` method.
// NSApplicationMain(C_ARGC, C_ARGV)
}
| 33.463415 | 134 | 0.690962 |
1da0b7210b89adef67da4e349f978b64cca8e6d7 | 4,410 | //
// SettingsViewController.swift
// NextPomodoro
//
// Created by Paul Traylor on 2019/09/08.
// Copyright © 2019 Paul Traylor. All rights reserved.
//
import UIKit
class SettingsViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(LeftTableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.register(ButtonTableViewCell.self)
}
// MARK: - Sections
fileprivate struct Section {
let title: String
let count: Int
}
private var sections = [
Section(title: "Info", count: 1),
Section(title: "Server", count: 2),
Section(title: "MQTT", count: 3),
Section(title: "", count: 1)
]
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
// MARK: - Rows
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath {
case [0, 0]:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Repository"
cell.detailTextLabel?.text = ApplicationSettings.repository.absoluteString
cell.accessoryType = .disclosureIndicator
return cell
case [1, 0]:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Host"
cell.detailTextLabel?.text = ApplicationSettings.defaults.string(forKey: .server)
cell.accessoryType = .disclosureIndicator
return cell
case [1, 1]:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "User"
cell.detailTextLabel?.text = ApplicationSettings.defaults.string(forKey: .username)
cell.accessoryType = .disclosureIndicator
return cell
case [2, 0]:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Host"
cell.detailTextLabel?.text = ApplicationSettings.defaults.string(forKey: .broker)
return cell
case [2, 1]:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "SSL"
cell.detailTextLabel?.text = ApplicationSettings.defaults.bool(forKey: .brokerSSL) ? "YES": "NO"
return cell
case [2, 2]:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Port"
cell.detailTextLabel?.text = ApplicationSettings.defaults.string(forKey: .brokerPort)
return cell
case [3, 0]:
let cell: ButtonTableViewCell = tableView.dequeueReusableCell(for: indexPath)
cell.configure("Logout", style: .destructive, handler: actionLogout)
return cell
default:
fatalError("cellForRowAt \(indexPath)")
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath {
case [0, 0]:
UIApplication.shared.open(ApplicationSettings.repository, options: [:], completionHandler: nil)
case [1, 0]:
guard var url = ApplicationSettings.defaults.url(forKey: .server) else { return}
UIApplication.shared.open(url.url!, options: [:], completionHandler: nil)
default:
let cell = tableView.cellForRow(at: indexPath)
cell?.setSelected(true, animated: true)
}
}
// MARK: - Actions
func actionLogout() {
ApplicationSettings.deleteLogin()
let login = LoginViewController.instantiate()
let nav = UINavigationController(rootViewController: login)
nav.modalPresentationStyle = .fullScreen
DispatchQueue.main.async {
self.present(nav, animated: true, completion: nil)
}
}
}
| 37.692308 | 109 | 0.635147 |
0a2b9d94494099c2f60f07ecb8411946629dd2ce | 5,003 | /**
* Copyright (c) Visly Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import UIKit
import AVFoundation
import SnapKit
protocol ScanViewControllerDelegate {
func didScan(url: URL)
}
class ScanViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
static let MinHeight: CGFloat = 50.0
private let cameraQueue = DispatchQueue(label: "camera")
private var previewLayer: CALayer? = nil
private let preview = UIView()
private var captureSession: AVCaptureSession? = nil
public var paused: Bool = false {
didSet {
if let captureSession = captureSession {
cameraQueue.async {
if (self.paused) {
captureSession.stopRunning()
} else {
captureSession.startRunning()
}
}
}
}
}
var delegate: ScanViewControllerDelegate? = nil
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(nibName: nil, bundle: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.paused = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.paused = false
}
override func loadView() {
let view = UIView()
view.clipsToBounds = true
preview.backgroundColor = .black
view.addSubview(preview)
preview.snp.makeConstraints {
$0.edges.equalTo(view)
}
let qrCodeContainer = UIView()
qrCodeContainer.backgroundColor = .white
qrCodeContainer.layer.cornerRadius = 3
view.addSubview(qrCodeContainer)
qrCodeContainer.snp.makeConstraints {
$0.left.equalTo(view).offset(20)
$0.bottom.equalTo(view).offset(-20)
$0.top.greaterThanOrEqualTo(view).offset(20)
$0.width.equalTo(30)
$0.height.equalTo(30)
}
let qrCode = UIImageView()
qrCode.image = UIImage(named: "qr")
qrCode.contentMode = .center
qrCodeContainer.addSubview(qrCode)
qrCode.snp.makeConstraints {
$0.width.equalTo(18)
$0.height.equalTo(18)
$0.center.equalTo(qrCodeContainer)
}
self.view = view
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let previewLayer = previewLayer {
previewLayer.frame = CGRect(
x: 0,
y: -(UIScreen.main.bounds.height - view.bounds.height) / 2,
width: self.view.bounds.width,
height: self.view.bounds.height
)
} else {
if (TARGET_OS_SIMULATOR == 0) {
startCamera()
}
}
}
func startCamera() {
let captureDevice = AVCaptureDevice.default(for: .video)
let input = try! AVCaptureDeviceInput(device: captureDevice!)
let captureSession = AVCaptureSession()
captureSession.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = [.qr]
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = .resizeAspectFill
previewLayer.frame = CGRect(
x: 0,
y: -(UIScreen.main.bounds.height - view.bounds.height) / 2,
width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height
)
preview.layer.addSublayer(previewLayer)
self.previewLayer = previewLayer
self.captureSession = captureSession
if (!paused) {
DispatchQueue.global().async {
captureSession.startRunning()
}
}
}
// MARK: - AVCaptureMetadataOutputObjectsDelegate
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if paused {
return;
}
let objects = metadataObjects.filter { $0.type == .qr }
guard objects.count == 1 else {
return
}
let object = objects[0] as! AVMetadataMachineReadableCodeObject
guard let shardPath = object.stringValue, let url = URL(string: "https://playground.shardlib.com/api/shards/\(shardPath)") else {
return
}
delegate?.didScan(url: url)
}
}
| 30.506098 | 145 | 0.586248 |
016d6ecf3cd2f6f8c1eed27237e432dddd6a748c | 12,644 | //
// NotesTableView.swift
// FSNotes
//
// Created by Oleksandr Glushchenko on 7/31/17.
// Copyright © 2017 Oleksandr Glushchenko. All rights reserved.
//
import Carbon
import Cocoa
import FSNotesCore_macOS
class NotesTableView: NSTableView, NSTableViewDataSource,
NSTableViewDelegate {
var noteList = [Note]()
var defaultCell = NoteCellView()
var pinnedCell = NoteCellView()
var storage = Storage.sharedInstance()
public var loadingQueue = OperationQueue.init()
public var fillTimestamp: Int64?
override func draw(_ dirtyRect: NSRect) {
self.dataSource = self
self.delegate = self
super.draw(dirtyRect)
}
override func keyUp(with event: NSEvent) {
guard let vc = self.window?.contentViewController as? ViewController else {
super.keyUp(with: event)
return
}
if let note = EditTextView.note, event.keyCode == kVK_Tab && !event.modifierFlags.contains(.control), !UserDefaultsManagement.preview || note.isRTF() {
vc.focusEditArea()
}
if (event.keyCode == kVK_LeftArrow) {
if let fr = self.window?.firstResponder, fr.isKind(of: NSTextView.self) {
super.keyUp(with: event)
return
}
vc.storageOutlineView.window?.makeFirstResponder(vc.storageOutlineView)
vc.storageOutlineView.selectRowIndexes([1], byExtendingSelection: false)
}
super.keyUp(with: event)
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
return true
}
override func mouseDown(with event: NSEvent) {
UserDataService.instance.searchTrigger = false
super.mouseDown(with: event)
}
override func rightMouseDown(with event: NSEvent) {
UserDataService.instance.searchTrigger = false
let point = self.convert(event.locationInWindow, from: nil)
let i = row(at: point)
if self.noteList.indices.contains(i) {
DispatchQueue.main.async {
let selectedRows = self.selectedRowIndexes
if !selectedRows.contains(i) {
self.selectRowIndexes(IndexSet(integer: i), byExtendingSelection: false)
self.scrollRowToVisible(i)
return
}
}
super.rightMouseDown(with: event)
}
}
// Custom note highlight style
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
return NoteRowView()
}
// Populate table data
func numberOfRows(in tableView: NSTableView) -> Int {
return noteList.count
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
let height = CGFloat(21 + UserDefaultsManagement.cellSpacing)
if !UserDefaultsManagement.horizontalOrientation && !UserDefaultsManagement.hidePreviewImages {
if noteList.indices.contains(row) {
let note = noteList[row]
if let urls = note.getImagePreviewUrl(), urls.count > 0 {
let previewCharsQty = note.preview.count
if (previewCharsQty == 0) {
if note.getTitle() != nil {
// Title + image
return 79 + 17
}
// Images only
return 79
}
// Title + Prevew + Images
return (height + 58)
}
}
}
// Title + preview
return height
}
// On selected row show notes in right panel
func tableViewSelectionDidChange(_ notification: Notification) {
let timestamp = Date().toMillis()
self.fillTimestamp = timestamp
let vc = self.window?.contentViewController as! ViewController
if vc.editAreaScroll.isFindBarVisible {
let menu = NSMenuItem(title: "", action: nil, keyEquivalent: "")
menu.tag = NSTextFinder.Action.hideFindInterface.rawValue
vc.editArea.performTextFinderAction(menu)
}
if UserDataService.instance.isNotesTableEscape {
if vc.storageOutlineView.selectedRow == -1 {
UserDataService.instance.isNotesTableEscape = false
}
vc.storageOutlineView.deselectAll(nil)
vc.editArea.clear()
return
}
if (noteList.indices.contains(selectedRow)) {
let note = noteList[selectedRow]
if !UserDefaultsManagement.inlineTags, let items = vc.storageOutlineView.sidebarItems {
for item in items {
if let tag = item as? Tag {
if note.tagNames.contains(tag.getName()) {
vc.storageOutlineView.selectTag(item: tag)
} else {
vc.storageOutlineView.deselectTag(item: tag)
}
}
}
}
self.loadingQueue.cancelAllOperations()
let operation = BlockOperation()
operation.addExecutionBlock { [weak self] in
DispatchQueue.main.async {
guard !operation.isCancelled, self?.fillTimestamp == timestamp else { return }
vc.editArea.fill(note: note, highlight: true)
if UserDefaultsManagement.focusInEditorOnNoteSelect && !UserDataService.instance.searchTrigger {
vc.focusEditArea(firstResponder: nil)
}
}
}
self.loadingQueue.addOperation(operation)
} else {
vc.editArea.clear()
if !UserDefaultsManagement.inlineTags {
vc.storageOutlineView.deselectAllTags()
}
}
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
if (noteList.indices.contains(row)) {
return noteList[row]
}
return nil
}
func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
let data = NSKeyedArchiver.archivedData(withRootObject: rowIndexes)
let type = NSPasteboard.PasteboardType.init(rawValue: "notesTable")
pboard.declareTypes([type], owner: self)
pboard.setData(data, forType: type)
return true
}
func getNoteFromSelectedRow() -> Note? {
var note: Note? = nil
let selected = self.selectedRow
if (selected < 0) {
return nil
}
if (noteList.indices.contains(selected)) {
note = noteList[selected]
}
return note
}
func getSelectedNote() -> Note? {
var note: Note? = nil
let row = selectedRow
if (noteList.indices.contains(row)) {
note = noteList[row]
}
return note
}
func getSelectedNotes() -> [Note]? {
var notes = [Note]()
for row in selectedRowIndexes {
if (noteList.indices.contains(row)) {
notes.append(noteList[row])
}
}
if notes.isEmpty {
return nil
}
return notes
}
public func deselectNotes() {
self.deselectAll(nil)
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if ([kVK_ANSI_8, kVK_ANSI_J, kVK_ANSI_K].contains(Int(event.keyCode)) && event.modifierFlags.contains(.command)) {
return true
}
if event.modifierFlags.contains(.control) && event.modifierFlags.contains(.shift) && event.keyCode == kVK_ANSI_B {
return true
}
if event.modifierFlags.contains(.control) && event.keyCode == kVK_Tab {
return true
}
if (event.keyCode == kVK_ANSI_M && event.modifierFlags.contains(.command) && event.modifierFlags.contains(.shift)) {
return true
}
return super.performKeyEquivalent(with: event)
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard noteList.indices.contains(row) else {
return nil
}
let note = noteList[row]
if (note.isPinned) {
pinnedCell = makeCell(note: note)
pinnedCell.pin.frame.size.width = 23
return pinnedCell
}
defaultCell = makeCell(note: note)
defaultCell.pin.frame.size.width = 0
return defaultCell
}
func makeCell(note: Note) -> NoteCellView {
let cell = makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "NoteCellView"), owner: self) as! NoteCellView
cell.configure(note: note)
cell.loadImagesPreview()
cell.attachHeaders(note: note)
return cell
}
override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {
if (clickedRow > -1 && selectedRow < 0) {
selectRowIndexes([clickedRow], byExtendingSelection: false)
}
if selectedRow < 0 {
return
}
guard let vc = self.window?.contentViewController as? ViewController else { return }
vc.loadMoveMenu()
}
func getIndex(_ note: Note) -> Int? {
if let index = noteList.firstIndex(where: {$0 === note}) {
return index
}
return nil
}
func selectNext() {
UserDataService.instance.searchTrigger = false
selectRow(selectedRow + 1)
}
func selectPrev() {
UserDataService.instance.searchTrigger = false
selectRow(selectedRow - 1)
}
func selectRow(_ i: Int) {
if (noteList.indices.contains(i)) {
DispatchQueue.main.async {
self.selectRowIndexes([i], byExtendingSelection: false)
self.scrollRowToVisible(i)
}
}
}
func setSelected(note: Note) {
if let i = getIndex(note) {
selectRow(i)
scrollRowToVisible(i)
}
}
func removeByNotes(notes: [Note]) {
for note in notes {
if let i = noteList.firstIndex(where: {$0 === note}) {
let indexSet = IndexSet(integer: i)
noteList.remove(at: i)
removeRows(at: indexSet, withAnimation: .slideDown)
}
}
}
@objc public func unDelete(_ urls: [URL: URL]) {
for (src, dst) in urls {
do {
if let note = storage.getBy(url: src) {
storage.removeBy(note: note)
}
try FileManager.default.moveItem(at: src, to: dst)
} catch {
print(error)
}
}
}
public func countVisiblePinned() -> Int {
var i = 0
for note in noteList {
if (note.isPinned) {
i += 1
}
}
return i
}
public func insertNew(note: Note) {
guard let vc = self.window?.contentViewController as? ViewController else { return }
guard vc.isFit(note: note, shouldLoadMain: true) else { return }
let at = self.countVisiblePinned()
self.noteList.insert(note, at: at)
vc.filteredNoteList?.insert(note, at: at)
self.beginUpdates()
self.insertRows(at: IndexSet(integer: at), withAnimation: .effectFade)
self.reloadData(forRowIndexes: IndexSet(integer: at), columnIndexes: [0])
self.endUpdates()
}
public func reloadRow(note: Note) {
DispatchQueue.main.async {
if let i = self.noteList.firstIndex(of: note) {
note.invalidateCache()
if let row = self.rowView(atRow: i, makeIfNecessary: false) as? NoteRowView, let cell = row.subviews.first as? NoteCellView {
cell.date.stringValue = note.getDateForLabel()
cell.loadImagesPreview(position: i)
cell.attachHeaders(note: note)
cell.renderPin()
self.noteHeightOfRows(withIndexesChanged: [i])
}
}
}
}
}
| 31.142857 | 159 | 0.55204 |
696290e1b2882c860e3abacb72e279baced4c488 | 753 | import XCTest
import SSCustomSideMenu
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.965517 | 111 | 0.60425 |
e929d449a1dc5604217ce6048507a80cda95bb85 | 2,759 | //
// SceneDelegate.swift
// Loan Caculator
//
// Created by Steve Dao on 25/2/20.
// Copyright © 2020 Steve Dao. All rights reserved.
//
import UIKit
import SwiftUI
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).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
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 neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.446154 | 147 | 0.705328 |
d6b9930feb3f50e5ff6783bc0c7eb129a3ece845 | 2,828 | //
// ViewController.swift
// 06_Msg-Notification
//
// Created by 한상혁 on 2021/10/19.
//
import UIKit
import UserNotifications
class ViewController: UIViewController {
@IBOutlet var msg: UITextField!
@IBOutlet var datepicker: UIDatePicker!
@IBAction func save(_ sender: Any) {
if #available(iOS 10.0, *) {
// UserNotification 프레임워크 사용한 로컬 알림
// 알림 동의 여부 확인
UNUserNotificationCenter.current().getNotificationSettings { settings in
if settings.authorizationStatus == UNAuthorizationStatus.authorized {
// 알림을 동의했을 때 알림 설정을 하는 곳
DispatchQueue.main.async {
// 알림 콘텐츠 정의
let nContent = UNMutableNotificationContent()
nContent.body = (self.msg.text)!
nContent.title = "미리 알림"
nContent.sound = UNNotificationSound.default
// 발송 시간 '지금으로부터 *초 형식'으로 변환
let time = self.datepicker.date.timeIntervalSinceNow
// 발송 조건 정의
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: time, repeats: false)
// 발송 요청 객체 정의
let request = UNNotificationRequest(identifier: "alarm", content: nContent, trigger: trigger)
// 노티센터에 추가
UNUserNotificationCenter.current().add(request) { (_) in
DispatchQueue.main.async {
// 발송 완료 메시지 창
let date = self.datepicker.date.addingTimeInterval(9*60*60)
let message = "알림이 등록되었습니다. 등록된 알림은 \(date)에 발송됩니다."
let alert = UIAlertController(title: "알림 등록", message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "확인", style: .default)
alert.addAction(ok)
self.present(alert, animated: false)
}
}
}
} else {
let alert = UIAlertController(title: "알림 등록", message: "알림이 허용되지 않았습니다.", preferredStyle: .alert)
let ok = UIAlertAction(title: "확인", style: .default)
alert.addAction(ok)
self.present(alert, animated: false)
return
}
}
} else {
// LocalNotification 객체를 사용한 로컬알림
}
}
}
| 39.277778 | 119 | 0.453678 |
0116b723a1e168886a9f0136ce1d22fd34426b35 | 2,236 | //
// SceneDelegate.swift
// Chat
//
// Created by 성단빈 on 2020/07/08.
// Copyright © 2020 seong. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 41.407407 | 143 | 0.74195 |
3aca02baa70529e4f1b520ce757d69fea43e04a1 | 3,318 | import AppKit
import Foundation
// MARK: - LocalAsset
public class LocalAsset: NSBox {
// MARK: Lifecycle
public init() {
super.init(frame: .zero)
setUpViews()
setUpConstraints()
update()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Private
private var imageView = NSImageView()
private var topPadding: CGFloat = 0
private var trailingPadding: CGFloat = 0
private var bottomPadding: CGFloat = 0
private var leadingPadding: CGFloat = 0
private var imageViewTopMargin: CGFloat = 0
private var imageViewTrailingMargin: CGFloat = 0
private var imageViewBottomMargin: CGFloat = 0
private var imageViewLeadingMargin: CGFloat = 0
private var imageViewTopAnchorConstraint: NSLayoutConstraint?
private var imageViewBottomAnchorConstraint: NSLayoutConstraint?
private var imageViewLeadingAnchorConstraint: NSLayoutConstraint?
private var imageViewHeightAnchorConstraint: NSLayoutConstraint?
private var imageViewWidthAnchorConstraint: NSLayoutConstraint?
private func setUpViews() {
boxType = .custom
borderType = .noBorder
contentViewMargins = .zero
addSubview(imageView)
imageView.fillColor = #colorLiteral(red: 0.847058823529, green: 0.847058823529, blue: 0.847058823529, alpha: 1)
imageView.image = NSImage(named: NSImage.Name(rawValue: "icon_128x128"))
}
private func setUpConstraints() {
translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false
let imageViewTopAnchorConstraint = imageView
.topAnchor
.constraint(equalTo: topAnchor, constant: topPadding + imageViewTopMargin)
let imageViewBottomAnchorConstraint = imageView
.bottomAnchor
.constraint(equalTo: bottomAnchor, constant: -(bottomPadding + imageViewBottomMargin))
let imageViewLeadingAnchorConstraint = imageView
.leadingAnchor
.constraint(equalTo: leadingAnchor, constant: leadingPadding + imageViewLeadingMargin)
let imageViewHeightAnchorConstraint = imageView.heightAnchor.constraint(equalToConstant: 100)
let imageViewWidthAnchorConstraint = imageView.widthAnchor.constraint(equalToConstant: 100)
NSLayoutConstraint.activate([
imageViewTopAnchorConstraint,
imageViewBottomAnchorConstraint,
imageViewLeadingAnchorConstraint,
imageViewHeightAnchorConstraint,
imageViewWidthAnchorConstraint
])
self.imageViewTopAnchorConstraint = imageViewTopAnchorConstraint
self.imageViewBottomAnchorConstraint = imageViewBottomAnchorConstraint
self.imageViewLeadingAnchorConstraint = imageViewLeadingAnchorConstraint
self.imageViewHeightAnchorConstraint = imageViewHeightAnchorConstraint
self.imageViewWidthAnchorConstraint = imageViewWidthAnchorConstraint
// For debugging
imageViewTopAnchorConstraint.identifier = "imageViewTopAnchorConstraint"
imageViewBottomAnchorConstraint.identifier = "imageViewBottomAnchorConstraint"
imageViewLeadingAnchorConstraint.identifier = "imageViewLeadingAnchorConstraint"
imageViewHeightAnchorConstraint.identifier = "imageViewHeightAnchorConstraint"
imageViewWidthAnchorConstraint.identifier = "imageViewWidthAnchorConstraint"
}
private func update() {}
}
| 35.677419 | 115 | 0.787824 |
c133bdd6c9e48ab9038799e0e6104ac278a071b6 | 5,257 | // Created by B.T. Franklin on 12/22/19.
import AudioKit
struct PadPartComposer {
private let identifier: PartIdentifier = .pad
private let channel: PartChannel = .pad
private let section: Section
private let song: Song
private let partGenotype: PadPartGenotype
private let velocity: MIDIVelocity
init(for section: Section, in song: Song, using partGenotype: PadPartGenotype) {
self.section = section
self.song = song
self.partGenotype = partGenotype
self.velocity = 100
}
func composeNormal() -> ComposedPartSection {
var midiNoteData: [MIDINoteData] = []
let phraseData = composeNormalPhrase()
for phraseNumber in 0..<section.descriptor.phraseCount {
let phraseOffset = Duration(beats: Double(phraseNumber) * section.descriptor.phraseDuration.beats)
for phraseMIDINoteDatum in phraseData {
midiNoteData.append(.init(noteNumber: phraseMIDINoteDatum.noteNumber,
velocity: phraseMIDINoteDatum.velocity,
channel: phraseMIDINoteDatum.channel,
duration: phraseMIDINoteDatum.duration,
position: phraseMIDINoteDatum.position + phraseOffset))
}
}
return ComposedPartSection(partIdentifier: identifier, section: section, midiNoteData: midiNoteData)
}
// TODO un-private this and make it real
private func composeIntro() -> ComposedPartSection {
var midiNoteData: [MIDINoteData] = []
for phraseNumber in 0..<section.descriptor.phraseCount {
let phraseOffset = Duration(beats: Double(phraseNumber) * section.descriptor.phraseDuration.beats)
var firstChord: Chord?
for chordIndex in 0..<section.chordProgression.chordDescriptors.count {
let chordDescriptor = section.chordProgression.chordDescriptors[chordIndex]
let chordPlacement = section.chordPlacementMapPerPhrase.chordPlacements[chordIndex]
let chord: Chord
if let firstChord = firstChord {
chord = firstChord.findClosestInversion(using: chordDescriptor)
} else {
chord = Chord(from: chordDescriptor, octave: partGenotype.octave)
firstChord = chord
}
midiNoteData.append(.init(noteNumber: chord.pitches[0].midiNoteNumber,
velocity: self.velocity,
channel: channel.rawValue,
duration: chordPlacement.duration,
position: chordPlacement.position + phraseOffset))
}
}
return ComposedPartSection(partIdentifier: identifier, section: section, midiNoteData: midiNoteData)
}
func composeFinale() -> ComposedPartSection {
var midiNoteData: [MIDINoteData] = []
let chordDescriptor = section.chordProgression.chordDescriptors.first!
let chordPlacement = section.chordPlacementMapPerPhrase.chordPlacements.first!
let chord = Chord(from: chordDescriptor, octave: partGenotype.octave)
for pitch in chord.pitches {
midiNoteData.append(.init(noteNumber: pitch.midiNoteNumber,
velocity: self.velocity,
channel: channel.rawValue,
duration: chordPlacement.duration,
position: chordPlacement.position))
}
return ComposedPartSection(partIdentifier: identifier, section: section, midiNoteData: midiNoteData)
}
private func composeNormalPhrase() -> [MIDINoteData] {
var midiNoteData: [MIDINoteData] = []
var firstChord: Chord?
for chordIndex in 0..<section.chordProgression.chordDescriptors.count {
let chordDescriptor = section.chordProgression.chordDescriptors[chordIndex]
let chordPlacement = section.chordPlacementMapPerPhrase.chordPlacements[chordIndex]
let chord: Chord
if let firstChord = firstChord {
chord = firstChord.findClosestInversion(using: chordDescriptor)
} else {
chord = Chord(from: chordDescriptor, octave: partGenotype.octave)
firstChord = chord
}
for pitch in chord.pitches {
midiNoteData.append(.init(noteNumber: pitch.midiNoteNumber,
velocity: self.velocity,
channel: channel.rawValue,
duration: chordPlacement.duration,
position: chordPlacement.position))
}
}
return midiNoteData
}
}
| 42.739837 | 110 | 0.563439 |
bf611f64b10a21e2b637e8a8cecfc650580a7817 | 2,463 | //
// ImageSpec.swift
// Exposure
//
// Created by Fredrik Sjöberg on 2017-05-16.
// Copyright © 2017 emp. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import Exposure
class ImageSpec: QuickSpec {
override func spec() {
super.spec()
describe("JSON") {
it("should succeed with valid response") {
let json = ImageJSON.valid()
let result = json.decode(Image.self)
expect(result).toNot(beNil())
expect(result?.height).toNot(beNil())
expect(result?.orientation).toNot(beNil())
expect(result?.type).toNot(beNil())
expect(result?.url).toNot(beNil())
expect(result?.width).toNot(beNil())
}
it("should init with partial response") {
let json = ImageJSON.missingKeys()
let result = json.decode(Image.self)
expect(result).toNot(beNil())
expect(result?.height).to(beNil())
expect(result?.orientation).to(beNil())
expect(result?.type).to(beNil())
expect(result?.url).to(beNil())
expect(result?.width).toNot(beNil())
}
it("should init with empty response") {
let json = ImageJSON.empty()
let result = json.decode(Image.self)
expect(result).toNot(beNil())
}
}
}
}
extension ImageSpec {
enum ImageJSON {
static let url = "https://azukifilesprestage.blob.core.windows.net/img/VU-21702_qwerty-b4fead6f454a4fe2ba1d6b391fb9f5ab_other.jpg"
static let height = 700
static let width = 500
static let orientation = "PORTRAIT"
static let type = "other"
static func valid() -> [String: Any] {
return [
"url": ImageJSON.url,
"height": ImageJSON.height,
"width": ImageJSON.width,
"orientation": ImageJSON.orientation,
"type": ImageJSON.type
]
}
static func missingKeys() -> [String: Any] {
return [
"width": ImageJSON.width
]
}
static func empty() -> [String: Any] {
return [:]
}
}
}
| 29.674699 | 138 | 0.498173 |
bbc1b6d56eab4fda975f931c20e47b35989e77c4 | 2,763 | //
// SocketTypes.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 4/8/15.
//
// 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
/// A marking protocol that says a type can be represented in a socket.io packet.
///
/// Example:
///
/// ```swift
/// struct CustomData : SocketData {
/// let name: String
/// let age: Int
///
/// func socketRepresentation() -> SocketData {
/// return ["name": name, "age": age]
/// }
/// }
///
/// socket.emit("myEvent", CustomData(name: "Erik", age: 24))
/// ```
public protocol SocketData {
// MARK: Methods
/// A representation of self that can sent over socket.io.
func socketRepresentation() throws -> SocketData
}
public extension SocketData {
/// Default implementation. Only works for native Swift types and a few Foundation types.
func socketRepresentation() -> SocketData {
return self
}
}
extension Array : SocketData { }
extension Bool : SocketData { }
extension Dictionary : SocketData { }
extension Double : SocketData { }
extension Int : SocketData { }
extension NSArray : SocketData { }
extension Data : SocketData { }
extension NSData : SocketData { }
extension NSDictionary : SocketData { }
extension NSString : SocketData { }
extension NSNull : SocketData { }
extension String : SocketData { }
/// A typealias for an ack callback.
public typealias AckCallback = ([Any]) -> ()
/// A typealias for a normal callback.
public typealias NormalCallback = ([Any], SocketAckEmitter) -> ()
typealias JSON = [String: Any]
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [Data])
typealias ProbeWaitQueue = [Probe]
enum Either<E, V> {
case left(E)
case right(V)
}
| 32.892857 | 93 | 0.706117 |
61a72004c00ec4ca5b9f17738209f2b4728004f1 | 3,674 | //
// LettersViewController.swift
// Kindergarten Literacy
//
// Created by Bingqing Xu on 11/23/20.
// Development taken over by TigerSHe
//
import UIKit
import AVFoundation
class letterMainPage: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
playIntroMessage()
// Do any additional setup after loading the view.
}
// reference to different storyboards
let letterStoryBoard:UIStoryboard = UIStoryboard(name: "LetterPages", bundle:nil)
let mainStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let beginStoryBoard:UIStoryboard = UIStoryboard(name: "BeginningSounds", bundle:nil)
//play intro sound
var audioPlayer: AVAudioPlayer?
func playIntroMessage() {
let pathToSound = Bundle.main.path(forResource: "00alphabet_letters", ofType: "mp3")!
let url = URL(fileURLWithPath: pathToSound)
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.play()
} catch {
//bruh
}
}
// functions for sidebar
@IBAction func backButtonTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func homeButtonTapped(_ sender: Any) {
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
@IBAction func puzzleButtonTapped(_ sender: Any) {
let vc = mainStoryBoard.instantiateViewController(identifier: "puzzle_vc")
present(vc, animated: true)
}
@IBAction func coinButtonTapped(_ sender: Any) {
let vc = mainStoryBoard.instantiateViewController(identifier: "coin_vc")
present(vc, animated: true)
}
// code for main level select buttons
@IBAction func toNameBmras(_ sender: Any) {
let vc = letterStoryBoard.instantiateViewController(identifier: "namebmras_vc")
present(vc, animated: true)
}
@IBAction func toNameBmrasCap(_ sender: Any) {
let vc = letterStoryBoard.instantiateViewController(identifier: "namebmrascap_vc")
present(vc, animated: true)
}
@IBAction func toNameAbcde(_ sender: Any) {
let vc = letterStoryBoard.instantiateViewController(identifier: "nameabcde_vc")
present(vc, animated: true)
}
@IBAction func toNameAbcdeCap(_ sender: Any) {
let vc = letterStoryBoard.instantiateViewController(identifier: "nameabcdecap_vc")
present(vc, animated: true)
}
//goes to beginning sound
@IBAction func toSoundBmras(_ sender: Any) {
let vc = beginStoryBoard.instantiateViewController(identifier: "twoButton_vc")
present(vc, animated: true)
}
@IBAction func toSoundAbcde(_ sender: Any) {
let vc = beginStoryBoard.instantiateViewController(identifier: "oneButton_vc")
present(vc, animated: true)
}
@IBAction func toSoundBmrasCap(_ sender: Any) {
let vc = beginStoryBoard.instantiateViewController(identifier: "fourButton_vc")
present(vc, animated: true)
}
@IBAction func toSoundAbcdeCap(_ sender: Any) {
let vc = beginStoryBoard.instantiateViewController(identifier: "threeButton_vc")
present(vc, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 32.22807 | 106 | 0.66331 |
5641afa01cc659ff49568e9a99afeab6b7da1898 | 851 | //
// String+DPStringTool.swift
//
//
// Created by Derrick Park on 2019-01-28.
//
extension String {
subscript(index: Int) -> String {
get {
return String(self[self.index(startIndex, offsetBy: index)])
}
set {
let startIndex = self.index(self.startIndex, offsetBy: index)
self = self.replacingCharacters(in: startIndex..<self.index(after: startIndex), with: newValue)
}
}
subscript(start: Int, end: Int) -> String {
get {
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: end)
return String(self[startIndex..<endIndex])
}
set {
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: end)
self = self.replacingCharacters(in: startIndex..<endIndex, with: newValue)
}
}
}
| 25.029412 | 98 | 0.687427 |
8980c6fd1de764af9c347867ec0bb26e2d2daa02 | 1,966 | // Swordfish
// By Phil Nash
//
// Include this file into a test target folder of a Swift project to use
//
// The repository is hosted at: https://github.com/philsquared/Swordfish
// This project is licensed under the BSD 2-Clause License
// See the associated LICENSE file in the root of this repository
import XCTest
public class SwordfishTests : XCTestCase {}
// Holds the LHS of the expression (as well as the auxiliary info,
// message, file and line) and provides overloads for comparison
// operators that forward on to XCTAssert...
// - as with Assertion, we should be able to capture rhs by @autoclosure
public struct ExprLhs<T : Equatable> {
let msg : String
let lhs : T
let file: StaticString
let line: UInt
func assertEqual( _ rhs: T ) {
XCTAssertEqual( lhs, rhs, msg, file:file, line: line )
}
func assertNotEqual( _ rhs: T ) {
XCTAssertNotEqual( lhs, rhs, msg, file:file, line: line )
}
public static func ==( lhsExpr : ExprLhs, rhs: T ) {
lhsExpr.assertEqual( rhs )
}
public static func !=( lhsExpr : ExprLhs, rhs: T ) {
lhsExpr.assertNotEqual( rhs )
}
}
// For now the only role of this type is to allow | to be overloaded, and
// pass on the message, file and line to the start of the expression object
public struct Assertion {
let msg : String
let file: StaticString
let line: UInt
// We're capturing the LHS value eagerly, but we should be able to capture
// as an @autoclosure
public static func | <T>(assertion: Assertion, lhs: T) -> ExprLhs<T> {
return ExprLhs(msg: assertion.msg, lhs: lhs, file: assertion.file, line: assertion.line )
}
}
// Captures an optional message, as well as file/ line number and bundles that up
// in an Assertion object
public func require( _ msg : String = String(), file: StaticString = #file, line: UInt = #line ) -> Assertion {
return Assertion( msg: msg, file: file, line: line )
} | 34.491228 | 111 | 0.678535 |
e842bc5bc6d84f4100ac3aa3f6c14767a5f389cd | 1,978 | //
// AssetListViewModel.swift
// AssetManagement
//
// Created by Onur Torna on 18.11.2018.
// Copyright © 2018 Onur Torna. All rights reserved.
//
import Foundation
final class AssetListState {
enum Change {
case error(message: String?)
case loading(Bool)
case dataFetch
}
var onChange: ((AssetListState.Change) -> Void)?
var isLoading = false {
didSet {
onChange?(.loading(isLoading))
}
}
/// Received error message to show to user
var receivedErrorMessage: String? {
didSet {
onChange?(.error(message: receivedErrorMessage))
}
}
/// All assets
var assets: [Asset]? {
didSet {
onChange?(.dataFetch)
}
}
}
final class AssetListViewModel {
private let state = AssetListState()
private let dataController: AssetListDataProtocol
var stateChangeHandler: ((AssetListState.Change) -> Void)? {
get {
return state.onChange
}
set {
state.onChange = newValue
}
}
/// Total number of assets
var assetCount: Int {
return state.assets?.count ?? 0
}
/// Returns specific asset at given index
func asset(at index: Int) -> Asset? {
guard let assets = state.assets else { return nil }
return assets[index]
}
init(dataController: AssetListDataProtocol) {
self.dataController = dataController
}
}
// MARK: - Network
extension AssetListViewModel {
func fetchAssets() {
state.isLoading = true
dataController.fetchAllAssets { [weak self] (assets, error) in
self?.state.isLoading = false
guard let strongSelf = self else { return }
guard error == nil else {
strongSelf.state.receivedErrorMessage = error?.am_message
return
}
strongSelf.state.assets = assets
}
}
}
| 21.5 | 73 | 0.580384 |
e82e2209f5f27265ac0a41ad915b5eb96d46596f | 6,007 | //
// Calculator.swift
// Calculator
//
// Created by Рабочий on 02/12/2018.
// Copyright © 2018 Рабочий. All rights reserved.
//
import Foundation
// MARK: Constants & Initializer
enum CalculatorConditions {
case firstNumberEnter
case secondNumberEnter
case ready
case equalResult
}
enum CalculatorOperations {
case none
case addition
case subtraction
case division
case multiplication
}
class Calculator {
private var firstNumber: Decimal
private var secondNumber: Decimal
private var condition: CalculatorConditions
private var operation: CalculatorOperations
private var inputHandler = InputHandler()
init() {
firstNumber = 0
secondNumber = 0
operation = CalculatorOperations.none
condition = CalculatorConditions.ready
}
// MARK: - Functions
// MARK: Input handling
func insertNumber(num: String) -> String {
guard let numInDouble = Double(inputHandler.digitAppend(num)) else {
return "Input handling error"
}
let decimalNumber = Decimal(numInDouble)
switch condition {
case .firstNumberEnter:
firstNumber = decimalNumber
return "\(firstNumber)"
case .secondNumberEnter:
secondNumber = decimalNumber
return "\(secondNumber)"
case .ready:
if(decimalNumber == 0) {
return "\(decimalNumber)"
}
firstNumber = decimalNumber
condition = .firstNumberEnter
return "\(firstNumber)"
case .equalResult:
_ = ac()
return insertNumber(num: num)
}
}
func insertKomma() -> String {
guard let numInDouble = Double(inputHandler.dotAppend()) else {
return "Input handling error"
}
let decimalNumber = Decimal(numInDouble)
switch condition {
case .firstNumberEnter:
firstNumber = decimalNumber
return "\(firstNumber)"
case .secondNumberEnter:
secondNumber = decimalNumber
return "\(secondNumber)"
case .ready:
firstNumber = 0
condition = .firstNumberEnter
return "\(firstNumber)"
case .equalResult:
_ = ac()
return "\(firstNumber)"
}
}
// MARK: Arithmetic logic
func unary() -> String {
guard let numInDouble = Double(inputHandler.minusPlus()) else {
return "Input handling error"
}
let decimalNumber = Decimal(numInDouble)
switch condition {
case .firstNumberEnter:
firstNumber = decimalNumber
return "\(firstNumber)"
case .secondNumberEnter:
secondNumber = decimalNumber
return "\(secondNumber)"
case .ready:
condition = .firstNumberEnter
firstNumber = decimalNumber
return "\(firstNumber)"
case .equalResult:
changeState(toCondition: .firstNumberEnter)
secondNumber = 0
return unary()
}
}
func procent() -> String {
switch condition {
case .firstNumberEnter:
secondNumber = 100
operation = .division
return equal()
case .secondNumberEnter:
firstNumber = secondNumber
secondNumber = 100
operation = .division
return equal()
case .ready:
return "\(firstNumber)"
case .equalResult:
changeState(toCondition: .firstNumberEnter)
return procent()
}
}
func ac() -> String {
if condition == .secondNumberEnter {
if secondNumber != 0 {
secondNumber = 0
inputHandler.clearAll()
return "\(secondNumber)"
} else {
firstNumber = 0
secondNumber = 0
operation = CalculatorOperations.none
changeState(toCondition: .ready)
return "\(firstNumber)"
}
} else {
firstNumber = 0
secondNumber = 0
operation = CalculatorOperations.none
changeState(toCondition: .ready)
return "\(firstNumber)"
}
}
func operate(type: CalculatorOperations) -> String {
operation = type
switch condition {
case .firstNumberEnter:
changeState(toCondition: .secondNumberEnter)
return "\(firstNumber)"
case .secondNumberEnter:
let result = equal()
changeState(toCondition: .secondNumberEnter)
return result
case .ready:
return "\(firstNumber)"
case .equalResult:
changeState(toCondition: .secondNumberEnter)
secondNumber = 0
return "\(firstNumber)"
}
}
func equal() -> String {
switch operation {
case .none:
return "\(firstNumber)"
case .multiplication:
firstNumber = firstNumber * secondNumber
changeState(toCondition: .equalResult)
case .addition:
firstNumber = firstNumber + secondNumber
changeState(toCondition: .equalResult)
case .division:
firstNumber = firstNumber / secondNumber
changeState(toCondition: .equalResult)
case .subtraction:
firstNumber = firstNumber - secondNumber
changeState(toCondition: .equalResult)
}
return "\(firstNumber)"
}
}
// MARK: - Helpers
extension Calculator {
func changeState(toCondition state: CalculatorConditions) {
condition = state
inputHandler.clearAll()
}
func currentStatusReturn() -> (CalculatorConditions, CalculatorOperations) {
return (condition, operation)
}
}
| 28.604762 | 80 | 0.563509 |
698f80b907109a70371c2d4efde9775aebe314d6 | 419 | //
// AppDelegate.swift
// LESwiftDemo
//
// Created by LQQ on 2019/1/16.
// Copyright © 2019 LQQ. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
| 20.95 | 145 | 0.720764 |
2271b749f133a7f33f7183420edfff225b083c8c | 669 | //
// GraphCoordinator.swift
// TechExam
//
// Created by Juan Carlos Carrera on 13/12/21.
//
import Foundation
import UIKit
class GraphCoordinator {
var navigationController: UINavigationController?
var graphViewController: GraphViewController?
init(navigationController: UINavigationController) {
self.navigationController = navigationController
let presenter = GraphPresenter(coordinator: self)
graphViewController = GraphViewController(presenter: presenter)
}
func start() {
guard let graphViewController = graphViewController else { return }
navigationController?.pushViewController(graphViewController, animated: true)
}
}
| 25.730769 | 81 | 0.77429 |
61d21a489e74060d38a9c287f558db64a75b685a | 2,158 | //
// AppDelegate.swift
// FilterLayer
//
// Created by Bastian Kohlbauer on 06.03.16.
// Copyright © 2016 Bastian Kohlbauer. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47.955556 | 285 | 0.742817 |
282efde38f38ffc8438d3713f2698f888e7d8ede | 1,081 | // swift-tools-version: 5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Safe",
platforms: [.iOS(.v13), .tvOS(.v13), .macOS(.v10_15), .watchOS(.v6), .macCatalyst(.v13)],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "Safe",
targets: ["Safe"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "Safe",
dependencies: []),
.testTarget(
name: "SafeTests",
dependencies: ["Safe"]),
]
)
| 36.033333 | 117 | 0.60592 |
eb07c365a9f11175dfed7e7af86b3385bb36558d | 428 | //
//
//
import SwiftUI
struct OnboardingView: View {
@StateObject var onboarding: OnboardingState = appState.onboarding
var body: some View {
ZStack {
NaviWindow(state: appState.routing.onboadingNaviState)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.background(
Color.plusDarkGreen
.ignoresSafeArea(.all)
)
}
}
| 20.380952 | 70 | 0.577103 |
6768d6942c2d3774f2cbbd714fe681d9ebdeb6d7 | 519 | import Foundation
extension URLRequest {
struct Example {
struct Correct {
static let json = URLRequest(url: URL.Example.Correct.json)
static let html = URLRequest(url: URL.Example.Correct.google)
}
struct Incorrect {
static let invalidUrl: URLRequest = {
var request = URLRequest(url: URL.Example.Incorrect.invalidUrl)
request.timeoutInterval = 1
return request
}()
}
}
}
| 27.315789 | 79 | 0.55684 |
215dfa362415707ab1ba69e90f7b4322384d9894 | 631 | //
// ASCIIShopTests.swift
// ASCIIShopTests
//
// Created by Dmytro Kabyshev on 11/24/16.
// Copyright © 2016 Dmytro Kabyshev. All rights reserved.
//
import XCTest
@testable import ASCIIShop
class ASCIIShopTests: 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() {
}
}
| 22.535714 | 111 | 0.645008 |
6a395ee6413e2de02c2f884605cb47d997a94ec3 | 4,995 | //
// UserTypeViewController.swift
// Chula Expo 2017
//
// Created by Pakpoom on 2/5/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
import CoreData
class UserTypeViewController: UIViewController {
var userType = "Academic"
var name: String?
var firstName: String?
var lastName: String?
var email: String?
var fbId: String!
var fbToken: String!
var fbImageProfileUrl: String?
var fbImage: UIImage?
var managedObjectContext: NSManagedObjectContext?
@IBOutlet var numberLabel: UILabel!
@IBOutlet var studentView: UIView!
@IBOutlet var studentIcon: UIImageView!
@IBOutlet var studentLabel: UILabel!
@IBOutlet var personView: UIView!
@IBOutlet var personIcon: UIImageView!
@IBOutlet var personLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
initialView()
}
override func viewDidLayoutSubviews() {
numberLabel.layer.cornerRadius = numberLabel.frame.height / 2
}
@IBAction func next(_ sender: UIButton) {
self.performSegue(withIdentifier: "toRegister", sender: self)
}
private func initialView() {
studentView.layer.borderWidth = 0
studentView.layer.borderColor = UIColor(red: 0.1725, green: 0.1922, blue: 0.2471, alpha: 1).cgColor
studentView.layer.cornerRadius = 6
studentView.layer.masksToBounds = true
let studentTapGesture = UITapGestureRecognizer(target: self, action: #selector(UserTypeViewController.wasTap(gestureRecognizer:)))
studentView.addGestureRecognizer(studentTapGesture)
personView.layer.borderWidth = 2
personView.layer.borderColor = UIColor(red: 0.1725, green: 0.1922, blue: 0.2471, alpha: 1).cgColor
personView.layer.cornerRadius = 6
personView.layer.masksToBounds = true
let personTapGesture = UITapGestureRecognizer(target: self, action: #selector(UserTypeViewController.wasTap(gestureRecognizer:)))
personView.addGestureRecognizer(personTapGesture)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.statusBarStyle = .default
}
func wasTap(gestureRecognizer: UITapGestureRecognizer) {
let tapView = gestureRecognizer.view!
if tapView == studentView {
userType = "Academic"
studentView.layer.borderWidth = 0
studentView.backgroundColor = UIColor(red: 0.1725, green: 0.1922, blue: 0.2471, alpha: 1)
studentIcon.image = #imageLiteral(resourceName: "studentWhite")
studentLabel.textColor = UIColor.white
personView.layer.borderWidth = 2
personView.backgroundColor = nil
personIcon.image = #imageLiteral(resourceName: "personBlack")
personLabel.textColor = UIColor(red: 0.1725, green: 0.1922, blue: 0.2471, alpha: 1)
} else {
userType = "Worker"
studentView.layer.borderWidth = 2
studentView.backgroundColor = nil
studentIcon.image = #imageLiteral(resourceName: "studentBlack")
studentLabel.textColor = UIColor(red: 0.1725, green: 0.1922, blue: 0.2471, alpha: 1)
personView.layer.borderWidth = 0
personView.backgroundColor = UIColor(red: 0.1725, green: 0.1922, blue: 0.2471, alpha: 1)
personIcon.image = #imageLiteral(resourceName: "personWhite")
personLabel.textColor = UIColor.white
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toRegister" {
let destination = segue.destination as! RegisterViewController
destination.userType = self.userType
destination.name = self.name
destination.firstName = self.firstName
destination.lastName = self.lastName
destination.email = self.email
destination.fbId = self.fbId
destination.fbToken = self.fbToken
destination.fbImageProfileUrl = self.fbImageProfileUrl
destination.fbImage = self.fbImage
destination.managedObjectContext = self.managedObjectContext
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 32.647059 | 138 | 0.624224 |
e5f748666c0f010b1a9a7821d6b9aaf0f857b248 | 424 |
extension Optional where Wrapped: ExpressibleByStringLiteral {
/// Convenience method for optional String character count.
/// Returns 0 for nil optional String *or* character count for non-nil optional String.
var wmf_safeCharacterCount: Int {
get {
guard let value = self as? String else {
return 0
}
return value.characters.count
}
}
}
| 30.285714 | 91 | 0.620283 |
110f24a3b07c578019832810454201afd5ef6c5a | 5,081 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
// This file was auto-autogenerated by scripts and templates at http://github.com/AudioKit/AudioKitDevTools/
import AVFoundation
/// AudioKit version of Apple's Expander Audio Unit
///
public class Expander: Node {
fileprivate let effectAU = AVAudioUnitEffect(appleEffect: kAudioUnitSubType_DynamicsProcessor)
let input: Node
/// Connected nodes
public var connections: [Node] { [input] }
/// Underlying AVAudioNode
public var avAudioNode: AVAudioNode { effectAU }
/// Specification details for expansionRatio
public static let expansionRatioDef = NodeParameterDef(
identifier: "expansionRatio",
name: "Expansion Ratio",
address: AUParameterAddress(kDynamicsProcessorParam_ExpansionRatio),
defaultValue: 2,
range: 1 ... 50.0,
unit: .rate)
/// Expansion Ratio (rate) ranges from 1 to 50.0 (Default: 2)
@Parameter(expansionRatioDef) public var expansionRatio: AUValue
/// Specification details for expansionThreshold
public static let expansionThresholdDef = NodeParameterDef(
identifier: "expansionThreshold",
name: "Expansion Threshold",
address: AUParameterAddress(kDynamicsProcessorParam_ExpansionThreshold),
defaultValue: 2,
range: 1 ... 50.0,
unit: .rate)
/// Expansion Threshold (rate) ranges from 1 to 50.0 (Default: 2)
@Parameter(expansionThresholdDef) public var expansionThreshold: AUValue
/// Specification details for attackTime
public static let attackTimeDef = NodeParameterDef(
identifier: "attackTime",
name: "Attack Time",
address: AUParameterAddress(kDynamicsProcessorParam_AttackTime),
defaultValue: 0.001,
range: 0.0001 ... 0.2,
unit: .seconds)
/// Attack Time (seconds) ranges from 0.0001 to 0.2 (Default: 0.001)
@Parameter(attackTimeDef) public var attackTime: AUValue
/// Specification details for releaseTime
public static let releaseTimeDef = NodeParameterDef(
identifier: "releaseTime",
name: "Release Time",
address: AUParameterAddress(kDynamicsProcessorParam_ReleaseTime),
defaultValue: 0.05,
range: 0.01 ... 3,
unit: .seconds)
/// Release Time (seconds) ranges from 0.01 to 3 (Default: 0.05)
@Parameter(releaseTimeDef) public var releaseTime: AUValue
/// Specification details for masterGain
public static let masterGainDef = NodeParameterDef(
identifier: "masterGain",
name: "Master Gain",
address: AUParameterAddress(kDynamicsProcessorParam_MasterGain),
defaultValue: 0,
range: -40 ... 40,
unit: .decibels)
/// Master Gain (decibels) ranges from -40 to 40 (Default: 0)
@Parameter(masterGainDef) public var masterGain: AUValue
/// Compression Amount (dB) read only
public var compressionAmount: AUValue {
return effectAU.auAudioUnit.parameterTree?.allParameters[7].value ?? 0
}
/// Input Amplitude (dB) read only
public var inputAmplitude: AUValue {
return effectAU.auAudioUnit.parameterTree?.allParameters[8].value ?? 0
}
/// Output Amplitude (dB) read only
public var outputAmplitude: AUValue {
return effectAU.auAudioUnit.parameterTree?.allParameters[9].value ?? 0
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted = true
/// Initialize the expander node
///
/// - parameter input: Input node to process
/// - parameter expansionRatio: Expansion Ratio (rate) ranges from 1 to 50.0 (Default: 2)
/// - parameter expansionThreshold: Expansion Threshold (rate) ranges from 1 to 50.0 (Default: 2)
/// - parameter attackTime: Attack Time (seconds) ranges from 0.0001 to 0.2 (Default: 0.001)
/// - parameter releaseTime: Release Time (seconds) ranges from 0.01 to 3 (Default: 0.05)
/// - parameter masterGain: Master Gain (decibels) ranges from -40 to 40 (Default: 0)
///
public init(
_ input: Node,
expansionRatio: AUValue = expansionRatioDef.defaultValue,
expansionThreshold: AUValue = expansionThresholdDef.defaultValue,
attackTime: AUValue = attackTimeDef.defaultValue,
releaseTime: AUValue = releaseTimeDef.defaultValue,
masterGain: AUValue = masterGainDef.defaultValue) {
self.input = input
associateParams(with: effectAU)
self.expansionRatio = expansionRatio
self.expansionThreshold = expansionThreshold
self.attackTime = attackTime
self.releaseTime = releaseTime
self.masterGain = masterGain
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
effectAU.bypass = false
isStarted = true
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
effectAU.bypass = true
isStarted = false
}
}
| 37.360294 | 108 | 0.681165 |
ef5cdc492ce7f47e0c36abe3be9e70a20bb72a28 | 4,975 | //
// InsetGroupedTableViewController.swift
// InstaQR
//
// Created by Oleg Abalonski on 12/18/19.
// Copyright © 2019 Oleg Abalonski. All rights reserved.
//
import UIKit
class InsetGroupedTableViewController: ViewController {
// MARK: - Internal Properties
var subtitle: String? {
didSet { subtitleLabel.text = subtitle }
}
var tableHeaderViewFont: UIFont =
UIFont.systemFont(ofSize: UIFont.preferredFont(forTextStyle: .body).pointSize, weight: .semibold) {
didSet { subtitleLabel.font = tableHeaderViewFont }
}
var tableHeaderViewBottomInset: CGFloat = 16.0
let tableViewCellID = "TableViewCellReuseIdentifier"
lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .insetGrouped)
tableView.tableHeaderView = containerView
tableView.separatorStyle = .none
tableView.backgroundColor = view.backgroundColor
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
lazy var containerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var subtitleLabel: UILabel = {
let label = UILabel()
label.font = tableHeaderViewFont
label.textColor = .label
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
containerView.addSubview(subtitleLabel)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layoutViews()
}
// MARK: - Layout
fileprivate func layoutViews() {
let headerViewWidth = view.frame.width - (view.layoutMargins.left + view.layoutMargins.right)
let headerViewHeight = heightForView(text: subtitle ?? "", width: headerViewWidth)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
containerView.topAnchor.constraint(equalTo: tableView.topAnchor),
containerView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
containerView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
containerView.heightAnchor.constraint(equalToConstant: headerViewHeight + tableHeaderViewBottomInset),
subtitleLabel.topAnchor.constraint(equalTo: containerView.topAnchor),
subtitleLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
subtitleLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
])
sizeHeaderToFit(tableView: tableView)
}
// MARK: - Private Methods
fileprivate func heightForView(text: String, width: CGFloat) -> CGFloat {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = tableHeaderViewFont
label.text = text
label.sizeToFit()
return label.frame.height
}
fileprivate func sizeHeaderToFit(tableView: UITableView) {
if let headerView = tableView.tableHeaderView {
let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
tableView.tableHeaderView = headerView
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
}
}
// MARK: - Internal Methods
func deselectTableViewRow() -> Void {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: selectedIndexPath, animated: true)
}
}
func rowIsLast(for indexPath: IndexPath) -> Bool {
let totalRows = tableView.numberOfRows(inSection: indexPath.section)
return (indexPath.row == totalRows - 1)
}
func animateReloadAllRows() {
var indexPaths: [IndexPath] = []
for i in 0..<tableView.numberOfSections {
for j in 0..<tableView.numberOfRows(inSection: i) {
indexPaths.append(IndexPath(row: j, section: i))
}
}
tableView.reloadRows(at: indexPaths, with: .fade)
}
}
| 34.79021 | 114 | 0.654673 |
093d079b81f459c65afac96d57b780c64ecfcf68 | 4,920 | import Combine
public extension Publisher where Self.Failure == Never {
/// Assigns a publisher’s output to a property of an object.
/// - Parameters:
/// - keyPath: A key path that indicates the property to assign.
/// - object: The object that contains the property.
/// The subscriber assigns the object’s property every time it receives a new value.
/// - ownership: The retainment / ownership strategy for the object.
/// The default value is `strong`.
/// - Returns:
/// An `AnyCancellable` instance.
/// Call `cancel()` on this instance when you no longer want the publisher to automatically assign the property.
/// Deinitializing this instance will also cancel automatic assignment.
func assign<Root: AnyObject>(to keyPath: ReferenceWritableKeyPath<Root, Self.Output>,
on object: Root,
ownership: ObjectOwnership = .strong) -> AnyCancellable {
switch ownership {
case .strong:
return assign(to: keyPath, on: object)
case .weak:
return sink { [weak object] value in
object?[keyPath: keyPath] = value
}
case .unowned:
return sink { [unowned object] value in
object[keyPath: keyPath] = value
}
}
}
/// Assigns each element from a Publisher to properties of the provided objects.
/// - Parameters:
/// - keyPath1: The key path of the first property to assign.
/// - object1: The first object on which to assign the value.
/// - keyPath2: The key path of the second property to assign.
/// - object2: The second object on which to assign the value.
/// - ownership: The retainment / ownership strategy for the object.
/// The default value is `strong`.
/// - Returns:
/// A cancellable instance; used when you end assignment of the received value.
/// Deallocation of the result will tear down the subscription stream.
func assign<Root1: AnyObject, Root2: AnyObject>(
to keyPath1: ReferenceWritableKeyPath<Root1, Output>, on object1: Root1,
and keyPath2: ReferenceWritableKeyPath<Root2, Output>, on object2: Root2,
ownership: ObjectOwnership = .strong
) -> AnyCancellable {
switch ownership {
case .strong:
return assign(to: keyPath1, on: object1, and: keyPath2, on: object2)
case .weak:
return sink { [weak object1, weak object2] value in
object1?[keyPath: keyPath1] = value
object2?[keyPath: keyPath2] = value
}
case .unowned:
return sink { [unowned object1, unowned object2] value in
object1[keyPath: keyPath1] = value
object2[keyPath: keyPath2] = value
}
}
}
/// Assigns each element from a Publisher to properties of the provided objects.
/// - Parameters:
/// - keyPath1: The key path of the first property to assign.
/// - object1: The first object on which to assign the value.
/// - keyPath2: The key path of the second property to assign.
/// - object2: The second object on which to assign the value.
/// - keyPath3: The key path of the third property to assign.
/// - object3: The third object on which to assign the value.
/// - ownership: The retainment / ownership strategy for the object.
/// The default value is `strong`.
/// - Returns:
/// A cancellable instance; used when you end assignment of the received value.
/// Deallocation of the result will tear down the subscription stream.
func assign<Root1: AnyObject, Root2: AnyObject, Root3: AnyObject>(
to keyPath1: ReferenceWritableKeyPath<Root1, Output>, on object1: Root1,
and keyPath2: ReferenceWritableKeyPath<Root2, Output>, on object2: Root2,
and keyPath3: ReferenceWritableKeyPath<Root3, Output>, on object3: Root3,
ownership: ObjectOwnership = .strong
) -> AnyCancellable {
switch ownership {
case .strong:
return assign(to: keyPath1, on: object1,
and: keyPath2, on: object2,
and: keyPath3, on: object3)
case .weak:
return sink { [weak object1, weak object2, weak object3] value in
object1?[keyPath: keyPath1] = value
object2?[keyPath: keyPath2] = value
object3?[keyPath: keyPath3] = value
}
case .unowned:
return sink { [unowned object1, unowned object2, unowned object3] value in
object1[keyPath: keyPath1] = value
object2[keyPath: keyPath2] = value
object3[keyPath: keyPath3] = value
}
}
}
}
| 46.857143 | 116 | 0.601626 |
cc4eb8fe0a7dd29f02edb4e65df38d799607a397 | 20,606 | //
// UIViewExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 SwifterSwift
//
#if canImport(UIKit) && !os(watchOS)
import UIKit
// MARK: - enums
public extension UIView {
/// SwifterSwift: Shake directions of a view.
///
/// - horizontal: Shake left and right.
/// - vertical: Shake up and down.
enum ShakeDirection {
/// SwifterSwift: Shake left and right.
case horizontal
/// SwifterSwift: Shake up and down.
case vertical
}
/// SwifterSwift: Angle units.
///
/// - degrees: degrees.
/// - radians: radians.
enum AngleUnit {
/// SwifterSwift: degrees.
case degrees
/// SwifterSwift: radians.
case radians
}
/// SwifterSwift: Shake animations types.
///
/// - linear: linear animation.
/// - easeIn: easeIn animation.
/// - easeOut: easeOut animation.
/// - easeInOut: easeInOut animation.
enum ShakeAnimationType {
/// SwifterSwift: linear animation.
case linear
/// SwifterSwift: easeIn animation.
case easeIn
/// SwifterSwift: easeOut animation.
case easeOut
/// SwifterSwift: easeInOut animation.
case easeInOut
}
}
// MARK: - Properties
public extension UIView {
/// SwifterSwift: Border color of view; also inspectable from Storyboard.
var borderColor: UIColor? {
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
set {
guard let color = newValue else {
layer.borderColor = nil
return
}
// Fix React-Native conflict issue
guard String(describing: type(of: color)) != "__NSCFType" else { return }
layer.borderColor = color.cgColor
}
}
/// SwifterSwift: Border width of view; also inspectable from Storyboard.
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
/// SwifterSwift: Corner radius of view; also inspectable from Storyboard.
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.masksToBounds = true
layer.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100)
}
}
/// SwifterSwift: Height of view.
var height: CGFloat {
get {
return frame.size.height
}
set {
frame.size.height = newValue
}
}
/// SwifterSwift: Check if view is in RTL format.
var isRightToLeft: Bool {
if #available(tvOS 10.0, *) {
return effectiveUserInterfaceLayoutDirection == .rightToLeft
} else {
return false
}
}
/// SwifterSwift: Take screenshot of view (if applicable).
var screenshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else { return nil }
layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext()
}
/// SwifterSwift: Shadow color of view; also inspectable from Storyboard.
var shadowColor: UIColor? {
get {
guard let color = layer.shadowColor else { return nil }
return UIColor(cgColor: color)
}
set {
layer.shadowColor = newValue?.cgColor
}
}
/// SwifterSwift: Shadow offset of view; also inspectable from Storyboard.
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
/// SwifterSwift: Shadow opacity of view; also inspectable from Storyboard.
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
/// SwifterSwift: Shadow radius of view; also inspectable from Storyboard.
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
/// SwifterSwift: Size of view.
var size: CGSize {
get {
return frame.size
}
set {
width = newValue.width
height = newValue.height
}
}
/// SwifterSwift: Get view's parent view controller
var parentViewController: UIViewController? {
weak var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
/// SwifterSwift: Width of view.
var width: CGFloat {
get {
return frame.size.width
}
set {
frame.size.width = newValue
}
}
/// SwifterSwift: x origin of view.
var x: CGFloat {
get {
return frame.origin.x
}
set {
frame.origin.x = newValue
}
}
/// SwifterSwift: y origin of view.
var y: CGFloat {
get {
return frame.origin.y
}
set {
frame.origin.y = newValue
}
}
}
// MARK: - Methods
public extension UIView {
/// SwifterSwift: Recursively find the first responder.
func firstResponder() -> UIView? {
var views = [UIView](arrayLiteral: self)
var index = 0
repeat {
let view = views[index]
if view.isFirstResponder {
return view
}
views.append(contentsOf: view.subviews)
index += 1
} while index < views.count
return nil
}
/// SwifterSwift: Set some or all corners radiuses of view.
///
/// - Parameters:
/// - corners: array of corners to change (example: [.bottomLeft, .topRight]).
/// - radius: radius for selected corners.
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let maskPath = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
layer.mask = shape
}
/// SwifterSwift: Add shadow to view.
///
/// - Parameters:
/// - color: shadow color (default is #137992).
/// - radius: shadow radius (default is 3).
/// - offset: shadow offset (default is .zero).
/// - opacity: shadow opacity (default is 0.5).
func addShadow(ofColor color: UIColor = UIColor(red: 0.07, green: 0.47, blue: 0.57, alpha: 1.0), radius: CGFloat = 3, offset: CGSize = .zero, opacity: Float = 0.5) {
layer.shadowColor = color.cgColor
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = opacity
layer.masksToBounds = false
}
/// SwifterSwift: Add array of subviews to view.
///
/// - Parameter subviews: array of subviews to add to self.
func addSubviews(_ subviews: [UIView]) {
subviews.forEach { addSubview($0) }
}
/// SwifterSwift: Fade in view.
///
/// - Parameters:
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil)
func fadeIn(duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
if isHidden {
isHidden = false
}
UIView.animate(withDuration: duration, animations: {
self.alpha = 1
}, completion: completion)
}
/// SwifterSwift: Fade out view.
///
/// - Parameters:
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil)
func fadeOut(duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
if isHidden {
isHidden = false
}
UIView.animate(withDuration: duration, animations: {
self.alpha = 0
}, completion: completion)
}
/// SwifterSwift: Load view from nib.
///
/// - Parameters:
/// - name: nib name.
/// - bundle: bundle of nib (default is nil).
/// - Returns: optional UIView (if applicable).
class func loadFromNib(named name: String, bundle: Bundle? = nil) -> UIView? {
return UINib(nibName: name, bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as? UIView
}
/// SwifterSwift: Remove all subviews in view.
func removeSubviews() {
subviews.forEach({ $0.removeFromSuperview() })
}
/// SwifterSwift: Remove all gesture recognizers from view.
func removeGestureRecognizers() {
gestureRecognizers?.forEach(removeGestureRecognizer)
}
/// SwifterSwift: Attaches gesture recognizers to the view. Attaching gesture recognizers to a view defines the scope of the represented gesture, causing it to receive touches hit-tested to that view and all of its subviews. The view establishes a strong reference to the gesture recognizers.
///
/// - Parameter gestureRecognizers: The array of gesture recognizers to be added to the view.
func addGestureRecognizers(_ gestureRecognizers: [UIGestureRecognizer]) {
for recognizer in gestureRecognizers {
addGestureRecognizer(recognizer)
}
}
/// SwifterSwift: Detaches gesture recognizers from the receiving view. This method releases gestureRecognizers in addition to detaching them from the view.
///
/// - Parameter gestureRecognizers: The array of gesture recognizers to be removed from the view.
func removeGestureRecognizers(_ gestureRecognizers: [UIGestureRecognizer]) {
for recognizer in gestureRecognizers {
removeGestureRecognizer(recognizer)
}
}
/// SwifterSwift: Rotate view by angle on relative axis.
///
/// - Parameters:
/// - angle: angle to rotate view by.
/// - type: type of the rotation angle.
/// - animated: set true to animate rotation (default is true).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func rotate(byAngle angle: CGFloat, ofType type: AngleUnit, animated: Bool = false, duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
let angleWithType = (type == .degrees) ? .pi * angle / 180.0 : angle
let aDuration = animated ? duration : 0
UIView.animate(withDuration: aDuration, delay: 0, options: .curveLinear, animations: { () -> Void in
self.transform = self.transform.rotated(by: angleWithType)
}, completion: completion)
}
/// SwifterSwift: Rotate view to angle on fixed axis.
///
/// - Parameters:
/// - angle: angle to rotate view to.
/// - type: type of the rotation angle.
/// - animated: set true to animate rotation (default is false).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func rotate(toAngle angle: CGFloat, ofType type: AngleUnit, animated: Bool = false, duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
let angleWithType = (type == .degrees) ? .pi * angle / 180.0 : angle
let aDuration = animated ? duration : 0
UIView.animate(withDuration: aDuration, animations: {
self.transform = self.transform.concatenating(CGAffineTransform(rotationAngle: angleWithType))
}, completion: completion)
}
/// SwifterSwift: Scale view by offset.
///
/// - Parameters:
/// - offset: scale offset
/// - animated: set true to animate scaling (default is false).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func scale(by offset: CGPoint, animated: Bool = false, duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
if animated {
UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () -> Void in
self.transform = self.transform.scaledBy(x: offset.x, y: offset.y)
}, completion: completion)
} else {
transform = transform.scaledBy(x: offset.x, y: offset.y)
completion?(true)
}
}
/// SwifterSwift: Shake view.
///
/// - Parameters:
/// - direction: shake direction (horizontal or vertical), (default is .horizontal)
/// - duration: animation duration in seconds (default is 1 second).
/// - animationType: shake animation type (default is .easeOut).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func shake(direction: ShakeDirection = .horizontal, duration: TimeInterval = 1, animationType: ShakeAnimationType = .easeOut, completion:(() -> Void)? = nil) {
CATransaction.begin()
let animation: CAKeyframeAnimation
switch direction {
case .horizontal:
animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
case .vertical:
animation = CAKeyframeAnimation(keyPath: "transform.translation.y")
}
switch animationType {
case .linear:
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
case .easeIn:
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
case .easeOut:
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
case .easeInOut:
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
}
CATransaction.setCompletionBlock(completion)
animation.duration = duration
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
CATransaction.commit()
}
/// SwifterSwift: Add Visual Format constraints.
///
/// - Parameters:
/// - withFormat: visual Format language
/// - views: array of views which will be accessed starting with index 0 (example: [v0], [v1], [v2]..)
@available(iOS 9, *) func addConstraints(withFormat: String, views: UIView...) {
// https://videos.letsbuildthatapp.com/
var viewsDictionary: [String: UIView] = [:]
for (index, view) in views.enumerated() {
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewsDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: withFormat, options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDictionary))
}
/// SwifterSwift: Anchor all sides of the view into it's superview.
@available(iOS 9, *)
func fillToSuperview() {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview {
let left = leftAnchor.constraint(equalTo: superview.leftAnchor)
let right = rightAnchor.constraint(equalTo: superview.rightAnchor)
let top = topAnchor.constraint(equalTo: superview.topAnchor)
let bottom = bottomAnchor.constraint(equalTo: superview.bottomAnchor)
NSLayoutConstraint.activate([left, right, top, bottom])
}
}
/// SwifterSwift: Add anchors from any side of the current view into the specified anchors and returns the newly added constraints.
///
/// - Parameters:
/// - top: current view's top anchor will be anchored into the specified anchor
/// - left: current view's left anchor will be anchored into the specified anchor
/// - bottom: current view's bottom anchor will be anchored into the specified anchor
/// - right: current view's right anchor will be anchored into the specified anchor
/// - topConstant: current view's top anchor margin
/// - leftConstant: current view's left anchor margin
/// - bottomConstant: current view's bottom anchor margin
/// - rightConstant: current view's right anchor margin
/// - widthConstant: current view's width
/// - heightConstant: current view's height
/// - Returns: array of newly added constraints (if applicable).
@available(iOS 9, *)
@discardableResult
func anchor(
top: NSLayoutYAxisAnchor? = nil,
left: NSLayoutXAxisAnchor? = nil,
bottom: NSLayoutYAxisAnchor? = nil,
right: NSLayoutXAxisAnchor? = nil,
topConstant: CGFloat = 0,
leftConstant: CGFloat = 0,
bottomConstant: CGFloat = 0,
rightConstant: CGFloat = 0,
widthConstant: CGFloat = 0,
heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
/// SwifterSwift: Anchor center X into current view's superview with a constant margin value.
///
/// - Parameter constant: constant of the anchor constraint (default is 0).
@available(iOS 9, *)
func anchorCenterXToSuperview(constant: CGFloat = 0) {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerXAnchor {
centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
}
/// SwifterSwift: Anchor center Y into current view's superview with a constant margin value.
///
/// - Parameter withConstant: constant of the anchor constraint (default is 0).
@available(iOS 9, *)
func anchorCenterYToSuperview(constant: CGFloat = 0) {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerYAnchor {
centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
}
/// SwifterSwift: Anchor center X and Y into current view's superview
@available(iOS 9, *)
func anchorCenterSuperview() {
// https://videos.letsbuildthatapp.com/
anchorCenterXToSuperview()
anchorCenterYToSuperview()
}
/// SwifterSwift: Search all superviews until a view with the condition is found.
///
/// - Parameter predicate: predicate to evaluate on superviews.
func ancestorView(where predicate: (UIView?) -> Bool) -> UIView? {
if predicate(superview) {
return superview
}
return superview?.ancestorView(where: predicate)
}
/// SwifterSwift: Search all superviews until a view with this class is found.
///
/// - Parameter name: class of the view to search.
func ancestorView<T: UIView>(withClass name: T.Type) -> T? {
return ancestorView(where: { $0 is T }) as? T
}
}
#endif
| 35.774306 | 296 | 0.616811 |
671ac7904a11216dec4d9509f28fa0b927e504dc | 662 | // Copyright SIX DAY LLC. All rights reserved.
import Foundation
public enum EthereumUnit: Int64 {
case wei = 1
case kwei = 1_000
case gwei = 1_000_000_000
case szabo = 1_000_000_000_000
case finney = 1_000_000_000_000_000
case ether = 1_000_000_000_000_000_000
}
extension EthereumUnit {
var name: String {
switch self {
case .wei: return "Wei"
case .kwei: return "Kwei"
case .gwei: return "Gwei"
case .szabo: return "Szabo"
case .finney: return "Finney"
case .ether: return "Ether"
}
}
}
//https://github.com/ethereumjs/ethereumjs-units/blob/master/units.json
| 23.642857 | 71 | 0.645015 |
4bc15686860266d1ae50dacfaffcb89f5fec8656 | 681 | //
// LandmarkRow.swift
// Landmarks
//
// Created by 孙强 on 2020/6/11.
// Copyright © 2020 孙强. All rights reserved.
//
import SwiftUI
struct LandmarkRow: View {
var landmark: Landmark
var body: some View {
HStack {
landmark.image.resizable().frame(width: 50, height: 50)
Text(landmark.name)
Spacer()
}.padding()
}
}
struct LandmarkRow_Previews: PreviewProvider {
static var previews: some View {
Group {
LandmarkRow(landmark: landmarkData[1])
LandmarkRow(landmark: landmarkData[2])
}.previewLayout(.fixed(width: UIScreen.main.bounds.width, height: 70))
}
}
| 21.967742 | 78 | 0.603524 |
6a26e526e29658a86da4487c4ffb8f7994073963 | 1,187 | //
// VPTextView.swift
// VelpayUI_Example
//
// Created by Rogelio Contreras Velázquez on 9/30/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
class VPTextView: UITextView {
@IBInspectable
var rounded : Bool = true {
didSet {
if rounded {
self.layer.cornerRadius = 5
} else {
self.layer.cornerRadius = 1
}
}
}
@IBInspectable
var borderWidth : CGFloat = 2.0 {
didSet {
self.layer.borderWidth = self.borderWidth
}
}
@IBInspectable
var borderColor : UIColor = .lightGray {
didSet {
self.layer.borderColor = self.borderColor.cgColor
}
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
| 22.826923 | 78 | 0.581297 |
d64b267946e391a0012e094831905560481ca75e | 749 | import XCTest
import BJCollection
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.827586 | 111 | 0.602136 |
e6e799365ff71de994c706c58a599dc172ed7506 | 3,702 | //
// Twilight.swift
// Twilight
//
// Copyright © 2021 Nikolaj Banke Jensen
//
// NOTICE: This file has been modified under compliance with the Apache 2.0 License
// from the original work of Richard "Shred" Körber. This file has been modified
// by translation from Java to Swift, including appropriate refactoring and adaptation.
//
// The original work can be found here: https://github.com/shred/commons-suncalc
//
// --------------------------------------------------------------------------------
//
// Copyright (C) 2017 Richard "Shred" Körber
// http://commons.shredzone.org
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
import Foundation
/// Structure for Twilight components.
public struct Twilight: Hashable {
/// The Sun's angle at the twilight position, in degrees.
public let angle: Double
/// The Sun's angle at the twilight position, in radians.
public var angleRad: Double {
return ExtendedMath.toRadians(angle)
}
/// Returns the angular position.
///
/// 0.0 means center of the Sun, 1.0 means upper edge
/// of the Sun.
///
/// Atmospheric refraction is taken into account.
public let position: Double?
/// True if this twilight position is topocentric.
///
/// Then the parallax and the atmospheric refration is taken into account.
public var isTopocentric: Bool {
return position != nil
}
/// Initializer for a Twilight structure.
/// - Parameters:
/// - angle: Sun angle at twilight position, in degrees.
/// - position: Angular position of the Sun.
public init(_ angle: Double, _ position: Double? = nil) {
self.angle = angle
self.position = position
}
}
/// Predefined Twilights.
public extension Twilight {
/// The moment when the visual upper edge of the Sun crosses the horizon.
///
/// This is commonly referred to as "sunrise" and "sunset".
///
/// Atmospheric refraction is taken into account.
static let visual = Twilight(0.0, 1.0)
/// The moment when the visual lower edge of the Sun crosses the horizon.
///
/// This is the ending of the sunrise and the starting of the sunset.
///
/// Atmospheric refraction is taken into account.
static let visualLower = Twilight(0.0, -1.0)
/// The moment when the center of the sun crosses the horizon (0°).
static let horizon = Twilight(0.0)
/// Civil twilight (-6°)
static let civil = Twilight(-6.0)
/// Nautical twilight (-12°)
static let nautical = Twilight(-12.0)
/// Astronomical twilight (-18°)
static let astronomical = Twilight(-18.0)
/// Golden hour (6°)
///
/// The Golden hour is between Golden hour and Blue hour.
///
/// The Magic hour is between Golden hour and Civil darkness.
static let goldenHour = Twilight(6.0)
/// Blue hour (-4°)
///
/// The Blue hour is between Night hour and Blue hour.
static let blueHour = Twilight(-4.0)
/// End of Blue hour (-8°)
///
/// "Night hour" is not an official term, but is just a name marking the beginning/end if the Blue hour.
static let nightHour = Twilight(-8.0)
/// Array of all predefined Twilights.
static let values = [visual, visualLower, horizon, civil, nautical, astronomical, goldenHour, blueHour, nightHour]
}
| 32.761062 | 118 | 0.635332 |
67aa38597b67b12bd0221edd4ac4ce65f41874ac | 579 | //
// JwtApiCompatible.swift
//
// Created by Chris Kobrzak on 05/03/2022.
//
import Foundation
public protocol JsonApiCompatible {
func post<T: Decodable>(url: URL, dictionary: [String: Any]) async throws -> T
func post<T: Decodable>(url: URL, dictionary: [String: Any], token: String) async throws -> T
func get<T: Decodable>(url: URL, token: String) async throws -> T
// The methods below currently assume the response is empty
func delete(url: URL, token: String) async throws
func patch(url: URL, dictionary: [String: Any], token: String) async throws
}
| 27.571429 | 95 | 0.704663 |
1d1c440afed00f7d10cfc1703d719f1274be3441 | 2,928 | //
// SpooferUI.swift
// NetworkResponseSpoofer
//
// Created by Deepu Mukundan on 11/14/16.
// Copyright © 2016 Hotwire. All rights reserved.
//
import Foundation
#if !COCOAPODS
import NetworkResponseSpoofer
#endif
import UIKit
public extension Spoofer {
/**
Starts recording a new scenario from a specific view controller.
- parameter sourceViewController: The view controller from which the record popup UI will be presented from
- Note: A popup will appear asking the user to name the scenario, before recording starts.
Use this method if you need to manually provide the scenario name
*/
class func startRecording(inViewController sourceViewController: UIViewController?) {
presentController(with: RecordTableViewController.identifier, sourceViewController: sourceViewController)
}
/**
Show recorded scenarios in Documents folder as a list for the user to select and start replay (Replay selection UI)
- parameter sourceViewController: The view controller from which to present the replay selection UI
- Note: The replay selection UI also has few other roles.
- It allows configuring the spoofer using a config button the nav bar,
allowing to tweak whitelist/blacklist/query parameters, normalization etc
- It shows the list of pre-recorded scenarios in the folder. Tapping a scenario starts replay directly and dismissed the UI
- It allows diving deeper into the scenario by tapping the info button along the right of each scenario.
This lists the url's which have recorded responses in the scenario.
*/
class func showRecordedScenarios(inViewController sourceViewController: UIViewController?) {
presentController(with: SuiteListController.identifier, sourceViewController: sourceViewController)
}
}
private extension Spoofer {
class func presentController(with identifier: String, sourceViewController: UIViewController?) {
guard let sourceViewController = sourceViewController else { return }
var viewControllerToPresent = spooferStoryBoard().instantiateViewController(withIdentifier: identifier)
// If SuiteListController was invoked directly, we are in replay mode, and so disallow suite creation and
/// wrap the controller in a navcontroller
switch viewControllerToPresent {
case let controller as SuiteListController:
controller.navigationItem.rightBarButtonItem = nil
viewControllerToPresent = UINavigationController(rootViewController: controller)
default: break
}
sourceViewController.present(viewControllerToPresent, animated: true, completion: nil)
}
class func spooferStoryBoard() -> UIStoryboard {
let frameworkBundle = Bundle(for: Spoofer.self)
let storyBoard = UIStoryboard(name: "Spoofer", bundle: frameworkBundle)
return storyBoard
}
}
| 41.828571 | 128 | 0.74556 |
e2a461408e4cf68b325ddae9e34d16abdaea9b3a | 2,124 | // This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let gbErrorDetails = try GbErrorDetails(json)
//
// Hashable or Equatable:
// The compiler will not be able to synthesize the implementation of Hashable or Equatable
// for types that require the use of JSONAny, nor will the implementation of Hashable be
// synthesized for types that have collections (such as arrays or dictionaries).
import Foundation
/// The schema for the response body when there is a 400 error because the beacon data was
/// invalid.
// MARK: - GbErrorDetails
public struct GbErrorDetails: Codable, Hashable {
/// The errors encountered while validating the beacon according to the request body JSON
/// Schemas.
public var jsonSchemaValidationErrors: [String]
public init(jsonSchemaValidationErrors: [String]) {
self.jsonSchemaValidationErrors = jsonSchemaValidationErrors
}
}
// MARK: GbErrorDetails convenience initializers and mutators
public extension GbErrorDetails {
init(data: Data) throws {
let me = try newJSONDecoder().decode(GbErrorDetails.self, from: data)
self.init(jsonSchemaValidationErrors: me.jsonSchemaValidationErrors)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
jsonSchemaValidationErrors: [String]? = nil
) -> GbErrorDetails {
return GbErrorDetails(
jsonSchemaValidationErrors: jsonSchemaValidationErrors ?? self.jsonSchemaValidationErrors
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
| 34.819672 | 101 | 0.700565 |
ab75602b787d040ef9bb2bb19bb4ad7699d1eb87 | 14,058 | //
// MMGeofencingServiceTestUtils.swift
// MobileMessagingExample
//
// Created by Andrey Kadochnikov on 13/11/2018.
//
import Foundation
import CoreLocation
@testable import MobileMessaging
extension Set where Element: MMRegion {
var findPula: MMRegion {
return self.filter { (region) -> Bool in
return region.title == "Pula"
}.first!
}
var findZagreb: MMRegion {
return self.filter { (region) -> Bool in
return region.title == "Zagreb"
}.first!
}
}
class LocationManagerStub: CLLocationManager {
var locationStub: CLLocation?
var monitoredRegionsArray = [CLRegion]()
init(locationStub: CLLocation? = nil) {
self.locationStub = locationStub
super.init()
}
override var monitoredRegions: Set<CLRegion> {
get { return Set(monitoredRegionsArray)}
set {}
}
override var location: CLLocation? {
return locationStub ?? super.location
}
override func startMonitoring(for region: CLRegion) {
monitoredRegionsArray.append(region)
}
override func stopMonitoring(for region: CLRegion) {
if let index = monitoredRegionsArray.index(of: region) {
monitoredRegionsArray.remove(at: index)
}
}
}
class GeofencingServiceAlwaysRunningStub: MMGeofencingService {
init(mmContext: MobileMessaging, locationManagerStub: LocationManagerStub = LocationManagerStub()) {
self.stubbedLocationManager = locationManagerStub
super.init(mmContext: mmContext)
}
var didEnterRegionCallback: ((MMRegion) -> Void)?
override var isRunning: Bool {
set {}
get { return true }
}
override var locationManager: CLLocationManager! {
set {}
get {
return stubbedLocationManager
}
}
var stubbedLocationManager: LocationManagerStub
override func authorizeService(kind: MMLocationServiceKind, usage: MMLocationServiceUsage, completion: @escaping (MMGeofencingCapabilityStatus) -> Void) {
completion(.authorized)
}
override func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {}
override func onEnter(datasourceRegion: MMRegion, completion: @escaping () -> Void) {
self.didEnterRegionCallback?(datasourceRegion)
completion()
}
override func stop(_ completion: ((Bool) -> Void)?) {
eventsHandlingQueue.cancelAllOperations()
self.isRunning = false
stubbedLocationManager.monitoredRegionsArray = [CLRegion]()
}
override public class var currentCapabilityStatus: MMGeofencingCapabilityStatus {
return MMGeofencingCapabilityStatus.authorized
}
}
class GeofencingServiceDisabledStub: MMGeofencingService {
init(mmContext: MobileMessaging, locationManagerStub: LocationManagerStub = LocationManagerStub()) {
self.locationManagerStub = locationManagerStub
super.init(mmContext: mmContext)
}
var didEnterRegionCallback: ((MMRegion) -> Void)?
override var isRunning: Bool {
set {}
get { return false }
}
override var locationManager: CLLocationManager! {
set {}
get {
return locationManagerStub
}
}
var locationManagerStub: LocationManagerStub
override func authorizeService(kind: MMLocationServiceKind, usage: MMLocationServiceUsage, completion: @escaping (MMGeofencingCapabilityStatus) -> Void) {
completion(.denied)
}
override func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {}
override func onEnter(datasourceRegion: MMRegion, completion: @escaping () -> Void) {
self.didEnterRegionCallback?(datasourceRegion)
completion()
}
override func stop(_ completion: ((Bool) -> Void)?) {
eventsHandlingQueue.cancelAllOperations()
self.isRunning = false
locationManagerStub.monitoredRegionsArray = [CLRegion]()
}
override public class var currentCapabilityStatus: MMGeofencingCapabilityStatus {
return MMGeofencingCapabilityStatus.denied
}
}
let expectedCampaignId = "campaign 1"
let expectedMessageId = "message 1"
let expectedCampaignText = "campaign text"
let expectedCampaignTitle = "campaign title"
let expectedInAppDismissBtnTitle = "Dismiss Button"
let expectedInAppOpenBtnTitle = "Open Button"
let expectedContentUrl = "http://hello.com"
let expectedInAppWebViewUrl = "http://hello.com"
let expectedInAppBrowserUrl = "http://hello.com"
let expectedInAppDeeplink = "mydomain://hello.com/first/second"
let expectedSound = "default"
let expectedStartDateString = "2016-08-05T12:20:16+03:00"
let expectedExpiryDateString = "2016-08-06T12:20:16+03:00"
var expectedStartDate: Date {
let comps = NSDateComponents()
comps.year = 2016
comps.month = 8
comps.day = 5
comps.hour = 12
comps.minute = 20
comps.second = 16
comps.timeZone = TimeZone(secondsFromGMT: 3*60*60) // has expected timezone
comps.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
return comps.date!
}
var expectedExpiryDate: Date {
let comps = NSDateComponents()
comps.year = 2016
comps.month = 8
comps.day = 6
comps.hour = 12
comps.minute = 20
comps.second = 16
comps.timeZone = TimeZone(secondsFromGMT: 3*60*60) // has expected timezone
comps.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
return comps.date!
}
var notExpectedDate: Date {
let comps = NSDateComponents()
comps.year = 2016
comps.month = 8
comps.day = 6
comps.hour = 12
comps.minute = 20
comps.second = 16
comps.timeZone = TimeZone(secondsFromGMT: 60*60) // has different (not expected) timezone
comps.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
return comps.date!
}
var buddhistCalendarDate_06_08_2560__12_20_16: Date {
let comps = NSDateComponents()
comps.year = 2560
comps.month = 8
comps.day = 6
comps.hour = 12
comps.minute = 20
comps.second = 16
comps.calendar = Calendar(identifier: Calendar.Identifier.buddhist)
comps.timeZone = TimeZone(secondsFromGMT: 0)
return comps.date!
}
var japCalendarDate_06_08_0029__12_20_16: Date {
let comps = NSDateComponents()
comps.year = 29
comps.month = 8
comps.day = 6
comps.hour = 12
comps.minute = 20
comps.second = 16
comps.calendar = Calendar(identifier: Calendar.Identifier.japanese)
comps.timeZone = TimeZone(secondsFromGMT: 0)
return comps.date!
}
var gregorianCalendarDate_06_08_2017__12_20_16: Date {
let comps = NSDateComponents()
comps.year = 2017
comps.month = 8
comps.day = 6
comps.hour = 12
comps.minute = 20
comps.second = 16
comps.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
comps.timeZone = TimeZone(secondsFromGMT: 0)
return comps.date!
}
func baseAPNSDict(messageId: String = expectedMessageId) -> MMAPNSPayload {
return
[
Consts.APNSPayloadKeys.messageId: messageId,
Consts.APNSPayloadKeys.aps: [
Consts.APNSPayloadKeys.contentAvailable: 1
]
]
}
let zagrebId = "6713245DA3638FDECFE448C550AD7681"
let pulaId = "A277A2A0D0612AFB652E9D2D80E02BF2"
let nestedPulaId = "M227A2A0D0612AFB652E9D2D80E0ZZ44"
// modern:
let modernZagrebDict: MMAPNSPayload = [
GeoConstants.RegionKeys.identifier: zagrebId,
GeoConstants.RegionKeys.latitude: 45.80869126677998,
GeoConstants.RegionKeys.longitude: 15.97206115722656,
GeoConstants.RegionKeys.radius: 9492.0,
GeoConstants.RegionKeys.title: "Zagreb"
]
let modernPulaDict: MMAPNSPayload = [
GeoConstants.RegionKeys.identifier: pulaId,
GeoConstants.RegionKeys.latitude: 44.86803631018752,
GeoConstants.RegionKeys.longitude: 13.84586334228516,
GeoConstants.RegionKeys.radius: 5257.0,
GeoConstants.RegionKeys.title: "Pula"
]
let nestedPulaDict: MMAPNSPayload = [
GeoConstants.RegionKeys.identifier: nestedPulaId,
GeoConstants.RegionKeys.latitude: 44.868036310,
GeoConstants.RegionKeys.longitude: 13.845863342,
GeoConstants.RegionKeys.radius: 5157.0,
GeoConstants.RegionKeys.title: "Pula smaller"
]
var modernInternalDataWithZagrebPulaDict: MMAPNSPayload {
var result = makeBaseInternalDataDict(campaignId: expectedCampaignId)
result[Consts.InternalDataKeys.geo] = [modernZagrebDict, modernPulaDict]
return result
}
var modernAPNSPayloadZagrebPulaDict: MMAPNSPayload {
return (baseAPNSDict() + [Consts.APNSPayloadKeys.internalData: modernInternalDataWithZagrebPulaDict])!
}
// jsons
let jsonStr = """
{
"aps": {
"content-available": 1
},
"messageId": "lY8Ja3GKmeN65J5hNlL9B9lLA9LrN//C/nH75iK+2KI=",
"internalData": {
"campaignId": "\(expectedCampaignId)",
"silent": {
"body": "\(expectedCampaignText)",
"title": "\(expectedCampaignTitle)",
"sound": "\(expectedSound)"
},
"atts": [{"url": "\(expectedContentUrl)"}],
"startTime": "\(expectedStartDateString)",
"expiryTime": "\(expectedExpiryDateString)",
"inApp": 1,
"inAppStyle": 1,
"inAppDismissTitle": "\(expectedInAppDismissBtnTitle)",
"inAppOpenTitle": "\(expectedInAppOpenBtnTitle)",
"webViewUrl": "\(expectedInAppWebViewUrl)",
"browserUrl": "\(expectedInAppBrowserUrl)",
"deeplink": "\(expectedInAppDeeplink)",
"geo": [
{
"id": "\(zagrebId)",
"latitude": 45.80869126677998,
"longitude": 15.97206115722656,
"radiusInMeters": 9492.0,
"title": "Zagreb"
},
{
"id": "\(pulaId)",
"latitude": 44.86803631018752,
"longitude": 13.84586334228516,
"radiusInMeters": 5257.0,
"title": "Pula"
}
]
}
}
"""
let jsonStrFromPushUp = """
{
"aps": {
"sound": "\(expectedSound)",
"alert": {
"body": "\(expectedCampaignText)",
"title": "\(expectedCampaignTitle)"
},
"silent": true,
},
"messageId": "lY8Ja3GKmeN65J5hNlL9B9lLA9LrN//C/nH75iK+2KI=",
"internalData": {
"campaignId": "\(expectedCampaignId)",
"messageType":"geo",
"silent": {
"body": "\(expectedCampaignText)",
"title": "\(expectedCampaignTitle)",
"sound": "\(expectedSound)"
},
"atts": [{"url": "\(expectedContentUrl)"}],
"startTime": "\(expectedStartDateString)",
"expiryTime": "\(expectedExpiryDateString)",
"inApp": 1,
"inAppStyle": 1,
"inAppDismissTitle": "\(expectedInAppDismissBtnTitle)",
"inAppOpenTitle": "\(expectedInAppOpenBtnTitle)",
"webViewUrl": "\(expectedInAppWebViewUrl)",
"browserUrl": "\(expectedInAppBrowserUrl)",
"deeplink": "\(expectedInAppDeeplink)",
"geo": [
{
"id": "\(zagrebId)",
"latitude": 45.80869126677998,
"longitude": 15.97206115722656,
"radiusInMeters": 9492.0,
"title": "Zagreb"
},
{
"id": "\(pulaId)",
"latitude": 44.86803631018752,
"longitude": 13.84586334228516,
"radiusInMeters": 5257.0,
"title": "Pula"
}
]
}
}
"""
let jsonStrWithoutStartTime =
"{" +
"\"aps\": { \"content-available\": 1}," +
"\"messageId\": \"lY8Ja3GKmeN65J5hNlL9B9lLA9LrN//C/nH75iK+2KI=\"," +
"\"internalData\": {" +
"\"campaignId\": \"\(expectedCampaignId)\"," +
"\"silent\": {" +
"\"body\": \"\(expectedCampaignText)\"," +
"\"sound\": \"\(expectedSound)\"" +
"}," +
"\"expiryTime\": \""+expectedExpiryDateString+"\"," +
"\"geo\": [" +
"{" +
"\"id\": \"\(zagrebId)\"," +
"\"latitude\": 45.80869126677998," +
"\"longitude\": 15.97206115722656," +
"\"radiusInMeters\": 9492.0," +
"\"title\": \"Zagreb\"" +
"}," +
"{" +
"\"id\": \"\(pulaId)\"," +
"\"latitude\": 44.86803631018752," +
"\"longitude\": 13.84586334228516," +
"\"radiusInMeters\": 5257.0," +
"\"title\": \"Pula\"" +
"}" +
"]" +
"}" +
"}"
let suspendedCampaignId = "suspendedCampaignId"
let finishedCampaignId = "finishedCampaignId"
func makeBaseInternalDataDict(campaignId: String) -> MMAPNSPayload {
return
[
GeoConstants.CampaignKeys.campaignId: campaignId,
GeoConstants.CampaignKeys.startDate: expectedStartDateString,
GeoConstants.CampaignKeys.expiryDate: expectedExpiryDateString,
Consts.InternalDataKeys.silent: [Consts.APNSPayloadKeys.body: expectedCampaignText, Consts.APNSPayloadKeys.sound: expectedSound],
Consts.InternalDataKeys.messageType: Consts.InternalDataKeys.messageTypeGeo
]
}
func makeApnsPayloadWithoutRegionsDataDict(campaignId: String, messageId: String) -> MMAPNSPayload {
return (baseAPNSDict(messageId: messageId) + [Consts.APNSPayloadKeys.internalData: makeBaseInternalDataDict(campaignId: campaignId)])!
}
func makeApnsPayload(withEvents events: [MMAPNSPayload]?, deliveryTime: MMAPNSPayload?, regions: [MMAPNSPayload], campaignId: String = expectedCampaignId, messageId: String = expectedMessageId) -> MMAPNSPayload {
var result = makeApnsPayloadWithoutRegionsDataDict(campaignId: campaignId, messageId: messageId)
var internalData = result[Consts.APNSPayloadKeys.internalData] as! MMAPNSPayload
internalData[Consts.InternalDataKeys.geo] = regions
internalData[Consts.InternalDataKeys.event] = events ?? [defaultEvent]
internalData[Consts.InternalDataKeys.deliveryTime] = deliveryTime
let distantFutureDateString = DateStaticFormatters.ISO8601SecondsFormatter.string(from: Date.distantFuture)
internalData[GeoConstants.CampaignKeys.expiryDate] = distantFutureDateString
result[Consts.APNSPayloadKeys.internalData] = internalData
return result
}
func makeEventDict(ofType type: RegionEventType, limit: Int, timeout: Int? = nil) -> MMAPNSPayload {
var result: MMAPNSPayload = [GeoConstants.RegionEventKeys.type: type.rawValue,
GeoConstants.RegionEventKeys.limit: limit]
result[GeoConstants.RegionEventKeys.timeout] = timeout
return result
}
func makeDeliveryTimeDict(withTimeIntervalString timeInterval: String? = nil, daysString days: String? = nil) -> MMAPNSPayload? {
var result = MMAPNSPayload()
result[GeoConstants.RegionDeliveryTimeKeys.timeInterval] = timeInterval
result[GeoConstants.RegionDeliveryTimeKeys.days] = days
return result.isEmpty ? nil : result
}
var defaultEvent = ["limit": 1, "rate": 0, "timeoutInMinutes": 0, "type": "entry"] as MMAPNSPayload
var succeedingApiStub: RemoteGeoAPIProviderStub = {
let remoteApiProvider = RemoteGeoAPIProviderStub()
remoteApiProvider.reportGeoEventClosure = { _,_,_,_ -> GeoEventReportingResult in
return GeoEventReportingResult.Success(GeoEventReportingResponse(json: JSON.parse(
"""
{
"messageIds": {
"tm1": "m1",
"tm2": "m2",
"tm3": "m3"
}
}
"""
))!)
}
return remoteApiProvider
}()
var failingApiStub: RemoteGeoAPIProviderStub = {
let remoteApiProvider = RemoteGeoAPIProviderStub()
remoteApiProvider.reportGeoEventClosure = { _,_,_,_ -> GeoEventReportingResult in
return GeoEventReportingResult.Failure(MMInternalErrorType.UnknownError.foundationError)
}
return remoteApiProvider
}()
| 28.86653 | 212 | 0.745696 |
db0d09c3041f7a91726119efa15547da5d837a8a | 702 | import Foundation;
// Problem given:
var json = """
{
"name": "Neha",
"studentId": 326156,
"academics": {
"field": "iOS",
"grade": "A"
}
}
""".data(using: .utf8)!
// TODO: define model objects here
struct Academics: Codable {
let field: String;
let grade: String;
}
struct Student: Codable {
let name: String;
let studentId: Int;
let academics: Academics; //subfield
}
// Test case:
let decoder = JSONDecoder();
let student: Student;
do {
// TODO: decode the JSON into the "student" constant
student = try decoder.decode(Student.self, from:json);
print(student)
} catch {
print(error)
}
// Extras: Access keys & values directly
| 17.55 | 58 | 0.616809 |
ed7e890852fae2ed44b7323f090e0300cedd3a42 | 1,407 | //
// OperationDispatcher.swift
// Purchases
//
// Created by Andrés Boedo on 8/5/20.
// Copyright © 2020 Purchases. All rights reserved.
//
import Foundation
@objc(RCOperationDispatcher) public class OperationDispatcher: NSObject {
private let mainQueue: DispatchQueue
private let workerQueue: DispatchQueue
private let maxJitterInSeconds: Double = 5
@objc public override init() {
mainQueue = DispatchQueue.main
workerQueue = DispatchQueue(label: "OperationDispatcherWorkerQueue")
}
@objc public func dispatchOnMainThread(_ block: @escaping () -> Void) {
if Thread.isMainThread {
block()
} else {
mainQueue.async { block() }
}
}
@objc public func dispatchOnWorkerThread(withRandomDelay: Bool = false,
block: @escaping () -> Void) {
if withRandomDelay {
let delay = Double.random(in: 0..<maxJitterInSeconds)
workerQueue.asyncAfter(deadline: .now() + delay) { block() }
} else {
workerQueue.async { block() }
}
}
@objc public func dispatchOnWorkerThread(afterDelayInSeconds delayInSeconds: Int,
block: @escaping () -> Void) {
workerQueue.asyncAfter(deadline: .now() + .seconds(delayInSeconds)) {
block()
}
}
}
| 29.93617 | 85 | 0.592751 |
08d71e7dfa96092920cf41b300776f619392a30f | 3,128 | //
// SearchSceneViewController.swift
// Findme
//
// Created by wentong on 2018/9/24.
// Copyright © 2018年 mmoaay. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
extension SearchSceneViewController {
}
extension SearchSceneViewController: SwitchViewDelegate {
func switched(status: OperationStatus) {
switch status {
case .locating:
sceneView.scene = route.scene
// Run the view's session
sceneView.session.run(configuration, options: .resetTracking)
break
case .going:
imageView.isHidden = true
break
case .done:
navigationController?.popViewController(animated: true)
break
default:
break
}
switchView.status = status.next(type: switchView.type)
}
}
class SearchSceneViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
@IBOutlet weak var switchView: SwitchView!
@IBOutlet weak var imageView: UIImageView!
var route = Route()
lazy var configuration = { () -> ARWorldTrackingConfiguration in
let configuration = ARWorldTrackingConfiguration()
configuration.worldAlignment = .gravityAndHeading
// configuration.isLightEstimationEnabled = false
return configuration
}()
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
// sceneView.showsStatistics = true
// sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin]
// Set the scene to the view
sceneView.scene = SCNScene()
// Run the view's session
sceneView.session.run(configuration)
switchView.type = .search
switchView.delegate = self
imageView.image = route.image
}
@IBAction func sharePressed(_ sender: UIBarButtonItem) {
ShareUtil.shared.shareRoute(view: self.view, identity: route.identity)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
// MARK: - ARSCNViewDelegate
// Override to create and configure nodes for anchors added to the view's session.
// func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
// let node = SCNNode()
//
// return node
// }
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
sceneView.session.run(configuration)
}
}
| 28.962963 | 103 | 0.638427 |
39f3e433af18741f32f13c1239fb84f15d0ed4fe | 786 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
public enum TodoCollectionError: Error {
case ConnectionRefused
case IDNotFound(String)
case CreationError(String)
case ParseError
case AuthError
}
| 29.111111 | 75 | 0.743003 |
6ad8f703c67041b0babe4892d99670c30a4644a2 | 959 | //
// CalculatorTests.swift
// CalculatorTests
//
// Created by Yanni Speron on 9/1/20.
// Copyright © 2020 YanniSperon. All rights reserved.
//
import XCTest
@testable import Calculator
class 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.4 | 111 | 0.67049 |
dd96e7252ac2f52d02a55d2c354203e85d6738bd | 82,695 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 SwiftShims
@_transparent
internal func _abstract(
methodName: StaticString = #function,
file: StaticString = #file, line: UInt = #line
) -> Never {
#if INTERNAL_CHECKS_ENABLED
_fatalErrorMessage("abstract method", methodName, file: file, line: line,
flags: _fatalErrorFlags())
#else
_conditionallyUnreachable()
#endif
}
// MARK: Type-erased abstract base classes
/// A type-erased key path, from any root type to any resulting value type.
public class AnyKeyPath: Hashable, _AppendKeyPath {
/// The root type for this key path.
@_inlineable
public static var rootType: Any.Type {
return _rootAndValueType.root
}
/// The value type for this key path.
@_inlineable
public static var valueType: Any.Type {
return _rootAndValueType.value
}
internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>?
final public var hashValue: Int {
var hash = 0
withBuffer {
var buffer = $0
while true {
let (component, type) = buffer.next()
hash ^= _mixInt(component.value.hashValue)
if let type = type {
hash ^= _mixInt(unsafeBitCast(type, to: Int.self))
} else {
break
}
}
}
return hash
}
public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool {
// Fast-path identical objects
if a === b {
return true
}
// Short-circuit differently-typed key paths
if type(of: a) != type(of: b) {
return false
}
return a.withBuffer {
var aBuffer = $0
return b.withBuffer {
var bBuffer = $0
// Two equivalent key paths should have the same reference prefix
if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix {
return false
}
while true {
let (aComponent, aType) = aBuffer.next()
let (bComponent, bType) = bBuffer.next()
if aComponent.header.endOfReferencePrefix
!= bComponent.header.endOfReferencePrefix
|| aComponent.value != bComponent.value
|| aType != bType {
return false
}
if aType == nil {
return true
}
}
}
}
}
// SPI for the Foundation overlay to allow interop with KVC keypath-based
// APIs.
public var _kvcKeyPathString: String? {
guard let ptr = _kvcKeyPathStringPtr else { return nil }
return String(validatingUTF8: ptr)
}
// MARK: Implementation details
// Prevent normal initialization. We use tail allocation via
// allocWithTailElems().
internal init() {
_sanityCheckFailure("use _create(...)")
}
// internal-with-availability
public class var _rootAndValueType: (root: Any.Type, value: Any.Type) {
_abstract()
}
public // @testable
static func _create(
capacityInBytes bytes: Int,
initializedBy body: (UnsafeMutableRawBufferPointer) -> Void
) -> Self {
_sanityCheck(bytes > 0 && bytes % 4 == 0,
"capacity must be multiple of 4 bytes")
let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue,
Int32.self)
result._kvcKeyPathStringPtr = nil
let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result,
Int32.self))
body(UnsafeMutableRawBufferPointer(start: base, count: bytes))
return result
}
func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T {
defer { _fixLifetime(self) }
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try f(KeyPathBuffer(base: base))
}
}
/// A partially type-erased key path, from a concrete root type to any
/// resulting value type.
public class PartialKeyPath<Root>: AnyKeyPath { }
// MARK: Concrete implementations
internal enum KeyPathKind { case readOnly, value, reference }
/// A key path from a specific root type to a specific resulting value type.
public class KeyPath<Root, Value>: PartialKeyPath<Root> {
public typealias _Root = Root
public typealias _Value = Value
public final override class var _rootAndValueType: (
root: Any.Type,
value: Any.Type
) {
return (Root.self, Value.self)
}
// MARK: Implementation
typealias Kind = KeyPathKind
class var kind: Kind { return .readOnly }
static func appendedType<AppendedValue>(
with t: KeyPath<Value, AppendedValue>.Type
) -> KeyPath<Root, AppendedValue>.Type {
let resultKind: Kind
switch (self.kind, t.kind) {
case (_, .reference):
resultKind = .reference
case (let x, .value):
resultKind = x
default:
resultKind = .readOnly
}
switch resultKind {
case .readOnly:
return KeyPath<Root, AppendedValue>.self
case .value:
return WritableKeyPath.self
case .reference:
return ReferenceWritableKeyPath.self
}
}
final func projectReadOnly(from root: Root) -> Value {
// TODO: For perf, we could use a local growable buffer instead of Any
var curBase: Any = root
return withBuffer {
var buffer = $0
while true {
let (rawComponent, optNextType) = buffer.next()
let valueType = optNextType ?? Value.self
let isLast = optNextType == nil
func project<CurValue>(_ base: CurValue) -> Value? {
func project2<NewValue>(_: NewValue.Type) -> Value? {
switch rawComponent.projectReadOnly(base,
to: NewValue.self, endingWith: Value.self) {
case .continue(let newBase):
if isLast {
_sanityCheck(NewValue.self == Value.self,
"key path does not terminate in correct type")
return unsafeBitCast(newBase, to: Value.self)
} else {
curBase = newBase
return nil
}
case .break(let result):
return result
}
}
return _openExistential(valueType, do: project2)
}
if let result = _openExistential(curBase, do: project) {
return result
}
}
}
}
deinit {
withBuffer { $0.destroy() }
}
}
/// A key path that supports reading from and writing to the resulting value.
public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> {
// MARK: Implementation detail
override class var kind: Kind { return .value }
// `base` is assumed to be undergoing a formal access for the duration of the
// call, so must not be mutated by an alias
func projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var p = UnsafeRawPointer(base)
var type: Any.Type = Root.self
var keepAlive: AnyObject?
return withBuffer {
var buffer = $0
_sanityCheck(!buffer.hasReferencePrefix,
"WritableKeyPath should not have a reference prefix")
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent.projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == UnsafeRawPointer(base),
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(type, do: project)
if optNextType == nil { break }
type = nextType
}
// TODO: With coroutines, it would be better to yield here, so that
// we don't need the hack of the keepAlive reference to manage closing
// accesses.
let typedPointer = p.assumingMemoryBound(to: Value.self)
return (pointer: UnsafeMutablePointer(mutating: typedPointer),
owner: keepAlive)
}
}
}
/// A key path that supports reading from and writing to the resulting value
/// with reference semantics.
public class ReferenceWritableKeyPath<Root, Value>: WritableKeyPath<Root, Value> {
// MARK: Implementation detail
final override class var kind: Kind { return .reference }
final override func projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
// Since we're a ReferenceWritableKeyPath, we know we don't mutate the base in
// practice.
return projectMutableAddress(from: base.pointee)
}
final func projectMutableAddress(from origBase: Root)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var keepAlive: AnyObject?
var address: UnsafeMutablePointer<Value> = withBuffer {
var buffer = $0
// Project out the reference prefix.
var base: Any = origBase
while buffer.hasReferencePrefix {
let (rawComponent, optNextType) = buffer.next()
_sanityCheck(optNextType != nil,
"reference prefix should not go to end of buffer")
let nextType = optNextType.unsafelyUnwrapped
func project<NewValue>(_: NewValue.Type) -> Any {
func project2<CurValue>(_ base: CurValue) -> Any {
return rawComponent.projectReadOnly(
base, to: NewValue.self, endingWith: Value.self)
.assumingContinue
}
return _openExistential(base, do: project2)
}
base = _openExistential(nextType, do: project)
}
// Start formal access to the mutable value, based on the final base
// value.
func formalMutation<MutationRoot>(_ base: MutationRoot)
-> UnsafeMutablePointer<Value> {
var base2 = base
return withUnsafeBytes(of: &base2) { baseBytes in
var p = baseBytes.baseAddress.unsafelyUnwrapped
var curType: Any.Type = MutationRoot.self
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent.projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == baseBytes.baseAddress,
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(curType, do: project)
if optNextType == nil { break }
curType = nextType
}
let typedPointer = p.assumingMemoryBound(to: Value.self)
return UnsafeMutablePointer(mutating: typedPointer)
}
}
return _openExistential(base, do: formalMutation)
}
return (address, keepAlive)
}
}
// MARK: Implementation details
internal enum KeyPathComponentKind {
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`
/// The keypath projects using a getter/setter pair.
case computed
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
}
internal struct ComputedPropertyID: Hashable {
var value: Int
var isStoredProperty: Bool
var isTableOffset: Bool
static func ==(x: ComputedPropertyID, y: ComputedPropertyID) -> Bool {
return x.value == y.value
&& x.isStoredProperty == y.isStoredProperty
&& x.isTableOffset == x.isTableOffset
}
var hashValue: Int {
var hash = 0
hash ^= _mixInt(value)
hash ^= _mixInt(isStoredProperty ? 13 : 17)
hash ^= _mixInt(isTableOffset ? 19 : 23)
return hash
}
}
internal struct ComputedArgumentWitnesses {
typealias Destroy = @convention(thin)
(_ instanceArguments: UnsafeMutableRawPointer, _ size: Int) -> ()
typealias Copy = @convention(thin)
(_ srcInstanceArguments: UnsafeRawPointer,
_ destInstanceArguments: UnsafeMutableRawPointer,
_ size: Int) -> ()
typealias Equals = @convention(thin)
(_ xInstanceArguments: UnsafeRawPointer,
_ yInstanceArguments: UnsafeRawPointer,
_ size: Int) -> Bool
typealias Hash = @convention(thin)
(_ instanceArguments: UnsafeRawPointer,
_ size: Int) -> Int
let destroy: Destroy?
let copy: Copy
let equals: Equals
let hash: Hash
}
internal enum KeyPathComponent: Hashable {
struct ArgumentRef {
var data: UnsafeRawBufferPointer
var witnesses: UnsafePointer<ComputedArgumentWitnesses>
}
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`(offset: Int)
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`(offset: Int)
/// The keypath projects using a getter.
case get(id: ComputedPropertyID,
get: UnsafeRawPointer, argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair. The setter can mutate
/// the base value in-place.
case mutatingGetSet(id: ComputedPropertyID,
get: UnsafeRawPointer, set: UnsafeRawPointer,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair that does not mutate its
/// base.
case nonmutatingGetSet(id: ComputedPropertyID,
get: UnsafeRawPointer, set: UnsafeRawPointer,
argument: ArgumentRef?)
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool {
switch (a, b) {
case (.struct(offset: let a), .struct(offset: let b)),
(.class (offset: let a), .class (offset: let b)):
return a == b
case (.optionalChain, .optionalChain),
(.optionalForce, .optionalForce),
(.optionalWrap, .optionalWrap):
return true
case (.get(id: let id1, get: _, argument: let argument1),
.get(id: let id2, get: _, argument: let argument2)),
(.mutatingGetSet(id: let id1, get: _, set: _, argument: let argument1),
.mutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)),
(.nonmutatingGetSet(id: let id1, get: _, set: _, argument: let argument1),
.nonmutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)):
if id1 != id2 {
return false
}
if let arg1 = argument1, let arg2 = argument2 {
// TODO: Sizes may differ if one key path was formed in a context
// capturing generic arguments and one wasn't.
_sanityCheck(arg1.data.count == arg2.data.count)
return arg1.witnesses.pointee.equals(
arg1.data.baseAddress.unsafelyUnwrapped,
arg2.data.baseAddress.unsafelyUnwrapped,
arg1.data.count)
}
// If only one component has arguments, that should indicate that the
// only arguments in that component were generic captures and therefore
// not affecting equality.
return true
case (.struct, _),
(.class, _),
(.optionalChain, _),
(.optionalForce, _),
(.optionalWrap, _),
(.get, _),
(.mutatingGetSet, _),
(.nonmutatingGetSet, _):
return false
}
}
var hashValue: Int {
var hash: Int = 0
func mixHashFromArgument(_ argument: KeyPathComponent.ArgumentRef?) {
if let argument = argument {
let addedHash = argument.witnesses.pointee.hash(
argument.data.baseAddress.unsafelyUnwrapped,
argument.data.count)
// Returning 0 indicates that the arguments should not impact the
// hash value of the overall key path.
if addedHash != 0 {
hash ^= _mixInt(addedHash)
}
}
}
switch self {
case .struct(offset: let a):
hash ^= _mixInt(0)
hash ^= _mixInt(a)
case .class(offset: let b):
hash ^= _mixInt(1)
hash ^= _mixInt(b)
case .optionalChain:
hash ^= _mixInt(2)
case .optionalForce:
hash ^= _mixInt(3)
case .optionalWrap:
hash ^= _mixInt(4)
case .get(id: let id, get: _, argument: let argument):
hash ^= _mixInt(5)
hash ^= _mixInt(id.hashValue)
mixHashFromArgument(argument)
case .mutatingGetSet(id: let id, get: _, set: _, argument: let argument):
hash ^= _mixInt(6)
hash ^= _mixInt(id.hashValue)
mixHashFromArgument(argument)
case .nonmutatingGetSet(id: let id, get: _, set: _, argument: let argument):
hash ^= _mixInt(7)
hash ^= _mixInt(id.hashValue)
mixHashFromArgument(argument)
}
return hash
}
}
// A class that maintains ownership of another object while a mutable projection
// into it is underway.
internal final class ClassHolder {
let previous: AnyObject?
let instance: AnyObject
init(previous: AnyObject?, instance: AnyObject) {
self.previous = previous
self.instance = instance
}
}
// A class that triggers writeback to a pointer when destroyed.
internal final class MutatingWritebackBuffer<CurValue, NewValue> {
let previous: AnyObject?
let base: UnsafeMutablePointer<CurValue>
let set: @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer) -> ()
let argument: UnsafeRawPointer
var value: NewValue
deinit {
set(value, &base.pointee, argument)
}
init(previous: AnyObject?,
base: UnsafeMutablePointer<CurValue>,
set: @escaping @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer) -> (),
argument: UnsafeRawPointer,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.value = value
}
}
// A class that triggers writeback to a non-mutated value when destroyed.
internal final class NonmutatingWritebackBuffer<CurValue, NewValue> {
let previous: AnyObject?
let base: CurValue
let set: @convention(thin) (NewValue, CurValue, UnsafeRawPointer) -> ()
let argument: UnsafeRawPointer
var value: NewValue
deinit {
set(value, base, argument)
}
init(previous: AnyObject?,
base: CurValue,
set: @escaping @convention(thin) (NewValue, CurValue, UnsafeRawPointer) -> (),
argument: UnsafeRawPointer,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.value = value
}
}
internal struct RawKeyPathComponent {
var header: Header
var body: UnsafeRawBufferPointer
struct Header {
static var payloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_PayloadMask
}
static var discriminatorMask: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorMask
}
static var discriminatorShift: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorShift
}
static var structTag: UInt32 {
return _SwiftKeyPathComponentHeader_StructTag
}
static var computedTag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedTag
}
static var classTag: UInt32 {
return _SwiftKeyPathComponentHeader_ClassTag
}
static var optionalTag: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalTag
}
static var optionalChainPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalChainPayload
}
static var optionalWrapPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalWrapPayload
}
static var optionalForcePayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalForcePayload
}
static var endOfReferencePrefixFlag: UInt32 {
return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag
}
static var outOfLineOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload
}
static var unresolvedFieldOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload
}
static var unresolvedIndirectOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload
}
static var computedMutatingFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedMutatingFlag
}
static var computedSettableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedSettableFlag
}
static var computedIDByStoredPropertyFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag
}
static var computedIDByVTableOffsetFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag
}
static var computedHasArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag
}
static var computedIDResolutionMask: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask
}
static var computedIDResolved: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolved
}
static var computedIDUnresolvedIndirectPointer: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer
}
var _value: UInt32
var discriminator: UInt32 {
return (_value & Header.discriminatorMask) >> Header.discriminatorShift
}
var payload: UInt32 {
get {
return _value & Header.payloadMask
}
set {
_sanityCheck(newValue & Header.payloadMask == newValue,
"payload too big")
_value = _value & ~Header.payloadMask | newValue
}
}
var endOfReferencePrefix: Bool {
get {
return _value & Header.endOfReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.endOfReferencePrefixFlag
} else {
_value &= ~Header.endOfReferencePrefixFlag
}
}
}
var kind: KeyPathComponentKind {
switch (discriminator, payload) {
case (Header.structTag, _):
return .struct
case (Header.classTag, _):
return .class
case (Header.computedTag, _):
return .computed
case (Header.optionalTag, Header.optionalChainPayload):
return .optionalChain
case (Header.optionalTag, Header.optionalWrapPayload):
return .optionalWrap
case (Header.optionalTag, Header.optionalForcePayload):
return .optionalForce
default:
_sanityCheckFailure("invalid header")
}
}
// The component header is 4 bytes, but may be followed by an aligned
// pointer field for some kinds of component, forcing padding.
static var pointerAlignmentSkew: Int {
return MemoryLayout<Int>.size - MemoryLayout<Int32>.size
}
}
var bodySize: Int {
switch header.kind {
case .struct, .class:
if header.payload == Header.payloadMask { return 4 } // overflowed
return 0
case .optionalChain, .optionalForce, .optionalWrap:
return 0
case .computed:
let ptrSize = MemoryLayout<Int>.size
// align to pointer, minimum two pointers for id and get
var total = Header.pointerAlignmentSkew + ptrSize * 2
// additional word for a setter
if header.payload & Header.computedSettableFlag != 0 {
total += ptrSize
}
// include the argument size
if header.payload & Header.computedHasArgumentsFlag != 0 {
// two words for argument header: size, witnesses
total += ptrSize * 2
// size of argument area
total += _computedArgumentSize
}
return total
}
}
var _structOrClassOffset: Int {
_sanityCheck(header.kind == .struct || header.kind == .class,
"no offset for this kind")
// An offset too large to fit inline is represented by a signal and stored
// in the body.
if header.payload == Header.outOfLineOffsetPayload {
// Offset overflowed into body
_sanityCheck(body.count >= MemoryLayout<UInt32>.size,
"component not big enough")
return Int(body.load(as: UInt32.self))
}
return Int(header.payload)
}
var _computedIDValue: Int {
_sanityCheck(header.kind == .computed,
"not a computed property")
return body.load(fromByteOffset: Header.pointerAlignmentSkew,
as: Int.self)
}
var _computedID: ComputedPropertyID {
let payload = header.payload
return ComputedPropertyID(
value: _computedIDValue,
isStoredProperty: payload & Header.computedIDByStoredPropertyFlag != 0,
isTableOffset: payload & Header.computedIDByVTableOffsetFlag != 0)
}
var _computedGetter: UnsafeRawPointer {
_sanityCheck(header.kind == .computed,
"not a computed property")
return body.load(
fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size,
as: UnsafeRawPointer.self)
}
var _computedSetter: UnsafeRawPointer {
_sanityCheck(header.kind == .computed,
"not a computed property")
_sanityCheck(header.payload & Header.computedSettableFlag != 0,
"not a settable property")
return body.load(
fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size * 2,
as: UnsafeRawPointer.self)
}
typealias ComputedArgumentLayoutFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer) -> (size: Int, alignmentMask: Int)
typealias ComputedArgumentInitializerFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer,
_ instanceArguments: UnsafeMutableRawPointer) -> ()
var _computedArgumentHeaderPointer: UnsafeRawPointer {
_sanityCheck(header.kind == .computed,
"not a computed property")
_sanityCheck(header.payload & Header.computedHasArgumentsFlag != 0,
"no arguments")
return body.baseAddress.unsafelyUnwrapped
+ Header.pointerAlignmentSkew
+ MemoryLayout<Int>.size *
(header.payload & Header.computedSettableFlag != 0 ? 3 : 2)
}
var _computedArgumentSize: Int {
return _computedArgumentHeaderPointer.load(as: Int.self)
}
var _computedArgumentWitnesses: UnsafePointer<ComputedArgumentWitnesses> {
return _computedArgumentHeaderPointer.load(
fromByteOffset: MemoryLayout<Int>.size,
as: UnsafePointer<ComputedArgumentWitnesses>.self)
}
var _computedArguments: UnsafeRawPointer {
return _computedArgumentHeaderPointer + MemoryLayout<Int>.size * 2
}
var _computedMutableArguments: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(mutating: _computedArguments)
}
var value: KeyPathComponent {
switch header.kind {
case .struct:
return .struct(offset: _structOrClassOffset)
case .class:
return .class(offset: _structOrClassOffset)
case .optionalChain:
return .optionalChain
case .optionalForce:
return .optionalForce
case .optionalWrap:
return .optionalWrap
case .computed:
let isSettable = header.payload & Header.computedSettableFlag != 0
let isMutating = header.payload & Header.computedMutatingFlag != 0
let id = _computedID
let get = _computedGetter
// Argument value is unused if there are no arguments, so pick something
// likely to already be in a register as a default.
let argument: KeyPathComponent.ArgumentRef?
if header.payload & Header.computedHasArgumentsFlag != 0 {
argument = KeyPathComponent.ArgumentRef(
data: UnsafeRawBufferPointer(start: _computedArguments,
count: _computedArgumentSize),
witnesses: _computedArgumentWitnesses)
} else {
argument = nil
}
switch (isSettable, isMutating) {
case (false, false):
return .get(id: id, get: get, argument: argument)
case (true, false):
return .nonmutatingGetSet(id: id,
get: get,
set: _computedSetter,
argument: argument)
case (true, true):
return .mutatingGetSet(id: id,
get: get,
set: _computedSetter,
argument: argument)
case (false, true):
_sanityCheckFailure("impossible")
}
}
}
func destroy() {
switch header.kind {
case .struct,
.class,
.optionalChain,
.optionalForce,
.optionalWrap:
// trivial
break
case .computed:
// Run destructor, if any
if header.payload & Header.computedHasArgumentsFlag != 0,
let destructor = _computedArgumentWitnesses.pointee.destroy {
destructor(_computedMutableArguments, _computedArgumentSize)
}
}
}
func clone(into buffer: inout UnsafeMutableRawBufferPointer,
endOfReferencePrefix: Bool) {
var newHeader = header
newHeader.endOfReferencePrefix = endOfReferencePrefix
var componentSize = MemoryLayout<Header>.size
buffer.storeBytes(of: newHeader, as: Header.self)
switch header.kind {
case .struct,
.class:
if header.payload == Header.outOfLineOffsetPayload {
let overflowOffset = body.load(as: UInt32.self)
buffer.storeBytes(of: overflowOffset, toByteOffset: 4,
as: UInt32.self)
componentSize += 4
}
case .optionalChain,
.optionalForce,
.optionalWrap:
break
case .computed:
// Fields are pointer-aligned after the header
componentSize += Header.pointerAlignmentSkew
// TODO: nontrivial arguments need to be copied by value witness
buffer.storeBytes(of: _computedIDValue,
toByteOffset: MemoryLayout<Int>.size,
as: Int.self)
buffer.storeBytes(of: _computedGetter,
toByteOffset: 2 * MemoryLayout<Int>.size,
as: UnsafeRawPointer.self)
var addedSize = MemoryLayout<Int>.size * 2
if header.payload & Header.computedSettableFlag != 0 {
buffer.storeBytes(of: _computedSetter,
toByteOffset: MemoryLayout<Int>.size * 3,
as: UnsafeRawPointer.self)
addedSize += MemoryLayout<Int>.size
}
if header.payload & Header.computedHasArgumentsFlag != 0 {
let argumentSize = _computedArgumentSize
buffer.storeBytes(of: argumentSize,
toByteOffset: addedSize + MemoryLayout<Int>.size,
as: Int.self)
buffer.storeBytes(of: _computedArgumentWitnesses,
toByteOffset: addedSize + MemoryLayout<Int>.size * 2,
as: UnsafePointer<ComputedArgumentWitnesses>.self)
_computedArgumentWitnesses.pointee.copy(
_computedArguments,
buffer.baseAddress.unsafelyUnwrapped + addedSize
+ MemoryLayout<Int>.size * 3,
argumentSize)
addedSize += MemoryLayout<Int>.size * 2 + argumentSize
}
componentSize += addedSize
}
buffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress.unsafelyUnwrapped + componentSize,
count: buffer.count - componentSize)
}
enum ProjectionResult<NewValue, LeafValue> {
/// Continue projecting the key path with the given new value.
case `continue`(NewValue)
/// Stop projecting the key path and use the given value as the final
/// result of the projection.
case `break`(LeafValue)
var assumingContinue: NewValue {
switch self {
case .continue(let x):
return x
case .break:
_sanityCheckFailure("should not have stopped key path projection")
}
}
}
func projectReadOnly<CurValue, NewValue, LeafValue>(
_ base: CurValue,
to: NewValue.Type,
endingWith: LeafValue.Type
) -> ProjectionResult<NewValue, LeafValue> {
switch value {
case .struct(let offset):
var base2 = base
return .continue(withUnsafeBytes(of: &base2) {
let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset)
// The contents of the struct should be well-typed, so we can assume
// typed memory here.
return p.assumingMemoryBound(to: NewValue.self).pointee
})
case .class(let offset):
_sanityCheck(CurValue.self is AnyObject.Type,
"base is not a class")
let baseObj = unsafeBitCast(base, to: AnyObject.self)
let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj))
defer { _fixLifetime(baseObj) }
return .continue(basePtr.advanced(by: offset)
.assumingMemoryBound(to: NewValue.self)
.pointee)
case .get(id: _, get: let rawGet, argument: let argument),
.mutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument),
.nonmutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument):
typealias Getter
= @convention(thin) (CurValue, UnsafeRawPointer) -> NewValue
let get = unsafeBitCast(rawGet, to: Getter.self)
return .continue(get(base, argument?.data.baseAddress ?? rawGet))
case .optionalChain:
// TODO: IUO shouldn't be a first class type
_sanityCheck(CurValue.self == Optional<NewValue>.self
|| CurValue.self == ImplicitlyUnwrappedOptional<NewValue>.self,
"should be unwrapping optional value")
_sanityCheck(_isOptional(LeafValue.self),
"leaf result should be optional")
if let baseValue = unsafeBitCast(base, to: Optional<NewValue>.self) {
return .continue(baseValue)
} else {
// TODO: A more efficient way of getting the `none` representation
// of a dynamically-optional type...
return .break((Optional<()>.none as Any) as! LeafValue)
}
case .optionalForce:
// TODO: IUO shouldn't be a first class type
_sanityCheck(CurValue.self == Optional<NewValue>.self
|| CurValue.self == ImplicitlyUnwrappedOptional<NewValue>.self,
"should be unwrapping optional value")
return .continue(unsafeBitCast(base, to: Optional<NewValue>.self)!)
case .optionalWrap:
// TODO: IUO shouldn't be a first class type
_sanityCheck(NewValue.self == Optional<CurValue>.self
|| CurValue.self == ImplicitlyUnwrappedOptional<CurValue>.self,
"should be wrapping optional value")
return .continue(
unsafeBitCast(base as Optional<CurValue>, to: NewValue.self))
}
}
func projectMutableAddress<CurValue, NewValue>(
_ base: UnsafeRawPointer,
from _: CurValue.Type,
to _: NewValue.Type,
isRoot: Bool,
keepAlive: inout AnyObject?
) -> UnsafeRawPointer {
switch value {
case .struct(let offset):
return base.advanced(by: offset)
case .class(let offset):
// A class dereference should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_sanityCheck(isRoot,
"class component should not appear in the middle of mutation")
// AnyObject memory can alias any class reference memory, so we can
// assume type here
let object = base.assumingMemoryBound(to: AnyObject.self).pointee
// The base ought to be kept alive for the duration of the derived access
keepAlive = keepAlive == nil
? object
: ClassHolder(previous: keepAlive, instance: object)
return UnsafeRawPointer(Builtin.bridgeToRawPointer(object))
.advanced(by: offset)
case .mutatingGetSet(id: _, get: let rawGet, set: let rawSet,
argument: let argument):
typealias Getter
= @convention(thin) (CurValue, UnsafeRawPointer) -> NewValue
typealias Setter
= @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer) -> ()
let get = unsafeBitCast(rawGet, to: Getter.self)
let set = unsafeBitCast(rawSet, to: Setter.self)
let baseTyped = UnsafeMutablePointer(
mutating: base.assumingMemoryBound(to: CurValue.self))
let argValue = argument?.data.baseAddress ?? rawGet
let writeback = MutatingWritebackBuffer(previous: keepAlive,
base: baseTyped,
set: set,
argument: argValue,
value: get(baseTyped.pointee, argValue))
keepAlive = writeback
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .nonmutatingGetSet(id: _, get: let rawGet, set: let rawSet,
argument: let argument):
// A nonmutating property should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_sanityCheck(isRoot,
"nonmutating component should not appear in the middle of mutation")
typealias Getter
= @convention(thin) (CurValue, UnsafeRawPointer) -> NewValue
typealias Setter
= @convention(thin) (NewValue, CurValue, UnsafeRawPointer) -> ()
let get = unsafeBitCast(rawGet, to: Getter.self)
let set = unsafeBitCast(rawSet, to: Setter.self)
let baseValue = base.assumingMemoryBound(to: CurValue.self).pointee
let argValue = argument?.data.baseAddress ?? rawGet
let writeback = NonmutatingWritebackBuffer(previous: keepAlive,
base: baseValue,
set: set,
argument: argValue,
value: get(baseValue, argValue))
keepAlive = writeback
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .optionalForce:
// TODO: ImplicitlyUnwrappedOptional should not be a first-class type
_sanityCheck(CurValue.self == Optional<NewValue>.self
|| CurValue.self == ImplicitlyUnwrappedOptional<NewValue>.self,
"should be unwrapping an optional value")
// Optional's layout happens to always put the payload at the start
// address of the Optional value itself, if a value is present at all.
let baseOptionalPointer
= base.assumingMemoryBound(to: Optional<NewValue>.self)
// Assert that a value exists
_ = baseOptionalPointer.pointee!
return base
case .optionalChain, .optionalWrap, .get:
_sanityCheckFailure("not a mutable key path component")
}
}
}
internal struct KeyPathBuffer {
var data: UnsafeRawBufferPointer
var trivial: Bool
var hasReferencePrefix: Bool
var mutableData: UnsafeMutableRawBufferPointer {
return UnsafeMutableRawBufferPointer(mutating: data)
}
struct Header {
var _value: UInt32
static var sizeMask: UInt32 {
return _SwiftKeyPathBufferHeader_SizeMask
}
static var reservedMask: UInt32 {
return _SwiftKeyPathBufferHeader_ReservedMask
}
static var trivialFlag: UInt32 {
return _SwiftKeyPathBufferHeader_TrivialFlag
}
static var hasReferencePrefixFlag: UInt32 {
return _SwiftKeyPathBufferHeader_HasReferencePrefixFlag
}
init(size: Int, trivial: Bool, hasReferencePrefix: Bool) {
_sanityCheck(size <= Int(Header.sizeMask), "key path too big")
_value = UInt32(size)
| (trivial ? Header.trivialFlag : 0)
| (hasReferencePrefix ? Header.hasReferencePrefixFlag : 0)
}
var size: Int { return Int(_value & Header.sizeMask) }
var trivial: Bool { return _value & Header.trivialFlag != 0 }
var hasReferencePrefix: Bool {
get {
return _value & Header.hasReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.hasReferencePrefixFlag
} else {
_value &= ~Header.hasReferencePrefixFlag
}
}
}
// In a key path pattern, the "trivial" flag is used to indicate
// "instantiable in-line"
var instantiableInLine: Bool {
return trivial
}
func validateReservedBits() {
_precondition(_value & Header.reservedMask == 0,
"reserved bits set to an unexpected bit pattern")
}
}
init(base: UnsafeRawPointer) {
let header = base.load(as: Header.self)
data = UnsafeRawBufferPointer(
start: base + MemoryLayout<Int>.size,
count: header.size)
trivial = header.trivial
hasReferencePrefix = header.hasReferencePrefix
}
func destroy() {
// Short-circuit if nothing in the object requires destruction.
if trivial { return }
var bufferToDestroy = self
while true {
let (component, type) = bufferToDestroy.next()
component.destroy()
guard let _ = type else { break }
}
}
mutating func next() -> (RawKeyPathComponent, Any.Type?) {
let header = pop(RawKeyPathComponent.Header.self)
// Track if this is the last component of the reference prefix.
if header.endOfReferencePrefix {
_sanityCheck(self.hasReferencePrefix,
"beginMutation marker in non-reference-writable key path?")
self.hasReferencePrefix = false
}
var component = RawKeyPathComponent(header: header, body: data)
// Shrinkwrap the component buffer size.
let size = component.bodySize
component.body = UnsafeRawBufferPointer(start: component.body.baseAddress,
count: size)
_ = popRaw(size: size, alignment: 1)
// fetch type, which is in the buffer unless it's the final component
let nextType: Any.Type?
if data.count == 0 {
nextType = nil
} else {
nextType = pop(Any.Type.self)
}
return (component, nextType)
}
mutating func pop<T>(_ type: T.Type) -> T {
_sanityCheck(_isPOD(T.self), "should be POD")
let raw = popRaw(size: MemoryLayout<T>.size,
alignment: MemoryLayout<T>.alignment)
let resultBuf = UnsafeMutablePointer<T>.allocate(capacity: 1)
_memcpy(dest: resultBuf,
src: UnsafeMutableRawPointer(mutating: raw.baseAddress.unsafelyUnwrapped),
size: UInt(MemoryLayout<T>.size))
let result = resultBuf.pointee
resultBuf.deallocate(capacity: 1)
return result
}
mutating func popRaw(size: Int, alignment: Int) -> UnsafeRawBufferPointer {
var baseAddress = data.baseAddress.unsafelyUnwrapped
var misalignment = Int(bitPattern: baseAddress) % alignment
if misalignment != 0 {
misalignment = alignment - misalignment
baseAddress += misalignment
}
let result = UnsafeRawBufferPointer(start: baseAddress, count: size)
data = UnsafeRawBufferPointer(
start: baseAddress + size,
count: data.count - size - misalignment
)
return result
}
}
// MARK: Library intrinsics for projecting key paths.
@_inlineable
public // COMPILER_INTRINSIC
func _projectKeyPathPartial<Root>(
root: Root,
keyPath: PartialKeyPath<Root>
) -> Any {
func open<Value>(_: Value.Type) -> Any {
return _projectKeyPathReadOnly(root: root,
keyPath: unsafeDowncast(keyPath, to: KeyPath<Root, Value>.self))
}
return _openExistential(type(of: keyPath).valueType, do: open)
}
@_inlineable
public // COMPILER_INTRINSIC
func _projectKeyPathAny<RootValue>(
root: RootValue,
keyPath: AnyKeyPath
) -> Any? {
let (keyPathRoot, keyPathValue) = type(of: keyPath)._rootAndValueType
func openRoot<KeyPathRoot>(_: KeyPathRoot.Type) -> Any? {
guard let rootForKeyPath = root as? KeyPathRoot else {
return nil
}
func openValue<Value>(_: Value.Type) -> Any {
return _projectKeyPathReadOnly(root: rootForKeyPath,
keyPath: unsafeDowncast(keyPath, to: KeyPath<KeyPathRoot, Value>.self))
}
return _openExistential(keyPathValue, do: openValue)
}
return _openExistential(keyPathRoot, do: openRoot)
}
public // COMPILER_INTRINSIC
func _projectKeyPathReadOnly<Root, Value>(
root: Root,
keyPath: KeyPath<Root, Value>
) -> Value {
return keyPath.projectReadOnly(from: root)
}
public // COMPILER_INTRINSIC
func _projectKeyPathWritable<Root, Value>(
root: UnsafeMutablePointer<Root>,
keyPath: WritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, AnyObject?) {
return keyPath.projectMutableAddress(from: root)
}
public // COMPILER_INTRINSIC
func _projectKeyPathReferenceWritable<Root, Value>(
root: Root,
keyPath: ReferenceWritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, AnyObject?) {
return keyPath.projectMutableAddress(from: root)
}
// MARK: Appending type system
// FIXME(ABI): The type relationships between KeyPath append operands are tricky
// and don't interact well with our overriding rules. Hack things by injecting
// a bunch of `appending` overloads as protocol extensions so they aren't
// constrained by being overrides, and so that we can use exact-type constraints
// on `Self` to prevent dynamically-typed methods from being inherited by
// statically-typed key paths.
/// This protocol is an implementation detail of key path expressions; do not
/// use it directly.
@_show_in_interface
public protocol _AppendKeyPath {}
extension _AppendKeyPath where Self == AnyKeyPath {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates key paths from `Array<Int>` to `String` and from `String` to
/// `Int`, and then tries appending each to the other:
///
/// let arrayDescription: AnyKeyPath = \Array<Int>.description
/// let stringLength: AnyKeyPath = \String.count
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: stringLength)
///
/// let invalidKeyPath = stringLength.appending(path: arrayDescription)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil`
/// because the root type of `arrayDescription`, `Array<Int>`, does not
/// match the value type of `stringLength`, `Int`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path and the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
public func appending(path: AnyKeyPath) -> AnyKeyPath? {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == PartialKeyPath<T> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates key paths from `Array<Int>` to `String` and from `String` to
/// `Int`, and then tries appending each to the other:
///
/// let arrayDescription: PartialKeyPath<Array<Int>> = \.description
/// let stringLength: PartialKeyPath<String> = \.count
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: stringLength)
///
/// let invalidKeyPath = stringLength.appending(path: arrayDescription)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil`
/// because the root type of `arrayDescription`, `Array<Int>`, does not
/// match the value type of `stringLength`, `Int`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path and the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
public func appending<Root>(path: AnyKeyPath) -> PartialKeyPath<Root>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates a key path from `Array<Int>` to `String`, and then tries
/// appending compatible and incompatible key paths:
///
/// let arrayDescription: PartialKeyPath<Array<Int>> = \.description
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: \String.count)
///
/// let invalidKeyPath = arrayDescription.appending(path: \Double.isZero)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil` because the root type
/// of the `path` parameter, `Double`, does not match the value type of
/// `arrayDescription`, `String`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
public func appending<Root, AppendedRoot, AppendedValue>(
path: KeyPath<AppendedRoot, AppendedValue>
) -> KeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type.
///
/// - Parameter path: The reference writeable key path to append.
/// - Returns: A key path from the root of this key path to the the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
public func appending<Root, AppendedRoot, AppendedValue>(
path: ReferenceWritableKeyPath<AppendedRoot, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == KeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation. In the following
/// example, `keyPath1` and `keyPath2` are equivalent:
///
/// let arrayDescription = \Array<Int>.description
/// let keyPath1 = arrayDescription.appending(path: \String.count)
///
/// let keyPath2 = \Array<Int>.description.count
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
public func appending<Root, Value, AppendedValue>(
path: KeyPath<Value, AppendedValue>
) -> KeyPath<Root, AppendedValue>
where Self: KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/* TODO
public func appending<Root, Value, Leaf>(
path: Leaf,
// FIXME: Satisfy "Value generic param not used in signature" constraint
_: Value.Type = Value.self
) -> PartialKeyPath<Root>?
where Self: KeyPath<Root, Value>, Leaf == AnyKeyPath {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
*/
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == WritableKeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> WritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == ReferenceWritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
// internal-with-availability
public func _tryToAppendKeyPaths<Result: AnyKeyPath>(
root: AnyKeyPath,
leaf: AnyKeyPath
) -> Result? {
let (rootRoot, rootValue) = type(of: root)._rootAndValueType
let (leafRoot, leafValue) = type(of: leaf)._rootAndValueType
if rootValue != leafRoot {
return nil
}
func open<Root>(_: Root.Type) -> Result {
func open2<Value>(_: Value.Type) -> Result {
func open3<AppendedValue>(_: AppendedValue.Type) -> Result {
let typedRoot = unsafeDowncast(root, to: KeyPath<Root, Value>.self)
let typedLeaf = unsafeDowncast(leaf,
to: KeyPath<Value, AppendedValue>.self)
let result = _appendingKeyPaths(root: typedRoot, leaf: typedLeaf)
return unsafeDowncast(result, to: Result.self)
}
return _openExistential(leafValue, do: open3)
}
return _openExistential(rootValue, do: open2)
}
return _openExistential(rootRoot, do: open)
}
// internal-with-availability
public func _appendingKeyPaths<
Root, Value, AppendedValue,
Result: KeyPath<Root, AppendedValue>
>(
root: KeyPath<Root, Value>,
leaf: KeyPath<Value, AppendedValue>
) -> Result {
let resultTy = type(of: root).appendedType(with: type(of: leaf))
return root.withBuffer {
var rootBuffer = $0
return leaf.withBuffer {
var leafBuffer = $0
// Reserve room for the appended KVC string, if both key paths are
// KVC-compatible.
let appendedKVCLength: Int, rootKVCLength: Int, leafKVCLength: Int
if let rootPtr = root._kvcKeyPathStringPtr,
let leafPtr = leaf._kvcKeyPathStringPtr {
rootKVCLength = Int(_swift_stdlib_strlen(rootPtr))
leafKVCLength = Int(_swift_stdlib_strlen(leafPtr))
// root + "." + leaf
appendedKVCLength = rootKVCLength + 1 + leafKVCLength
} else {
rootKVCLength = 0
leafKVCLength = 0
appendedKVCLength = 0
}
// Result buffer has room for both key paths' components, plus the
// header, plus space for the middle type.
// Align up the root so that we can put the component type after it.
let alignMask = MemoryLayout<Int>.alignment - 1
let rootSize = (rootBuffer.data.count + alignMask) & ~alignMask
let resultSize = rootSize + leafBuffer.data.count
+ 2 * MemoryLayout<Int>.size
// Tail-allocate space for the KVC string.
let totalResultSize = (resultSize + appendedKVCLength + 3) & ~3
var kvcStringBuffer: UnsafeMutableRawPointer? = nil
let result = resultTy._create(capacityInBytes: totalResultSize) {
var destBuffer = $0
// Remember where the tail-allocated KVC string buffer begins.
if appendedKVCLength > 0 {
kvcStringBuffer = destBuffer.baseAddress.unsafelyUnwrapped
.advanced(by: resultSize)
destBuffer = .init(start: destBuffer.baseAddress,
count: resultSize)
}
func pushRaw(size: Int, alignment: Int)
-> UnsafeMutableRawBufferPointer {
var baseAddress = destBuffer.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) % alignment
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
let result = UnsafeMutableRawBufferPointer(
start: baseAddress,
count: size)
destBuffer = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destBuffer.count - size - misalign)
return result
}
func push<T>(_ value: T) {
let buf = pushRaw(size: MemoryLayout<T>.size,
alignment: MemoryLayout<T>.alignment)
buf.storeBytes(of: value, as: T.self)
}
// Save space for the header.
let leafIsReferenceWritable = type(of: leaf).kind == .reference
let header = KeyPathBuffer.Header(
size: resultSize - MemoryLayout<Int>.size,
trivial: rootBuffer.trivial && leafBuffer.trivial,
hasReferencePrefix: rootBuffer.hasReferencePrefix
|| leafIsReferenceWritable
)
push(header)
// Start the components at pointer alignment
_ = pushRaw(size: RawKeyPathComponent.Header.pointerAlignmentSkew,
alignment: 4)
let leafHasReferencePrefix = leafBuffer.hasReferencePrefix
// Clone the root components into the buffer.
while true {
let (component, type) = rootBuffer.next()
let isLast = type == nil
// If the leaf appended path has a reference prefix, then the
// entire root is part of the reference prefix.
let endOfReferencePrefix: Bool
if leafHasReferencePrefix {
endOfReferencePrefix = false
} else if isLast && leafIsReferenceWritable {
endOfReferencePrefix = true
} else {
endOfReferencePrefix = component.header.endOfReferencePrefix
}
component.clone(
into: &destBuffer,
endOfReferencePrefix: endOfReferencePrefix)
if let type = type {
push(type)
} else {
// Insert our endpoint type between the root and leaf components.
push(Value.self as Any.Type)
break
}
}
// Clone the leaf components into the buffer.
while true {
let (component, type) = leafBuffer.next()
component.clone(
into: &destBuffer,
endOfReferencePrefix: component.header.endOfReferencePrefix)
if let type = type {
push(type)
} else {
break
}
}
_sanityCheck(destBuffer.count == 0,
"did not fill entire result buffer")
}
// Build the KVC string if there is one.
if let kvcStringBuffer = kvcStringBuffer {
let rootPtr = root._kvcKeyPathStringPtr.unsafelyUnwrapped
let leafPtr = leaf._kvcKeyPathStringPtr.unsafelyUnwrapped
_memcpy(dest: kvcStringBuffer,
src: UnsafeMutableRawPointer(mutating: rootPtr),
size: UInt(rootKVCLength))
kvcStringBuffer.advanced(by: rootKVCLength)
.storeBytes(of: 0x2E /* '.' */, as: CChar.self)
_memcpy(dest: kvcStringBuffer.advanced(by: rootKVCLength + 1),
src: UnsafeMutableRawPointer(mutating: leafPtr),
size: UInt(leafKVCLength))
result._kvcKeyPathStringPtr =
UnsafePointer(kvcStringBuffer.assumingMemoryBound(to: CChar.self))
kvcStringBuffer.advanced(by: rootKVCLength + leafKVCLength + 1)
.storeBytes(of: 0 /* '\0' */, as: CChar.self)
}
return unsafeDowncast(result, to: Result.self)
}
}
}
// The distance in bytes from the address point of a KeyPath object to its
// buffer header. Includes the size of the Swift heap object header and the
// pointer to the KVC string.
internal var keyPathObjectHeaderSize: Int {
return MemoryLayout<HeapObject>.size + MemoryLayout<Int>.size
}
// Runtime entry point to instantiate a key path object.
@_cdecl("swift_getKeyPath")
public func _swift_getKeyPath(pattern: UnsafeMutableRawPointer,
arguments: UnsafeRawPointer)
-> UnsafeRawPointer {
// The key path pattern is laid out like a key path object, with a few
// modifications:
// - Instead of the two-word object header with isa and refcount, two
// pointers to metadata accessors are provided for the root and leaf
// value types of the key path.
// - The header reuses the "trivial" bit to mean "instantiable in-line",
// meaning that the key path described by this pattern has no contextually
// dependent parts (no dependence on generic parameters, subscript indexes,
// etc.), so it can be set up as a global object once. (The resulting
// global object will itself always have the "trivial" bit set, since it
// never needs to be destroyed.)
// - Components may have unresolved forms that require instantiation.
// - Type metadata pointers are unresolved, and instead
// point to accessor functions that instantiate the metadata.
//
// The pattern never precomputes the capabilities of the key path (readonly/
// writable/reference-writable), nor does it encode the reference prefix.
// These are resolved dynamically, so that they always reflect the dynamic
// capability of the properties involved.
let oncePtr = pattern
let patternPtr = pattern.advanced(by: MemoryLayout<Int>.size)
let bufferPtr = patternPtr.advanced(by: keyPathObjectHeaderSize)
// If the pattern is instantiable in-line, do a dispatch_once to
// initialize it. (The resulting object will still have the
// "trivial" bit set, since a global object never needs destruction.)
let bufferHeader = bufferPtr.load(as: KeyPathBuffer.Header.self)
bufferHeader.validateReservedBits()
if bufferHeader.instantiableInLine {
Builtin.onceWithContext(oncePtr._rawValue, _getKeyPath_instantiateInline,
patternPtr._rawValue)
// Return the instantiated object at +1.
// TODO: This will be unnecessary once we support global objects with inert
// refcounting.
let object = Unmanaged<AnyKeyPath>.fromOpaque(patternPtr)
_ = object.retain()
return UnsafeRawPointer(patternPtr)
}
// Otherwise, instantiate a new key path object modeled on the pattern.
return _getKeyPath_instantiatedOutOfLine(patternPtr, arguments)
}
internal func _getKeyPath_instantiatedOutOfLine(
_ pattern: UnsafeRawPointer,
_ arguments: UnsafeRawPointer)
-> UnsafeRawPointer {
// Do a pass to determine the class of the key path we'll be instantiating
// and how much space we'll need for it.
let (keyPathClass, rootType, size, alignmentMask)
= _getKeyPathClassAndInstanceSizeFromPattern(pattern, arguments)
_sanityCheck(alignmentMask < MemoryLayout<Int>.alignment,
"overalignment not implemented")
// Allocate the instance.
let instance = keyPathClass._create(capacityInBytes: size) { instanceData in
// Instantiate the pattern into the instance.
let patternBufferPtr = pattern.advanced(by: keyPathObjectHeaderSize)
let patternBuffer = KeyPathBuffer(base: patternBufferPtr)
_instantiateKeyPathBuffer(patternBuffer, instanceData, rootType, arguments)
}
// Take the KVC string from the pattern.
let kvcStringPtr = pattern.advanced(by: MemoryLayout<HeapObject>.size)
instance._kvcKeyPathStringPtr = kvcStringPtr
.load(as: Optional<UnsafePointer<CChar>>.self)
// Hand it off at +1.
return UnsafeRawPointer(Unmanaged.passRetained(instance).toOpaque())
}
internal func _getKeyPath_instantiateInline(
_ objectRawPtr: Builtin.RawPointer
) {
let objectPtr = UnsafeMutableRawPointer(objectRawPtr)
// Do a pass to determine the class of the key path we'll be instantiating
// and how much space we'll need for it.
// The pattern argument doesn't matter since an in-place pattern should never
// have arguments.
let (keyPathClass, rootType, instantiatedSize, alignmentMask)
= _getKeyPathClassAndInstanceSizeFromPattern(objectPtr, objectPtr)
_sanityCheck(alignmentMask < MemoryLayout<Int>.alignment,
"overalignment not implemented")
let bufferPtr = objectPtr.advanced(by: keyPathObjectHeaderSize)
let buffer = KeyPathBuffer(base: bufferPtr)
let totalSize = buffer.data.count + MemoryLayout<Int>.size
let bufferData = UnsafeMutableRawBufferPointer(
start: bufferPtr,
count: instantiatedSize)
// TODO: Eventually, we'll need to handle cases where the instantiated
// key path has a larger size than the pattern (because it involves
// resilient types, for example), and fall back to out-of-place instantiation
// when that happens.
_sanityCheck(instantiatedSize <= totalSize,
"size-increasing in-place instantiation not implemented")
// Instantiate the pattern in place.
_instantiateKeyPathBuffer(buffer, bufferData, rootType, bufferPtr)
_swift_instantiateInertHeapObject(objectPtr,
unsafeBitCast(keyPathClass, to: OpaquePointer.self))
}
internal typealias MetadataAccessor =
@convention(c) (UnsafeRawPointer) -> UnsafeRawPointer
internal func _getKeyPathClassAndInstanceSizeFromPattern(
_ pattern: UnsafeRawPointer,
_ arguments: UnsafeRawPointer
) -> (
keyPathClass: AnyKeyPath.Type,
rootType: Any.Type,
size: Int,
alignmentMask: Int
) {
// Resolve the root and leaf types.
let rootAccessor = pattern.load(as: MetadataAccessor.self)
let leafAccessor = pattern.load(fromByteOffset: MemoryLayout<Int>.size,
as: MetadataAccessor.self)
let root = unsafeBitCast(rootAccessor(arguments), to: Any.Type.self)
let leaf = unsafeBitCast(leafAccessor(arguments), to: Any.Type.self)
// Scan the pattern to figure out the dynamic capability of the key path.
// Start off assuming the key path is writable.
var capability: KeyPathKind = .value
let bufferPtr = pattern.advanced(by: keyPathObjectHeaderSize)
var buffer = KeyPathBuffer(base: bufferPtr)
var size = buffer.data.count + MemoryLayout<Int>.size
var alignmentMask = MemoryLayout<Int>.alignment - 1
scanComponents: while true {
let header = buffer.pop(RawKeyPathComponent.Header.self)
func popOffset() {
if header.payload == RawKeyPathComponent.Header.unresolvedFieldOffsetPayload
|| header.payload == RawKeyPathComponent.Header.outOfLineOffsetPayload {
_ = buffer.pop(UInt32.self)
}
if header.payload == RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload {
_ = buffer.pop(Int.self)
// On 64-bit systems the pointer to the ivar offset variable is
// pointer-sized and -aligned, but the resulting offset ought to be
// 32 bits only and fit into padding between the 4-byte header and
// pointer-aligned type word. We don't need this space after
// instantiation.
if MemoryLayout<Int>.size == 8 {
size -= MemoryLayout<UnsafeRawPointer>.size
}
}
}
switch header.kind {
case .struct:
// No effect on the capability.
// TODO: we should dynamically prevent "let" properties from being
// reassigned.
popOffset()
case .class:
// The rest of the key path could be reference-writable.
// TODO: we should dynamically prevent "let" properties from being
// reassigned.
capability = .reference
popOffset()
case .computed:
let settable =
header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0
let mutating =
header.payload & RawKeyPathComponent.Header.computedMutatingFlag != 0
let hasArguments =
header.payload & RawKeyPathComponent.Header.computedHasArgumentsFlag != 0
switch (settable, mutating) {
case (false, false):
// If the property is get-only, the capability becomes read-only, unless
// we get another reference-writable component.
capability = .readOnly
case (true, false):
capability = .reference
case (true, true):
// Writable if the base is. No effect.
break
case (false, true):
_sanityCheckFailure("unpossible")
}
_ = buffer.popRaw(size: MemoryLayout<Int>.size * (settable ? 3 : 2),
alignment: MemoryLayout<Int>.alignment)
// Get the instantiated size and alignment of the argument payload
// by asking the layout function to compute it for our given argument
// file.
if hasArguments {
let getLayoutRaw =
buffer.pop(UnsafeRawPointer.self)
let _ /*witnesses*/ = buffer.pop(UnsafeRawPointer.self)
let _ /*initializer*/ = buffer.pop(UnsafeRawPointer.self)
let getLayout = unsafeBitCast(getLayoutRaw,
to: RawKeyPathComponent.ComputedArgumentLayoutFn.self)
let (addedSize, addedAlignmentMask) = getLayout(arguments)
// TODO: Handle over-aligned values
_sanityCheck(addedAlignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed property element not supported")
// Argument payload replaces the space taken by the initializer
// function pointer in the pattern.
size += (addedSize + alignmentMask) & ~alignmentMask
- MemoryLayout<Int>.size
}
case .optionalChain,
.optionalWrap:
// Chaining always renders the whole key path read-only.
capability = .readOnly
break scanComponents
case .optionalForce:
// No effect.
break
}
// Break if this is the last component.
if buffer.data.count == 0 { break }
// Pop the type accessor reference.
_ = buffer.popRaw(size: MemoryLayout<Int>.size,
alignment: MemoryLayout<Int>.alignment)
}
// Grab the class object for the key path type we'll end up with.
func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type {
func openLeaf<Leaf>(_: Leaf.Type) -> AnyKeyPath.Type {
switch capability {
case .readOnly:
return KeyPath<Root, Leaf>.self
case .value:
return WritableKeyPath<Root, Leaf>.self
case .reference:
return ReferenceWritableKeyPath<Root, Leaf>.self
}
}
return _openExistential(leaf, do: openLeaf)
}
let classTy = _openExistential(root, do: openRoot)
return (keyPathClass: classTy, rootType: root,
size: size, alignmentMask: alignmentMask)
}
internal func _instantiateKeyPathBuffer(
_ origPatternBuffer: KeyPathBuffer,
_ origDestData: UnsafeMutableRawBufferPointer,
_ rootType: Any.Type,
_ arguments: UnsafeRawPointer
) {
// NB: patternBuffer and destData alias when the pattern is instantiable
// in-line. Therefore, do not read from patternBuffer after the same position
// in destData has been written to.
var patternBuffer = origPatternBuffer
let destHeaderPtr = origDestData.baseAddress.unsafelyUnwrapped
var destData = UnsafeMutableRawBufferPointer(
start: destHeaderPtr.advanced(by: MemoryLayout<Int>.size),
count: origDestData.count - MemoryLayout<Int>.size)
func pushDest<T>(_ value: T) {
_sanityCheck(_isPOD(T.self))
var value2 = value
let size = MemoryLayout<T>.size
let alignment = MemoryLayout<T>.alignment
var baseAddress = destData.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) % alignment
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
_memcpy(dest: baseAddress, src: &value2,
size: UInt(size))
destData = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destData.count - size - misalign)
}
// Track the triviality of the resulting object data.
var isTrivial = true
// Track where the reference prefix begins.
var endOfReferencePrefixComponent: UnsafeMutableRawPointer? = nil
var previousComponentAddr: UnsafeMutableRawPointer? = nil
// Instantiate components that need it.
var base: Any.Type = rootType
// Some pattern forms are pessimistically larger than what we need in the
// instantiated key path. Keep track of this.
while true {
let componentAddr = destData.baseAddress.unsafelyUnwrapped
let header = patternBuffer.pop(RawKeyPathComponent.Header.self)
func tryToResolveOffset() {
if header.payload == RawKeyPathComponent.Header.unresolvedFieldOffsetPayload {
// Look up offset in type metadata. The value in the pattern is the
// offset within the metadata object.
let metadataPtr = unsafeBitCast(base, to: UnsafeRawPointer.self)
let offsetOfOffset = patternBuffer.pop(UInt32.self)
let offset = metadataPtr.load(fromByteOffset: Int(offsetOfOffset),
as: UInt32.self)
// Rewrite the header for a resolved offset.
var newHeader = header
newHeader.payload = RawKeyPathComponent.Header.outOfLineOffsetPayload
pushDest(newHeader)
pushDest(offset)
return
}
if header.payload == RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload {
// Look up offset in the indirectly-referenced variable we have a
// pointer.
let offsetVar = patternBuffer.pop(UnsafeRawPointer.self)
let offsetValue = UInt32(offsetVar.load(as: UInt.self))
// Rewrite the header for a resolved offset.
var newHeader = header
newHeader.payload = RawKeyPathComponent.Header.outOfLineOffsetPayload
pushDest(newHeader)
pushDest(offsetValue)
return
}
// Otherwise, just transfer the pre-resolved component.
pushDest(header)
if header.payload == RawKeyPathComponent.Header.outOfLineOffsetPayload {
let offset = patternBuffer.pop(UInt32.self)
pushDest(offset)
}
}
switch header.kind {
case .struct:
// The offset may need to be resolved dynamically.
tryToResolveOffset()
case .class:
// Crossing a class can end the reference prefix, and makes the following
// key path potentially reference-writable.
endOfReferencePrefixComponent = previousComponentAddr
// The offset may need to be resolved dynamically.
tryToResolveOffset()
case .optionalChain,
.optionalWrap,
.optionalForce:
// No instantiation necessary.
pushDest(header)
break
case .computed:
// A nonmutating settable property can end the reference prefix and
// makes the following key path potentially reference-writable.
if header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0
&& header.payload & RawKeyPathComponent.Header.computedMutatingFlag == 0 {
endOfReferencePrefixComponent = previousComponentAddr
}
// The ID may need resolution if the property is keyed by a selector.
var newHeader = header
var id = patternBuffer.pop(Int.self)
switch header.payload
& RawKeyPathComponent.Header.computedIDResolutionMask {
case RawKeyPathComponent.Header.computedIDResolved:
// Nothing to do.
break
case RawKeyPathComponent.Header.computedIDUnresolvedIndirectPointer:
// The value in the pattern is a pointer to the actual unique word-sized
// value in memory.
let idPtr = UnsafeRawPointer(bitPattern: id).unsafelyUnwrapped
id = idPtr.load(as: Int.self)
default:
_sanityCheckFailure("unpossible")
}
newHeader.payload &= ~RawKeyPathComponent.Header.computedIDResolutionMask
pushDest(newHeader)
pushDest(id)
// Carry over the accessors.
let getter = patternBuffer.pop(UnsafeRawPointer.self)
pushDest(getter)
if header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0{
let setter = patternBuffer.pop(UnsafeRawPointer.self)
pushDest(setter)
}
// Carry over the arguments.
if header.payload
& RawKeyPathComponent.Header.computedHasArgumentsFlag != 0 {
let getLayoutRaw = patternBuffer.pop(UnsafeRawPointer.self)
let getLayout = unsafeBitCast(getLayoutRaw,
to: RawKeyPathComponent.ComputedArgumentLayoutFn.self)
let witnesses = patternBuffer.pop(
UnsafePointer<ComputedArgumentWitnesses>.self)
if let _ = witnesses.pointee.destroy {
isTrivial = false
}
let initializerRaw = patternBuffer.pop(UnsafeRawPointer.self)
let initializer = unsafeBitCast(initializerRaw,
to: RawKeyPathComponent.ComputedArgumentInitializerFn.self)
let (size, alignmentMask) = getLayout(arguments)
_sanityCheck(alignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed arguments not implemented yet")
// The real buffer stride will be rounded up to alignment.
let stride = (size + alignmentMask) & ~alignmentMask
pushDest(stride)
pushDest(witnesses)
_sanityCheck(Int(bitPattern: destData.baseAddress) & alignmentMask == 0,
"argument destination not aligned")
initializer(arguments, destData.baseAddress.unsafelyUnwrapped)
destData = UnsafeMutableRawBufferPointer(
start: destData.baseAddress.unsafelyUnwrapped + stride,
count: destData.count - stride)
}
}
// Break if this is the last component.
if patternBuffer.data.count == 0 { break }
// Resolve the component type.
let componentTyAccessor = patternBuffer.pop(MetadataAccessor.self)
base = unsafeBitCast(componentTyAccessor(arguments), to: Any.Type.self)
pushDest(base)
previousComponentAddr = componentAddr
}
// We should have traversed both buffers.
_sanityCheck(patternBuffer.data.isEmpty && destData.count == 0)
// Write out the header.
let destHeader = KeyPathBuffer.Header(
size: origDestData.count - MemoryLayout<Int>.size,
trivial: isTrivial,
hasReferencePrefix: endOfReferencePrefixComponent != nil)
destHeaderPtr.storeBytes(of: destHeader, as: KeyPathBuffer.Header.self)
// Mark the reference prefix if there is one.
if let endOfReferencePrefixComponent = endOfReferencePrefixComponent {
var componentHeader = endOfReferencePrefixComponent
.load(as: RawKeyPathComponent.Header.self)
componentHeader.endOfReferencePrefix = true
endOfReferencePrefixComponent.storeBytes(of: componentHeader,
as: RawKeyPathComponent.Header.self)
}
}
| 36.900937 | 91 | 0.659798 |
febf1fd7fc30b403f04bccc14e371c6f1ce4949b | 2,536 | //
// FlickrImageDetailsModelTest.swift
// FlickrPhotoSearchTests
//
// Created by Sauvik Dolui on 24/07/19.
// Copyright © 2019 Sauvik Dolu. All rights reserved.
//
import XCTest
@testable import FlickrPhotoSearch
class FlickrImageDetailsModelTest: XCTestCase {
var validResultJSON: String!
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
validResultJSON = try! String(contentsOfFile: Bundle(for: FlickrImageSearchModelTest.self).path(forResource: "ImageDetails", ofType: "json")!)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func test_model_preparation() {
var result = try! JSONDecoder().decode(PhotoDetailsResult.self, from: validResultJSON.data(using: .utf8)!)
XCTAssertNotNil(result, "Result Must not be nil")
XCTAssertEqual(result.stat, "ok", "Stat not same")
XCTAssertNotNil(result.photo, "Photo must not be nil")
XCTAssertNotNil(result.photo.title, "Title must not be nil")
XCTAssertNotNil(result.photo.photoDescription, "Description must not be nil")
XCTAssertNotNil(result.photo.tags, "Tags must not be nil")
XCTAssertNotNil(result.photo.tags.tag, "Tag Array must not be nil")
XCTAssertGreaterThan(result.photo.tags.tag.count, 0 , "tags array must contain more than one tag")
XCTAssertEqual(result.photo.photoDescription.content,
"the ntypical nstreetnsceneninnevery ncitynnutter CHAOSnto the UNINITIATEDn ntotally normal nto the nlocal.nncatch the tout trying to ntake me to the spice marketnand Chadni Chowk while nthe motorcyclist wants to bite his head offnfor being in his way. nnTouts are omnipresent ncannot be avoided.nnOLD DELHInin front of the JAMA MASJIDnthe largest MOSQUE in nthe largest Democracy in the worldnn",
"Desc does not match")
// Empty Description Test
result.photo.photoDescription.content = ""
XCTAssertEqual(result.photo.getDescription(), "Not Available")
// Tag tests
let tags = result.photo.getTagsString(separator: ",")
XCTAssertTrue(tags.count > 0, "Must value value in tags")
// Zero Tag test
result.photo.tags.tag = []
XCTAssertEqual(result.photo.getTagsString(separator: ","), "Not Available")
}
}
| 45.285714 | 425 | 0.686909 |
69bf2cc6ddaa0344f9932cb934a39b22358ba383 | 194 | //
// UIColor+Random.swift
// YBSlantedCollectionViewLayoutSample
//
// Created by Yassir Barchi on 30/12/2017.
// Copyright © 2017 Yassir Barchi. All rights reserved.
//
import Foundation
| 19.4 | 56 | 0.731959 |
d9d6ae2ab97d5c2c97e8f58634024ac14e1d2b6d | 517 | //
// ChannelModel.swift
// DanTangSwift
//
// Created by 思 彭 on 16/10/6.
// Copyright © 2016年 思 彭. All rights reserved.
//
import UIKit
class ChannelModel: NSObject {
/*
{
"editable": true,
"id": 14,
"name": "美食"
},
*/
var editable: Bool?
var id: Int?
var name: String?
init(dict: [String: AnyObject]) {
super.init()
editable = dict["editable"] as? Bool
id = dict["id"] as? Int
name = dict["name"] as? String
}
}
| 16.15625 | 47 | 0.512573 |
33cac9c61be2669a01c3cea285f7885ac4cb7152 | 328 | //
// StudentDataModel.swift
// GPA Tracker
//
// Created by Hugo Courthias on 10/03/2019.
// Copyright © 2019 Hugo Courthias. All rights reserved.
//
import UIKit
class StudentDataModel {
var gpa : Double = 0
var name : String = ""
var logTime : Double = 0
var credits : Int = 0
var promo : Int = 0
}
| 18.222222 | 57 | 0.631098 |
4a0e89e9bd63d384f7f186a57864a9df1c63b089 | 7,916 | //===----------------------------------------------------------------------===//
//
// 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/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import NIO
//MARK: Paginators
extension FraudDetector {
/// Gets all of the model versions for the specified model type or for the specified model type and model ID. You can also get details for a single, specified model version.
public func describeModelVersionsPaginator(
_ input: DescribeModelVersionsRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeModelVersionsResult,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: describeModelVersions, tokenKey: \DescribeModelVersionsResult.nextToken, on: eventLoop, onPage: onPage)
}
/// Gets all of detectors. This is a paginated API. If you provide a null maxSizePerPage, this actions retrieves a maximum of 10 records per page. If you provide a maxSizePerPage, the value must be between 5 and 10. To get the next page results, provide the pagination token from the GetEventTypesResponse as part of your request. A null pagination token fetches the records from the beginning.
public func getDetectorsPaginator(
_ input: GetDetectorsRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetDetectorsResult,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: getDetectors, tokenKey: \GetDetectorsResult.nextToken, on: eventLoop, onPage: onPage)
}
/// Gets the details for one or more Amazon SageMaker models that have been imported into the service. This is a paginated API. If you provide a null maxSizePerPage, this actions retrieves a maximum of 10 records per page. If you provide a maxSizePerPage, the value must be between 5 and 10. To get the next page results, provide the pagination token from the GetExternalModelsResult as part of your request. A null pagination token fetches the records from the beginning.
public func getExternalModelsPaginator(
_ input: GetExternalModelsRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetExternalModelsResult,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: getExternalModels, tokenKey: \GetExternalModelsResult.nextToken, on: eventLoop, onPage: onPage)
}
/// Gets all of the models for the AWS account, or the specified model type, or gets a single model for the specified model type, model ID combination.
public func getModelsPaginator(
_ input: GetModelsRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetModelsResult,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: getModels, tokenKey: \GetModelsResult.nextToken, on: eventLoop, onPage: onPage)
}
/// Gets one or more outcomes. This is a paginated API. If you provide a null maxSizePerPage, this actions retrieves a maximum of 10 records per page. If you provide a maxSizePerPage, the value must be between 50 and 100. To get the next page results, provide the pagination token from the GetOutcomesResult as part of your request. A null pagination token fetches the records from the beginning.
public func getOutcomesPaginator(
_ input: GetOutcomesRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetOutcomesResult,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: getOutcomes, tokenKey: \GetOutcomesResult.nextToken, on: eventLoop, onPage: onPage)
}
/// Gets all rules available for the specified detector.
public func getRulesPaginator(
_ input: GetRulesRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetRulesResult,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: getRules, tokenKey: \GetRulesResult.nextToken, on: eventLoop, onPage: onPage)
}
/// Gets all of the variables or the specific variable. This is a paginated API. Providing null maxSizePerPage results in retrieving maximum of 100 records per page. If you provide maxSizePerPage the value must be between 50 and 100. To get the next page result, a provide a pagination token from GetVariablesResult as part of your request. Null pagination token fetches the records from the beginning.
public func getVariablesPaginator(
_ input: GetVariablesRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetVariablesResult,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: getVariables, tokenKey: \GetVariablesResult.nextToken, on: eventLoop, onPage: onPage)
}
}
extension FraudDetector.DescribeModelVersionsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FraudDetector.DescribeModelVersionsRequest {
return .init(
maxResults: self.maxResults,
modelId: self.modelId,
modelType: self.modelType,
modelVersionNumber: self.modelVersionNumber,
nextToken: token
)
}
}
extension FraudDetector.GetDetectorsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FraudDetector.GetDetectorsRequest {
return .init(
detectorId: self.detectorId,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension FraudDetector.GetExternalModelsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FraudDetector.GetExternalModelsRequest {
return .init(
maxResults: self.maxResults,
modelEndpoint: self.modelEndpoint,
nextToken: token
)
}
}
extension FraudDetector.GetModelsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FraudDetector.GetModelsRequest {
return .init(
maxResults: self.maxResults,
modelId: self.modelId,
modelType: self.modelType,
nextToken: token
)
}
}
extension FraudDetector.GetOutcomesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FraudDetector.GetOutcomesRequest {
return .init(
maxResults: self.maxResults,
name: self.name,
nextToken: token
)
}
}
extension FraudDetector.GetRulesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FraudDetector.GetRulesRequest {
return .init(
detectorId: self.detectorId,
maxResults: self.maxResults,
nextToken: token,
ruleId: self.ruleId,
ruleVersion: self.ruleVersion
)
}
}
extension FraudDetector.GetVariablesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FraudDetector.GetVariablesRequest {
return .init(
maxResults: self.maxResults,
name: self.name,
nextToken: token
)
}
}
| 44.47191 | 478 | 0.691132 |
5b0af846feb991eae145a5b46da08a59f6a9b5d8 | 646 | // Auto-generated code. Do not edit.
import Foundation
import DLJSONAPI
// MARK: - CancelCloseDeferredPaymentRequestOpResource
extension Horizon {
open class CancelCloseDeferredPaymentRequestOpResource: BaseOperationDetailsResource {
open override class var resourceType: String {
return "operations-cancel-close-deferred-payment-request"
}
public enum CodingKeys: String, CodingKey {
// relations
case request
}
// MARK: Relations
open var request: Horizon.ReviewableRequestResource? {
return self.relationSingleOptionalValue(key: CodingKeys.request)
}
}
}
| 23.071429 | 86 | 0.708978 |
878db7a7141d2a45676dc6793ef28b817f000a3c | 2,004 | //
// LoggedOutInteractor.swift
// TicTacToe
//
// Created by Varun Santhanam on 7/9/18.
// Copyright © 2018 Uber. All rights reserved.
//
import RIBs
import RxSwift
protocol LoggedOutRouting: ViewableRouting {
// TODO: Declare methods the interactor can invoke to manage sub-tree via the router.
}
protocol LoggedOutPresentable: Presentable {
var listener: LoggedOutPresentableListener? { get set }
// TODO: Declare methods the interactor can invoke the presenter to present data.
}
protocol LoggedOutListener: class {
// TODO: Declare methods the interactor can invoke to communicate with other RIBs.
}
final class LoggedOutInteractor: PresentableInteractor<LoggedOutPresentable>, LoggedOutInteractable, LoggedOutPresentableListener {
weak var router: LoggedOutRouting?
weak var listener: LoggedOutListener?
// TODO: Add additional dependencies to constructor. Do not perform any logic
// in constructor.
override init(presenter: LoggedOutPresentable) {
super.init(presenter: presenter)
presenter.listener = self
}
override func didBecomeActive() {
super.didBecomeActive()
// TODO: Implement business logic here.
}
override func willResignActive() {
super.willResignActive()
// TODO: Pause any business logic.
}
// MARK: - LoggedOutPresentableListener
func login(withPlayer1Name player1Name: String?, player2Name: String?) {
let player1NameWithDefault = playerName(player1Name, withDefaultName: "Player 1")
let player2NameWithDefault = playerName(player2Name, withDefaultName: "Player 2")
print("\(player1NameWithDefault) vs \(player2NameWithDefault)")
}
// MARK: - Private
private func playerName(_ name: String?, withDefaultName defaultName: String) -> String {
if let name = name {
return name.isEmpty ? defaultName : name
} else {
return defaultName
}
}
}
| 30.363636 | 131 | 0.693114 |
2678154717a1b84c11370e3f85903520d3b39d22 | 407 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created ___FULLUSERNAME___ on ___DATE___.
// Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import Foundation
class ___VARIABLE_MODULENAME___DefaultInteractor {
weak var presenter: ___VARIABLE_MODULENAME___Presenter?
}
extension ___VARIABLE_MODULENAME___DefaultInteractor: ___VARIABLE_MODULENAME___Interactor {
}
| 20.35 | 91 | 0.798526 |
d97fa8e562520c165e501a5566ac660fd066b549 | 1,506 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/noppoMan/aws-sdk-swift/blob/master/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import Foundation
import AWSSDKSwiftCore
import NIO
/**
AWS EC2 Connect Service is a service that enables system administrators to publish temporary SSH keys to their EC2 instances in order to establish connections to their instances without leaving a permanent authentication option.
*/
public struct EC2InstanceConnect {
let client: AWSClient
public init(accessKeyId: String? = nil, secretAccessKey: String? = nil, region: AWSSDKSwiftCore.Region? = nil, endpoint: String? = nil) {
self.client = AWSClient(
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: region,
amzTarget: "AWSEC2InstanceConnectService",
service: "ec2-instance-connect",
serviceProtocol: ServiceProtocol(type: .json, version: ServiceProtocol.Version(major: 1, minor: 1)),
apiVersion: "2018-04-02",
endpoint: endpoint,
middlewares: [],
possibleErrorTypes: [EC2InstanceConnectErrorType.self]
)
}
/// Pushes an SSH public key to a particular OS user on a given EC2 instance for 60 seconds.
public func sendSSHPublicKey(_ input: SendSSHPublicKeyRequest) throws -> Future<SendSSHPublicKeyResponse> {
return try client.send(operation: "SendSSHPublicKey", path: "/", httpMethod: "POST", input: input)
}
} | 43.028571 | 228 | 0.700531 |
8a3baab3726cc833c3335ee37f06a6d957a47d6e | 1,352 | //
// Glider
// Fast, Lightweight yet powerful logging system for Swift.
//
// Created by Daniele Margutti
// Email: [email protected]
// Web: http://www.danielemargutti.com
//
// Copyright ©2021 Daniele Margutti. All rights reserved.
// Licensed under MIT License.
//
import Foundation
import Network
internal class NetworkStatus {
static let shared = NetworkStatus()
private var pathMonitor: NWPathMonitor!
private var path: NWPath?
private let backgroudQueue = DispatchQueue.global(qos: .background)
private lazy var pathUpdateHandler: ((NWPath) -> Void) = { path in
self.path = path
if path.status == NWPath.Status.satisfied {
print("Connected")
} else if path.status == NWPath.Status.unsatisfied {
print("unsatisfied")
} else if path.status == NWPath.Status.requiresConnection {
print("requiresConnection")
}
}
private init() {
pathMonitor = NWPathMonitor()
pathMonitor.pathUpdateHandler = self.pathUpdateHandler
pathMonitor.start(queue: backgroudQueue)
}
func isNetworkAvailable() -> Bool {
if let path = self.path {
if path.status == NWPath.Status.satisfied {
return true
}
}
return false
}
}
| 26 | 71 | 0.621302 |
1e97a20307d7f16dedbd9ffb15da2ad7912eda77 | 1,010 |
/// Currencies List
public class CurrencyList {
/// Total number of currencies documents that matched your query.
public let total: Int
/// List of currencies.
public let currencies: [Currency]
init(
total: Int,
currencies: [Currency]
) {
self.total = total
self.currencies = currencies
}
public static func from(map: [String: Any]) -> CurrencyList {
return CurrencyList(
total: map["total"] as! Int,
currencies: (map["currencies"] as! [[String: Any]]).map { Currency.from(map: $0) }
)
}
public func toMap() -> [String: Any] {
return [
"total": total as Any,
"currencies": currencies.map { $0.toMap() } as Any
]
}
} | 30.606061 | 232 | 0.424752 |
904fdde2df15ecac74925e94eb12d71c041148cd | 4,742 | //
// ViewController.swift
// ExchangeRates
//
// Created by Oszkó Tamás on 21/11/15.
// Copyright © 2015 Oszi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, JBLineChartViewDataSource, JBLineChartViewDelegate {
@IBOutlet weak var chartView: JBLineChartView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var rateLabel: UILabel!
@IBOutlet weak var updatedLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var changeLabel: UILabel!
var ratesDownloader: RatesDownloader?
var rates: [Rate]?
private let color = UIColor(red: 23/255, green: 109/255, blue: 250/255, alpha: 1)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
chartView.dataSource = self
chartView.delegate = self
segmentedControl.setTitle("EUR", forSegmentAtIndex: 0)
segmentedControl.setTitle("NOK", forSegmentAtIndex: 1)
segmentedControl.tintColor = color
rateLabel.textColor = color
updatedLabel.textColor = color
activityIndicator.tintColor = color
refreshRates()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
refreshRates()
}
}
func numberOfLinesInLineChartView(lineChartView: JBLineChartView!) -> UInt {
return 1
}
func lineChartView(lineChartView: JBLineChartView!, numberOfVerticalValuesAtLineIndex lineIndex: UInt) -> UInt {
guard let rates = rates else {
return 0
}
return UInt(rates.count)
}
func lineChartView(lineChartView: JBLineChartView!, verticalValueForHorizontalIndex horizontalIndex: UInt, atLineIndex lineIndex: UInt) -> CGFloat {
let index = Int(horizontalIndex)
let rate = rates![index]
return CGFloat(rate.value.floatValue)
}
func lineChartView(lineChartView: JBLineChartView!, colorForLineAtLineIndex lineIndex: UInt) -> UIColor! {
return color
}
public func lineChartView(lineChartView: JBLineChartView!, widthForLineAtLineIndex lineIndex: UInt) -> CGFloat {
return 1.0
}
private func refreshRates() {
ratesDownloader = createRatesDownloader()
rates?.removeAll()
chartView.reloadData()
activityIndicator.startAnimating()
rateLabel.text = "-"
changeLabel.text = "-"
changeLabel.textColor = self.color
updatedLabel.text = "Refreshing..."
ratesDownloader?.getRates({ (rates: [Rate]?, updated: NSDate?, error: NSError?) -> () in
self.activityIndicator.stopAnimating()
if let error = error {
self.updatedLabel.text = "Refresh error \(error.localizedDescription)"
return
}
let df = NSDateFormatter()
df.dateFormat = "MM/dd HH:mm"
self.updatedLabel.text = "Updated at \(df.stringFromDate(updated!))"
self.rates = rates
self.chartView.reloadData()
guard let lastRate = rates?[0], let last2Rate = rates?[1] else {
self.rateLabel.text = "-"
self.changeLabel.textColor = self.color
self.changeLabel.text = "0.0"
return
}
let chg = lastRate.value.floatValue - last2Rate.value.floatValue
self.rateLabel.text = "\(lastRate.value)\(lastRate.currencyTo)"
if chg > 0 {
self.changeLabel.textColor = UIColor.redColor()
self.changeLabel.text = "\(chg)"
} else if chg < 0 {
self.changeLabel.textColor = UIColor.greenColor()
self.changeLabel.text = "+\(chg)"
} else {
self.changeLabel.textColor = self.color
self.changeLabel.text = "0.0"
}
})
}
private func createRatesDownloader() -> RatesDownloader {
let currency = segmentedControl.titleForSegmentAtIndex(segmentedControl.selectedSegmentIndex)
return MNBRatesDownloader(currency: currency!)
}
@IBAction func segmentedControlChanged(sender: AnyObject) {
refreshRates()
}
}
| 32.930556 | 152 | 0.617461 |
dba303796f3ec78648ab6d9e827678f33b4e70ce | 1,485 | //
// MovieDetailsPresenter.swift
// MovieBuff
//
// Created by Mac Tester on 10/16/16.
// Copyright © 2016 Lunaria Software LLC. All rights reserved.
//
import Foundation
class MovieDetailPresenter {
// Presenting view associated with this presenter
fileprivate weak var attachedView:MovieDetailsPresentingViewProtocol?
}
extension MovieDetailPresenter:MovieDetailsPresenterProtocol {
func fetchDetailsOfMovileWithIMDBId(_ id:String) {
attachedView?.dataStartedLoading()
ServerManager.sharedInstance.detailsWithIMDBID(id, handler: { [weak self](movie, error) in
self?.attachedView?.dataFinishedLoading()
print (movie)
if let error = error {
self?.attachedView?.showErrorAlertWithTitle("Error!", message: error.localizedDescription)
}
else {
if let movie = movie {
self?.attachedView?.onMovieDetailsFetched(movie)
}
else {
self?.attachedView?.onMovieDetailsFetched(nil)
}
}
})
}
func attachPresentingView(_ view:PresentingViewProtocol) {
attachedView = view as? MovieDetailsPresentingViewProtocol
}
func detachPresentingView(_ view:PresentingViewProtocol){
if attachedView == view as! _OptionalNilComparisonType {
attachedView = nil
}
}
}
| 29.117647 | 106 | 0.616162 |
505503165d38896000d21aa534110de8ce526eb2 | 8,401 | //
// MDCourseMemoryStorage_Tests.swift
// MyDictionary_App_SwiftTests
//
// Created by Dmytro Chumakov on 24.08.2021.
//
import XCTest
@testable import MyDictionary_App_Swift
final class MDCourseMemoryStorage_Tests: XCTestCase {
fileprivate var courseMemoryStorage: MDCourseMemoryStorageProtocol!
override func setUpWithError() throws {
try super.setUpWithError()
let courseMemoryStorage: MDCourseMemoryStorageProtocol = MDCourseMemoryStorage.init(operationQueue: Constants_For_Tests.operationQueueManager.operationQueue(byName: MDConstants.QueueName.courseMemoryStorageOperationQueue)!,
array: .init())
self.courseMemoryStorage = courseMemoryStorage
}
}
extension MDCourseMemoryStorage_Tests {
func test_Create_Course_Functionality() {
let expectation = XCTestExpectation(description: "Create Course Expectation")
courseMemoryStorage.createCourse(Constants_For_Tests.mockedCourse) { createResult in
switch createResult {
case .success(let courseEntity):
XCTAssertTrue(courseEntity.userId == Constants_For_Tests.mockedCourse.userId)
XCTAssertTrue(courseEntity.courseId == Constants_For_Tests.mockedCourse.courseId)
XCTAssertTrue(courseEntity.languageId == Constants_For_Tests.mockedCourse.languageId)
XCTAssertTrue(courseEntity.languageName == Constants_For_Tests.mockedCourse.languageName)
XCTAssertTrue(courseEntity.createdAt == Constants_For_Tests.mockedCourse.createdAt)
expectation.fulfill()
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout)
}
func test_Create_Courses_Functionality() {
let expectation = XCTestExpectation(description: "Create Courses Expectation")
courseMemoryStorage.createCourses(Constants_For_Tests.mockedCourses) { createResult in
switch createResult {
case .success(let courseEntities):
XCTAssertTrue(courseEntities.count == Constants_For_Tests.mockedCourses.count)
expectation.fulfill()
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout)
}
func test_Read_Course_Functionality() {
let expectation = XCTestExpectation(description: "Read Course Expectation")
courseMemoryStorage.createCourse(Constants_For_Tests.mockedCourse) { [unowned self] createResult in
switch createResult {
case .success(let createCourseEntity):
courseMemoryStorage.readCourse(fromCourseId: createCourseEntity.courseId) { readResult in
switch readResult {
case .success(let readCourseEntity):
XCTAssertTrue(readCourseEntity.userId == createCourseEntity.userId)
XCTAssertTrue(readCourseEntity.courseId == createCourseEntity.courseId)
XCTAssertTrue(readCourseEntity.languageId == createCourseEntity.languageId)
XCTAssertTrue(readCourseEntity.languageName == createCourseEntity.languageName)
XCTAssertTrue(readCourseEntity.createdAt == createCourseEntity.createdAt)
expectation.fulfill()
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout)
}
func test_Delete_Course_Functionality() {
let expectation = XCTestExpectation(description: "Delete Course Expectation")
courseMemoryStorage.createCourse(Constants_For_Tests.mockedCourse) { [unowned self] createResult in
switch createResult {
case .success(let createCourseEntity):
courseMemoryStorage.deleteCourse(fromCourseId: createCourseEntity.courseId) { [unowned self] deleteResult in
switch deleteResult {
case .success:
self.courseMemoryStorage.entitiesIsEmpty { entitiesIsEmptyResult in
switch entitiesIsEmptyResult {
case .success(let entitiesIsEmpty):
XCTAssertTrue(entitiesIsEmpty)
expectation.fulfill()
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout)
}
func test_Delete_All_Courses_Functionality() {
let expectation = XCTestExpectation(description: "Delete All Courses Expectation")
courseMemoryStorage.createCourse(Constants_For_Tests.mockedCourse) { [unowned self] createResult in
switch createResult {
case .success:
courseMemoryStorage.deleteAllCourses() { [unowned self] deleteResult in
switch deleteResult {
case .success:
self.courseMemoryStorage.entitiesIsEmpty { entitiesIsEmptyResult in
switch entitiesIsEmptyResult {
case .success(let entitiesIsEmpty):
XCTAssertTrue(entitiesIsEmpty)
expectation.fulfill()
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
case .failure(let error):
XCTExpectFailure(error.localizedDescription)
expectation.fulfill()
}
}
wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout)
}
}
| 38.186364 | 231 | 0.515415 |
4b5e8974b3e85dbcfbfcd364bdf0931db3985562 | 5,368 | //
// MainSecureInternetSectionHeaderCell.swift
// EduVPN
//
#if os(macOS)
import AppKit
#elseif os(iOS)
import UIKit
#endif
class MainSecureInternetSectionHeaderCell: SectionHeaderCell {
private struct ServerEntry {
let baseURLString: DiscoveryData.BaseURLString
let countryCode: String
let countryName: String
}
private var selectedBaseURLString: DiscoveryData.BaseURLString?
private var onLocationChanged: ((DiscoveryData.BaseURLString) -> Void)?
private var serverEntries: [ServerEntry] = []
#if os(macOS)
@IBOutlet weak var changeLocationPullDown: NSPopUpButton!
#endif
#if os(iOS)
private weak var environment: Environment?
private weak var containingViewController: ViewController?
private var selectedIndex: Int = -1
#endif
func configureMainSecureInternetSectionHeader(
environment: Environment,
containingViewController: ViewController,
serversMap: [DiscoveryData.BaseURLString: DiscoveryData.SecureInternetServer],
selectedBaseURLString: DiscoveryData.BaseURLString,
onLocationChanged: @escaping (DiscoveryData.BaseURLString) -> Void) {
super.configure(as: .secureInternetServerSectionHeaderKind, isAdding: false)
#if os(iOS)
self.environment = environment
self.containingViewController = containingViewController
#endif
self.selectedBaseURLString = selectedBaseURLString
self.onLocationChanged = onLocationChanged
var serverEntries: [ServerEntry] = []
for server in serversMap.values {
let serverEntry = ServerEntry(
baseURLString: server.baseURLString,
countryCode: server.countryCode,
countryName: Locale.current.localizedString(forRegionCode: server.countryCode) ??
NSLocalizedString(
"Unknown country",
comment: "unknown country code"))
serverEntries.append(serverEntry)
}
serverEntries.sort { $0.countryName < $1.countryName }
self.serverEntries = serverEntries
#if os(macOS)
changeLocationPullDown.removeAllItems()
if let menu = changeLocationPullDown.menu {
let buttonTitle = NSLocalizedString(
"Change Location",
comment: "macOS main list change location pull-down menu title")
menu.addItem(NSMenuItem(title: buttonTitle, action: nil, keyEquivalent: ""))
for (index, serverEntry) in serverEntries.enumerated() {
let menuItem = NSMenuItem(
title: serverEntry.countryName,
action: #selector(locationSelected(sender:)),
keyEquivalent: "")
menuItem.state = (serverEntry.baseURLString == selectedBaseURLString) ? .on : .off
menuItem.target = self
menuItem.tag = index
menu.addItem(menuItem)
}
}
#elseif os(iOS)
for (index, serverEntry) in serverEntries.enumerated() {
// Using an 'if' is clearer than a 'where' here.
// swiftlint:disable:next for_where
if serverEntry.baseURLString == selectedBaseURLString {
selectedIndex = index
}
}
#endif
}
#if os(macOS)
@objc func locationSelected(sender: Any) {
guard let menuItem = sender as? NSMenuItem else { return }
guard menuItem.tag < serverEntries.count else { return }
let serverEntry = serverEntries[menuItem.tag]
if serverEntry.baseURLString != selectedBaseURLString {
onLocationChanged?(serverEntry.baseURLString)
}
}
#endif
#if os(iOS)
@IBAction func changeLocationTapped(_ sender: Any) {
guard let environment = self.environment,
let containingViewController = self.containingViewController else {
return
}
var items: [ItemSelectionViewController.Item] = []
for serverEntry in serverEntries {
let item = ItemSelectionViewController.Item(
imageName: "CountryFlag_\(serverEntry.countryCode)",
text: serverEntry.countryName)
items.append(item)
}
let selectionVC = environment.instantiateItemSelectionViewController(
items: items, selectedIndex: selectedIndex)
selectionVC.title = NSLocalizedString(
"Select a location",
comment: "iOS location selection view title")
selectionVC.delegate = self
let navigationVC = UINavigationController(rootViewController: selectionVC)
navigationVC.modalPresentationStyle = .pageSheet
containingViewController.present(navigationVC, animated: true, completion: nil)
}
#endif
}
#if os(iOS)
extension MainSecureInternetSectionHeaderCell: ItemSelectionViewControllerDelegate {
func itemSelectionViewController(_ viewController: ItemSelectionViewController, didSelectIndex index: Int) {
guard index >= 0 && index < serverEntries.count else { return }
let serverEntry = serverEntries[index]
if serverEntry.baseURLString != selectedBaseURLString {
onLocationChanged?(serverEntry.baseURLString)
}
}
}
#endif
| 37.538462 | 112 | 0.650335 |
7addc3b35240c2433f19ea5ccac63e2c4434ad2a | 1,373 | // swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "DataModel-DPE",
platforms: [
.macOS(.v10_12), .iOS(.v8), .tvOS(.v9), .watchOS(.v3)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "DPE_V1_0",
targets: ["DPE_V1_0"]),
.library(
name: "DPE_V1_1",
targets: ["DPE_V1_1"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/spilikin/SwiftXMLTools.git", .exact("0.5.1")),
.package(url: "https://github.com/Quick/Nimble.git", .upToNextMinor(from: "8.0.0")),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "DPE_V1_0",
dependencies: ["XMLTools"]),
.target(
name: "DPE_V1_1",
dependencies: ["XMLTools"]),
],
swiftLanguageVersions: [.v5]
)
| 37.108108 | 122 | 0.595047 |
e9cebfc439f9c95af2727f653260f20fba50a0e9 | 2,149 | //
// AppDelegate.swift
// MovieFlix
//
// Created by Sumaiya Mansur on 2/13/16.
// Copyright © 2016 Sumaiya Mansur. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.723404 | 285 | 0.754304 |
8a1683f4035578bcc8793927315a8da20a05474f | 824 | //
// PolymorphicViewsUITestsLaunchTests.swift
// PolymorphicViewsUITests
//
// Created by Joey Hinckley on 3/25/22.
//
import XCTest
class PolymorphicViewsUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 24.969697 | 88 | 0.683252 |
0a783031b46f956a9ed84ca82ddc57d7530ba7e8 | 286 | //
// MainView.swift
// pushHandle
//
// Created by Kyryl Horbushko on 06.11.2021.
//
import Foundation
import SwiftUI
struct MainView: View {
var body: some View {
NavigationView {
SideMenuView()
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
}
}
| 15.052632 | 59 | 0.678322 |
7141dfc0469fc6765ccb052a74d0a5d4afa021d8 | 1,353 | //
// AppDelegate.swift
// Tip Calculator
//
// Created by Thong Nguyen on 1/15/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.567568 | 179 | 0.74575 |
ed1672066a6568ba39fdd4b2e7bf808af6a19a9f | 6,025 | //
// BaseUISegmentedControl.swift
// TTBaseUIKit
//
// Created by Truong Quang Tuan on 4/20/19.
// Copyright © 2019 Truong Quang Tuan. All rights reserved.
//
import Foundation
import UIKit
open class TTBaseUISegmentedControl: UISegmentedControl {
open var selectedColor:UIColor { get { return TTView.segSelectedColor }}
open var bgDefStyleColor:UIColor { get { return TTView.segBgDef } }
open var bgLineStyleColor:UIColor { get { return TTView.segBgLine } }
open var textColor:UIColor { get { return TTView.segTextColor }}
open var textSelectedColor:UIColor { get { return TTView.segTextSelectedColor }}
open var borderColor:UIColor { get { return TTView.segSelectedColor }}
open var borderHeight:CGFloat { get { return TTSize.H_BORDER }}
open var isRemoveBorder:Bool { get { return true }}
open var lineBottomHeight:CGFloat { get { return TTSize.H_SEG_LINE }}
open var lineBottomColor:UIColor { get { return TTView.segLineBottomBg }}
open var textLineBottomColor:UIColor { get { return TTView.segTextLineBottomBg }}
open var paddingLine:(CGFloat,CGFloat,CGFloat,CGFloat) { get { return (0,0,0,0)}}
open var conerRadio:CGFloat { get { return TTSize.CORNER_RADIUS }}
open var fontSize:CGFloat { get { return TTFont.getHeaderSize() } }
public enum TYPE {
case DEFAULT
case LINE_BOTTOM
}
public lazy var underlineView = UIView()
fileprivate lazy var type:TYPE = .DEFAULT
public var onTouchHandler:((_ seg:TTBaseUISegmentedControl, _ indexSelected:Int) -> Void)?
open func updateUI() { }
public init(with type:TYPE, items:[Any], bgColor:UIColor = UIColor.blue) {
super.init(items: items)
self.type = type
if type == .LINE_BOTTOM {
self.addUnderlineForSelectedSegment()
self.updateUIByStyle()
}
self.setupUI()
self.updateUI()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
self.updateUI()
}
public override init(items: [Any]?) {
super.init(items: items)
self.setupUI()
self.updateUI()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupUI() {
self.translatesAutoresizingMaskIntoConstraints = false
self.setTitleTextAttributes([NSAttributedString.Key.font: TTFont.getFont().withSize(self.fontSize)], for: UIControl.State())
self.updateUIByStyle()
self.addTarget(self, action: #selector(self.selectionDidChange(_:)), for: .valueChanged)
}
fileprivate func updateUIByStyle() {
if self.type == .DEFAULT {
self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: self.textSelectedColor], for: .selected)
self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: self.textColor], for: .normal)
self.tintColor = self.selectedColor
self.backgroundColor = self.bgDefStyleColor
self.selectedSegmentIndex = 0
self.layer.borderWidth = self.borderHeight
self.layer.borderColor = self.borderColor.cgColor
self.setConerRadius(with: self.conerRadio)
if isRemoveBorder {self.removeBorders(withColor: self.bgDefStyleColor, selected: self.selectedColor, hightLight: self.bgDefStyleColor.withAlphaComponent(0.4))}
} else {
self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: self.textLineBottomColor], for: .selected)
self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: self.textLineBottomColor.withAlphaComponent(0.5)], for: .normal)
self.tintColor = UIColor.clear
self.backgroundColor = self.bgLineStyleColor
self.selectedSegmentIndex = 0
self.layer.borderWidth = 0
self.layer.borderColor = UIColor.clear.cgColor
self.setConerRadius(with: self.conerRadio)
self.removeBorders(withColor: self.bgLineStyleColor, selected: bgLineStyleColor, hightLight: self.lineBottomColor.withAlphaComponent(0.4))
}
}
}
// MARK: For private base funcs
extension TTBaseUISegmentedControl {
@objc fileprivate func selectionDidChange(_ sender: UISegmentedControl) {
let index = sender.selectedSegmentIndex
self.setSelectedIndex(with: index)
self.onTouchHandler?(self, index)
}
fileprivate func addUnderlineForSelectedSegment() {
let widthLine:CGFloat = TTSize.W / CGFloat(self.numberOfSegments)
self.addSubview(self.underlineView)
self.underlineView.isUserInteractionEnabled = false
self.underlineView.layer.zPosition = 200
self.underlineView.frame = CGRect(x: 0, y: TTSize.H_SEG - self.lineBottomHeight, width: widthLine, height: self.lineBottomHeight)
self.underlineView.backgroundColor = self.lineBottomColor
}
}
// MARK: For public base funcs
extension TTBaseUISegmentedControl {
public func changeUnderlinePosition() {
DispatchQueue.main.async {
let widthLine:CGFloat = UIScreen.main.bounds.width / CGFloat(self.numberOfSegments)
self.underlineView.frame.size.width = widthLine
let underlineFinalXPosition = (self.bounds.width / CGFloat(self.numberOfSegments)) * CGFloat(self.selectedSegmentIndex)
UIView.animate(withDuration: 0.4, animations: { [weak self] in guard let strongSelf = self else { return }
strongSelf.underlineView.frame.origin.x = underlineFinalXPosition
})
}
}
public func setSelectedIndex(with index:Int) {
self.selectedSegmentIndex = index
if self.type == .LINE_BOTTOM { self.changeUnderlinePosition() }
}
}
| 39.379085 | 171 | 0.669212 |
8762200d6c2a55b00d9f2fd5cc99b832c04c2a68 | 1,922 | //
// InformationView.swift
// CovidSimpleApp
//
// Created by Furkan on 16.05.2020.
// Copyright © 2020 Furkan İbili. All rights reserved.
//
import UIKit
class InformationView: UIViewController {
//Outlets
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
giveDelegate()
// Do any additional setup after loading the view.
}
//Save which row selected on tableView.
var selectedRow = 0
}
extension InformationView: UITableViewDelegate,UITableViewDataSource {
//Create row with static Information Header Count
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Informations.shared.dataHeader.count
}
//Show headers on cell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "information") as! InformationCell
cell.contentView.layer.cornerRadius = 20
cell.headerLabel.text = Informations.shared.dataHeader[indexPath.row]
cell.headerLabel.numberOfLines = 2
return cell
}
//Go to detail page with selected row id.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedRow = indexPath.row
self.performSegue(withIdentifier: "showInformation", sender: self)
}
func giveDelegate() {
self.tableView.register(UINib.init(nibName: "InformationCell", bundle: nil), forCellReuseIdentifier: "information")
self.tableView.delegate = self
self.tableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! InformationDetailsView
vc.selectedRow = self.selectedRow
}
}
| 29.121212 | 123 | 0.67898 |
61eeeb0e5f76d489e6efd25b44c2b2d7615780db | 2,170 | //
// AppDelegate.swift
// ARPlaneDetection
//
// Created by wuufone on 2019/7/22.
// Copyright © 2019 江武峯. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.170213 | 285 | 0.7553 |
1a6f6557742736587ea34aab0623774942ca03b1 | 392 | import UIKit
import Coordinator
class ___VARIABLE_productName:identifier___Coordinator: WindowCoordinator, ControllerContainer, ___VARIABLE_productName:identifier___CoordinatorRoute {
internal var controller: Controller!
// MARK: - Life cycle
override func start() {
controller.router = self
controller.configure()
}
// MARK: - Actions
}
| 21.777778 | 151 | 0.711735 |
bbe9570ee9738c125db7471cb051932f06a6d849 | 1,958 | import Foundation
/// A type that will add (or modify if existing) a query item to `URLComponents`
public struct QueryItem: URLComponentsModifier {
let name: String
let string: String
/// Initialises a new instance of `QueryItem`
/// - Parameters:
/// - name: the name (or key) of the represented query item
/// - value: the represented value of the query item
public init?(name: String, value: QueryStringConvertible?) {
guard let valueString = value?.queryItemRepresentation else {
return nil
}
self.name = name
self.string = valueString
}
/// Initialises a new instance of `QueryItem`
/// - Parameters:
/// - name: the name (or key) of the represented query item
/// - values: an array of item represented by the query item
public init?(name: String, values: [QueryStringConvertible?]?) {
guard let values = values, let valueString = values.compactMap({ $0?.queryItemRepresentation }).queryItemRepresentation else {
return nil
}
self.name = name
self.string = valueString
}
/// Initialises a new instance of `QueryItem`
/// - Parameters:
/// - name: the name (or key) of the represented query item
/// - value: the value represented by the query item
/// - digits: the amount of digits the `value` parameter should be rounded to when converting to a `String`
public init?(name: String, value: Double?, digits: Int) {
guard let value = value else {
return nil
}
self.name = name
self.string = String(format: "%.\(digits)f", value)
}
public func modifyURLComponents(_ components: inout URLComponents) {
let item = URLQueryItem(name: name, value: string)
if var queryItems = components.queryItems, !queryItems.isEmpty {
if let existingItemIndex = queryItems.firstIndex(where: { $0.name == self.name }) {
queryItems[existingItemIndex] = item
} else {
queryItems.append(item)
}
components.queryItems = queryItems
} else {
components.queryItems = [item]
}
}
}
| 32.098361 | 128 | 0.699183 |
90434b8ac13f6301baad7bcd94c6262449181c17 | 7,429 | /*
A speed-improved simplex noise algorithm for 2D. Based on public domain
example code by Stefan Gustavson.
http://staffwww.itn.liu.se/~stegu/simplexnoise/SimplexNoise.java
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org>
*/
import Foundation
import SpriteKit
class SimplexNoise {
private let grad3 : [Grad] = [
Grad(x: 1, y: 1, z: 0), Grad(x: -1, y: 1, z: 0), Grad(x: 1, y: -1, z: 0), Grad(x: -1, y: -1, z: 0),
Grad(x: 1, y: 0, z: 1), Grad(x: -1, y: 0, z: 1), Grad(x: 1, y: 0, z: -1), Grad(x: -1, y: 0, z: -1),
Grad(x: 0, y: 1, z: 1), Grad(x: 0, y: -1, z: 1), Grad(x: 0, y: 1, z: -1), Grad(x: 0, y: -1, z: -1)
]
private let p : [Int] = [151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]
private var perm = Array(repeating: 0, count: 512)
private var permMod12 = Array(repeating: 0, count: 512)
init() {
for i in 0..<512 {
perm[i] = p[i & 255]
permMod12[i] = perm[i] % 12
}
}
private let F2 = 0.5 * (sqrt(3.0) - 1.0)
private let G2 = (3.0 - sqrt(3.0)) / 6.0
private func dot(g: Grad, x: Double, y: Double) -> Double {
return g.x * x + g.y * y
}
private func fastfloor(x: Double) -> Int {
let xi = Int(x)
return x < Double(xi) ? xi - 1 : xi
}
/* func generatedNoise(chunk: CGPoint, octaves: Int, roughness: Double, scale: Double) -> [[Double]] {
let width = Int(MapConstants.chunkSize.width)
let height = Int(MapConstants.chunkSize.height)
var noise = Array(count: width, repeatedValue: Array(count: height, repeatedValue: 0.0))
var layerFrequency = scale
var layerWeight = 1.0
var weightSum = 0.0
for _ in 0..<octaves {
for i in 0..<noise.count {
for j in 0..<noise[i].count {
let chunkPos = IsometricTilemap.translateFromChunkPosition(CGPoint(x: j, y: i), chunk: chunk)
noise[i][j] = noise2d(Double(chunkPos.x) * layerFrequency, y: Double(chunkPos.y) * layerFrequency) * layerWeight
}
}
layerFrequency *= 2
weightSum += layerWeight
layerWeight *= roughness
}
for i in 0..<noise.count {
for j in 0..<noise[i].count {
noise[i][j] /= weightSum
noise[i][j] = (noise[i][j] + 1) / 2
}
}
return noise
}*/
func noise2d(x: Double, y: Double) -> Double {
var n0, n1, n2: Double // noise from the three corners
// skew the input space to determine the current simplex cell
let s = (x + y) * F2 // hairy factor for 2D
let i = fastfloor(x: (x + s))
let j = fastfloor(x: (y + s))
let t = Double(i + j) * G2
// unskew the cell origins back to (x,y) space and
// calculate the x/y distances from the cell origin
let xorigin = Double(i) - t
let yorigin = Double(j) - t
let x0 = x - xorigin
let y0 = y - yorigin
// for 2D the simplex shape is an equilateral triangle
// determine which simplex we are in
var i1, j1 : Int // offsets for second (middle) corner of simplex in (i,j) coords
if (x0 > y0) {
// lower triangle, XY order: (0,0)->(1,0)->(1,1)
i1 = 1
j1 = 0
} else {
// upper triangle, YX order: (0,0)->(0,1)->(1,1)
i1 = 0
j1 = 1
}
// a step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
let x1 = x0 - Double(i1) + G2 // offsets for middle corner in (x,y) unskewed coords
let y1 = y0 - Double(j1) + G2
let x2 = x0 - 1.0 + 2.0 * G2 // offsets for the last corner (x,y) unskewed coords
let y2 = y0 - 1.0 + 2.0 * G2
// work out the hashed gradient indices of the three simplex corners
let ii = i & 255
let jj = j & 255
let gi0 = permMod12[ii + perm[jj]]
let gi1 = permMod12[ii + i1 + perm[jj + j1]]
let gi2 = permMod12[ii + 1 + perm[jj + 1]]
// calculate the contribution from the three corners
var t0 = 0.5 - x0 * x0 - y0 * y0
if (t0 < 0) {
n0 = 0.0
} else {
t0 *= t0
n0 = t0 * t0 * dot(g: grad3[gi0], x: x0, y: y0) // (x,y) of grad3 used for 2D gradient
}
var t1 = 0.5 - x1 * x1 - y1 * y1
if (t1 < 0) {
n1 = 0.0
} else {
t1 *= t1
n1 = t1 * t1 * dot(g: grad3[gi1], x: x1, y: y1)
}
var t2 = 0.5 - x2 * x2 - y2 * y2
if (t2 < 0) {
n2 = 0.0
} else {
t2 *= t2
n2 = t2 * t2 * dot(g: grad3[gi2], x: x2, y: y2)
}
// add contributions from each corner to get the final noise
// the result is scaled to return values in the interval [-1,1]
return 70 * (n0 + n1 + n2)
}
}
private struct Grad {
let x, y, z: Double
}
| 38.895288 | 132 | 0.554853 |
62a873db54f462ab075499059d379436e472c9a6 | 6,648 | //
// BTCPeer_Tests.swift
// BitcoinSwift
//
// Created by Chance on 2017/5/20.
//
//
import XCTest
@testable import BitcoinSwift
class BTCPeer_Tests: XCTestCase {
let QUIT: String = "QUIT"
let port: Int32 = 8333
// let host: String = "::ffff:7f00:0001"
let host: String = "73.243.216.34"
let path: String = "/tmp/server.test.socket"
override func setUp() {
super.setUp()
print("//////////////////// 测试开始 ////////////////////\n")
}
override func tearDown() {
print("//////////////////// 测试结束 ////////////////////\n")
super.tearDown()
}
/// 测试地址转换host
func testAddressToHost() {
do {
//测试 ipv4
let u128: [UInt32] = [UInt32(bigEndian: 0x00),
UInt32(bigEndian: 0x00),
UInt32(bigEndian: 0x0000ffff),
UInt32(bigEndian: 0x49f3d822)]
let address = UInt128(u128)
let peer = BTCPeer(address: address, port: port)
print("host = \(peer.host)")
XCTAssert("73.243.216.34" == peer.host, "error host = \(peer.host)")
}
do {
let u128: [UInt32] = [UInt32(bigEndian: 0x20010db8),
UInt32(bigEndian: 0x85a308d3),
UInt32(bigEndian: 0x13198a2e),
UInt32(bigEndian: 0x03707344)]
let address = UInt128(u128)
let peer = BTCPeer(address: address, port: port)
print("host = \(peer.host)")
XCTAssert("2001:db8:85a3:8d3:1319:8a2e:370:7344" == peer.host, "error host = \(peer.host)")
}
}
// func testPeerConnect() {
// let peer = BTCPeer(host: self.host, port: port)
// peer.host = self.host
// //peer.connect()
// }
//运行一个接收监听的服务端
func launchServerHelper(family: Socket.ProtocolFamily = .inet) {
let queue: DispatchQueue? = DispatchQueue.global(qos: .userInteractive)
guard let pQueue = queue else {
print("Unable to access global interactive QOS queue")
XCTFail()
return
}
pQueue.async { [unowned self] in
do {
try self.serverHelper(family: family)
} catch let error {
guard let socketError = error as? Socket.Error else {
print("Unexpected error...")
XCTFail()
return
}
print("launchServerHelper Error reported:\n \(socketError.description)")
XCTFail()
}
}
}
func serverHelper(family: Socket.ProtocolFamily = .inet) throws {
var keepRunning: Bool = true
var listenSocket: Socket? = nil
do {
try listenSocket = Socket.create(family: family)
guard let listener = listenSocket else {
print("Unable to unwrap socket...")
XCTFail()
return
}
var socket: Socket
// Are we setting uo a TCP or UNIX based server?
if family == .inet || family == .inet6 {
// Setting up TCP...
try listener.listen(on: Int(port), maxBacklogSize: 10)
print("Listening on port: \(port)")
socket = try listener.acceptClientConnection()
print("Accepted connection from: \(socket.remoteHostname) on port \(socket.remotePort), Secure? \(socket.signature!.isSecure)")
} else {
// Setting up UNIX...
try listener.listen(on: path, maxBacklogSize: 10)
print("Listening on path: \(path)")
socket = try listener.acceptClientConnection()
print("Accepted connection from: \(socket.remotePath!), Secure? \(socket.signature!.isSecure)")
}
try socket.write(from: "Hello, type 'QUIT' to end session\n")
var bytesRead = 0
repeat {
var readData = Data()
bytesRead = try socket.read(into: &readData)
if bytesRead > 0 {
guard let response = NSString(data: readData, encoding: String.Encoding.utf8.rawValue) else {
print("Error decoding response...")
readData.count = 0
XCTFail()
break
}
if response.hasPrefix(QUIT) {
keepRunning = false
}
// TCP or UNIX?
if family == .inet || family == .inet6 {
print("Server received from connection at \(socket.remoteHostname):\(socket.remotePort): \(response) ")
} else {
print("Server received from connection at \(socket.remotePath!): \(response) ")
}
let reply = "Server response: \n\(response)\n"
try socket.write(from: reply)
}
if bytesRead == 0 {
break
}
} while keepRunning
socket.close()
XCTAssertFalse(socket.isActive)
} catch let error {
guard let socketError = error as? Socket.Error else {
print("Unexpected error...")
XCTFail()
return
}
// This error is expected when we're shutting it down...
if socketError.errorCode == Int32(Socket.SOCKET_ERR_WRITE_FAILED) {
return
}
print("serverHelper Error reported: \(socketError.description)")
XCTFail()
}
}
}
| 32.429268 | 143 | 0.427497 |
1c07daf058129243077dc4427ba36e118a941698 | 1,795 | //
// UIColor+Extension.swift
// Tutee
//
// Created by Hosein Abbaspour on 12/13/19.
// Copyright © 2019 Sishemi. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
/**
Initializes and returns a color object using the specified opacity and RGB component values.
- Parameter R: Abbreviation of red, this parameter accebt value from 0 to 255.
- Parameter G: Abbreviation of green, this parameter accebt value from 0 to 255.
- Parameter B: Abbreviation of blue, this parameter accebt value from 0 to 255.
- Parameter alpha: The opacity value of the color object, specified as a value from 0.0 to 1.0.
*/
convenience public init (R: CGFloat, G: CGFloat, B: CGFloat, alpha: CGFloat = 1) {
self.init(red: R/255, green: G/255, blue: B/255, alpha: alpha)
}
convenience public init? (_ hex:String) {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return nil
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
let red = CGFloat((rgbValue & 0xFF0000) >> 16)
let green = CGFloat((rgbValue & 0x00FF00) >> 8)
let blue = CGFloat(rgbValue & 0x0000FF)
self.init(R: red, G: green, B: blue)
}
}
extension UIColor {
func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { rendererContext in
self.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
}
}
| 30.948276 | 100 | 0.612256 |
1c6e1f6686483f2cdd1fb568f31a3bdafab1d61d | 422 | //
// flickrPhotos.swift
// VirtualTourist
//
// Created by Hajar F on 12/4/19.
// Copyright © 2019 Hajar F. All rights reserved.
//
struct Constants {
static let key = "2ac76dbc3aa3f406f2ff5eeabaf37b29"
static let flickrPhotos = "https://api.flickr.com/services/rest?method=flickr.photos.search&format=json&api_key=\(Constants.key)&bbox={bbox}&per_page=21&page={page}&extras=url_m&nojsoncallback=1"
}
| 26.375 | 199 | 0.718009 |
751357ce853828e02c26d6dfbb5aecdffa7b5b23 | 13,807 | //
// PrimitiveSequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/5/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// Observable sequences containing 0 or 1 element.
public struct PrimitiveSequence<Trait, Element> {
let source: Observable<Element>
init(raw: Observable<Element>) {
self.source = raw
}
}
/// Observable sequences containing 0 or 1 element
public protocol PrimitiveSequenceType {
/// Additional constraints
associatedtype TraitType
/// Sequence element type
associatedtype ElementType
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
var primitiveSequence: PrimitiveSequence<TraitType, ElementType> { get }
}
extension PrimitiveSequence: PrimitiveSequenceType {
/// Additional constraints
public typealias TraitType = Trait
/// Sequence element type
public typealias ElementType = Element
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
public var primitiveSequence: PrimitiveSequence<TraitType, ElementType> {
return self
}
}
extension PrimitiveSequence: ObservableConvertibleType {
/// Type of elements in sequence.
public typealias E = Element
/// Converts `self` to `Observable` sequence.
///
/// - returns: Observable sequence that represents `self`.
public func asObservable() -> Observable<E> {
return source
}
}
extension PrimitiveSequence {
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.deferred {
try observableFactory().asObservable()
})
}
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: primitiveSequence.source.delay(dueTime, scheduler: scheduler))
}
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.delaySubscription(dueTime, scheduler: scheduler))
}
/**
Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription
actions have side-effects that require to be run on a scheduler, use `subscribeOn`.
- seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html)
- parameter scheduler: Scheduler to notify observers on.
- returns: The source sequence whose observations happen on the specified scheduler.
*/
public func observeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.observeOn(scheduler))
}
/**
Wraps the source sequence in order to run its subscription and unsubscription logic on the specified
scheduler.
This operation is not commonly used.
This only performs the side-effects of subscription and unsubscription on the specified scheduler.
In order to invoke observer callbacks on a `scheduler`, use `observeOn`.
- seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html)
- parameter scheduler: Scheduler to perform subscription and unsubscription actions on.
- returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
public func subscribeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.subscribeOn(scheduler))
}
/**
Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter handler: Error handler function, producing another observable sequence.
- returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
*/
public func catchError(_ handler: @escaping (Swift.Error) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.catchError { try handler($0).asObservable() })
}
/**
If the initial subscription to the observable sequence emits an error event, try repeating it up to the specified number of attempts (inclusive of the initial attempt) or until is succeeds. For example, if you want to retry a sequence once upon failure, you should use retry(2) (once for the initial attempt, and once for the retry).
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter maxAttemptCount: Maximum number of times to attempt the sequence subscription.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
public func retry(_ maxAttemptCount: Int)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retry(maxAttemptCount))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Prints received events for all observers on standard output.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter identifier: Identifier that is printed together with event description to standard output.
- parameter trimOutput: Should output be trimmed to max 40 characters.
- returns: An observable sequence whose events are printed to standard output.
*/
public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function))
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter primitiveSequenceFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
public static func using<Resource: Disposable>(_ resourceFactory: @escaping () throws -> Resource, primitiveSequenceFactory: @escaping (Resource) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.using(resourceFactory, observableFactory: { (resource: Resource) throws -> Observable<E> in
return try primitiveSequenceFactory(resource).asObservable()
}))
}
/**
Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: An observable sequence with a `RxError.timeout` in case of a timeout.
*/
public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence<Trait, Element>(raw: primitiveSequence.source.timeout(dueTime, scheduler: scheduler))
}
/**
Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter other: Sequence to return in case of a timeout.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: The source sequence switching to the other sequence in case of a timeout.
*/
public func timeout(_ dueTime: RxTimeInterval,
other: PrimitiveSequence<Trait, Element>,
scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence<Trait, Element>(raw: primitiveSequence.source.timeout(dueTime, other: other.source, scheduler: scheduler))
}
}
extension PrimitiveSequenceType where ElementType: RxAbstractInteger {
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
public static func timer(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable<ElementType>.timer(dueTime, scheduler: scheduler))
}
}
| 51.71161 | 338 | 0.734555 |
9cd738174874478c28760993ee12d1f3645bf827 | 374 | //
// FieldItemDelegate.swift
// AnKitPlayground
//
// Created by Anvipo on 07.11.2021.
//
protocol FieldItemDelegate: AnyObject {
func fieldItemDidBeginEditing(_ item: FieldItem)
func fieldItemDidEndEditing(_ item: FieldItem)
}
extension FieldItemDelegate {
func fieldItemDidBeginEditing(_ item: FieldItem) {}
func fieldItemDidEndEditing(_ item: FieldItem) {}
}
| 19.684211 | 52 | 0.764706 |
f7162fdb490216e83af7ad3250bf99dc91496a90 | 917 | import Foundation
import Cocoa
class DropTextField : NSTextField {
weak var dropDelegate: DropTextFieldDelegate?
override func awakeFromNib() {
super.awakeFromNib()
registerForDraggedTypes([.fileURL])
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
return NSDragOperation.generic
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
let files = sender.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as! [String]
guard let file = files.first else {
return false
}
return dropDelegate?.dropTextField(self, onFileDropped: file) ?? false
}
}
protocol DropTextFieldDelegate: class {
func dropTextField(_ field: DropTextField, onFileDropped file: String) -> Bool
}
| 28.65625 | 144 | 0.676118 |
fe67683f1bff11113115acbd34c6e85b972cc44b | 1,343 | //
// AppDelegate.swift
// Prework
//
// Created by user190938 on 2/2/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.297297 | 179 | 0.745346 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.