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
|
|---|---|---|---|---|---|
ed385a3647104821156495c333963da760145ea5
| 1,552 |
//
// BYColorSwatch.swift
// BYColorPickerSwiftExample
//
// Created by Berk Yuksel on 08/01/2017.
// Copyright © 2017 Berk Yuksel. All rights reserved.
//
import UIKit
class BYColorSwatch: UIView {
var color : UIColor? = nil {
didSet {
self.setNeedsDisplay()
}
}
// Mark: - Drawing
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
let context : CGContext = UIGraphicsGetCurrentContext()!
context.saveGState()
let strokeSize : CGFloat = 1.0
context.addEllipse(in: self.bounds.insetBy(dx: strokeSize, dy: strokeSize))
if (color != nil) {
context.setFillColor(color!.cgColor)
context.fillPath()
}
context.setLineWidth(strokeSize)
context.setStrokeColor(UIColor.lightGray.cgColor)
context.addEllipse(in: self.bounds.insetBy(dx: strokeSize, dy: strokeSize))
let shadowColor : UIColor = UIColor.init(white: 0.1, alpha: 0.4)
let innerShadowPath : CGPath = CGPath.init(ellipseIn: self.bounds.insetBy(dx: strokeSize, dy: strokeSize), transform: nil)
BYGfxUtility.drawInnerShadow(inContext: context, withPath: innerShadowPath, color: shadowColor.cgColor, offset: CGSize.init(width: 0, height: 3), blurRadius: 4)
context.restoreGState()
}
}
| 29.846154 | 168 | 0.623711 |
d7bd9dc813d3ec21e53b2c7a616068413ba776d4
| 1,293 |
@testable import LibMakeColors
import XCTest
final class ColorHSVTest: XCTestCase {
func testHSV0Degrees() {
let color = Color(hue: 0, saturation: 0xFF, value: 0xFF)
XCTAssertEqual(color, Color(red: 0xFF, green: 0, blue: 0))
}
func testHSV60Degrees() {
let color = Color(hue: 60, saturation: 0xFF, value: 0xFF)
XCTAssertEqual(color, Color(red: 0xFF, green: 0xFF, blue: 0))
}
func testHSV120Degrees() {
let color = Color(hue: 120, saturation: 0xFF, value: 0xFF)
XCTAssertEqual(color, Color(red: 0, green: 0xFF, blue: 0))
}
func testHSV180Degrees() {
let color = Color(hue: 180, saturation: 0xFF, value: 0xFF)
XCTAssertEqual(color, Color(red: 0, green: 0xFF, blue: 0xFF))
}
func testHSV240Degrees() {
let color = Color(hue: 240, saturation: 0xFF, value: 0xFF)
XCTAssertEqual(color, Color(red: 0, green: 0, blue: 0xFF))
}
func testHSV300Degrees() {
let color = Color(hue: 300, saturation: 0xFF, value: 0xFF)
XCTAssertEqual(color, Color(red: 0xFF, green: 0, blue: 0xFF))
}
func testHSV360Degrees() {
let color = Color(hue: 360, saturation: 0xFF, value: 0xFF)
XCTAssertEqual(color, Color(red: 0xFF, green: 0, blue: 0))
}
}
| 32.325 | 69 | 0.625677 |
22d00ffda7fe6c61032e67095c417e08ebbef1a1
| 1,153 |
//
// TheiaUITests.swift
// TheiaUITests
//
// Created by Vishnu Dasu on 10/11/18.
// Copyright © 2018 Vishnu Dasu. All rights reserved.
//
import XCTest
class TheiaUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 32.942857 | 182 | 0.687771 |
21a1ace154cf24b531d5b36b482bcac469ff446b
| 1,472 |
//
// AppDelegate.swift
//
// Copyright (c) 2015-2017 Jason Nam (http://www.jasonnam.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
}
| 40.888889 | 151 | 0.757473 |
de5641e5fcc7361b548b3433395546d0ad9e3a2d
| 37,535 |
//
// RecordActivityTableViewController.swift
// Introspective
//
// Created by Bryan Nova on 11/20/18.
// Copyright © 2018 Bryan Nova. All rights reserved.
//
import CoreData
import Instructions
import os
import Presentr
import UIKit
import AttributeRestrictions
import Common
import DependencyInjection
import Persistence
import Queries
import Samples
import Settings
import UIExtensions
public final class RecordActivityTableViewController: UITableViewController {
// MARK: - Static Variables
private typealias Me = RecordActivityTableViewController
// MARK: Notification Names
private static let activityDefinitionCreated = Notification.Name("activityDefinitionCreated")
private static let activityEditedOrCreated = Notification.Name("activityEdited")
private static let activityDefinitionEdited = Notification.Name("activityDefinitionEdited")
// MARK: Presenters
private static let presenter = injected(UiUtil.self).customPresenter(
width: .full,
height: .custom(size: 300),
center: .topCenter
)
// MARK: Logging / Performance
private static let signpost =
Signpost(log: OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "Activity Display"))
private static let log = Log()
// MARK: - Instance Variables
final fileprivate let searchController = UISearchController(searchResultsController: nil)
private final var finishedLoading = false {
didSet {
DispatchQueue.main.async {
self.searchController.searchBar.isUserInteractionEnabled = self.finishedLoading
self.tableView.reloadData()
}
}
}
private final var definitionEditIndex: IndexPath?
private final var currentSort: NSSortDescriptor?
private final let defaultSort = NSSortDescriptor(key: "recordScreenIndex", ascending: true)
private final var activeActivitiesFetchedResultsController: NSFetchedResultsController<ActivityDefinition>!
private final var inactiveActivitiesFetchedResultsController: NSFetchedResultsController<ActivityDefinition>!
private final let coachMarksController = CoachMarksController()
private final var coachMarksDataSourceAndDelegate: CoachMarksDataSourceAndDelegate!
// MARK: - UIViewController Overrides
public final override func viewDidLoad() {
super.viewDidLoad()
let addButton = barButton(
title: "+",
quickPress: #selector(quickPressAddButton),
longPress: #selector(longPressAddButton)
)
let stopAllButton = UIBarButtonItem(
title: "■",
style: .plain,
target: self,
action: #selector(stopAllButtonPressed)
)
let sortButton = barButton(title: "⇅", action: #selector(sortButtonPressed))
navigationItem.rightBarButtonItems = [addButton, stopAllButton, sortButton]
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search Activities"
searchController.hidesNavigationBarDuringPresentation = false
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true
loadActivitiyDefinitions()
observe(selector: #selector(activityDefinitionCreated), name: Me.activityDefinitionCreated, object: nil)
observe(selector: #selector(activityEditedOrCreated), name: Me.activityEditedOrCreated, object: nil)
observe(selector: #selector(activityDefinitionEdited), name: Me.activityDefinitionEdited, object: nil)
observe(selector: #selector(sortByRecentCount), name: .timePeriodChosen)
observe(selector: #selector(persistenceLayerDidRefresh), name: .persistenceLayerDidRefresh)
observe(selector: #selector(persistenceLayerWillRefresh), name: .persistenceLayerWillRefresh)
reorderOnLongPress(allowReorder: { $0.section == 1 && ($1 == nil || $1?.section == 1) })
coachMarksDataSourceAndDelegate = RecordActivityTableViewControllerCoachMarksDataSourceAndDelegate(self)
coachMarksController.dataSource = coachMarksDataSourceAndDelegate
coachMarksController.delegate = coachMarksDataSourceAndDelegate
coachMarksController.skipView = DefaultCoachMarksDataSourceAndDelegate.defaultSkipInstructionsView()
}
public final override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !injected(UserDefaultsUtil.self).bool(forKey: .recordActivitiesInstructionsShown) {
coachMarksController.start(in: .window(over: self))
}
}
public final override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
coachMarksController.stop(immediately: true)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - TableView Data Source
public final override func numberOfSections(in _: UITableView) -> Int {
if !finishedLoading {
return 1
}
return 2
}
public final override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
if !finishedLoading {
return 1
}
if section == 0 {
if let fetchedObjects = activeActivitiesFetchedResultsController.fetchedObjects {
return fetchedObjects.count
}
} else if section == 1 {
if let fetchedObjects = inactiveActivitiesFetchedResultsController.fetchedObjects {
return fetchedObjects.count
}
}
Me.log.error("Unable to determine number of expected rows because fetched objects was nil")
return 0
}
// MARK: - TableView Delegate
public final override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
if !finishedLoading {
return tableView.dequeueReusableCell(withIdentifier: "waiting", for: indexPath)
}
let cell = tableView.dequeueReusableCell(
withIdentifier: "activity",
for: indexPath
) as! RecordActivityDefinitionTableViewCell
cell.activityDefinition = definition(at: indexPath)
return cell
}
public final override func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
if !finishedLoading {
return 44
}
return 57
}
public final override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
guard finishedLoading else { return }
let activityDefinition = definition(at: indexPath)
guard let cell = visibleCellFor(indexPath) else {
return
}
if cell.running {
if let activity = getMostRecentlyStartedIncompleteActivity(for: activityDefinition) {
stopActivity(activity, associatedCell: cell)
} else {
Me.log.error("Could not find activity to stop.")
showError(title: "Failed to stop activity")
}
} else {
startActivity(for: activityDefinition, cell: cell)
}
loadActivitiyDefinitions()
}
// MARK: - TableView Reordering
public final override func tableView(_: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
indexPath.section == 1
}
public final override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
let definitionsFromIndex = Int(definition(at: fromIndexPath).recordScreenIndex)
let definitionsToIndex = Int(definition(at: to).recordScreenIndex)
do {
let allFetchedResultsController = try getAllFetchedResultsController()
let transaction = injected(Database.self).transaction()
if definitionsFromIndex < definitionsToIndex {
for i in definitionsFromIndex + 1 ... definitionsToIndex {
if let definition = allFetchedResultsController.fetchedObjects?[i] {
try transaction.pull(savedObject: definition).recordScreenIndex -= 1
} else {
Me.log.error("Failed to get activity definition for index %d", i)
}
}
} else {
for i in definitionsToIndex ..< definitionsFromIndex {
if let definition = allFetchedResultsController.fetchedObjects?[i] {
try transaction.pull(savedObject: definition).recordScreenIndex += 1
} else {
Me.log.error("Failed to get activity definition for index %d", i)
}
}
}
if let definition = allFetchedResultsController.fetchedObjects?[definitionsFromIndex] {
try transaction.pull(savedObject: definition).recordScreenIndex = Int16(definitionsToIndex)
} else {
Me.log.error("Failed to get activity definition for index %d", definitionsFromIndex)
}
try retryOnFail({ try transaction.commit() }, maxRetries: 2)
} catch {
Me.log.error("Failed to reorder activities: %@", errorInfo(error))
}
resetInactiveActivitiesFetchedResultsController()
tableView.reloadSections(IndexSet(arrayLiteral: 1), with: .automatic)
}
// MARK: - Swipe Actions
public final override func tableView(
_: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath
) -> UISwipeActionsConfiguration? {
let activityDefinition = definition(at: indexPath)
var actions = [
getEditActivityDefinitionActionFor(activityDefinition, at: indexPath),
getDeleteActivityDefinitionActionFor(activityDefinition, at: indexPath),
]
if activityDefinition.activities.count > 0 {
actions.append(getViewHistoryActionFor(activityDefinition))
}
return UISwipeActionsConfiguration(actions: actions)
}
public final override func tableView(
_: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
) -> UISwipeActionsConfiguration? {
let activityDefinition = definition(at: indexPath)
var actions: [UIContextualAction] = [getAddNewActionFor(activityDefinition)]
if let activity = getMostRecentActivity(activityDefinition) {
actions.append(getEditLastActionFor(activity))
actions.append(getDeleteActivityActionFor(activity))
}
return UISwipeActionsConfiguration(actions: actions)
}
private final func getViewHistoryActionFor(_ definition: ActivityDefinition) -> UIContextualAction {
let action = injected(UiUtil.self).contextualAction(
style: .normal,
title: "History"
) { _, _, completion in
let query = injected(QueryFactory.self).activityQuery()
query.expression = EqualToStringAttributeRestriction(
restrictedAttribute: Activity.nameAttribute,
value: definition.name
)
let controller = self.viewController(named: "results", fromStoryboard: "Results") as! ResultsViewController
controller.query = query
query.runQuery { result, error in
if error != nil {
DispatchQueue.main.async {
controller.showError(title: "Failed to run query", error: error)
}
completion(false)
return
}
controller.samples = result?.samples
}
controller.query = query
controller.backButtonTitle = "Activities"
completion(true)
self.pushToNavigationController(controller)
}
action.accessibilityLabel = "view all history for \(definition.name)"
action.backgroundColor = .blue
return action
}
private final func getDeleteActivityActionFor(_ activity: Activity) -> UIContextualAction {
let deleteAction = injected(UiUtil.self).contextualAction(
style: .destructive,
title: "🗑️ Last"
) { _, _, completion in
let timeText = self.getTimeTextFor(activity)
let alert = UIAlertController(
title: "Are you sure you want to delete '\(activity.definition.name)'?",
message: "This will only delete the most recent instance \(timeText).",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Yes", style: .destructive) { _ in
do {
let transaction = injected(Database.self).transaction()
try transaction.delete(activity)
try retryOnFail({ try transaction.commit() }, maxRetries: 2)
self.loadActivitiyDefinitions()
} catch {
Me.log.error("Failed to delete activity: %@", errorInfo(error))
self.showError(title: "Failed to delete activity instance", error: error)
}
})
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
self.present(alert, animated: false, completion: { completion(true) })
}
deleteAction.accessibilityLabel = "delete most recent \(activity.definition.name)"
return deleteAction
}
private final func getEditLastActionFor(_ activity: Activity) -> UIContextualAction {
let editLast = injected(UiUtil.self).contextualAction(
style: .normal,
title: "✎ Last"
) { _, _, completion in
completion(true)
self.showEditScreenForActivity(activity)
}
editLast.backgroundColor = .orange
return editLast
}
private final func getAddNewActionFor(_ activityDefinition: ActivityDefinition) -> UIContextualAction {
let addNew = injected(UiUtil.self).contextualAction(
style: .normal,
title: "+"
) { _, _, completion in
let controller = self.viewController(named: "editActivity") as! EditActivityTableViewController
controller.definition = activityDefinition
controller.notificationToSendOnAccept = Me.activityEditedOrCreated
completion(true)
self.navigationController?.pushViewController(controller, animated: false)
}
addNew.backgroundColor = .blue
return addNew
}
private final func getDeleteActivityDefinitionActionFor(
_ activityDefinition: ActivityDefinition,
at _: IndexPath
) -> UIContextualAction {
injected(UiUtil.self).contextualAction(
style: .destructive,
title: "🗑️ All"
) { _, _, completion in
let alert = UIAlertController(
title: "Are you sure you want to delete \(activityDefinition.name)?",
message: "This will delete all history for this activity and cannot be undone.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Yes", style: .destructive) { _ in
let secondAlert = UIAlertController(
title: "Are you sure you want to delete \(activityDefinition.name)?",
message: "This will delete all history for this activity and cannot be undone.",
preferredStyle: .alert
)
secondAlert.addAction(UIAlertAction(title: "Yes", style: .destructive) { _ in
do {
let transaction = injected(Database.self).transaction()
try transaction.delete(activityDefinition)
try retryOnFail({ try transaction.commit() }, maxRetries: 2)
self.loadActivitiyDefinitions()
} catch {
Me.log.error("Failed to delete activity definition: %@", errorInfo(error))
self.showError(title: "Failed to delete activity", error: error)
}
})
secondAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
})
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
self.present(alert, animated: false, completion: { completion(true) })
}
}
private final func getEditActivityDefinitionActionFor(
_ activityDefinition: ActivityDefinition,
at indexPath: IndexPath
) -> UIContextualAction {
let editDefinitionAction = injected(UiUtil.self).contextualAction(
style: .normal,
title: "✎ All"
) { _, _, completion in
self.definitionEditIndex = indexPath
let controller: EditActivityDefinitionTableViewController = self
.viewController(named: "editActivityDefinition")
controller.activityDefinition = activityDefinition
controller.notificationToSendOnAccept = Me.activityDefinitionEdited
completion(true)
self.navigationController?.pushViewController(controller, animated: false)
}
editDefinitionAction.backgroundColor = .orange
editDefinitionAction.accessibilityLabel = "edit \(activityDefinition.name)"
return editDefinitionAction
}
// MARK: - Received Notifications
@objc private final func activityDefinitionCreated(notification: Notification) {
if let activityDefinition: ActivityDefinition? = value(for: .activityDefinition, from: notification) {
do {
let transaction = injected(Database.self).transaction()
if let activityDefinition = activityDefinition {
let allDefinitionsController = try getAllFetchedResultsController()
let newIndex = Int16(allDefinitionsController.fetchedObjects?.count ?? 1) - 1
try transaction.pull(savedObject: activityDefinition).recordScreenIndex = newIndex
try retryOnFail({ try transaction.commit() }, maxRetries: 2)
}
loadActivitiyDefinitions()
} catch {
Me.log.error("Failed to save activity definition: %@", errorInfo(error))
showError(
title: "Failed to save activity",
error: error,
tryAgain: { self.activityDefinitionCreated(notification: notification) }
)
}
}
}
@objc private final func activityEditedOrCreated(notification _: Notification) {
loadActivitiyDefinitions()
}
@objc private final func activityDefinitionEdited(notification _: Notification) {
if let indexPath = definitionEditIndex {
tableView.reloadRows(at: [indexPath], with: .automatic)
} else {
Me.log.error(
"Failed to find activity definition in original set. Resorting to reload of activity definitions."
)
loadActivitiyDefinitions()
}
}
@objc private final func sortByRecentCount(notification: Notification) {
guard let numTimeUnits: Int = value(for: .number, from: notification) else { return }
guard let timeUnit: Calendar.Component = value(for: .calendarComponent, from: notification) else { return }
do {
let transaction = injected(Database.self).transaction()
let allDefinitions = try transaction.query(ActivityDefinition.fetchRequest())
var counts = [String: Int]()
for definition in allDefinitions {
let recentActivities: NSFetchRequest<NSFetchRequestResult> = Activity.fetchRequest()
let minStartDate = injected(CalendarUtil.self).ago(numTimeUnits, timeUnit)
recentActivities.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
NSPredicate(format: "startDate > %@", minStartDate as NSDate),
NSPredicate(format: "definition == %@", definition),
])
counts[definition.name] = try transaction.count(recentActivities)
}
let sortedDefinitions = try allDefinitions.sorted { (definition1, definition2) throws -> Bool in
if counts[definition1.name]! > counts[definition2.name]! {
return true
}
if counts[definition1.name]! < counts[definition2.name]! {
return false
}
guard let mostRecent1 = self.getMostRecentActivity(definition1) else { return false }
guard let mostRecent2 = self.getMostRecentActivity(definition2) else { return true }
return mostRecent1.start.isAfterDate(mostRecent2.start, orEqual: true, granularity: .second)
}
var i: Int16 = 0
for definition in sortedDefinitions {
definition.recordScreenIndex = i
i += 1
}
try retryOnFail({ try transaction.commit() }, maxRetries: 2)
currentSort = nil
loadActivitiyDefinitions()
} catch {
showError(title: "Failed to sort by recent count. Sorry for thee inconvenience.")
}
}
@objc private final func persistenceLayerDidRefresh(notification _: Notification) {
loadActivitiyDefinitions()
}
@objc private final func persistenceLayerWillRefresh(notification _: Notification) {
finishedLoading = false
}
// MARK: - Actions
@IBAction final func quickPressAddButton() {
showActivityDefinitionCreationScreen()
}
@IBAction final func longPressAddButton() {
quickCreateAndStart()
}
@IBAction final func stopAllButtonPressed(_ sender: Any) {
do {
let activitiesToAutoNote = try injected(ActivityDAO.self).stopAllActivities()
loadActivitiyDefinitions()
for activity in activitiesToAutoNote {
showEditScreenForActivity(activity, autoFocusNote: true)
}
} catch {
showError(
title: "Failed to stop activities",
message: "Something went wrong while trying to stop all activities. Sorry for the inconvenience.",
error: error,
tryAgain: { self.stopAllButtonPressed(sender) }
)
}
}
@IBAction final func sortButtonPressed() {
let actionsController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionsController.addAction(getSortAlphabeticallyAction())
actionsController.addAction(getSortZetabeticallyAction())
actionsController.addAction(getManualSortAction())
actionsController.addAction(getSortByRecentCountAction())
actionsController.addAction(injected(UiUtil.self).alertAction(
title: "Cancel",
style: .cancel,
handler: nil
))
present(actionsController, animated: false, completion: nil)
}
private final func getSortAlphabeticallyAction() -> UIAlertAction {
injected(UiUtil.self).alertAction(
title: "Sort Alphabetically",
style: .default,
handler: { _ in
self.currentSort = NSSortDescriptor(key: "name", ascending: true)
self.loadActivitiyDefinitions()
}
)
}
private final func getSortZetabeticallyAction() -> UIAlertAction {
injected(UiUtil.self).alertAction(
title: "Sort Zetabetically",
style: .default,
handler: { _ in
self.currentSort = NSSortDescriptor(key: "name", ascending: false)
self.loadActivitiyDefinitions()
}
)
}
private final func getManualSortAction() -> UIAlertAction {
injected(UiUtil.self).alertAction(
title: "Manual Sort",
style: .default,
handler: { _ in
self.currentSort = nil
self.loadActivitiyDefinitions()
}
)
}
private final func getSortByRecentCountAction() -> UIAlertAction {
injected(UiUtil.self).alertAction(
title: "Permanent Sort by Recent Count",
style: .default,
handler: { _ in self.presentSortByRecentCountOptions() }
)
}
// MARK: - Helper Functions
private final func presentSortByRecentCountOptions() {
let controller = viewController(named: "chooseRecentTimePeriod") as! ChooseRecentTimePeriodViewController
controller.initialTimeUnit = .weekOfYear
controller.initialNumTimeUnits = 2
present(controller, using: Me.presenter)
}
final fileprivate func loadActivitiyDefinitions() {
resetFetchedResultsControllers()
finishedLoading = true
}
private final func getSearchTextPredicate(_ searchText: String) -> NSPredicate {
NSPredicate(
format: "name CONTAINS[cd] %@ OR activityDescription CONTAINS[cd] %@ OR SUBQUERY(tags, $tag, $tag.name CONTAINS[cd] %@) .@count > 0",
searchText,
searchText,
searchText
)
}
final fileprivate func quickCreateAndStart() {
let searchText = getSearchText()
if !searchText.isEmpty {
do {
guard try !activityDefinitionWithNameExists(searchText) else {
showError(title: "Activity named '\(searchText)' already exists.")
return
}
let activityDefinition = try injected(ActivityDAO.self).createDefinition(name: searchText)
let now = Date()
try injected(ActivityDAO.self).createActivity(
definition: activityDefinition,
startDate: now,
startDateSetAt: now
)
searchController.searchBar.text = ""
loadActivitiyDefinitions()
} catch {
Me.log.error("Failed to quick create / start activity: %@", errorInfo(error))
showError(
title: "Failed to create and start",
message: "Something went wrong while trying to save this activity. Sorry for the inconvenience.",
error: error
)
}
}
}
private final func startActivity(
for activityDefinition: ActivityDefinition,
cell: RecordActivityDefinitionTableViewCell
) {
do {
try injected(ActivityDAO.self).startActivity(activityDefinition)
// just calling updateUiElements here doesn't display the progress indicator for some reason
cell.activityDefinition = try injected(Database.self).pull(savedObject: activityDefinition)
} catch {
Me.log.error("Failed to start activity: %@", errorInfo(error))
showError(title: "Failed to start activity", error: error)
}
}
private final func stopActivity(_ activity: Activity, associatedCell: RecordActivityDefinitionTableViewCell) {
let now = Date()
if injected(ActivityDAO.self).autoIgnoreIfAppropriate(activity, end: now) {
associatedCell.updateUiElements()
return
}
do {
let transaction = injected(Database.self).transaction()
activity.end = now
try retryOnFail({ try transaction.commit() }, maxRetries: 2)
associatedCell.updateUiElements()
if activity.definition.autoNote {
showEditScreenForActivity(activity, autoFocusNote: true)
}
} catch {
showError(title: "Failed to stop activity", error: error)
}
}
private final func getTimeTextFor(_ activity: Activity) -> String {
var timeText: String
let startsToday = activity.start.isToday()
if startsToday {
timeText = TimeOfDay(activity.start).toString()
} else {
timeText = injected(CalendarUtil.self)
.string(for: activity.start, dateStyle: .short, timeStyle: .short)
}
if let endDate = activity.end {
let endDateText: String
if startsToday {
endDateText = TimeOfDay(endDate).toString()
} else {
endDateText = injected(CalendarUtil.self)
.string(for: endDate, dateStyle: .short, timeStyle: .short)
}
return "from " + timeText + " to " + endDateText
} else {
return "starting at " + timeText
}
}
private final func showActivityDefinitionCreationScreen() {
let controller: EditActivityDefinitionTableViewController = viewController(named: "editActivityDefinition")
controller.notificationToSendOnAccept = Me.activityDefinitionCreated
controller.initialName = getSearchText()
navigationController?.pushViewController(controller, animated: false)
}
private final func showEditScreenForActivity(_ activity: Activity, autoFocusNote: Bool = false) {
let controller = viewController(named: "editActivity") as! EditActivityTableViewController
controller.activity = activity
controller.notificationToSendOnAccept = Me.activityEditedOrCreated
controller.autoFocusNote = autoFocusNote
pushToNavigationController(controller, animated: false)
}
private final func getMostRecentlyStartedIncompleteActivity(
for activityDefinition: ActivityDefinition
) -> Activity? {
do {
return try injected(ActivityDAO.self)
.getMostRecentlyStartedIncompleteActivity(for: activityDefinition)
} catch {
Me.log.error("Failed to fetch most recent activity: %@", errorInfo(error))
return nil
}
}
private final func getMostRecentActivity(_ activityDefinition: ActivityDefinition) -> Activity? {
do {
return try injected(ActivityDAO.self)
.getMostRecentlyStartedActivity(for: activityDefinition)
} catch {
Me.log.error("Failed to fetch activities while retrieving most recent: %@", errorInfo(error))
return nil
}
}
private final func getSearchText() -> String {
searchController.searchBar.text!
}
private final func activityDefinitionWithNameExists(_ name: String) throws -> Bool {
try injected(ActivityDAO.self).activityDefinitionWithNameExists(name)
}
private final func definition(at indexPath: IndexPath) -> ActivityDefinition {
if indexPath.section == 0 {
return activeActivitiesFetchedResultsController.object(at: indexPath)
}
let offsetIndexPath = IndexPath(row: indexPath.row, section: 0)
return inactiveActivitiesFetchedResultsController.object(at: offsetIndexPath)
}
private final func visibleCellFor(_ indexPath: IndexPath) -> RecordActivityDefinitionTableViewCell? {
let targetDefinition = definition(at: indexPath)
let cells = tableView.visibleCells.map { $0 as! RecordActivityDefinitionTableViewCell }
for cell in cells {
if cell.activityDefinition.equalTo(targetDefinition) {
return cell
}
}
return nil
}
// MARK: FetchedResultsController Helpers
private final func resetFetchedResultsControllers() {
resetActiveActivitiesFetchedResultsController()
resetInactiveActivitiesFetchedResultsController()
}
private final func resetActiveActivitiesFetchedResultsController() {
do {
Me.signpost.begin(name: "resetting active fetched results controller")
activeActivitiesFetchedResultsController = injected(Database.self).fetchedResultsController(
type: ActivityDefinition.self,
sortDescriptors: [currentSort ?? defaultSort],
cacheName: "activeDefinitions"
)
let fetchRequest = activeActivitiesFetchedResultsController.fetchRequest
let isActivePredicate =
NSPredicate(format: "SUBQUERY(activities, $activity, $activity.endDate == nil) .@count > 0")
fetchRequest.predicate = isActivePredicate
let searchText: String = getSearchText()
if !searchText.isEmpty {
fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
isActivePredicate,
getSearchTextPredicate(searchText),
])
}
try activeActivitiesFetchedResultsController.performFetch()
Me.signpost.end(name: "resetting active fetched results controller")
} catch {
Me.log.error("Failed to fetch active activities: %@", errorInfo(error))
showError(
title: "Failed to retrieve activities",
message: "Something went wrong while trying to retrieve the list of your activities. Sorry for the inconvenience.",
error: error,
tryAgain: loadActivitiyDefinitions
)
}
}
private final func resetInactiveActivitiesFetchedResultsController() {
do {
Me.signpost.begin(name: "resetting inactive fetched results controller")
inactiveActivitiesFetchedResultsController = injected(Database.self).fetchedResultsController(
type: ActivityDefinition.self,
sortDescriptors: [currentSort ?? defaultSort],
cacheName: "definitions"
)
let fetchRequest = inactiveActivitiesFetchedResultsController.fetchRequest
let isInactivePredicate =
NSPredicate(format: "SUBQUERY(activities, $activity, $activity.endDate == nil) .@count == 0")
fetchRequest.predicate = isInactivePredicate
let searchText: String = getSearchText()
if !searchText.isEmpty {
fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
isInactivePredicate,
getSearchTextPredicate(searchText),
])
}
try inactiveActivitiesFetchedResultsController.performFetch()
Me.signpost.end(name: "resetting inactive fetched results controller")
} catch {
Me.log.error("Failed to fetch activities: %@", errorInfo(error))
showError(
title: "Failed to retrieve activities",
message: "Something went wrong while trying to retrieve the list of your activities. Sorry for the inconvenience.",
error: error,
tryAgain: loadActivitiyDefinitions
)
}
}
private final func getAllFetchedResultsController() throws -> NSFetchedResultsController<ActivityDefinition> {
Me.signpost.begin(name: "getting all fetched results controller")
let controller = injected(Database.self).fetchedResultsController(
type: ActivityDefinition.self,
sortDescriptors: [currentSort ?? defaultSort],
cacheName: "definitions"
)
try controller.performFetch()
Me.signpost.end(name: "getting all fetched results controller")
return controller
}
}
// MARK: - UISearchResultsUpdating
extension RecordActivityTableViewController: UISearchResultsUpdating {
/// This is used to provide a hook into setting the search text for testing. For some reason
/// passing searchController into resetFetchedResultsControllers() directly from
/// updateSearchResults() to use it instead results in localSearchController.searchBar being
/// nil in that function even though it is not nil when passed in.
public func setSearchText(_ text: String) {
searchController.searchBar.text = text
}
public func updateSearchResults(for _: UISearchController) {
loadActivitiyDefinitions()
}
}
// MARK: - Instructions
/// This class is used to break retain cycles between `RecordActivityTableViewController` and the closures used by `CoachMarkInfo`, preventing them from causing memory leaks
final fileprivate class RecordActivityTableViewControllerCoachMarksDataSourceAndDelegate: CoachMarksDataSourceAndDelegate {
private typealias Me = RecordActivityTableViewControllerCoachMarksDataSourceAndDelegate
private typealias Super = DefaultCoachMarksDataSourceAndDelegate
private typealias ControllerClass = RecordActivityTableViewController
// MARK: Static Variables
private static let exampleActivityName = "Example activity"
private static let log = Log()
// MARK: Instance Variables
private weak final var controller: RecordActivityTableViewController?
private lazy final var coachMarksInfo: [CoachMarkInfo] = [
CoachMarkInfo(
hint: "Tap the + button to create new activities. You can also type the name of a new activity in the search bar and long press the + button to quickly create and start it.",
useArrow: true,
view: { self.controller?.navigationItem.rightBarButtonItems?[0].value(forKey: "view") as? UIView }
),
CoachMarkInfo(
hint: "You can filter on the name of an activity, its description or its tags.",
useArrow: true,
view: { self.controller?.searchController.searchBar }
),
CoachMarkInfo(
hint: "This is the name of the activity.",
useArrow: true,
view: { self.getExampleActivityCell()?.nameLabel },
setup: {
guard let controller = self.controller else { return }
if controller.tableView.visibleCells.isEmpty {
controller.searchController.searchBar.text = Me.exampleActivityName
controller.quickCreateAndStart()
}
}
),
CoachMarkInfo(
hint: "If an activity is currently running, meaning it was started and has not yet been stopped, it will have a progress indicator here.",
useArrow: true,
view: { self.getExampleActivityCell()?.progressIndicator }
),
CoachMarkInfo(
hint: "All running activities will be bubbled to the top of the list",
useArrow: true,
view: { self.controller?.tableView.visibleCells[0] },
setup: {
if let exampleActivityCell = self.getExampleActivityCell() {
if !exampleActivityCell.running {
self.controller?.searchController.searchBar.text = Me.exampleActivityName
self.controller?.quickCreateAndStart()
}
}
}
),
CoachMarkInfo(
hint: "To start or stop an activity, simply tap it.",
useArrow: true,
view: { self.controller?.tableView.visibleCells[0] }
),
CoachMarkInfo(
hint: "You can also stop all activities by tapping this button.",
useArrow: true,
view: { self.controller?.navigationItem.rightBarButtonItems?[1].value(forKey: "view") as? UIView }
),
CoachMarkInfo(
hint: "This is the total amount of time spent on this activity today.",
useArrow: true,
view: {
self.getExampleActivityCell()?.totalDurationTodayLabel
}
),
CoachMarkInfo(
hint: "This is the duration of the most recent time this activity was done.",
useArrow: true,
view: {
self.getExampleActivityCell()?.currentInstanceDurationLabel
}
),
CoachMarkInfo(
hint: "This is the start and end timestamps for the most recent instance of this activity.",
useArrow: true,
view: {
self.getExampleActivityCell()?.mostRecentTimeLabel
}
),
CoachMarkInfo(
hint: "Swipe left for actions related to individual instances of this activity. Swipe right for actions related to all instances of this activity.",
useArrow: true,
view: { self.controller?.tableView.visibleCells[0] }
),
CoachMarkInfo(
hint: "Long press on an activity to reorder it.",
useArrow: true,
view: { self.controller?.tableView.visibleCells[0] }
),
]
private lazy var delegate: DefaultCoachMarksDataSourceAndDelegate = {
DefaultCoachMarksDataSourceAndDelegate(
coachMarksInfo,
instructionsShownKey: .recordActivitiesInstructionsShown,
cleanup: deleteExampleActivity,
skipViewLayoutConstraints: Super.defaultCoachMarkSkipViewConstraints()
)
}()
// MARK: Initializers
public init(_ controller: RecordActivityTableViewController) {
self.controller = controller
}
// MARK: Functions
public final func coachMarksController(
_ coachMarksController: CoachMarksController,
coachMarkViewsAt index: Int,
madeFrom coachMark: CoachMark
) -> (bodyView: CoachMarkBodyView, arrowView: CoachMarkArrowView?) {
delegate.coachMarksController(coachMarksController, coachMarkViewsAt: index, madeFrom: coachMark)
}
public final func coachMarksController(
_ coachMarksController: CoachMarksController,
coachMarkAt index: Int
) -> CoachMark {
delegate.coachMarksController(coachMarksController, coachMarkAt: index)
}
public final func numberOfCoachMarks(for controller: CoachMarksController) -> Int {
delegate.numberOfCoachMarks(for: controller)
}
public final func coachMarksController(
_ coachMarksController: CoachMarksController,
constraintsForSkipView skipView: UIView,
inParent parentView: UIView
) -> [NSLayoutConstraint]? {
delegate.coachMarksController(coachMarksController, constraintsForSkipView: skipView, inParent: parentView)
}
public final func coachMarksController(
_ coachMarksController: CoachMarksController,
didEndShowingBySkipping skipped: Bool
) {
delegate.coachMarksController(coachMarksController, didEndShowingBySkipping: skipped)
}
private final func deleteExampleActivity() {
let definitionFetchRequest: NSFetchRequest<ActivityDefinition> = ActivityDefinition.fetchRequest()
definitionFetchRequest.predicate = NSPredicate(format: "name == %@", Me.exampleActivityName)
do {
let definitions = try injected(Database.self).query(definitionFetchRequest)
for definition in definitions {
let transaction = injected(Database.self).transaction()
try transaction.delete(definition)
try retryOnFail({ try transaction.commit() }, maxRetries: 2)
controller?.loadActivitiyDefinitions()
}
} catch {
Me.log.error("Failed to delete example activity: %@", errorInfo(error))
}
}
private final func getExampleActivityCell() -> RecordActivityDefinitionTableViewCell? {
guard let controller = self.controller else { return nil }
guard controller.tableView.visibleCells.count > 0 else {
Me.log.error("No visible cells while trying to present instruction")
return nil
}
let cell = controller.tableView.visibleCells[0]
guard let exampleActivityCell = cell as? RecordActivityDefinitionTableViewCell else {
Me.log.error(
"unable to cast to RecordActivityDefinitionTableViewCell: was a %@",
String(describing: type(of: cell))
)
return nil
}
return exampleActivityCell
}
}
| 35.377003 | 177 | 0.753377 |
c1ffd8ca6bf1b950b80185118234cf126ca7371d
| 355 |
//
// ViewController.swift
// Project2
//
// Created by Paul Hudson on 21/03/2017.
// Copyright © 2017 Paul Hudson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| 16.904762 | 80 | 0.667606 |
0a49d84b38e1f7a556efb20081613c9659a9149c
| 396 |
// swift-tools-version:5.2
import PackageDescription
let package = Package(
name: "R.swift.Library",
platforms: [
.iOS(.v11),
.tvOS(.v9),
.watchOS(.v2)
],
products: [
.library(name: "Rswift", targets: ["Rswift"]),
.library(name: "RswiftDynamic", type: .dynamic, targets: ["Rswift"])
],
targets: [
.target(name: "Rswift", path: "Library")
]
)
| 19.8 | 76 | 0.573232 |
abe5d2c473615bb901e07caa674bd0189e20e475
| 5,673 |
import Foundation
import FoundationExtensions
/**
An operand token is an abstract representation of a single operand within an RGBDS assembly instruction.
This enables a statement to be represented as a pattern to which other instructions can be matched. This is primarily
used by the Windfish macro system.
*/
public enum InstructionOperandToken: Equatable {
/** A generic numeric token. Examples: 123, 0xff, 0b10101010. */
case numeric
/** An generic address token. Examples: [$abcd], [$dd]. */
case address
/** A generic stack pointer offset token. Examples: sp+$fa. */
case stackPointerOffset
/**
A specific token.
Examples: [bc].
Primarily used when the token is specific but can't be correctly inferred from the operand's type.
*/
case specific(String)
/** Creates a token from the given string. */
public init(string: String) {
let lowercasedString: String = string.lowercased()
if lowercasedString.hasPrefix("sp+") {
self = .stackPointerOffset
return
}
if lowercasedString == "[$ff00+c]" {
self = .specific(string)
return
}
if (string.hasPrefix("@+") || string.hasPrefix("@-")) && isNumber(String(string.dropFirst(2))) {
self = .numeric
return
}
if isNumber(string) || (string.hasPrefix("bank(") && string.hasSuffix(")")) {
self = .numeric
return
}
if string.hasPrefix("[") && string.hasSuffix("]") {
let withinBrackets: String = String(string.dropFirst().dropLast())
if isNumber(withinBrackets) {
self = .address
return
}
}
self = .specific(string)
}
/** Returns a representation of this token as a string. */
public func asString() -> String {
switch self {
case .numeric: return "#"
case .address: return "[#]"
case .stackPointerOffset: return "sp+#"
case .specific(let string): return string
}
}
}
/** An abstract representation of an instruction's operand as an RGBDS token. */
public protocol InstructionOperandTokenizable {
/** The operand's representation as an RGBDS token. */
var token: InstructionOperandToken { get }
}
/**
Returns true if the given string is a numerical representation in RGBDS.
Reference: https://rgbds.gbdev.io/docs/v0.4.2/rgbasm.5#Numeric_Formats
*/
private func isNumber(_ string: String) -> Bool {
return
string.hasPrefix(NumericPrefix.hexadecimal)
|| string.hasPrefix(NumericPrefix.octal)
|| string.hasPrefix(NumericPrefix.binary)
|| string.hasPrefix(NumericPrefix.placeholder)
|| string.hasPrefix(NumericPrefix.gameboyGraphics)
|| (string.hasPrefix("-") && isNumber(String(string.dropFirst())))
|| Int(string) != nil
|| (string.contains(".") && Float(string) != nil)
}
// MARK: - RGBDS string -> number conversions
/** Returns a UInt16 representation of the string, assuming the string is represented using RGBDS address notation. */
public func integer(fromAddress string: String) -> UInt16? {
precondition(string.hasPrefix("[") && string.hasSuffix("]"))
return integer(from: String(string.dropFirst().dropLast().trimmed()))
}
/**
Returns a UInt8 representation of the string, assuming the string is represented using RGBDS stack pointer notation.
*/
public func integer(fromStackPointer string: String) -> UInt8? {
precondition(string.hasPrefix("sp+"))
return integer(from: String(string.dropFirst(3).trimmed()))
}
/**
Returns a UInt16 representation of the string, assuming the string is represented using RGBDS numeric notation.
Negative values are bit-casted to UInt16 from an Int16 representation first.
*/
public func integer(from string: String) -> UInt16? {
var value: String = string
let isNegative: Bool = value.starts(with: "-")
if isNegative {
value = String(value.dropFirst(1))
}
var numericPart: String
var radix: Int
if value.starts(with: NumericPrefix.hexadecimal) {
numericPart = String(value.dropFirst())
radix = 16
} else if value.starts(with: NumericPrefix.octal) {
numericPart = String(value.dropFirst())
radix = 8
} else if value.starts(with: NumericPrefix.binary) {
numericPart = String(value.dropFirst())
radix = 2
} else {
numericPart = value
radix = 10
}
if isNegative {
guard let negativeValue: Int16 = Int16(numericPart, radix: radix) else {
return nil
}
return UInt16(bitPattern: -negativeValue)
}
guard let numericValue = UInt16(numericPart, radix: radix) else {
return nil
}
return numericValue
}
/**
Returns a UInt8 representation of the string, assuming the string is represented using RGBDS numeric notation.
Negative values are bit-casted to UInt8 from an Int8 representation first.
*/
public func integer(from string: String) -> UInt8? {
var value: String = string
let isNegative: Bool = value.starts(with: "-")
if isNegative {
value = String(value.dropFirst(1))
}
var numericPart: String
var radix: Int
if value.starts(with: NumericPrefix.hexadecimal) {
numericPart = String(value.dropFirst())
radix = 16
} else if value.starts(with: NumericPrefix.octal) {
numericPart = String(value.dropFirst())
radix = 8
} else if value.starts(with: NumericPrefix.binary) {
numericPart = String(value.dropFirst())
radix = 2
} else {
numericPart = value
radix = 10
}
if isNegative {
guard let negativeValue: Int8 = Int8(numericPart, radix: radix) else {
return nil
}
return UInt8(bitPattern: -negativeValue)
}
guard let numericValue = UInt8(numericPart, radix: radix) else {
return nil
}
return numericValue
}
| 28.796954 | 118 | 0.682002 |
2fe7be090317373c69ed954fd04ecd48a7d6142f
| 5,019 |
import UIKit
public protocol QHTabBarDataSource: NSObjectProtocol {
func tabBarViewForRows(_ tabBarView: QHTabBarView) -> [QHTabBar]
func tabBarViewForMiddle(_ tabBarView: QHTabBarView, size: CGSize) -> UIView?
}
@objc protocol QHTabBarDelegate: NSObjectProtocol {
@objc optional func tabBarView(_ tabBarView: QHTabBarView, didSelectRowAt index: Int)
}
public class QHTabBarView: UIView {
weak var dataSource: QHTabBarDataSource?
weak var delegate: QHTabBarDelegate?
var superView: UIView?
var selectIndex: Int = 0//从1开始
public override init(frame: CGRect) {
super.init(frame: frame)
p_setup()
reloadData()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
p_setup()
reloadData()
}
//MARK: Private
func p_setup() {
self.backgroundColor = UIColor.clear
}
//MARK: Public
func reloadData() {
superView?.removeFromSuperview()
superView = UIView(frame: self.bounds)
superView!.backgroundColor = UIColor.clear
if let dataS = self.dataSource {
let dataArray = dataS.tabBarViewForRows(self)
var width = CGFloat(self.frame.size.width) / CGFloat(dataArray.count + 1)
let hight = CGFloat(self.frame.size.height)
let middleView = dataS.tabBarViewForMiddle(self, size: CGSize(width: width, height: hight))
var middleIndex = Int(dataArray.count) / 2
if nil == middleView {
width = CGFloat(self.frame.size.width) / CGFloat(dataArray.count)
middleIndex = 0
}
var xIndex = 0
for (index, value) in dataArray.enumerated() {
xIndex = index
if xIndex >= middleIndex && middleIndex != 0 {
xIndex += 1
}
if index == middleIndex && middleIndex != 0 {
let view = UIView(frame: CGRect(x: CGFloat(middleIndex) * width, y: 5, width: width, height: hight))
view.backgroundColor = UIColor.clear
view.addSubview(middleView!)
superView!.addSubview(view)
}
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: CGFloat(xIndex) * width, y: UIDevice.current.isiPhoneXSeriesDevices() ? 10 : 0, width: width, height: 44)
btn.backgroundColor = UIColor.clear
let normalTitle = NSMutableAttributedString(string: value.title, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor(white: 0.85, alpha: 0.95)])
btn.setAttributedTitle(normalTitle, for: .normal)
let selectTitle = NSMutableAttributedString(string: value.title, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.white])
btn.setAttributedTitle(selectTitle, for: .selected)
btn.addTarget(self, action: #selector(QHTabBarView.selectAction(sender:)),for: UIControl.Event.touchUpInside)
btn.isSelected = false
btn.tag = index + 1
let lineView = UIView(frame: CGRect(x: CGFloat(xIndex) * width + width*2.5/7, y: UIDevice.current.isiPhoneXSeriesDevices() ? 54 : 41, width: width*2/7, height: 2))
lineView.backgroundColor = UIColor.white
lineView.layer.cornerRadius = 1.0
lineView.layer.masksToBounds = true
lineView.tag = (index + 1) * 100
lineView.isHidden = (index + 1) != 1
superView!.addSubview(btn)
superView!.addSubview(lineView)
}
}
self.addSubview(superView!)
}
func selectTabBar(index: Int) {
if index == selectIndex {
return
}
if let btn: UIButton = superView?.viewWithTag(index) as? UIButton, let line = superView?.viewWithTag(index * 100) {
if let selectedBtn: UIButton = superView?.viewWithTag(selectIndex) as? UIButton, let lineSelected = superView?.viewWithTag(selectIndex * 100) {
selectedBtn.isSelected = false
lineSelected.isHidden = true
}
btn.isSelected = true
line.isHidden = false
selectIndex = index
}
}
//MARK: Action
@objc func selectAction(sender: UIButton) {
if let del = self.delegate {
if (del.tabBarView) != nil {
del.tabBarView?(self, didSelectRowAt: (sender.tag - 1))
}
selectTabBar(index: sender.tag)
}
}
}
| 37.455224 | 233 | 0.568639 |
6418837d534541b0670f924c635e79f073f5d863
| 3,442 |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache 2.0
*/
import Foundation
import SoraCrypto
import RobinHood
typealias DocumentConfigurationBlock = () throws -> DecentralizedDocumentObject
protocol DecentralizedResolverOperationFactoryProtocol {
func createDecentralizedDocumentFetchOperation(decentralizedId: String)
-> NetworkOperation<DecentralizedDocumentObject>
func createDecentralizedDocumentOperation(with documentConfigBlock: @escaping DocumentConfigurationBlock)
-> NetworkOperation<Bool>
}
final class DecentralizedResolverOperationFactory {
private(set) var url: URL
init(url: URL) {
self.url = url
}
}
extension DecentralizedResolverOperationFactory: DecentralizedResolverOperationFactoryProtocol {
func createDecentralizedDocumentFetchOperation(decentralizedId: String)
-> NetworkOperation<DecentralizedDocumentObject> {
let fetchUrl = url.appendingPathComponent(decentralizedId)
let requestFactory = BlockNetworkRequestFactory {
var request = URLRequest(url: fetchUrl)
request.httpMethod = HttpMethod.get.rawValue
return request
}
let resultFactory = AnyNetworkResultFactory { (data) -> DecentralizedDocumentObject in
let resultData = try JSONDecoder().decode(ResultData<DecentralizedDocumentObject>.self, from: data)
guard resultData.status.isSuccess else {
if let serviceError = DecentralizedDocumentQueryDataError.error(from: resultData.status) {
throw serviceError
} else {
throw ResultStatusError(statusData: resultData.status)
}
}
guard let decentralizedObject = resultData.result else {
throw NetworkBaseError.unexpectedResponseObject
}
return decentralizedObject
}
return NetworkOperation<DecentralizedDocumentObject>(requestFactory: requestFactory,
resultFactory: resultFactory)
}
func createDecentralizedDocumentOperation(with documentConfigBlock: @escaping DocumentConfigurationBlock)
-> NetworkOperation<Bool> {
let creationUrl = url
let requestFactory = BlockNetworkRequestFactory {
let document = try documentConfigBlock()
var request = URLRequest(url: creationUrl)
request.httpMethod = HttpMethod.post.rawValue
request.httpBody = try JSONEncoder().encode(document)
request.setValue(HttpContentType.json.rawValue, forHTTPHeaderField: HttpHeaderKey.contentType.rawValue)
return request
}
let resultFactory = AnyNetworkResultFactory { (data) -> Bool in
let resultData = try JSONDecoder().decode(ResultData<Bool>.self, from: data)
guard resultData.status.isSuccess else {
if let serviceError = DecentralizedDocumentCreationDataError.error(from: resultData.status) {
throw serviceError
} else {
throw ResultStatusError(statusData: resultData.status)
}
}
return true
}
return NetworkOperation<Bool>(requestFactory: requestFactory,
resultFactory: resultFactory)
}
}
| 37.010753 | 115 | 0.665601 |
186e6fdd89e660e337d82204950f1e9f3788db2a
| 8,100 |
#if canImport(UIKit)
import UIKit
public typealias TextAttributesFont = UIFont
public typealias TextAttributesColor = UIColor
#elseif canImport(AppKit)
import AppKit
public typealias TextAttributesFont = NSFont
public typealias TextAttributesColor = NSColor
#else
#error("unsupported platform")
#endif
@dynamicMemberLookup
public struct TextAttributes {
@usableFromInline
static let defaultParagraphStyle = NSMutableParagraphStyle()
@usableFromInline
var _paragraphStyle🐮: CowHelper<NSMutableParagraphStyle>!
@usableFromInline
var _attributes: [NSAttributedString.Key: Any] = [:]
// MARK: Initializers
public init() {}
public init(_ builder: (inout TextAttributes) -> Void) {
builder(&self)
}
}
// MARK: Equatable
extension TextAttributes: Equatable {
public static func == (lhs: TextAttributes, rhs: TextAttributes) -> Bool {
(lhs.attributes as NSDictionary).isEqual(to: rhs.attributes)
}
}
public extension TextAttributes {
// MARK: Attributes
/// Set the given attribute for the given key.
/// - Parameters:
/// - attribute: The attribute.
/// - key: The key.
/// - Note: Prefer the type safe properties. Only use this for instances
/// where Apple has added a new property that this library does not yet
/// support.
@inlinable
mutating func setAttribute(_ attribute: Any?, forKey key: NSAttributedString.Key) {
assert(key != .paragraphStyle, "Please use the paragraph style property")
_attributes[key] = attribute
}
@inlinable
func attribute(forKey key: NSAttributedString.Key) -> Any? {
if key == .paragraphStyle {
return paragraphStyle
} else {
return _attributes[key]
}
}
@inlinable
internal subscript<T>(key: NSAttributedString.Key) -> T? {
get { _attributes[key] as? T }
set { _attributes[key] = newValue }
}
@inlinable
var attributes: [NSAttributedString.Key: Any] {
if let style = paragraphStyle {
var attributes = _attributes
attributes[.paragraphStyle] = style.copy()
return attributes
} else {
return _attributes
}
}
// MARK: Font
@inlinable
var font: TextAttributesFont? {
get { self[.font] }
set { self[.font] = newValue }
}
// MARK: Foreground color
@inlinable
var foregroundColor: TextAttributesColor? {
get { self[.foregroundColor] }
set { self[.foregroundColor] = newValue }
}
// MARK: Background color
@inlinable
var backgroundColor: TextAttributesColor? {
get { self[.backgroundColor] }
set { self[.backgroundColor] = newValue }
}
// MARK: Ligature
@inlinable
var ligature: Int? {
get { self[.ligature] }
set { self[.ligature] = newValue }
}
// MARK: Kern
@inlinable
var kern: CGFloat? {
get { self[.kern] }
set { self[.kern] = newValue }
}
// MARK: Strikethrough style
@inlinable
var strikethroughStyle: NSUnderlineStyle? {
get { self[.strikethroughStyle] }
set { self[.strikethroughStyle] = newValue }
}
// MARK: Strikethrough color
@inlinable
var strikethroughColor: TextAttributesColor? {
get { self[.strikethroughColor] }
set { self[.strikethroughColor] = newValue }
}
// MARK: Underline style
@inlinable
var underlineStyle: NSUnderlineStyle? {
get { self[.underlineStyle] }
set { self[.underlineStyle] = newValue }
}
// MARK: Underline color
@inlinable
var underlineColor: TextAttributesColor? {
get { self[.underlineColor] }
set { self[.underlineColor] = newValue }
}
// MARK: Stroke color
@inlinable
var strokeColor: TextAttributesColor? {
get { self[.strokeColor] }
set { self[.strokeColor] = newValue }
}
// MARK: Stroke width
@inlinable
var strokeWidth: CGFloat? {
get { self[.strokeWidth] }
set { self[.strokeWidth] = newValue }
}
// MARK: Shadow
@inlinable
var shadow: NSShadow? {
get { self[.shadow] }
set { self[.shadow] = newValue }
}
// MARK: Text effect
@inlinable
var textEffect: NSAttributedString.TextEffectStyle? {
get { self[.textEffect] }
set { self[.textEffect] = newValue }
}
#if !os(watchOS)
// MARK: Attachment
@inlinable
var attachment: NSTextAttachment? {
get { self[.attachment] }
set { self[.attachment] = newValue }
}
#endif
// MARK: Link
@inlinable
var link: URL? {
get { self[.link] }
set { self[.link] = newValue }
}
// MARK: Baseline offset
@inlinable
var baselineOffset: CGFloat? {
get { self[.baselineOffset] }
set { self[.baselineOffset] = newValue }
}
// MARK: Obliqueness
@inlinable
var obliqueness: CGFloat? {
get { self[.obliqueness] }
set { self[.obliqueness] = newValue }
}
// MARK: Expansion
@inlinable
var expansion: CGFloat? {
get { self[.expansion] }
set { self[.expansion] = newValue }
}
// MARK: Writing direction
@inlinable
var writingDirection: [NSWritingDirection]? {
get { self[.writingDirection] }
set { self[.writingDirection] = newValue }
}
// MARK: Vertical glyph form
@inlinable
var verticalGlyphForm: Int? {
get { self[.verticalGlyphForm] }
set { self[.verticalGlyphForm] = newValue }
}
// MARK: Paragraph style
/// The paragraph style. New values will be copied upon being set.
/// - Note: Prefer to use the specific properties on ``TextAttributes`` for
/// manipulating the paragraph style attributes; this property will override
/// those values.
@inlinable
var paragraphStyle: NSParagraphStyle? {
get {
// Defensively copy out the value.
_paragraphStyle🐮?.value.copy() as? NSParagraphStyle
}
set {
if let value = newValue {
// Defensively copy in the new value.
_paragraphStyle🐮 = CowHelper(value.mutableCopy() as! NSMutableParagraphStyle)
} else {
_paragraphStyle🐮 = nil
}
}
}
@inlinable
subscript<T>(dynamicMember keyPath: WritableKeyPath<NSMutableParagraphStyle, T>) -> T {
get {
(_paragraphStyle🐮?.value ?? Self.defaultParagraphStyle)[keyPath: keyPath]
}
set {
if _paragraphStyle🐮 == nil {
// It's not been set yet, create it.
_paragraphStyle🐮 = CowHelper(NSMutableParagraphStyle())
} else if !isKnownUniquelyReferenced(&_paragraphStyle🐮) {
// It's been set, but is shared with another style, so
// create a mutable copy to help keep COW semantics.
_paragraphStyle🐮 = _paragraphStyle🐮.mutableCopy()
}
// else: it's been set but is not shared with another style so we
// don't need to do anything and can just modify it in place.
_paragraphStyle🐮.value[keyPath: keyPath] = newValue
}
}
}
// MARK: String
public extension String {
func attributedString(withStyle style: TextAttributes) -> NSAttributedString {
NSAttributedString(string: self, attributes: style.attributes)
}
func mutableAttributedString(withStyle style: TextAttributes) -> NSMutableAttributedString {
NSMutableAttributedString(string: self, attributes: style.attributes)
}
}
public extension TextAttributes {
func attributedString(from string: String) -> NSAttributedString {
NSAttributedString(string: string, attributes: attributes)
}
func mutableAttributedString(from string: String) -> NSMutableAttributedString {
NSMutableAttributedString(string: string, attributes: attributes)
}
}
| 26.129032 | 96 | 0.61321 |
de00fd28d6097a43adce06cc4cf6c73056a0cde9
| 4,249 |
/*
IntegerProtcool.swift
This source file is part of the SDGCornerstone open source project.
https://sdggiesbrecht.github.io/SDGCornerstone
Copyright ©2016–2021 Jeremy David Giesbrecht and the SDGCornerstone project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
import SDGLogic
import SDGMathematics
import SDGText
extension IntegerProtocol {
// @localization(🇩🇪DE) @crossReference(IntegerProtocol.inDigits(thousandsSeparator:))
// #documentation(SDGCornerstone.WholeNumberProtocol.inZahlzeichen(tausendertrennzeichen:))
/// Gibt die Zahl in Zahlzeichen zurück.
///
/// - Parameters:
/// - tausendertrennzeichen: Das Tausendertrennzeichen. (Ein Leerzeichen, wenn nicht angegeben.)
@inlinable public func inZahlzeichen(
tausendertrennzeichen: Unicode.Skalar = " "
) -> StrengeZeichenkette {
return inDigits(thousandsSeparator: tausendertrennzeichen)
}
// @localization(🇨🇦EN) @crossReference(IntegerProtocol.inDigits(thousandsSeparator:))
// #documentation(SDGCornerstone.WholeNumberProtocol.inDigits(thousandsSeparator:))
/// Returns the number in digits.
///
/// - Parameters:
/// - thousandsSeparator: The character to use as a thousands separator. (Space by default.)
public func inDigits(thousandsSeparator: UnicodeScalar = " ") -> StrictString {
return integralDigits(thousandsSeparator: thousandsSeparator)
}
// #documentation(SDGCornerstone.WholeNumberProtocol.abbreviatedEnglishOrdinal())
/// Returns the ordinal in its abbreviated English form.
///
/// i.e. “1st”, “2nd”, “3rd”...
public func abbreviatedEnglishOrdinal() -> SemanticMarkup {
return generateAbbreviatedEnglishOrdinal()
}
// @localization(🇩🇪DE) @notLocalized(🇨🇦EN)
// #documentation(SDGCornerstone.WholeNumberProtocol.abgekürzteDeutscheOrdnungszahl())
/// Gibt die Ordnungszahl in deutscher abgekürzter Form zurück.
///
/// d. h. „1.“, „2.“, „3.“ ...
public func abgekürzteDeutscheOrdnungszahl() -> StrictString {
return abgekürzteDeutscheOrdnungszahlErzeugen()
}
// @localization(🇫🇷FR) @notLocalized(🇨🇦EN)
// #documentation(SDGCornerstone.WholeNumberProtocol.ordinalFrançaisAbrégé())
/// Renvoie l’ordinal dans la forme abrégée française.
///
/// c.‐à‐d. « 1er », « 2e », « 3e »...
public func ordinalFrançaisAbrégé(
genre: GenreGrammatical,
nombre: GrammaticalNumber
) -> SemanticMarkup {
return générerOrdinalFrançaisAbrégé(genre: genre, nombre: nombre)
}
// @localization(🇩🇪DE) @crossReference(IntegerProtocol.inRomanNumerals(lowercase:))
// #documentation(SDGCornerstone.WholeNumberProtocol.inRömischerZahlschrift(kleinbuchstaben:))
/// Gibt die Zahl in römischer Zahlschrift zurück.
///
/// - Parameters:
/// - kleinbuchstaben: Ob Kleinbuchstaben verwendet werden sollen. (`falsch` wenn nicht angegeben.)
@inlinable public func inRömischerZahlschrift(
kleinbuchstaben: Bool = falsch
) -> StrengeZeichenkette {
return inRomanNumerals(lowercase: kleinbuchstaben)
}
// @localization(🇨🇦EN) @crossReference(IntegerProtocol.inRomanNumerals(lowercase:))
// #documentation(SDGCornerstone.WholeNumberProtocol.inRomanNumerals(lowercase:))
/// Returns the number in roman numerals.
///
/// - Parameters:
/// - lowercase: Whether the numeral should be in lowercase. (`false` by default.)
public func inRomanNumerals(lowercase: Bool = false) -> StrictString {
return romanNumerals(lowercase: lowercase)
}
// @localization(🇬🇷ΕΛ) @notLocalized(🇨🇦EN)
// #documentation(SDGCornerstone.WholeNumberProtocol.σεΕλληνικούςΑριθμούς())
/// Επιστρέφει τον αριθμός σε ελληνικούς αριθμούς.
public func σεΕλληνικούςΑριθμούς(
μικράΓράμματα: Bool = false,
κεραία: Bool = true
) -> StrictString {
return ελληνικοίΑριθμοί(μικράΓράμματα: μικράΓράμματα, κεραία: κεραία)
}
// @localization(🇮🇱עב) @notLocalized(🇨🇦EN)
// #documentation(SDGCornerstone.WholeNumberProtocol.בספרות־עבריות())
/// משיבה את המספר בספרות עבריות.
public func בספרות־עבריות(גרשיים: Bool = true) -> StrictString {
return ספרות־עבריות(גרשיים: גרשיים)
}
}
| 38.981651 | 105 | 0.728171 |
e26aceca4b594eef869ce10aaffe805801f3e033
| 3,012 |
import Foundation
public class WienProvider: AbstractEfaProvider {
static let API_BASE = "https://www.wienerlinien.at/ogd_routing/"
public init() {
super.init(networkId: .WIEN, apiBase: WienProvider.API_BASE)
includeRegionId = false
styles = [
// Wien
"SS1": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#1e5cb3"), foregroundColor: LineStyle.white),
"SS2": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#59c594"), foregroundColor: LineStyle.white),
"SS3": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#c8154c"), foregroundColor: LineStyle.white),
"SS7": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#dc35a3"), foregroundColor: LineStyle.white),
"SS40": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#f24d3e"), foregroundColor: LineStyle.white),
"SS45": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#0f8572"), foregroundColor: LineStyle.white),
"SS50": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#34b6e5"), foregroundColor: LineStyle.white),
"SS60": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#82b429"), foregroundColor: LineStyle.white),
"SS80": LineStyle(shape: .rounded, backgroundColor: LineStyle.parseColor("#e96619"), foregroundColor: LineStyle.white),
"UU1": LineStyle(shape: .rect, backgroundColor: LineStyle.parseColor("#c6292a"), foregroundColor: LineStyle.white),
"UU2": LineStyle(shape: .rect, backgroundColor: LineStyle.parseColor("#a82783"), foregroundColor: LineStyle.white),
"UU3": LineStyle(shape: .rect, backgroundColor: LineStyle.parseColor("#f39315"), foregroundColor: LineStyle.white),
"UU4": LineStyle(shape: .rect, backgroundColor: LineStyle.parseColor("#23a740"), foregroundColor: LineStyle.white),
"UU6": LineStyle(shape: .rect, backgroundColor: LineStyle.parseColor("#be762c"), foregroundColor: LineStyle.white)
]
}
override func queryTripsParameters(builder: UrlBuilder, from: Location, via: Location?, to: Location, date: Date, departure: Bool, tripOptions: TripOptions) {
super.queryTripsParameters(builder: builder, from: from, via: via, to: to, date: date, departure: departure, tripOptions: tripOptions)
if let products = tripOptions.products, products.contains(.bus) {
builder.addParameter(key: "inclMOT_11", value: "on") // night bus
}
}
override func split(directionName: String?) -> (name: String?, place: String?) {
guard let directionName = directionName else { return (nil, nil) }
if directionName.hasPrefix("Wien ") {
return (directionName.substring(from: "Wien ".count), "Wien")
}
return super.split(directionName: directionName)
}
}
| 64.085106 | 162 | 0.676959 |
fcc593f9d7388bf571a94ee9d6b9cc9de5f0c66a
| 1,358 |
//
// SceneDelegate.swift
// StitchTester-iOS
//
// Created by Elizabeth Siemer on 7/1/19.
// Copyright © 2019 Dark Chocolate Software, LLC. All rights reserved.
//
import UIKit
@available (iOS 13.0, *)
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 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 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.
}
}
| 38.8 | 145 | 0.722386 |
22bccfe2693a50ab40fc31ca494e2176c67f7709
| 743 |
//
// UIViewController+rx.swift
// Snip
//
// Created by Sameer Khavanekar on 6/24/18.
// Copyright © 2018 Sameer Khavanekar. All rights reserved.
//
import UIKit
import RxSwift
extension UIViewController {
func alert(title: String, message: String) -> Completable {
return Completable.create { [weak self](observer) -> Disposable in
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
observer(.completed)
}))
self?.present(alertVC, animated: true, completion: nil)
return Disposables.create()
}
}
}
| 27.518519 | 99 | 0.625841 |
6499e71d3b0945acc24c42591aa737a479f8a44f
| 2,426 |
import Foundation
import MapboxMaps
@objc(BuildingExtrusionsExample)
public class BuildingExtrusionsExample: UIViewController, ExampleProtocol {
internal var mapView: MapView!
override public func viewDidLoad() {
super.viewDidLoad()
let options = MapInitOptions(styleURI: .light)
mapView = MapView(frame: view.bounds, mapInitOptions: options)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(mapView)
mapView.mapboxMap.onNext(.styleLoaded) { _ in
self.setupExample()
}
}
internal func setupExample() {
addBuildingExtrusions()
let cameraOptions = CameraOptions(center: CLLocationCoordinate2D(latitude: 40.7135, longitude: -74.0066),
zoom: 15.5,
bearing: -17.6,
pitch: 45)
mapView.camera.setCamera(to: cameraOptions)
// The below lines are used for internal testing purposes only.
DispatchQueue.main.asyncAfter(deadline: .now()+5.0) {
self.finish()
}
}
// See https://docs.mapbox.com/mapbox-gl-js/example/3d-buildings/ for equivalent gl-js example
internal func addBuildingExtrusions() {
var layer = FillExtrusionLayer(id: "3d-buildings")
layer.source = "composite"
layer.minZoom = 15
layer.sourceLayer = "building"
layer.paint?.fillExtrusionColor = .constant(ColorRepresentable(color: .lightGray))
layer.paint?.fillExtrusionOpacity = .constant(0.6)
layer.filter = Exp(.eq) {
Exp(.get) {
"extrude"
}
"true"
}
layer.paint?.fillExtrusionHeight = .expression(
Exp(.interpolate) {
Exp(.linear)
Exp(.zoom)
15
0
15.05
Exp(.get) {
"height"
}
}
)
layer.paint?.fillExtrusionBase = .expression(
Exp(.interpolate) {
Exp(.linear)
Exp(.zoom)
15
0
15.05
Exp(.get) { "min_height"}
}
)
try! mapView.style.addLayer(layer)
}
}
| 29.950617 | 113 | 0.515251 |
5d2b050b9a3742718664a491b4fd03dbbfc45c5f
| 767 |
// Recursion is a way to solve problems alternatively to using iterations such
// as using loops. Although recursion code can be more compact and elegant, it
// is a not very efficient when it comes to memory. Because of its excessive
// use of the call stack, it makes it very inefficient compared to regular
// old iterations. In some cases though, recursion can be better. For example,
// because recursion requires less code to be written, this means that there
// is a smaller chance of making an error in our code, and also makes it easier
// to debug if we do have a problem.
import UIKit
func factorial(value: UInt) -> UInt {
if value == 0 {
return 1
}
return value * factorial(value: value - 1)
}
print (factorial(value: 5))
| 36.52381 | 80 | 0.718383 |
0e45216c3f622264de660b1cca2c4b27fec5b359
| 850 |
//
// String+Replace.swift
// SwiftKit
//
// Created by Daniel Saidi on 2016-01-08.
// Copyright © 2020 Daniel Saidi. All rights reserved.
//
// Read more here:
// https://danielsaidi.com/blog/2020/06/04/string-replace
//
import Foundation
public extension String {
/**
This is a shortcut to `replacingOccurrences(of:with:)`.
*/
func replacing(_ string: String, with: String) -> String {
replacingOccurrences(of: string, with: with)
}
/**
This is a shortcut to `replacingOccurrences(of:with:)`,
with a `caseInsensitive` option enabled.
*/
func replacing(_ string: String, with: String, caseSensitive: Bool) -> String {
caseSensitive
? replacing(string, with: with)
: replacingOccurrences(of: string, with: with, options: .caseInsensitive)
}
}
| 25.757576 | 85 | 0.635294 |
713fc5dc1e0f1258c4892101ba194217070382ae
| 989 |
//
// RefurViewerTests.swift
// RefurViewerTests
//
// Created by Ray Park on 2015. 9. 21..
// Copyright © 2015년 Ray Park. All rights reserved.
//
import XCTest
@testable import RefurViewer
class RefurViewerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.72973 | 111 | 0.635996 |
46edb2d72acaa5c81219b7e54bc5d9211a43b777
| 16,087 |
//
// PaintColorPicker.swift
// Coloretta
//
// Created by Bohdan Savych on 10/20/19.
// Copyright © 2019 Padres. All rights reserved.
//
import UIKit
private struct Constants {
static var lowestInertiaVelocity: CGFloat { 0.3 }
static var inertiaResistence: CGFloat { 2 }
}
public final class CircularColorPickerView: UIView {
private var collectionView: UICollectionView!
private let realRadius: CGFloat
private let infiniteSize: Int
private lazy var layout = CircularCollectionViewLayout()
private lazy var globalOffset: CGFloat = 0
private lazy var outerColorsIndex = 0
private lazy var innerColorsIndex = 0
private lazy var item = DynamicItem()
private lazy var dynamicAnimator = UIDynamicAnimator(referenceView: self.collectionView)
private lazy var intersection = CircularCollectionViewLayout.calculateIntersectionPoint(
itemSize: CircularCollectionViewLayout.itemSize,
items: CircularCollectionViewLayout.normalizeRows(self.infiniteSize))
private lazy var itemCutIntersection = CircularCollectionViewLayout.calculateItemCutIntersection(
itemSize: CircularCollectionViewLayout.itemSize,
cutRadius: self.itemCutRadius,
normalizedElementsCount: CircularCollectionViewLayout.normalizeRows(self.infiniteSize))
private lazy var topIntersectionYPoint = CircularCollectionViewLayout.calculateTopIntersectionYPoint(
itemSize: CircularCollectionViewLayout.itemSize,
items: CircularCollectionViewLayout.normalizeRows(self.infiniteSize))
private lazy var itemCutRadius = CircularCollectionViewLayout.calculateItemCutRadius(
itemSize: CircularCollectionViewLayout.itemSize,
anglePerItem: CGFloat.pi * 2 / CGFloat(CircularCollectionViewLayout.normalizeRows(self.infiniteSize)))
private lazy var inneRadius = CircularCollectionViewLayout.calculateInnerRadius(
itemSize: CircularCollectionViewLayout.itemSize,
anglePerItem: CGFloat.pi * 2 / CGFloat(CircularCollectionViewLayout.normalizeRows(self.infiniteSize)))
private lazy var innerBottomRadius = CircularCollectionViewLayout.calculateInnerBottomRadius(
itemSize: CircularCollectionViewLayout.itemSize,
items: CircularCollectionViewLayout.normalizeRows(self.infiniteSize))
private lazy var currentColorView = CurrentColorView()
private lazy var touchHandlerView = TouchHandlerView()
private var previousPoint: CGPoint?
private var currentPoint: CGPoint?
private let minPickerStep: CGFloat = 0
private let maxPickerStep: CGFloat = 12
private let xMultiplier: CGFloat = 1.4
private var keyValueObserver: NSKeyValueObservation?
private lazy var isInerting = false
private var prevOffset: CGPoint?
private let colors: [[PaintColor]]
private var tapNormalizationTimer: Timer?
// MARK: - Public
public var didChangeColor: ((PaintColor) -> Void)?
public var currentColor: PaintColor? {
currentColorView.currentColor
}
public init(frame: CGRect, colors: [[PaintColor]] = Colors.default) {
self.infiniteSize = Int(1_000_000 / colors.count) * colors.count
self.colors = colors
self.realRadius = CircularCollectionViewLayout.calculateRealRadius(itemSize: CircularCollectionViewLayout.itemSize, items: CircularCollectionViewLayout.normalizeRows(self.infiniteSize))
super.init(frame: frame)
self.configureCollectionView(size: frame.size)
self.configureTouchHandler()
self.attachViews()
self.configureContentOffsetObserver()
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func toMiddle() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
guard let self = self else { return }
self.collectionView?.setContentOffset(CGPoint(x: self.collectionView.contentSize.width / 2, y: 0), animated: false)
DispatchQueue.main.async {
self.adjustOffset(targetContentOffset: nil)
UIView.animate(withDuration: 0.2) {
self.collectionView?.alpha = 1
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
guard let cell = self.collectionView.visibleCells.first as? ColorsCollectionViewCell else { return }
cell.colorCollectionView.setContentOffset(CGPoint(x: 0, y: cell.colorCollectionView.contentSize.height / 2), animated: true)
}
self.colorWasChanged()
}
}
}
func update(color: UIColor) {
let newColor = PaintColor(uicolor: color)
let flattenColors = colors.flatMap { $0 }
var minDiffColor = flattenColors.first!
var minDiff = CGFloat(Int.max)
for color in flattenColors {
let diff = newColor.diff(from: color)
if diff < minDiff {
minDiffColor = color
minDiff = diff
}
}
let index = colors.firstIndex(where: { $0.contains(minDiffColor) })
let groupIndex = Int(index ?? 0)
let leftDiff = groupIndex - self.layout.headIndex
let sign = self.layout.headIndex > groupIndex ? 1 : -1
var rightDiff = colors.count - (self.layout.headIndex > groupIndex ? self.layout.headIndex - groupIndex : groupIndex - self.layout.headIndex)
rightDiff *= sign
let diff = abs(leftDiff) < abs(rightDiff) ? leftDiff : rightDiff
let offsetChanges = (CGFloat(diff) * (CircularCollectionViewLayout.itemSize.width + CircularCollectionViewLayout.minimumItemSpacing))
guard let elementIndex = colors[groupIndex].firstIndex(of: minDiffColor) else { return }
let newOffset = CGPoint(x: self.collectionView.contentOffset.x + offsetChanges, y: self.collectionView.contentOffset.y)
collectionView.setContentOffset(newOffset, animated: true)
let colorCellHeight = (collectionView.visibleCells.first?.bounds.height ?? 0) / 2
let newContentOffset = CGPoint(x: 0, y: (colorCellHeight * CGFloat(elementIndex)) - colorCellHeight / 2)
guard let cell = self.collectionView.visibleCells.first as? ColorsCollectionViewCell else { return }
cell.colorCollectionView.setContentOffset(newContentOffset, animated: true)
self.globalOffset = newContentOffset.y
}
}
// MARK: - UICollectionViewDelegate
extension CircularColorPickerView: UICollectionViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let index = layout.headIndex
if index != self.outerColorsIndex {
self.outerColorsIndex = index
colorWasChanged()
}
self.outerColorsIndex = index
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
adjustOffset(targetContentOffset: targetContentOffset)
}
private func adjustOffset(targetContentOffset: UnsafeMutablePointer<CGPoint>?) {
targetContentOffset?.pointee = collectionView.contentOffset
let visibleCells = collectionView.visibleCells.compactMap { $0 as? ColorsCollectionViewCell }
guard var closestToCenterCell = visibleCells.first else { return }
var closestToCenterOffset = abs(closestToCenterCell.frame.midX - self.collectionView.contentOffset.x - (self.collectionView.bounds.width / 2))
for cell in visibleCells {
let offset = abs(cell.frame.midX - self.collectionView.contentOffset.x - (self.collectionView.bounds.width / 2))
if offset < closestToCenterOffset {
closestToCenterCell = cell
closestToCenterOffset = offset
}
}
visibleCells.first?.page()
let offsetWithSign = closestToCenterCell.frame.midX - self.collectionView.contentOffset.x - (self.collectionView.bounds.width / 2)
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
let newOffset = self.collectionView.contentOffset.x + offsetWithSign
self.collectionView.setContentOffset(CGPoint(x: newOffset, y: 0), animated: true)
}
}
}
// MARK: - UICollectionViewDataSource
extension CircularColorPickerView: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.infiniteSize
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: String(describing: ColorsCollectionViewCell.self),
for: indexPath) as! ColorsCollectionViewCell
let index = indexPath.row % self.colors.count
let colors = self.colors[index]
cell.configure(colors: colors, title: "\(indexPath.row)", realRadius: self.realRadius, innerRadius: inneRadius, innerBottomRadius: innerBottomRadius, size: CircularCollectionViewLayout.itemSize, intersectionPoint: self.intersection, offset: self.globalOffset, itemCutIntersection: self.itemCutIntersection, topIntersectionYPoint: topIntersectionYPoint)
cell.didSelectColor = { [weak self] color in
self?.update(color: color.uicolor)
}
cell.didScroll = { [weak self] offset, index in
self?.globalOffset = offset
if index != self?.innerColorsIndex {
self?.innerColorsIndex = index
self?.colorWasChanged()
}
self?.innerColorsIndex = index
collectionView.visibleCells.compactMap { $0 as? ColorsCollectionViewCell}.forEach { cell in
cell.colorCollectionView.contentOffset = CGPoint(x: 0, y: offset)
}
}
return cell
}
}
// MARK: - Private
private extension CircularColorPickerView {
func attachViews() {
self.currentColorView.isUserInteractionEnabled = false
self.currentColorView.translatesAutoresizingMaskIntoConstraints = false
self.touchHandlerView.translatesAutoresizingMaskIntoConstraints = false
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.collectionView)
self.addSubview(self.currentColorView)
self.addSubview(self.touchHandlerView)
NSLayoutConstraint.activate([
self.currentColorView.widthAnchor.constraint(equalToConstant: CircularCollectionViewLayout.itemSize.width / 2),
self.currentColorView.heightAnchor.constraint(equalToConstant: CircularCollectionViewLayout.itemSize.height / 2),
self.currentColorView.topAnchor.constraint(
equalTo: self.topAnchor,
constant: CircularCollectionViewLayout.itemSize.height / 4),
self.currentColorView.centerXAnchor.constraint(equalTo: self.centerXAnchor)
])
NSLayoutConstraint.activate([
self.touchHandlerView.leftAnchor.constraint(equalTo: self.leftAnchor),
self.touchHandlerView.rightAnchor.constraint(equalTo: self.rightAnchor),
self.touchHandlerView.topAnchor.constraint(equalTo: self.topAnchor),
self.touchHandlerView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
NSLayoutConstraint.activate([
self.collectionView.leftAnchor.constraint(equalTo: self.leftAnchor),
self.collectionView.rightAnchor.constraint(equalTo: self.rightAnchor),
self.collectionView.topAnchor.constraint(equalTo: self.topAnchor),
self.collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
func configureCollectionView(size: CGSize) {
self.collectionView = UICollectionView(frame: CGRect(origin: .zero, size: size), collectionViewLayout: self.layout)
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
self.collectionView?.alpha = 0
self.collectionView?.backgroundColor = .clear
self.collectionView.clipsToBounds = false
self.collectionView.decelerationRate = .fast
self.collectionView?.register(ColorsCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: ColorsCollectionViewCell.self))
}
func configureContentOffsetObserver() {
self.keyValueObserver = self.collectionView.observe(
\UICollectionView.contentOffset,
options: .new
) { [weak self] collection, change in
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
guard let oldValue = self.prevOffset,
let newValue = change.newValue else {
self.prevOffset = change.newValue
return
}
if self.isInerting &&
abs(oldValue.x - newValue.x) < Constants.lowestInertiaVelocity {
self.dynamicAnimator.removeAllBehaviors()
self.adjustOffset(targetContentOffset: nil)
self.isInerting = false
self.prevOffset = nil
}
self.prevOffset = newValue
}
}
}
func configureTouchHandler() {
self.collectionView.isUserInteractionEnabled = false
self.touchHandlerView.touchBeganEvent = { [unowned self] point, velocity in
self.previousPoint = point
self.isInerting = false
self.dynamicAnimator.removeAllBehaviors()
}
self.touchHandlerView.touchMovedEvent = { [unowned self] point, velocity in
self.currentPoint = point
self.move(prevPoint: self.previousPoint ?? .zero, curPoint: point)
self.previousPoint = self.currentPoint
}
self.touchHandlerView.touchesEnded = { [unowned self] point, velocity in
let removeVerticalVelocity = CGPoint(x: -velocity.x, y: 0)
self.isInerting = true
self.item.center = self.collectionView.contentOffset
let decelerationBehavior = UIDynamicItemBehavior(items: [self.item])
decelerationBehavior.resistance = Constants.inertiaResistence
decelerationBehavior.addLinearVelocity(removeVerticalVelocity, for: self.item)
decelerationBehavior.action = {
self.collectionView.contentOffset = self.item.center
}
self.dynamicAnimator.addBehavior(decelerationBehavior)
}
self.touchHandlerView.touchesCancelled = { [unowned self] point, velocity in
self.adjustOffset(targetContentOffset: nil)
}
self.touchHandlerView.onTap = { [weak self, weak touchHandlerView] point in
guard
let self = self else { return }
let convertedPoint = self.collectionView.convert(point, from: self.touchHandlerView)
var indexPath: IndexPath?
for visibleCell in self.collectionView.visibleCells {
if visibleCell.frame.contains(convertedPoint) {
indexPath = self.collectionView.indexPath(for: visibleCell)
break
}
}
guard
let unwrappedIndexPath = indexPath
else { return }
let index = unwrappedIndexPath.row % self.colors.count
let color = self.colors[index][self.innerColorsIndex]
self.update(color: color.uicolor)
if self.tapNormalizationTimer != nil {
self.tapNormalizationTimer?.invalidate()
self.tapNormalizationTimer = nil
}
self.tapNormalizationTimer = Timer.scheduledTimer(
withTimeInterval: 0.5,
repeats: false
) { timer in
touchHandlerView?.touchesEnded?(point, .init(x: 1, y: 1))
}
}
}
func move(prevPoint: CGPoint, curPoint: CGPoint) {
let xDiff = curPoint.x - prevPoint.x
let yDiff = curPoint.y - prevPoint.y
let xSign = xDiff == 0 ? 1 : (xDiff / abs(xDiff))
let ySign = yDiff == 0 ? 1 : (yDiff / abs(yDiff))
let x = max(min(abs(xDiff), self.maxPickerStep), self.minPickerStep) * -xSign * self.xMultiplier
let y = max(min(abs(yDiff), self.maxPickerStep), self.minPickerStep) * -ySign
let offset = CGPoint(x: self.collectionView.contentOffset.x + x, y: self.collectionView.contentOffset.y)
let cell = (self.collectionView.visibleCells.first as? ColorsCollectionViewCell)
let innerOffset = cell?.colorCollectionView.contentOffset ?? .zero
let inset = (cell?.colorCollectionView.contentInset.top ?? 0) * 2
let innerYContentOffset = min(max(innerOffset.y + y, -inset), (cell?.colorCollectionView.contentSize.height ?? 0) - inset)
cell?.colorCollectionView.contentOffset = CGPoint(x: innerOffset.x, y: innerYContentOffset)
self.collectionView.contentOffset = offset
}
func colorWasChanged() {
let index = self.layout.headIndex % self.colors.count
let color = self.colors[index][self.innerColorsIndex]
self.currentColorView.update(color: color)
self.didChangeColor?(color)
}
}
| 40.829949 | 356 | 0.73693 |
1c8a0ac98627007de6e4dad9375a998009efffe2
| 3,166 |
//
// PartOfDayButton.swift
// Patriot
//
// Created by Ron Lisle on 5/11/22.
//
import SwiftUI
struct PartOfDayButton: View {
@EnvironmentObject var model: PatriotModel
var body: some View {
Button(action: {
withAnimation {
print("PartOfDay")
}
}) {
PartOfDayView()
}.foregroundColor(Color("TextColor"))
}
}
struct PartOfDayView: View {
@EnvironmentObject var model: PatriotModel
var body: some View {
Image(systemName: partOfDayIcon())
.imageScale(.large)
}
func partOfDayIcon() -> String {
switch model.partOfDay {
case .Night:
return "moon.stars.fill"
case .Dawn, .Dusk:
return "moon.fill"
case .Sunrise, .Sunset:
return "sun.and.horizon"
case .Noon:
return "sun.max"
case .unknown:
return "questionmark"
default:
return "sun.min"
}
}
}
struct PartOfDayButton_Previews: PreviewProvider {
static var previews: some View {
Group {
PartOfDayButton()
.environmentObject(PatriotModel(testMode: .on, partOfDay: .Night))
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Night")
.background(Color("BackgroundColor"))
PartOfDayButton()
.environmentObject(PatriotModel(testMode: .on, partOfDay: .Sunrise))
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Sunrise")
.background(Color("BackgroundColor"))
PartOfDayButton()
.environmentObject(PatriotModel(testMode: .on, partOfDay: .Morning))
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Morning")
.background(Color("BackgroundColor"))
PartOfDayButton()
.environmentObject(PatriotModel(testMode: .on, partOfDay: .Noon))
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Noon")
.background(Color("BackgroundColor"))
PartOfDayButton()
.environmentObject(PatriotModel(testMode: .on, partOfDay: .Afternoon))
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Afternoon")
.background(Color("BackgroundColor"))
PartOfDayButton()
.environmentObject(PatriotModel(testMode: .on, partOfDay: .Sunset))
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Sunset")
.background(Color("BackgroundColor"))
PartOfDayButton()
.environmentObject(PatriotModel(testMode: .on, partOfDay: .Dusk))
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Dusk")
.background(Color("BackgroundColor"))
}
}
}
| 29.867925 | 86 | 0.537271 |
5686f33e580c2de951dbad7a63a3f0ab99cf89a6
| 1,691 |
//
// QuiverFloatingValidatorsTests.swift
// Quiver
//
// Created by Heitor Costa on 19/09/17.
// Copyright © 2017 Heitor Costa. All rights reserved.
//
import XCTest
@testable import Quiver
class QuiverFloatingValidatorsTests: 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 testEqualFloatingValidator() throws {
let validator: Validator = .equal(to: 32.1)
var result = try validator.validate(with: nil)
XCTAssert(result == true, "Expected 'true', but result was '\(result)'")
result = try validator.validate(with: 32.0)
XCTAssert(result == false, "Expected 'false', but result was '\(result)'")
result = try validator.validate(with: 32.1)
XCTAssert(result == true, "Expected 'true', but result was '\(result)'")
}
func testDifferentFloatingValidator() throws {
let validator: Validator = .different(to: 25.87)
var result = try validator.validate(with: nil)
XCTAssert(result == true, "Expected 'true', but result was '\(result)'")
result = try validator.validate(with: 25.87)
XCTAssert(result == false, "Expected 'false', but result was '\(result)'")
result = try validator.validate(with: 25.8)
XCTAssert(result == true, "Expected 'true', but result was '\(result)'")
}
}
| 33.82 | 111 | 0.621526 |
d535f340537c0a7fbb0aa4114b529a21e16012fd
| 1,317 |
//
// RhsLayoutConstraint.swift
// Pods
//
// Created by Ahmad Baraka on 7/17/16.
//
//
import Foundation
/// Right handside of a `LayoutConstraint.`
public struct RhsLayoutConstraint<V: AnyObject>: LayoutConstraintType {
public let object: V?
public var attribute: NSLayoutAttribute
public var constant: CGFloat
public var multiplier: CGFloat
public init(_ object: V?, attribute: NSLayoutAttribute, constant: CGFloat, multiplier: CGFloat) {
self.object = object
self.attribute = attribute
self.constant = constant
self.multiplier = multiplier
}
public init<L :LayoutConstraintType>(_ object: V?, constraint: L) {
self.object = object
attribute = constraint.attribute
constant = constraint.constant
multiplier = constraint.multiplier
}
}
public extension RhsLayoutConstraint {
public init<L :LayoutConstraintType where L.Value == V>(constraint: L) {
self.init(constraint.object, constraint: constraint)
}
public init(_ object: V?, attribute: NSLayoutAttribute) {
self.init(object, attribute: attribute, constant: DefaultConsant, multiplier: DefaultMultiplier)
}
public init(constant: CGFloat) {
self.init(nil)
self.constant = constant
}
}
| 28.021277 | 104 | 0.672741 |
f51708603c74feccb8c51e9164a362869c5fea2c
| 1,308 |
//
// THUXUrlParameteredNetworkCall.swift
// ThryvUXComponents
//
// Created by Elliot Schrock on 4/30/18.
//
import UIKit
import FunkyNetwork
import Prelude
open class THUXUrlParameteredNetworkCall: THUXAuthenticatedNetworkCall {
public var urlParams: [String: Any]?
public override init(configuration: ServerConfigurationProtocol, httpMethod: String, httpHeaders: Dictionary<String, String>?, endpoint: String, postData: Data?, networkErrorHandler: NetworkErrorHandler?, stubHolder: StubHolderProtocol?) {
super.init(configuration: configuration, httpMethod: httpMethod, httpHeaders: httpHeaders, endpoint: endpoint, postData: postData, networkErrorHandler: networkErrorHandler, stubHolder: stubHolder)
let superUrlString = urlString
urlString = { endpoint in
return endpoint |> superUrlString |> self.addParamsToUrl
}
}
open func addParamsToUrl(_ url: String) -> String {
if let params = urlParams, params.keys.count > 0 {
return "\(url)?\(params |> THUXUrlParameteredNetworkCall.pairsToString)"
}
return url
}
public static func pairsToString(_ params: [String: Any]) -> String {
return params.keys.map({ "\($0)=\(params[$0]!)" }).joined(separator: "&")
}
}
| 36.333333 | 243 | 0.691896 |
fc893fab5dfeb798e65077a4c585e42330adace3
| 3,563 |
// Copyright (c) 2019 Razeware LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
// distribute, sublicense, create a derivative work, and/or sell copies of the
// Software in any work that is designed, intended, or marketed for pedagogical or
// instructional purposes related to programming, coding, application development,
// or information technology. Permission for such use, copying, modification,
// merger, publication, distribution, sublicensing, creation of derivative works,
// or sale is expressly withheld.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import struct Foundation.URL
public struct User: Equatable, Codable {
// MARK: - Properties
public let externalId: String
public let email: String
public let username: String
public let avatarURL: URL
public let name: String
public let token: String
let permissions: [Permission]?
public var canStreamPro: Bool {
guard let permissions = permissions else { return false }
return !permissions.filter { $0.tag == .streamPro }.isEmpty
}
public var canStream: Bool {
guard let permissions = permissions else { return false }
return !permissions.filter { $0.tag == .streamBeginner }.isEmpty
}
public var canDownload: Bool {
guard let permissions = permissions else { return false }
return !permissions.filter { $0.tag == .download }.isEmpty
}
public var hasPermissionToUseApp: Bool {
canStreamPro || canStream || canDownload
}
// MARK: - Initializers
init?(dictionary: [String: String]) {
guard
let externalId = dictionary["external_id"],
let email = dictionary["email"],
let username = dictionary["username"],
let avatarURLString = dictionary["avatar_url"],
let avatarURL = URL(string: avatarURLString),
let name = dictionary["name"]?.replacingOccurrences(of: "+", with: " "),
let token = dictionary["token"]
else
{ return nil }
self.externalId = externalId
self.email = email
self.username = username
self.avatarURL = avatarURL
self.name = name
self.token = token
permissions = .none
}
private init(user: User, permissions: [Permission]) {
externalId = user.externalId
email = user.email
username = user.username
avatarURL = user.avatarURL
name = user.name
token = user.token
self.permissions = permissions
}
func with(permissions: [Permission]) -> User {
User(user: self, permissions: permissions)
}
}
| 35.63 | 82 | 0.712321 |
1e85b468d3671eb45495963847734aa63c3a0bde
| 3,626 |
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol b {
class func e()
}
struct c {
var d: b.Type
func e() {
d.e()
}
}
import Foun {
func j
var _ = j
}
}
class x {
s m
func j(m)
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
let u: v.l
}
protocol y {
o= p>(r: m<v>)
}
struct D : y {
s p = Int
func y<v k r {
s m
}
class y<D> {
w <r:
func j<v x: v) {
x.k()
}
func x(j: Int = a) {
}
let k = x
class j {
func y((Any, j))(v: (Any, AnyObject)) {
y(v)
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
({})
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
u n
}
y q<x> {
s w(x, () -> ())
}
o n {
func j() p
}
class r {
func s() -> p {
t ""
}
}
class w: r, n {
k v: ))] = []
}
class n<x : n>
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
func b<e>(e : e) -> c { e
struct j<l : o> {
k b: l
}
func a<l>() -> [j<l>] {
return []
}
f
k)
func f<l>() -> (l, l -> l) -> l {
l j l.n = {
}
{
l) {
n }
}
protocol f {
class func n()
}
class l: f{ class func n {}
func a<i>() {
b b {
l j
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
typealias l
typealias k
}
struct j<n : b> : b {
typealias l = n
typealias k = a<j<n>, l>
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func f(c: i, l: i) -> (((i, i) -> i) -> i) {
b {
(h -> i) d $k
}
let e: Int = 1, 1)
class g<j :g
func f<m>() -> (m, m -> m) -> m {
e c e.i = {
}}
func h<d {
enum h {
func e
var _ = e
}
}
protocol e {
e func e()
}
struct h {
var d: e.h
func e() {
d.e()
}
}
protocol f {
i []
}
func f<g>() -> (g, g -> g) -> g
func a<T>() {
enum b {
case c
}
}
)
func n<w>() -> (w, w -> w) -> w {
o m o.q = {
}
{
w) {
k }
}
protocol n {
class func q()
}
class o: n{ class func q {}
func p(e: Int = x) {
}
let c = p
c()
func r<o: y, s q n<s> ==(r(t))
protocol p : p {
}
protocol p {
class func c()
}
class e: p {
class func c() { }
}
(e() u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) {
func o() as o).m.k()
func p(k: b) -> <i>(() -> i) -> b {
n { o f "\(k): \(o())" }
}
struct d<d : n, o:j n {
l p
}
protocol o : o {
}
func o<
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
w
class x<u>: d {
l i: u
init(i: u) {
o.i = j {
r { w s "\(f): \(w())" }
}
protocol h {
q k {
t w
}
w
protocol k : w { func v <h: h m h.p == k>(l: h.p) {
}
}
protocol h {
n func w(w:
}
class h<u : h> {
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
func n<p>() -> (p, p -> p) -> p {
b, l]
g(o(q))
h e {
j class func r()
}
class k: h{ class func r {}
var k = 1
var s: r -> r t -> r) -> r m
u h>] {
u []
}
func r(e: () -> ()) {
}
class n {
var _ = r()
| 13.529851 | 87 | 0.402648 |
3897285ae7a361e5330c2c9b81d0c89fa35c800f
| 3,060 |
//
// Secp256k1Error.swift
// CITA
//
// Created by XiaoLu on 2019/4/2.
// Copyright © 2019 Cryptape. All rights reserved.
//
import Foundation
/// Errors for secp256k1
public enum Secp256k1Error: Error {
/// Signature failed
case signingFailed
/// Cannot verify private key
case invalidPrivateKey
/// Hash size should be 32 bytes long
case invalidHashSize
/// Private key size should be 32 bytes long
case invalidPrivateKeySize
/// Signature size should be 65 bytes long
case invalidSignatureSize
/// Public key size should be 65 bytes long
case invalidPublicKeySize
/// Printable / user displayable description
public var localizedDescription: String {
switch self {
case .signingFailed:
return "Signature failed"
case .invalidPrivateKey:
return "Cannot verify private key"
case .invalidHashSize:
return "Hash size should be 32 bytes long"
case .invalidPrivateKeySize:
return "Private key size should be 32 bytes long"
case .invalidSignatureSize:
return "Signature size should be 65 bytes long"
case .invalidPublicKeySize:
return "Public key size should be 65 bytes long"
}
}
}
public enum Secp256DataError: Error {
/// Cannot recover public key
case cannotRecoverPublicKey
/// Cannot extract public key from private key
case cannotExtractPublicKeyFromPrivateKey
/// Cannot make recoverable signature
case cannotMakeRecoverableSignature
/// Cannot parse signature
case cannotParseSignature
/// Cannot parse public key
case cannotParsePublicKey
/// Cannot serialize public key
case cannotSerializePublicKey
/// Cannot combine public keys
case cannotCombinePublicKeys
/// Cannot serialize signature
case cannotSerializeSignature
/// Signature corrupted
case signatureCorrupted
/// Invalid marshal signature size
case invalidMarshalSignatureSize
/// Printable / user displayable description
public var localizedDescription: String {
switch self {
case .cannotRecoverPublicKey:
return "Cannot recover public key"
case .cannotExtractPublicKeyFromPrivateKey:
return "Cannot extract public key from private key"
case .cannotMakeRecoverableSignature:
return "Cannot make recoverable signature"
case .cannotParseSignature:
return "Cannot parse signature"
case .cannotParsePublicKey:
return "Cannot parse public key"
case .cannotSerializePublicKey:
return "Cannot serialize public key"
case .cannotCombinePublicKeys:
return "Cannot combine public keys"
case .cannotSerializeSignature:
return "Cannot serialize signature"
case .signatureCorrupted:
return "Signature corrupted"
case .invalidMarshalSignatureSize:
return "Invalid marshal signature size"
}
}
}
| 33.626374 | 63 | 0.677124 |
8af68d2ab894a09b6b4ac96a64691df3e1a9acf3
| 408 |
//
// CuotasModuleLandingModels.swift
// Pods
//
// Copyright © 2018 Banco de Crédito e Inversiones. All rights reserved.
//
enum CuotasModuleLanding {
enum Basic {
struct Request { }
struct Response {
let title: String
let subtitle: String
}
struct ViewModel {
let title: String
let subtitle: String
}
}
}
| 18.545455 | 73 | 0.553922 |
1a8a7258e206339545f7cada3a59367a70c1d106
| 5,280 |
//
// WinkLoadingView.swift
// Pods
//
// Created by Botond Magyarosi on 11/02/2017.
//
//
import UIKit
private struct KeyPath {
static let rotate = "rotate"
static let smile = "smile"
static let wink = "wink"
}
@IBDesignable
public class WinkLoadingView: UIView {
// MARK: - Public attributes
/// The padding between the inner and outter circles.
@IBInspectable open var padding: CGFloat = 10
/// The line width of the inner outter circle.
@IBInspectable open var lineWidth: CGFloat = 8
/// The color of the layers.
@IBInspectable open var color: UIColor = UIColor.black
/// The duration of a phase of the animation. default is **1.5**
@IBInspectable open var duration: Double = 1.5
/// A timing function used for movement animations.
open var timingFunction = CAMediaTimingFunction(controlPoints: 0.6, 0.1, 0.4, 0.9)
/// This completion block gets called after finishLoading was called and the component finished animating.
open var animationCompletionHandler: (() -> Void)?
// MARK: - Properties
fileprivate var rightEye = CAShapeLayer()
fileprivate var leftEye = CAShapeLayer()
fileprivate var outterCircle = CAShapeLayer()
fileprivate var finished = false
// MARK: - UI
func initUI() {
let dotSize = min(bounds.size.width, bounds.size.height) / 2
let dotOffset = dotSize / 2
[leftEye, rightEye].forEach { eye in
eye.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: dotSize, height: dotSize)).cgPath
eye.frame = CGRect(x: dotOffset, y: dotOffset, width: dotSize, height: dotSize)
eye.anchorPoint = CGPoint(x: 0.5, y: 0.5)
eye.fillColor = color.cgColor
layer.addSublayer(eye)
}
let radius = dotSize / 2 + padding
let circleOffset = dotSize / 2 - padding
outterCircle.path = UIBezierPath(arcCenter: CGPoint(x: radius, y: radius), radius: radius, startAngle: -CGFloat.pi / 4, endAngle: -(3 * CGFloat.pi / 4), clockwise: false).cgPath
outterCircle.frame = CGRect(x: circleOffset, y: circleOffset, width: radius * 2, height: radius * 2)
outterCircle.anchorPoint = CGPoint(x: 0.5, y: 0.5)
outterCircle.lineWidth = lineWidth
outterCircle.strokeColor = color.cgColor
outterCircle.fillColor = nil
layer.addSublayer(outterCircle)
}
open func startLoading() {
initUI()
startSpinning()
}
open func finishLoading() {
finished = true
}
}
// MARK: - Animation phases
extension WinkLoadingView {
fileprivate func startSpinning() {
let anim = CABasicAnimation(keyPath: "transform.rotation.z")
anim.fromValue = 0
anim.toValue = -CGFloat.pi * 2
anim.duration = 1.5
anim.delegate = self
anim.timingFunction = timingFunction
anim.isRemovedOnCompletion = false
outterCircle.add(anim, forKey: KeyPath.rotate)
}
fileprivate func startSmileyTransition() {
let anim = CABasicAnimation(keyPath: "transform.rotation.z")
anim.fromValue = 0
anim.toValue = -CGFloat.pi
anim.duration = 0.7
anim.delegate = self
anim.timingFunction = timingFunction
anim.fillMode = CAMediaTimingFillMode.forwards
anim.isRemovedOnCompletion = false
outterCircle.add(anim, forKey: nil)
scale(layer: leftEye, to: 0.3, moveX: outterCircle.frame.minX + outterCircle.frame.width / 4, duration: 0.7, delegate: nil)
scale(layer: rightEye, to: 0.3, moveX: outterCircle.frame.maxX - outterCircle.frame.width / 4, duration: 0.7, delegate: self)
}
fileprivate func wink() {
let anim = CABasicAnimation(keyPath: "transform.scale.y")
anim.toValue = 0.2
anim.delegate = self
anim.autoreverses = true
anim.isRemovedOnCompletion = false
rightEye.add(anim, forKey: KeyPath.wink)
}
private func scale(layer: CALayer, to: CGFloat, moveX: CGFloat, duration: Double, delegate: CAAnimationDelegate?) {
let anim1 = CABasicAnimation(keyPath: "transform.scale")
anim1.fromValue = 1
anim1.toValue = to
let anim2 = CABasicAnimation(keyPath: "position.x")
anim2.toValue = moveX
let group = CAAnimationGroup()
group.animations = [anim1, anim2]
group.duration = duration
group.timingFunction = timingFunction
group.delegate = delegate
group.isRemovedOnCompletion = false
group.fillMode = CAMediaTimingFillMode.forwards
layer.add(group, forKey: KeyPath.smile)
}
}
// MARK: - CAAnimationDelegate
extension WinkLoadingView: CAAnimationDelegate {
// spinning -> smile -> wink
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if anim == outterCircle.animation(forKey: KeyPath.rotate) {
if finished {
startSmileyTransition()
} else {
startSpinning()
}
} else if anim == rightEye.animation(forKey: KeyPath.smile) {
wink()
} else if anim == rightEye.animation(forKey: KeyPath.wink) {
animationCompletionHandler?()
}
}
}
| 32.795031 | 185 | 0.641098 |
2277fe778301fac1918156b8201a02b170cf547b
| 595 |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct d<d: T) {
struct c: a {
class func a(Any) -> (Any) -> () -> {
}
struct c {
func n: b(c: Collection where B : e : Boolean)
func a<T> {
class a {
}
class A {
class func a<b: a {}
}
}
func b.s
| 25.869565 | 79 | 0.685714 |
23ba616799c8dbce216e4aa2c394c0e4593ab3ce
| 1,956 |
//
// KWGradientView.swift
// KWGradientView
//
// Created by Pavan Kotesh on 7/1/16.
// Copyright © 2016 KeepWorks. All rights reserved.
//
import UIKit
open class KWGradientView: UIView {
// MARK: - Lifecycle
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// You don't need to implement this
}
// MARK: - Open Methods
open func addGradientLayerAlongXAxis(colors: [UIColor]) -> CAGradientLayer {
let gradient = gradientFrom(colors: colors)
gradient.startPoint = CGPoint(x: 0.0, y: 0)
gradient.endPoint = CGPoint(x: 1.0, y: 0.0)
layer.insertSublayer(gradient, at: 0)
return gradient
}
open func addGradientLayerAlongYAxis(colors: [UIColor]) -> CAGradientLayer {
let gradient = gradientFrom(colors: colors)
gradient.startPoint = CGPoint(x: 0.0, y: 0)
gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
layer.insertSublayer(gradient, at: 0)
return gradient
}
open func addDiagonalGradient(colors: [UIColor]) -> CAGradientLayer {
let gradient = gradientFrom(colors: colors)
gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
layer.addSublayer(gradient)
return gradient
}
open func updateDiagonalGradient(_ layer: CAGradientLayer, colors: [UIColor]) {
UIView.animate(withDuration: 1, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: {
CATransaction.begin()
CATransaction.setAnimationDuration(1.0)
layer.colors = colors.map { (color) -> CGColor in
return color.cgColor
}
CATransaction.commit()
}, completion: nil)
}
// MARK: - Private Methods
private func gradientFrom(colors: [UIColor]) -> CAGradientLayer {
let gradientColors = colors.map { (color) -> CGColor in
return color.cgColor
}
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = gradientColors
return gradient
}
}
| 24.45 | 104 | 0.683538 |
bb66aafcf66b6d465cd1c80c5ef482c89160edae
| 206 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var f = [ T
( ) {
for {
class
case ,
| 20.6 | 87 | 0.718447 |
50b737f8c127c39598b2fbd2475d56afe949982f
| 6,123 |
import AST
/// A Val type that has been lowered to its VIL representation.
///
/// The type of an expression in Val purposely hide a number of implementation details that are
/// only relevant in the context of Val's low-level operational semantics. The most important
/// abstraction relates to the distinction between addressable and non-addressable values. The
/// former are stored in memory and can therefore be referenced by their address, whereas the
/// latter represent notional or temporary values.
///
/// Stored variables, properties and parameter references are represented by pointers to a phyiscal
/// storage internally. Hence, when lowered to VIL, these expressions must be associated with an
/// address type and must be loaded explicitly before being used as an actual value.
///
/// As Val does not have a first-class references, addressable values are not first-class neither:
/// the address of an address is not a legal value in VIL.
public class VILType: CustomStringConvertible {
/// The high level Val from which this type is lowered.
public final let valType: ValType
/// A flag that indicates whether the type is an address type.
public final let isAddress: Bool
/// A flag that indicates whether the type is an object type.
public final var isObject: Bool { !isAddress }
fileprivate init(valType: ValType, isAddress: Bool) {
self.valType = valType
self.isAddress = isAddress
}
/// The address variant of this type.
public var address: VILType {
return VILType(valType: valType, isAddress: true)
}
/// The object variant of this type.
public var object: VILType {
return VILType(valType: valType, isAddress: false)
}
/// Returns this vil type contextualized in the given environment.
///
/// - Parameters:
/// - env: A generic environment.
/// - useSite: The declaration space in which the type is being used.
public func contextualized(in env: GenericEnv, from useSite: DeclSpace) -> VILType {
let (contextualType, _) = env.contextualize(valType, from: useSite)
let vilType = VILType.lower(contextualType)
return isAddress
? vilType.address
: vilType.object
}
/// A flag that indicates whether the type is existential.
public var isExistential: Bool { valType.isExistential }
public var description: String {
var desc = String(describing: valType)
if desc.contains(" ") {
desc = "(\(desc))"
}
return isAddress ? "*\(desc)" : desc
}
static func lower(_ type: ValType) -> VILType {
switch type.dealiased {
case let valType as FunType:
// Lower each parameter and determine its passing convention.
var paramTypes: [VILType] = []
var paramConvs: [VILParamConv] = []
for valType in valType.paramTypeList {
paramTypes.append(lower(valType))
paramConvs.append(VILParamConv(for: valType))
}
// Lower the return type and determine its passing convention.
let retType = lower(valType.retType)
let retConv = VILParamConv(for: valType.retType)
// Create a VIL function type.
return VILFunType(
valType: valType,
paramTypes: paramTypes,
paramConvs: paramConvs,
retType: retType,
retConv: retConv)
case let valType as InoutType:
// Mutable parameters get an address type.
return VILType(valType: valType.base, isAddress: true)
case let valType:
return VILType(valType: valType, isAddress: false)
}
}
}
/// The type of a VIL function.
public final class VILFunType: VILType {
// The VIL type of each parameter.
public let paramTypes: [VILType]
/// The passing convention of the function's parameters.
public let paramConvs: [VILParamConv]
/// The VIL type of the function's return value.
public let retType: VILType
/// The passing convention of the function's return value.
public let retConv: VILParamConv
init(
valType: FunType,
paramTypes: [VILType],
paramConvs: [VILParamConv],
retType: VILType,
retConv: VILParamConv,
isAddress: Bool = false
) {
assert(paramTypes.count == paramConvs.count)
self.paramTypes = paramTypes
self.paramConvs = paramConvs
self.retType = retType
self.retConv = retConv
super.init(valType: valType, isAddress: isAddress)
}
/// The address variant of this type.
public override var address: VILType {
return VILFunType(
valType: valType as! FunType,
paramTypes: paramTypes,
paramConvs: paramConvs,
retType: retType,
retConv: retConv,
isAddress: true)
}
/// The object variant of this type.
public override var object: VILType {
return VILFunType(
valType: valType as! FunType,
paramTypes: paramTypes,
paramConvs: paramConvs,
retType: retType,
retConv: retConv,
isAddress: false)
}
public override var description: String {
var domain = "("
for i in 0 ..< paramTypes.count {
if i > 0 { domain.append(", ") }
domain += "@\(paramConvs[i]) \(paramTypes[i])"
}
domain += ")"
let codomain = "@\(retConv) \(retType)"
if isAddress {
return "*(\(domain) -> \(codomain))"
} else {
return "\(domain) -> \(codomain)"
}
}
}
/// The convention of a VIL parameter.
public enum VILParamConv {
/// The value is passed directly and must be consumed by the callee.
case owned
/// The value is passed directly and must *not* be consumed by the callee.
case localOwned
/// The value is passed indirectly, by reference.
///
/// The referenced value is initialized and may be aliased. Both the caller and the callee agree
/// not to mutate it for the duration of the call.
case borrowed
/// The value is passed indirectly, by reference.
///
/// The referenced value is initialized and unaliased. The caller must not to mutate it for the
/// duration of the call; the callee must not to consume it.
case mutating
public init(for type: ValType) {
switch type {
case is InoutType: self = .mutating
default: self = .owned
}
}
}
| 30.462687 | 99 | 0.681365 |
e202726ac8a49c27d18827f77b87f6513c369b68
| 7,981 |
//
// MyEOSWalletSDKSimpleWallet.swift
// MyEOSWallet SDK
//
// Created by Vitalii Havryliuk on 11/24/18.
// Copyright © 2018 Baltic International Group OU. All rights reserved.
//
import Foundation
public extension MyEOSWalletSDK {
public typealias LoginRequest = SimpleWallet.LoginRequest
public typealias TransferRequest = SimpleWallet.TransferRequest
public class SimpleWallet {
enum Action: String {
case login = "login"
case transfer = "transfer"
}
enum ProtocolName: String {
case myEOSWallet = "MyEOSWallet"
}
enum Result: Int {
case cancel = 0
case success = 1
case failure = 2
}
}
}
extension MyEOSWalletSDK.SimpleWallet {
public struct AppInfo {
public let name: String
public let iconUrl: String?
public let version: String?
public let description: String?
}
public struct LoginRequest: ToDictionaryConvertible {
private struct Keys {
static let appName = "dappName"
static let appIcon = "dappIcon"
static let appVersion = "version"
static let appDescription = "loginMemo"
static let loginUrl = "loginUrl"
static let action = "action"
static let `protocol` = "protocol"
static let uuID = "uuID"
static let callbackUrl = "callback"
}
public let appName: String
public let appIcon: String?
public let appVersion: String?
public let appDescription: String?
/// The unique id generated by dapp server for login verification.
/// Needed only for Simple Wallet protocol.
public let uuID: String
/// The url on dapp server to accept the login validation information
/// Needed only for Simple Wallet protocol.
public let loginUrl: String?
/// After user completes login, the wallet pulls up the callback URL of the app
public let callbackUrl: String?
public init(appName: String,
appIcon: String?,
appVersion: String?,
appDescription: String?,
uuID: String = "unset-uuid",
loginUrl: String? = nil,
callbackUrl: String? = nil) {
self.appName = appName.trimmed()
self.appIcon = appIcon?.trimmed()
self.appVersion = appVersion?.trimmed()
self.appDescription = appDescription?.trimmed()
self.uuID = uuID.trimmed()
self.loginUrl = loginUrl?.trimmed()
self.callbackUrl = callbackUrl?.trimmed()
}
public init(app: AppInfo,
uuID: String = "unset-uuid",
loginUrl: String? = nil,
callbackUrl: String? = nil) {
self.init(appName: app.name,
appIcon: app.iconUrl,
appVersion: app.version,
appDescription: app.description,
uuID: uuID,
loginUrl: loginUrl,
callbackUrl: callbackUrl)
}
func asDictionary() -> [String : Any?] {
return [
Keys.appName: appName,
Keys.appIcon: appIcon,
Keys.appVersion: appVersion,
Keys.appDescription: appDescription,
Keys.uuID: uuID,
Keys.loginUrl: loginUrl,
Keys.callbackUrl: callbackUrl,
Keys.action: Action.login.rawValue,
Keys.protocol: ProtocolName.myEOSWallet.rawValue
]
}
}
public struct TransferRequest: ToDictionaryConvertible {
private struct Keys {
static let appName = "dappName"
static let appIcon = "dappIcon"
static let appVersion = "version"
static let appDescription = "desc"
static let to = "to"
static let amount = "amount"
static let contract = "contract"
static let symbol = "symbol"
static let precision = "precision"
static let memo = "dappData"
static let action = "action"
static let `protocol` = "protocol"
static let callbackUrl = "callback"
}
public let appName: String
public let appIcon: String?
public let appVersion: String?
public let appDescription: String?
/// Recipient EOS account name
public let to: String
/// Transfer amount
public let amount: Decimal
/// Name of smart contract to be used by EOS transfer transaction
/// eosio.token for EOS transfers
public let contract: String
/// Token symbol
/// EOS for EOS transfers
public let symbol: String
/// Token precision
/// 4 for EOS Transfers
public let precision: UInt8
/// Transfer memo. DApp can send data needed for trading
public let memo: String?
/// After user completes transfer, the wallet pulls up the callback URL of the app
public let callbackUrl: String?
public init(appName: String,
appIcon: String?,
appVersion: String?,
appDescription: String?,
to: String,
amount: Decimal,
contract: String,
symbol: String,
precision: UInt8,
memo: String?,
callbackUrl: String? = nil) {
guard amount >= 0 else {
preconditionFailure("TransferRequest.init amount cannot be negative")
}
self.appName = appName.trimmed()
self.appIcon = appIcon?.trimmed()
self.appVersion = appVersion?.trimmed()
self.appDescription = appDescription?.trimmed()
self.to = to.trimmed()
self.amount = amount
self.contract = contract.trimmed()
self.symbol = symbol.trimmed()
self.precision = precision
self.memo = memo
self.callbackUrl = callbackUrl?.trimmed()
}
public init(app: AppInfo,
to: String,
amount: Decimal,
contract: String,
symbol: String,
precision: UInt8,
memo: String?,
callbackUrl: String? = nil) {
self.init(appName: app.name,
appIcon: app.iconUrl,
appVersion: app.version,
appDescription: app.description,
to: to,
amount: amount,
contract: contract,
symbol: symbol,
precision: precision,
memo: memo,
callbackUrl: callbackUrl)
}
func asDictionary() -> [String : Any?] {
return [
Keys.appName: appName,
Keys.appIcon: appIcon,
Keys.appVersion: appVersion,
Keys.appDescription: appDescription,
Keys.to: to,
Keys.amount: amount.description,
Keys.contract: contract,
Keys.symbol: symbol,
Keys.precision: precision,
Keys.memo: memo,
Keys.callbackUrl: callbackUrl,
Keys.action: Action.transfer.rawValue,
Keys.protocol: ProtocolName.myEOSWallet.rawValue
]
}
}
}
| 34.400862 | 90 | 0.513469 |
9b948a2b77a6bff87334d60e0d88bd1c11209527
| 423 |
//
// Project.swift
// Butt In The Chair
//
// Created by Yosemite Retail on 6/20/15.
// Copyright (c) 2015 Inked Voices. All rights reserved.
//
import UIKit
import CoreData
@objc(Project) class Project: NSManagedObject {
@NSManaged var username: String
@NSManaged var project_name: String
@NSManaged var data1:String
@NSManaged var data2: String
//you can have other attributes here
}
| 19.227273 | 57 | 0.690307 |
f5448186e751758b32bcc45f3954c5f8b65477ce
| 2,322 |
// (C) 2017-2020 - The Woorti app is a research (non-commercial) application that was
// developed in the context of the European research project MoTiV (motivproject.eu). The
// code was developed by partner INESC-ID with contributions in graphics design by partner
// TIS. The Woorti app development was one of the outcomes of a Work Package of the MoTiV
// project.
// The Woorti app was originally intended as a tool to support data collection regarding
// mobility patterns from city and country-wide campaigns and provide the data and user
// management to campaign managers.
// The Woorti app development followed an agile approach taking into account ongoing
// feedback of partners and testing users while continuing under development. This has
// been carried out as an iterative process deploying new app versions. Along the
// timeline, various previously unforeseen requirements were identified, some requirements
// Were revised, there were requests for modifications, extensions, or new aspects in
// functionality or interaction as found useful or interesting to campaign managers and
// other project partners. Most stemmed naturally from the very usage and ongoing testing
// of the Woorti app. Hence, code and data structures were successively revised in a
// way not only to accommodate this but, also importantly, to maintain compatibility with
// the functionality, data and data structures of previous versions of the app, as new
// version roll-out was never done from scratch.
// The code developed for the Woorti app is made available as open source, namely to
// contribute to further research in the area of the MoTiV project, and the app also makes
// use of open source components as detailed in the Woorti app license.
// This project has received funding from the European Union’s Horizon 2020 research and
// innovation programme under grant agreement No. 770145.
// This file is part of the Woorti app referred to as SOFTWARE.
import UIKit
class TubeTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 48.375 | 90 | 0.768303 |
4691e0bd8e65930984dbcc3301cee6fb2f3edcec
| 79,574 |
/*
Copyright (c) 2015, Apple Inc. All rights reserved.
Copyright (c) 2015-2016, Ricardo Sánchez-Sáez.
Copyright (c) 2017, Macro Yau.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import ResearchKit
import AudioToolbox
/**
Wraps a SystemSoundID.
A class is used in order to provide appropriate cleanup when the sound is
no longer needed.
*/
class SystemSound {
var soundID: SystemSoundID = 0
init?(soundURL: URL) {
if AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID) != noErr {
return nil
}
}
deinit {
AudioServicesDisposeSystemSoundID(soundID)
}
}
/**
An enum that corresponds to a row displayed in a `TaskListViewController`.
Each of the tasks is composed of one or more steps giving examples of the
types of functionality supported by the ResearchKit framework.
*/
enum TaskListRow: Int, CustomStringConvertible {
case form = 0
case survey
case booleanQuestion
case customBooleanQuestion
case dateQuestion
case dateTimeQuestion
case imageChoiceQuestion
case locationQuestion
case numericQuestion
case scaleQuestion
case textQuestion
case textChoiceQuestion
case timeIntervalQuestion
case timeOfDayQuestion
case valuePickerChoiceQuestion
case validatedTextQuestion
case imageCapture
case videoCapture
case wait
case eligibilityTask
case consent
case accountCreation
case login
case passcode
case audio
case fitness
case holePegTest
case psat
case reactionTime
case shortWalk
case spatialSpanMemory
case stroop
case timedWalk
case timedWalkWithTurnAround
case toneAudiometry
case towerOfHanoi
case tremorTest
case twoFingerTappingInterval
case walkBackAndForth
case heightQuestion
case weightQuestion
case kneeRangeOfMotion
case shoulderRangeOfMotion
case trailMaking
case videoInstruction
case webView
class TaskListRowSection {
var title: String
var rows: [TaskListRow]
init(title: String, rows: [TaskListRow]) {
self.title = title
self.rows = rows
}
}
/// Returns an array of all the task list row enum cases.
static var sections: [ TaskListRowSection ] {
return [
TaskListRowSection(title: "Surveys", rows:
[
.form,
.survey,
]),
TaskListRowSection(title: "Survey Questions", rows:
[
.booleanQuestion,
.customBooleanQuestion,
.dateQuestion,
.dateTimeQuestion,
.heightQuestion,
.weightQuestion,
.imageChoiceQuestion,
.locationQuestion,
.numericQuestion,
.scaleQuestion,
.textQuestion,
.textChoiceQuestion,
.timeIntervalQuestion,
.timeOfDayQuestion,
.valuePickerChoiceQuestion,
.validatedTextQuestion,
.imageCapture,
.videoCapture,
.wait,
]),
TaskListRowSection(title: "Onboarding", rows:
[
.eligibilityTask,
.consent,
.accountCreation,
.login,
.passcode,
]),
TaskListRowSection(title: "Active Tasks", rows:
[
.audio,
.fitness,
.holePegTest,
.psat,
.reactionTime,
.shortWalk,
.spatialSpanMemory,
.stroop,
.timedWalk,
.timedWalkWithTurnAround,
.toneAudiometry,
.towerOfHanoi,
.tremorTest,
.twoFingerTappingInterval,
.walkBackAndForth,
.kneeRangeOfMotion,
.shoulderRangeOfMotion,
.trailMaking
]),
TaskListRowSection(title: "Miscellaneous", rows:
[
.videoInstruction,
.webView
]),
]}
// MARK: CustomStringConvertible
var description: String {
switch self {
case .form:
return NSLocalizedString("Form Survey Example", comment: "")
case .survey:
return NSLocalizedString("Simple Survey Example", comment: "")
case .booleanQuestion:
return NSLocalizedString("Boolean Question", comment: "")
case .customBooleanQuestion:
return NSLocalizedString("Custom Boolean Question", comment: "")
case .dateQuestion:
return NSLocalizedString("Date Question", comment: "")
case .dateTimeQuestion:
return NSLocalizedString("Date and Time Question", comment: "")
case .heightQuestion:
return NSLocalizedString("Height Question", comment: "")
case .weightQuestion:
return NSLocalizedString("Weight Question", comment: "")
case .imageChoiceQuestion:
return NSLocalizedString("Image Choice Question", comment: "")
case .locationQuestion:
return NSLocalizedString("Location Question", comment: "")
case .numericQuestion:
return NSLocalizedString("Numeric Question", comment: "")
case .scaleQuestion:
return NSLocalizedString("Scale Question", comment: "")
case .textQuestion:
return NSLocalizedString("Text Question", comment: "")
case .textChoiceQuestion:
return NSLocalizedString("Text Choice Question", comment: "")
case .timeIntervalQuestion:
return NSLocalizedString("Time Interval Question", comment: "")
case .timeOfDayQuestion:
return NSLocalizedString("Time of Day Question", comment: "")
case .valuePickerChoiceQuestion:
return NSLocalizedString("Value Picker Choice Question", comment: "")
case .validatedTextQuestion:
return NSLocalizedString("Validated Text Question", comment: "")
case .imageCapture:
return NSLocalizedString("Image Capture Step", comment: "")
case .videoCapture:
return NSLocalizedString("Video Capture Step", comment: "")
case .wait:
return NSLocalizedString("Wait Step", comment: "")
case .eligibilityTask:
return NSLocalizedString("Eligibility Task Example", comment: "")
case .consent:
return NSLocalizedString("Consent-Obtaining Example", comment: "")
case .accountCreation:
return NSLocalizedString("Account Creation", comment: "")
case .login:
return NSLocalizedString("Login", comment: "")
case .passcode:
return NSLocalizedString("Passcode Creation", comment: "")
case .audio:
return NSLocalizedString("Audio", comment: "")
case .fitness:
return NSLocalizedString("Fitness Check", comment: "")
case .holePegTest:
return NSLocalizedString("Hole Peg Test", comment: "")
case .psat:
return NSLocalizedString("PSAT", comment: "")
case .reactionTime:
return NSLocalizedString("Reaction Time", comment: "")
case .shortWalk:
return NSLocalizedString("Short Walk", comment: "")
case .spatialSpanMemory:
return NSLocalizedString("Spatial Span Memory", comment: "")
case .stroop:
return NSLocalizedString("Stroop", comment: "")
case .timedWalk:
return NSLocalizedString("Timed Walk", comment: "")
case .timedWalkWithTurnAround:
return NSLocalizedString("Timed Walk with Turn Around", comment: "")
case .toneAudiometry:
return NSLocalizedString("Tone Audiometry", comment: "")
case .towerOfHanoi:
return NSLocalizedString("Tower of Hanoi", comment: "")
case .twoFingerTappingInterval:
return NSLocalizedString("Two Finger Tapping Interval", comment: "")
case .walkBackAndForth:
return NSLocalizedString("Walk Back and Forth", comment: "")
case .tremorTest:
return NSLocalizedString("Tremor Test", comment: "")
case .videoInstruction:
return NSLocalizedString("Video Instruction Task", comment: "")
case .kneeRangeOfMotion:
return NSLocalizedString("Knee Range of Motion", comment: "")
case .shoulderRangeOfMotion:
return NSLocalizedString("Shoulder Range of Motion", comment: "")
case .trailMaking:
return NSLocalizedString("Trail Making Test", comment: "")
case .webView:
return NSLocalizedString("Web View", comment: "")
}
}
// MARK: Types
/**
Every step and task in the ResearchKit framework has to have an identifier.
Within a task, the step identifiers should be unique.
Here we use an enum to ensure that the identifiers are kept unique. Since
the enum has a raw underlying type of a `String`, the compiler can determine
the uniqueness of the case values at compile time.
In a real application, the identifiers for your tasks and steps might
come from a database, or in a smaller application, might have some
human-readable meaning.
*/
private enum Identifier {
// Task with a form, where multiple items appear on one page.
case formTask
case formStep
case formItem01
case formItem02
case formItem03
// Survey task specific identifiers.
case surveyTask
case introStep
case questionStep
case summaryStep
// Task with a Boolean question.
case booleanQuestionTask
case booleanQuestionStep
// Task with an example of date entry.
case dateQuestionTask
case dateQuestionStep
// Task with an example of date and time entry.
case dateTimeQuestionTask
case dateTimeQuestionStep
// Task with an example of height entry.
case heightQuestionTask
case heightQuestionStep1
case heightQuestionStep2
case heightQuestionStep3
case heightQuestionStep4
// Task with an example of weight entry.
case weightQuestionTask
case weightQuestionStep1
case weightQuestionStep2
case weightQuestionStep3
case weightQuestionStep4
case weightQuestionStep5
case weightQuestionStep6
case weightQuestionStep7
// Task with an image choice question.
case imageChoiceQuestionTask
case imageChoiceQuestionStep1
case imageChoiceQuestionStep2
// Task with a location entry.
case locationQuestionTask
case locationQuestionStep
// Task with examples of numeric questions.
case numericQuestionTask
case numericQuestionStep
case numericNoUnitQuestionStep
// Task with examples of questions with sliding scales.
case scaleQuestionTask
case discreteScaleQuestionStep
case continuousScaleQuestionStep
case discreteVerticalScaleQuestionStep
case continuousVerticalScaleQuestionStep
case textScaleQuestionStep
case textVerticalScaleQuestionStep
// Task with an example of free text entry.
case textQuestionTask
case textQuestionStep
// Task with an example of a multiple choice question.
case textChoiceQuestionTask
case textChoiceQuestionStep
// Task with an example of time of day entry.
case timeOfDayQuestionTask
case timeOfDayQuestionStep
// Task with an example of time interval entry.
case timeIntervalQuestionTask
case timeIntervalQuestionStep
// Task with a value picker.
case valuePickerChoiceQuestionTask
case valuePickerChoiceQuestionStep
// Task with an example of validated text entry.
case validatedTextQuestionTask
case validatedTextQuestionStepEmail
case validatedTextQuestionStepDomain
// Image capture task specific identifiers.
case imageCaptureTask
case imageCaptureStep
// Video capture task specific identifiers.
case VideoCaptureTask
case VideoCaptureStep
// Task with an example of waiting.
case waitTask
case waitStepDeterminate
case waitStepIndeterminate
// Eligibility task specific indentifiers.
case eligibilityTask
case eligibilityIntroStep
case eligibilityFormStep
case eligibilityFormItem01
case eligibilityFormItem02
case eligibilityFormItem03
case eligibilityIneligibleStep
case eligibilityEligibleStep
// Consent task specific identifiers.
case consentTask
case visualConsentStep
case consentSharingStep
case consentReviewStep
case consentDocumentParticipantSignature
case consentDocumentInvestigatorSignature
// Account creation task specific identifiers.
case accountCreationTask
case registrationStep
case waitStep
case verificationStep
// Login task specific identifiers.
case loginTask
case loginStep
case loginWaitStep
// Passcode task specific identifiers.
case passcodeTask
case passcodeStep
// Active tasks.
case audioTask
case fitnessTask
case holePegTestTask
case psatTask
case reactionTime
case shortWalkTask
case spatialSpanMemoryTask
case stroopTask
case timedWalkTask
case timedWalkWithTurnAroundTask
case toneAudiometryTask
case towerOfHanoi
case tremorTestTask
case twoFingerTappingIntervalTask
case walkBackAndForthTask
case kneeRangeOfMotion
case shoulderRangeOfMotion
case trailMaking
// Video instruction tasks.
case videoInstructionTask
case videoInstructionStep
// Web view tasks.
case webViewTask
case webViewStep
}
// MARK: Properties
/// Returns a new `ORKTask` that the `TaskListRow` enumeration represents.
var representedTask: ORKTask {
switch self {
case .form:
return formTask
case .survey:
return surveyTask
case .booleanQuestion:
return booleanQuestionTask
case .customBooleanQuestion:
return customBooleanQuestionTask
case .dateQuestion:
return dateQuestionTask
case .dateTimeQuestion:
return dateTimeQuestionTask
case .heightQuestion:
return heightQuestionTask
case .weightQuestion:
return weightQuestionTask
case .imageChoiceQuestion:
return imageChoiceQuestionTask
case .locationQuestion:
return locationQuestionTask
case .numericQuestion:
return numericQuestionTask
case .scaleQuestion:
return scaleQuestionTask
case .textQuestion:
return textQuestionTask
case .textChoiceQuestion:
return textChoiceQuestionTask
case .timeIntervalQuestion:
return timeIntervalQuestionTask
case .timeOfDayQuestion:
return timeOfDayQuestionTask
case .valuePickerChoiceQuestion:
return valuePickerChoiceQuestionTask
case .validatedTextQuestion:
return validatedTextQuestionTask
case .imageCapture:
return imageCaptureTask
case .videoCapture:
return videoCaptureTask
case .wait:
return waitTask
case .eligibilityTask:
return eligibilityTask
case .consent:
return consentTask
case .accountCreation:
return accountCreationTask
case .login:
return loginTask
case .passcode:
return passcodeTask
case .audio:
return audioTask
case .fitness:
return fitnessTask
case .holePegTest:
return holePegTestTask
case .psat:
return PSATTask
case .reactionTime:
return reactionTimeTask
case .shortWalk:
return shortWalkTask
case .spatialSpanMemory:
return spatialSpanMemoryTask
case .stroop:
return stroopTask
case .timedWalk:
return timedWalkTask
case .timedWalkWithTurnAround:
return timedWalkWithTurnAroundTask
case .toneAudiometry:
return toneAudiometryTask
case .towerOfHanoi:
return towerOfHanoiTask
case .twoFingerTappingInterval:
return twoFingerTappingIntervalTask
case .walkBackAndForth:
return walkBackAndForthTask
case .tremorTest:
return tremorTestTask
case .kneeRangeOfMotion:
return kneeRangeOfMotion
case .shoulderRangeOfMotion:
return shoulderRangeOfMotion
case .trailMaking:
return trailMaking;
case .videoInstruction:
return videoInstruction
case .webView:
return webView
}
}
// MARK: Task Creation Convenience
/**
This task demonstrates a form step, in which multiple items are presented
in a single scrollable form. This might be used for entering multi-value
data, like taking a blood pressure reading with separate systolic and
diastolic values.
*/
private var formTask: ORKTask {
let step = ORKFormStep(identifier: String(describing:Identifier.formStep), title: exampleQuestionText, text: exampleDetailText)
// A first field, for entering an integer.
let formItem01Text = NSLocalizedString("Field01", comment: "")
let formItem01 = ORKFormItem(identifier: String(describing:Identifier.formItem01), text: formItem01Text, answerFormat: ORKAnswerFormat.integerAnswerFormat(withUnit: nil))
formItem01.placeholder = NSLocalizedString("Your placeholder here", comment: "")
// A second field, for entering a time interval.
let formItem02Text = NSLocalizedString("Field02", comment: "")
let formItem02 = ORKFormItem(identifier: String(describing:Identifier.formItem02), text: formItem02Text, answerFormat: ORKTimeIntervalAnswerFormat())
formItem02.placeholder = NSLocalizedString("Your placeholder here", comment: "")
step.formItems = [
formItem01,
formItem02
]
return ORKOrderedTask(identifier: String(describing:Identifier.formTask), steps: [step])
}
/**
A task demonstrating how the ResearchKit framework can be used to present a simple
survey with an introduction, a question, and a conclusion.
*/
private var surveyTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(describing:Identifier.introStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
// Add a question step.
let questionStepAnswerFormat = ORKBooleanAnswerFormat()
let questionStepTitle = NSLocalizedString("Would you like to subscribe to our newsletter?", comment: "")
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.questionStep), title: questionStepTitle, answer: questionStepAnswerFormat)
// Add a summary step.
let summaryStep = ORKInstructionStep(identifier: String(describing:Identifier.summaryStep))
summaryStep.title = NSLocalizedString("Thanks", comment: "")
summaryStep.text = NSLocalizedString("Thank you for participating in this sample survey.", comment: "")
return ORKOrderedTask(identifier: String(describing:Identifier.surveyTask), steps: [
instructionStep,
questionStep,
summaryStep
])
}
/// This task presents just a single "Yes" / "No" question.
private var booleanQuestionTask: ORKTask {
let answerFormat = ORKBooleanAnswerFormat()
// We attach an answer format to a question step to specify what controls the user sees.
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.booleanQuestionStep), title: exampleQuestionText, answer: answerFormat)
// The detail text is shown in a small font below the title.
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.booleanQuestionTask), steps: [questionStep])
}
/// This task presents a customized "Yes" / "No" question.
private var customBooleanQuestionTask: ORKTask {
let answerFormat = ORKBooleanAnswerFormat(yesString: "Agree", noString: "Disagree")
// We attach an answer format to a question step to specify what controls the user sees.
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.booleanQuestionStep), title: exampleQuestionText, answer: answerFormat)
// The detail text is shown in a small font below the title.
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.booleanQuestionTask), steps: [questionStep])
}
/// This task demonstrates a question which asks for a date.
private var dateQuestionTask: ORKTask {
/*
The date answer format can also support minimum and maximum limits,
a specific default value, and overriding the calendar to use.
*/
let answerFormat = ORKAnswerFormat.dateAnswerFormat()
let step = ORKQuestionStep(identifier: String(describing:Identifier.dateQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.dateQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for a date and time of an event.
private var dateTimeQuestionTask: ORKTask {
/*
This uses the default calendar. Use a more detailed constructor to
set minimum / maximum limits.
*/
let answerFormat = ORKAnswerFormat.dateTime()
let step = ORKQuestionStep(identifier: String(describing:Identifier.dateTimeQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.dateTimeQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for the user height.
private var heightQuestionTask: ORKTask {
let answerFormat1 = ORKAnswerFormat.heightAnswerFormat()
let step1 = ORKQuestionStep(identifier: String(describing:Identifier.heightQuestionStep1), title: "Height", answer: answerFormat1)
step1.text = "Local system"
let answerFormat2 = ORKAnswerFormat.heightAnswerFormat(with: ORKMeasurementSystem.metric)
let step2 = ORKQuestionStep(identifier: String(describing:Identifier.heightQuestionStep2), title: "Height", answer: answerFormat2)
step2.text = "Metric system"
let answerFormat3 = ORKAnswerFormat.heightAnswerFormat(with: ORKMeasurementSystem.USC)
let step3 = ORKQuestionStep(identifier: String(describing:Identifier.heightQuestionStep3), title: "Height", answer: answerFormat3)
step3.text = "USC system"
let answerFormat4 = ORKHealthKitQuantityTypeAnswerFormat(quantityType: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!, unit: HKUnit.meterUnit(with: .centi), style: .decimal)
let step4 = ORKQuestionStep(identifier: String(describing:Identifier.heightQuestionStep4), title: "Height", answer: answerFormat4)
step4.text = "HealthKit, height"
return ORKOrderedTask(identifier: String(describing:Identifier.heightQuestionTask), steps: [step1, step2, step3, step4])
}
/// This task demonstrates a question asking for the user weight.
private var weightQuestionTask: ORKTask {
let answerFormat1 = ORKAnswerFormat.weightAnswerFormat()
let step1 = ORKQuestionStep(identifier: String(describing:Identifier.weightQuestionStep1), title: "Weight", answer: answerFormat1)
step1.text = "Local system, default precision"
let answerFormat2 = ORKAnswerFormat.weightAnswerFormat(with: ORKMeasurementSystem.metric)
let step2 = ORKQuestionStep(identifier: String(describing:Identifier.weightQuestionStep2), title: "Weight", answer: answerFormat2)
step2.text = "Metric system, default precision"
let answerFormat3 = ORKAnswerFormat.weightAnswerFormat(with: ORKMeasurementSystem.metric, numericPrecision: ORKNumericPrecision.low, minimumValue: ORKDoubleDefaultValue, maximumValue: ORKDoubleDefaultValue, defaultValue: ORKDoubleDefaultValue)
let step3 = ORKQuestionStep(identifier: String(describing:Identifier.weightQuestionStep3), title: "Weight", answer: answerFormat3)
step3.text = "Metric system, low precision"
let answerFormat4 = ORKAnswerFormat.weightAnswerFormat(with: ORKMeasurementSystem.metric, numericPrecision: ORKNumericPrecision.high, minimumValue: 20.0, maximumValue: 100.0, defaultValue: 45.50)
let step4 = ORKQuestionStep(identifier: String(describing:Identifier.weightQuestionStep4), title: "Weight", answer: answerFormat4)
step4.text = "Metric system, high precision"
let answerFormat5 = ORKAnswerFormat.weightAnswerFormat(with: ORKMeasurementSystem.USC)
let step5 = ORKQuestionStep(identifier: String(describing:Identifier.weightQuestionStep5), title: "Weight", answer: answerFormat5)
step5.text = "USC system, default precision"
let answerFormat6 = ORKAnswerFormat.weightAnswerFormat(with: ORKMeasurementSystem.USC, numericPrecision: ORKNumericPrecision.high, minimumValue: 50.0, maximumValue: 150.0, defaultValue: 100.0)
let step6 = ORKQuestionStep(identifier: String(describing:Identifier.weightQuestionStep6), title: "Weight", answer: answerFormat6)
step6.text = "USC system, high precision"
let answerFormat7 = ORKHealthKitQuantityTypeAnswerFormat(quantityType: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!, unit: HKUnit.gramUnit(with: .kilo), style: .decimal)
let step7 = ORKQuestionStep(identifier: String(describing:Identifier.weightQuestionStep7), title: "Weight", answer: answerFormat7)
step7.text = "HealthKit, body mass"
return ORKOrderedTask(identifier: String(describing:Identifier.weightQuestionTask), steps: [step1, step2, step3, step4, step5, step6, step7])
}
/**
This task demonstrates a survey question involving picking from a series of
image choices. A more realistic applciation of this type of question might be to
use a range of icons for faces ranging from happy to sad.
*/
private var imageChoiceQuestionTask: ORKTask {
let roundShapeImage = UIImage(named: "round_shape")!
let roundShapeText = NSLocalizedString("Round Shape", comment: "")
let squareShapeImage = UIImage(named: "square_shape")!
let squareShapeText = NSLocalizedString("Square Shape", comment: "")
let imageChoces = [
ORKImageChoice(normalImage: roundShapeImage, selectedImage: nil, text: roundShapeText, value: roundShapeText as NSCoding & NSCopying & NSObjectProtocol),
ORKImageChoice(normalImage: squareShapeImage, selectedImage: nil, text: squareShapeText, value: squareShapeText as NSCoding & NSCopying & NSObjectProtocol)
]
let answerFormat1 = ORKAnswerFormat.choiceAnswerFormat(with: imageChoces)
let questionStep1 = ORKQuestionStep(identifier: String(describing:Identifier.imageChoiceQuestionStep1), title: exampleQuestionText, answer: answerFormat1)
questionStep1.text = exampleDetailText
let answerFormat2 = ORKAnswerFormat.choiceAnswerFormat(with: imageChoces, style: .singleChoice, vertical: true)
let questionStep2 = ORKQuestionStep(identifier: String(describing:Identifier.imageChoiceQuestionStep2), title: exampleQuestionText, answer: answerFormat2)
questionStep2.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.imageChoiceQuestionTask), steps: [questionStep1, questionStep2])
}
/// This task presents just a single location question.
private var locationQuestionTask: ORKTask {
let answerFormat = ORKLocationAnswerFormat()
// We attach an answer format to a question step to specify what controls the user sees.
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.locationQuestionStep), title: exampleQuestionText, answer: answerFormat)
// The detail text is shown in a small font below the title.
questionStep.text = exampleDetailText
questionStep.placeholder = NSLocalizedString("Address", comment: "");
return ORKOrderedTask(identifier: String(describing:Identifier.locationQuestionTask), steps: [questionStep])
}
/**
This task demonstrates use of numeric questions with and without units.
Note that the unit is just a string, prompting the user to enter the value
in the expected unit. The unit string propagates into the result object.
*/
private var numericQuestionTask: ORKTask {
// This answer format will display a unit in-line with the numeric entry field.
let localizedQuestionStep1AnswerFormatUnit = NSLocalizedString("Your unit", comment: "")
let questionStep1AnswerFormat = ORKAnswerFormat.decimalAnswerFormat(withUnit: localizedQuestionStep1AnswerFormatUnit)
let questionStep1 = ORKQuestionStep(identifier: String(describing:Identifier.numericQuestionStep), title: exampleQuestionText, answer: questionStep1AnswerFormat)
questionStep1.text = exampleDetailText
questionStep1.placeholder = NSLocalizedString("Your placeholder.", comment: "")
// This answer format is similar to the previous one, but this time without displaying a unit.
let questionStep2 = ORKQuestionStep(identifier: String(describing:Identifier.numericNoUnitQuestionStep), title: exampleQuestionText, answer: ORKAnswerFormat.decimalAnswerFormat(withUnit: nil))
questionStep2.text = exampleDetailText
questionStep2.placeholder = NSLocalizedString("Placeholder without unit.", comment: "")
return ORKOrderedTask(identifier: String(describing:Identifier.numericQuestionTask), steps: [
questionStep1,
questionStep2
])
}
/// This task presents two options for questions displaying a scale control.
private var scaleQuestionTask: ORKTask {
// The first step is a scale control with 10 discrete ticks.
let step1AnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: false, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText)
let questionStep1 = ORKQuestionStep(identifier: String(describing:Identifier.discreteScaleQuestionStep), title: exampleQuestionText, answer: step1AnswerFormat)
questionStep1.text = exampleDetailText
// The second step is a scale control that allows continuous movement with a percent formatter.
let step2AnswerFormat = ORKAnswerFormat.continuousScale(withMaximumValue: 1.0, minimumValue: 0.0, defaultValue: 99.0, maximumFractionDigits: 0, vertical: false, maximumValueDescription: nil, minimumValueDescription: nil)
step2AnswerFormat.numberStyle = .percent
let questionStep2 = ORKQuestionStep(identifier: String(describing:Identifier.continuousScaleQuestionStep), title: exampleQuestionText, answer: step2AnswerFormat)
questionStep2.text = exampleDetailText
// The third step is a vertical scale control with 10 discrete ticks.
let step3AnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: true, maximumValueDescription: nil, minimumValueDescription: nil)
let questionStep3 = ORKQuestionStep(identifier: String(describing:Identifier.discreteVerticalScaleQuestionStep), title: exampleQuestionText, answer: step3AnswerFormat)
questionStep3.text = exampleDetailText
// The fourth step is a vertical scale control that allows continuous movement.
let step4AnswerFormat = ORKAnswerFormat.continuousScale(withMaximumValue: 5.0, minimumValue: 1.0, defaultValue: 99.0, maximumFractionDigits: 2, vertical: true, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText)
let questionStep4 = ORKQuestionStep(identifier: String(describing:Identifier.continuousVerticalScaleQuestionStep), title: exampleQuestionText, answer: step4AnswerFormat)
questionStep4.text = exampleDetailText
// The fifth step is a scale control that allows text choices.
let textChoices : [ORKTextChoice] = [ORKTextChoice(text: "Poor", value: 1 as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "Fair", value: 2 as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "Good", value: 3 as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "Above Average", value: 10 as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "Excellent", value: 5 as NSCoding & NSCopying & NSObjectProtocol)]
let step5AnswerFormat = ORKAnswerFormat.textScale(with: textChoices, defaultIndex: NSIntegerMax, vertical: false)
let questionStep5 = ORKQuestionStep(identifier: String(describing:Identifier.textScaleQuestionStep), title: exampleQuestionText, answer: step5AnswerFormat)
questionStep5.text = exampleDetailText
// The sixth step is a vertical scale control that allows text choices.
let step6AnswerFormat = ORKAnswerFormat.textScale(with: textChoices, defaultIndex: NSIntegerMax, vertical: true)
let questionStep6 = ORKQuestionStep(identifier: String(describing:Identifier.textVerticalScaleQuestionStep), title: exampleQuestionText, answer: step6AnswerFormat)
questionStep6.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.scaleQuestionTask), steps: [
questionStep1,
questionStep2,
questionStep3,
questionStep4,
questionStep5,
questionStep6
])
}
/**
This task demonstrates asking for text entry. Both single and multi-line
text entry are supported, with appropriate parameters to the text answer
format.
*/
private var textQuestionTask: ORKTask {
let answerFormat = ORKAnswerFormat.textAnswerFormat()
let step = ORKQuestionStep(identifier: String(describing:Identifier.textQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.textQuestionTask), steps: [step])
}
/**
This task demonstrates a survey question for picking from a list of text
choices. In this case, the text choices are presented in a table view
(compare with the `valuePickerQuestionTask`).
*/
private var textChoiceQuestionTask: ORKTask {
let textChoiceOneText = NSLocalizedString("Choice 1", comment: "")
let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "")
let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "")
// The text to display can be separate from the value coded for each choice:
let textChoices = [
ORKTextChoice(text: textChoiceOneText, value: "choice_1" as NSCoding & NSCopying & NSObjectProtocol),
ORKTextChoice(text: textChoiceTwoText, value: "choice_2" as NSCoding & NSCopying & NSObjectProtocol),
ORKTextChoice(text: textChoiceThreeText, value: "choice_3" as NSCoding & NSCopying & NSObjectProtocol)
]
let answerFormat = ORKAnswerFormat.choiceAnswerFormat(with: .singleChoice, textChoices: textChoices)
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.textChoiceQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.textChoiceQuestionTask), steps: [questionStep])
}
/**
This task demonstrates requesting a time interval. For example, this might
be a suitable answer format for a question like "How long is your morning
commute?"
*/
private var timeIntervalQuestionTask: ORKTask {
/*
The time interval answer format is constrained to entering a time
less than 24 hours and in steps of minutes. For times that don't fit
these restrictions, use another mode of data entry.
*/
let answerFormat = ORKAnswerFormat.timeIntervalAnswerFormat()
let step = ORKQuestionStep(identifier: String(describing:Identifier.timeIntervalQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.timeIntervalQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for a time of day.
private var timeOfDayQuestionTask: ORKTask {
/*
Because we don't specify a default, the picker will default to the
time the step is presented. For questions like "What time do you have
breakfast?", it would make sense to set the default on the answer
format.
*/
let answerFormat = ORKAnswerFormat.timeOfDayAnswerFormat()
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.timeOfDayQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.timeOfDayQuestionTask), steps: [questionStep])
}
/**
This task demonstrates a survey question using a value picker wheel.
Compare with the `textChoiceQuestionTask` and `imageChoiceQuestionTask`
which can serve a similar purpose.
*/
private var valuePickerChoiceQuestionTask: ORKTask {
let textChoiceOneText = NSLocalizedString("Choice 1", comment: "")
let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "")
let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "")
// The text to display can be separate from the value coded for each choice:
let textChoices = [
ORKTextChoice(text: textChoiceOneText, value: "choice_1" as NSCoding & NSCopying & NSObjectProtocol),
ORKTextChoice(text: textChoiceTwoText, value: "choice_2" as NSCoding & NSCopying & NSObjectProtocol),
ORKTextChoice(text: textChoiceThreeText, value: "choice_3" as NSCoding & NSCopying & NSObjectProtocol)
]
let answerFormat = ORKAnswerFormat.valuePickerAnswerFormat(with: textChoices)
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.valuePickerChoiceQuestionStep), title: exampleQuestionText,
answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.valuePickerChoiceQuestionTask), steps: [questionStep])
}
/**
This task demonstrates asking for text entry. Both single and multi-line
text entry are supported, with appropriate parameters to the text answer
format.
*/
private var validatedTextQuestionTask: ORKTask {
let answerFormatEmail = ORKAnswerFormat.emailAnswerFormat()
let stepEmail = ORKQuestionStep(identifier: String(describing:Identifier.validatedTextQuestionStepEmail), title: NSLocalizedString("Email", comment: ""), answer: answerFormatEmail)
stepEmail.text = exampleDetailText
let domainRegularExpressionPattern = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
let domainRegularExpression = try! NSRegularExpression(pattern: domainRegularExpressionPattern)
let answerFormatDomain = ORKAnswerFormat.textAnswerFormat(withValidationRegularExpression: domainRegularExpression, invalidMessage:"Invalid URL: %@")
answerFormatDomain.multipleLines = false
answerFormatDomain.keyboardType = .URL
answerFormatDomain.autocapitalizationType = UITextAutocapitalizationType.none
answerFormatDomain.autocorrectionType = UITextAutocorrectionType.no
answerFormatDomain.spellCheckingType = UITextSpellCheckingType.no
let stepDomain = ORKQuestionStep(identifier: String(describing:Identifier.validatedTextQuestionStepDomain), title: NSLocalizedString("URL", comment: ""), answer: answerFormatDomain)
stepDomain.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.validatedTextQuestionTask), steps: [stepEmail, stepDomain])
}
/// This task presents the image capture step in an ordered task.
private var imageCaptureTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(describing:Identifier.introStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
let handSolidImage = UIImage(named: "hand_solid")!
instructionStep.image = handSolidImage.withRenderingMode(.alwaysTemplate)
let imageCaptureStep = ORKImageCaptureStep(identifier: String(describing:Identifier.imageCaptureStep))
imageCaptureStep.isOptional = false
imageCaptureStep.accessibilityInstructions = NSLocalizedString("Your instructions for capturing the image", comment: "")
imageCaptureStep.accessibilityHint = NSLocalizedString("Captures the image visible in the preview", comment: "")
imageCaptureStep.templateImage = UIImage(named: "hand_outline_big")!
imageCaptureStep.templateImageInsets = UIEdgeInsets(top: 0.05, left: 0.05, bottom: 0.05, right: 0.05)
return ORKOrderedTask(identifier: String(describing:Identifier.imageCaptureTask), steps: [
instructionStep,
imageCaptureStep
])
}
/// This task presents the video capture step in an ordered task.
private var videoCaptureTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(describing:Identifier.introStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
let handSolidImage = UIImage(named: "hand_solid")!
instructionStep.image = handSolidImage.withRenderingMode(.alwaysTemplate)
let videoCaptureStep = ORKVideoCaptureStep(identifier: String(describing:Identifier.VideoCaptureStep))
videoCaptureStep.accessibilityInstructions = NSLocalizedString("Your instructions for capturing the video", comment: "")
videoCaptureStep.accessibilityHint = NSLocalizedString("Captures the video visible in the preview", comment: "")
videoCaptureStep.templateImage = UIImage(named: "hand_outline_big")!
videoCaptureStep.templateImageInsets = UIEdgeInsets(top: 0.05, left: 0.05, bottom: 0.05, right: 0.05)
videoCaptureStep.duration = 30.0; // 30 seconds
return ORKOrderedTask(identifier: String(describing:Identifier.VideoCaptureTask), steps: [
instructionStep,
videoCaptureStep
])
}
/// This task presents a wait task.
private var waitTask: ORKTask {
let waitStepIndeterminate = ORKWaitStep(identifier: String(describing:Identifier.waitStepIndeterminate))
waitStepIndeterminate.title = exampleQuestionText
waitStepIndeterminate.text = exampleDescription
waitStepIndeterminate.indicatorType = ORKProgressIndicatorType.indeterminate
let waitStepDeterminate = ORKWaitStep(identifier: String(describing:Identifier.waitStepDeterminate))
waitStepDeterminate.title = exampleQuestionText
waitStepDeterminate.text = exampleDescription
waitStepDeterminate.indicatorType = ORKProgressIndicatorType.progressBar
return ORKOrderedTask(identifier: String(describing:Identifier.waitTask), steps: [waitStepIndeterminate, waitStepDeterminate])
}
/**
A task demonstrating how the ResearchKit framework can be used to determine
eligibility using a navigable ordered task.
*/
private var eligibilityTask: ORKTask {
// Intro step
let introStep = ORKInstructionStep(identifier: String(describing:Identifier.eligibilityIntroStep))
introStep.title = NSLocalizedString("Eligibility Task Example", comment: "")
// Form step
let formStep = ORKFormStep(identifier: String(describing:Identifier.eligibilityFormStep))
formStep.title = NSLocalizedString("Eligibility", comment: "")
formStep.text = exampleQuestionText
formStep.isOptional = false
// Form items
let textChoices : [ORKTextChoice] = [ORKTextChoice(text: "Yes", value: "Yes" as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "No", value: "No" as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "N/A", value: "N/A" as NSCoding & NSCopying & NSObjectProtocol)]
let answerFormat = ORKTextChoiceAnswerFormat(style: ORKChoiceAnswerStyle.singleChoice, textChoices: textChoices)
let formItem01 = ORKFormItem(identifier: String(describing:Identifier.eligibilityFormItem01), text: exampleQuestionText, answerFormat: answerFormat)
formItem01.isOptional = false
let formItem02 = ORKFormItem(identifier: String(describing:Identifier.eligibilityFormItem02), text: exampleQuestionText, answerFormat: answerFormat)
formItem02.isOptional = false
let formItem03 = ORKFormItem(identifier: String(describing:Identifier.eligibilityFormItem03), text: exampleQuestionText, answerFormat: answerFormat)
formItem03.isOptional = false
formStep.formItems = [
formItem01,
formItem02,
formItem03
]
// Ineligible step
let ineligibleStep = ORKInstructionStep(identifier: String(describing:Identifier.eligibilityIneligibleStep))
ineligibleStep.title = NSLocalizedString("You are ineligible to join the study", comment: "")
// Eligible step
let eligibleStep = ORKCompletionStep(identifier: String(describing:Identifier.eligibilityEligibleStep))
eligibleStep.title = NSLocalizedString("You are eligible to join the study", comment: "")
// Create the task
let eligibilityTask = ORKNavigableOrderedTask(identifier: String(describing:Identifier.eligibilityTask), steps: [
introStep,
formStep,
ineligibleStep,
eligibleStep
])
// Build navigation rules.
var resultSelector = ORKResultSelector(stepIdentifier: String(describing:Identifier.eligibilityFormStep), resultIdentifier: String(describing:Identifier.eligibilityFormItem01))
let predicateFormItem01 = ORKResultPredicate.predicateForChoiceQuestionResult(with: resultSelector, expectedAnswerValue: "Yes" as NSCoding & NSCopying & NSObjectProtocol)
resultSelector = ORKResultSelector(stepIdentifier: String(describing:Identifier.eligibilityFormStep), resultIdentifier: String(describing:Identifier.eligibilityFormItem02))
let predicateFormItem02 = ORKResultPredicate.predicateForChoiceQuestionResult(with: resultSelector, expectedAnswerValue: "Yes" as NSCoding & NSCopying & NSObjectProtocol)
resultSelector = ORKResultSelector(stepIdentifier: String(describing:Identifier.eligibilityFormStep), resultIdentifier: String(describing:Identifier.eligibilityFormItem03))
let predicateFormItem03 = ORKResultPredicate.predicateForChoiceQuestionResult(with: resultSelector, expectedAnswerValue: "No" as NSCoding & NSCopying & NSObjectProtocol)
let predicateEligible = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateFormItem01, predicateFormItem02, predicateFormItem03])
let predicateRule = ORKPredicateStepNavigationRule(resultPredicatesAndDestinationStepIdentifiers: [ (predicateEligible, String(describing:Identifier.eligibilityEligibleStep)) ])
eligibilityTask.setNavigationRule(predicateRule, forTriggerStepIdentifier:String(describing:Identifier.eligibilityFormStep))
// Add end direct rules to skip unneeded steps
let directRule = ORKDirectStepNavigationRule(destinationStepIdentifier: ORKNullStepIdentifier)
eligibilityTask.setNavigationRule(directRule, forTriggerStepIdentifier:String(describing:Identifier.eligibilityIneligibleStep))
return eligibilityTask
}
/// A task demonstrating how the ResearchKit framework can be used to obtain informed consent.
private var consentTask: ORKTask {
/*
Informed consent starts by presenting an animated sequence conveying
the main points of your consent document.
*/
let visualConsentStep = ORKVisualConsentStep(identifier: String(describing:Identifier.visualConsentStep), document: consentDocument)
let investigatorShortDescription = NSLocalizedString("Institution", comment: "")
let investigatorLongDescription = NSLocalizedString("Institution and its partners", comment: "")
let localizedLearnMoreHTMLContent = NSLocalizedString("Your sharing learn more content here.", comment: "")
/*
If you want to share the data you collect with other researchers for
use in other studies beyond this one, it is best practice to get
explicit permission from the participant. Use the consent sharing step
for this.
*/
let sharingConsentStep = ORKConsentSharingStep(identifier: String(describing:Identifier.consentSharingStep), investigatorShortDescription: investigatorShortDescription, investigatorLongDescription: investigatorLongDescription, localizedLearnMoreHTMLContent: localizedLearnMoreHTMLContent)
/*
After the visual presentation, the consent review step displays
your consent document and can obtain a signature from the participant.
The first signature in the document is the participant's signature.
This effectively tells the consent review step which signatory is
reviewing the document.
*/
let signature = consentDocument.signatures!.first
let reviewConsentStep = ORKConsentReviewStep(identifier: String(describing:Identifier.consentReviewStep), signature: signature, in: consentDocument)
// In a real application, you would supply your own localized text.
reviewConsentStep.text = loremIpsumText
reviewConsentStep.reasonForConsent = loremIpsumText
return ORKOrderedTask(identifier: String(describing:Identifier.consentTask), steps: [
visualConsentStep,
sharingConsentStep,
reviewConsentStep
])
}
/// This task presents the Account Creation process.
private var accountCreationTask: ORKTask {
/*
A registration step provides a form step that is populated with email and password fields.
If you wish to include any of the additional fields, then you can specify it through the `options` parameter.
*/
let registrationTitle = NSLocalizedString("Registration", comment: "")
let passcodeValidationRegularExpressionPattern = "^(?=.*\\d).{4,8}$"
let passcodeValidationRegularExpression = try! NSRegularExpression(pattern: passcodeValidationRegularExpressionPattern)
let passcodeInvalidMessage = NSLocalizedString("A valid password must be 4 and 8 digits long and include at least one numeric character.", comment: "")
let registrationOptions: ORKRegistrationStepOption = [.includeGivenName, .includeFamilyName, .includeGender, .includeDOB]
let registrationStep = ORKRegistrationStep(identifier: String(describing:Identifier.registrationStep), title: registrationTitle, text: exampleDetailText, passcodeValidationRegularExpression: passcodeValidationRegularExpression, passcodeInvalidMessage: passcodeInvalidMessage, options: registrationOptions)
/*
A wait step allows you to upload the data from the user registration onto your server before presenting the verification step.
*/
let waitTitle = NSLocalizedString("Creating account", comment: "")
let waitText = NSLocalizedString("Please wait while we upload your data", comment: "")
let waitStep = ORKWaitStep(identifier: String(describing:Identifier.waitStep))
waitStep.title = waitTitle
waitStep.text = waitText
/*
A verification step view controller subclass is required in order to use the verification step.
The subclass provides the view controller button and UI behavior by overriding the following methods.
*/
class VerificationViewController : ORKVerificationStepViewController {
override func resendEmailButtonTapped() {
let alertTitle = NSLocalizedString("Resend Verification Email", comment: "")
let alertMessage = NSLocalizedString("Button tapped", comment: "")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
let verificationStep = ORKVerificationStep(identifier: String(describing:Identifier.verificationStep), text: exampleDetailText, verificationViewControllerClass: VerificationViewController.self)
return ORKOrderedTask(identifier: String(describing:Identifier.accountCreationTask), steps: [
registrationStep,
waitStep,
verificationStep
])
}
/// This tasks presents the login step.
private var loginTask: ORKTask {
/*
A login step view controller subclass is required in order to use the login step.
The subclass provides the behavior for the login step forgot password button.
*/
class LoginViewController : ORKLoginStepViewController {
override func forgotPasswordButtonTapped() {
let alertTitle = NSLocalizedString("Forgot password?", comment: "")
let alertMessage = NSLocalizedString("Button tapped", comment: "")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
/*
A login step provides a form step that is populated with email and password fields,
and a button for `Forgot password?`.
*/
let loginTitle = NSLocalizedString("Login", comment: "")
let loginStep = ORKLoginStep(identifier: String(describing:Identifier.loginStep), title: loginTitle, text: exampleDetailText, loginViewControllerClass: LoginViewController.self)
/*
A wait step allows you to validate the data from the user login against your server before proceeding.
*/
let waitTitle = NSLocalizedString("Logging in", comment: "")
let waitText = NSLocalizedString("Please wait while we validate your credentials", comment: "")
let waitStep = ORKWaitStep(identifier: String(describing:Identifier.loginWaitStep))
waitStep.title = waitTitle
waitStep.text = waitText
return ORKOrderedTask(identifier: String(describing:Identifier.loginTask), steps: [loginStep, waitStep])
}
/// This task demonstrates the Passcode creation process.
private var passcodeTask: ORKTask {
/*
If you want to protect the app using a passcode. It is reccomended to
ask user to create passcode as part of the consent process and use the
authentication and editing view controllers to interact with the passcode.
The passcode is stored in the keychain.
*/
let passcodeConsentStep = ORKPasscodeStep(identifier: String(describing:Identifier.passcodeStep))
return ORKOrderedTask(identifier: String(describing:Identifier.passcodeStep), steps: [passcodeConsentStep])
}
/// This task presents the Audio pre-defined active task.
private var audioTask: ORKTask {
return ORKOrderedTask.audioTask(withIdentifier: String(describing:Identifier.audioTask), intendedUseDescription: exampleDescription, speechInstruction: exampleSpeechInstruction, shortSpeechInstruction: exampleSpeechInstruction, duration: 20, recordingSettings: nil, checkAudioLevel: true, options: [])
}
/**
This task presents the Fitness pre-defined active task. For this example,
short walking and rest durations of 20 seconds each are used, whereas more
realistic durations might be several minutes each.
*/
private var fitnessTask: ORKTask {
return ORKOrderedTask.fitnessCheck(withIdentifier: String(describing:Identifier.fitnessTask), intendedUseDescription: exampleDescription, walkDuration: 20, restDuration: 20, options: [])
}
/// This task presents the Hole Peg Test pre-defined active task.
private var holePegTestTask: ORKTask {
return ORKNavigableOrderedTask.holePegTest(withIdentifier: String(describing:Identifier.holePegTestTask), intendedUseDescription: exampleDescription, dominantHand: .right, numberOfPegs: 9, threshold: 0.2, rotated: false, timeLimit: 300, options: [])
}
/// This task presents the PSAT pre-defined active task.
private var PSATTask: ORKTask {
return ORKOrderedTask.psatTask(withIdentifier: String(describing:Identifier.psatTask), intendedUseDescription: exampleDescription, presentationMode: ORKPSATPresentationMode.auditory.union(.visual), interStimulusInterval: 3.0, stimulusDuration: 1.0, seriesLength: 60, options: [])
}
/// This task presents the Reaction Time pre-defined active task.
private var reactionTimeTask: ORKTask {
/// An example of a custom sound.
let successSoundURL = Bundle.main.url(forResource:"tap", withExtension: "aif")!
let successSound = SystemSound(soundURL: successSoundURL)!
return ORKOrderedTask.reactionTime(withIdentifier: String(describing:Identifier.reactionTime), intendedUseDescription: exampleDescription, maximumStimulusInterval: 10, minimumStimulusInterval: 4, thresholdAcceleration: 0.5, numberOfAttempts: 3, timeout: 3, successSound: successSound.soundID, timeoutSound: 0, failureSound: UInt32(kSystemSoundID_Vibrate), options: [])
}
/// This task presents the Gait and Balance pre-defined active task.
private var shortWalkTask: ORKTask {
return ORKOrderedTask.shortWalk(withIdentifier: String(describing:Identifier.shortWalkTask), intendedUseDescription: exampleDescription, numberOfStepsPerLeg: 20, restDuration: 20, options: [])
}
/// This task presents the Spatial Span Memory pre-defined active task.
private var spatialSpanMemoryTask: ORKTask {
return ORKOrderedTask.spatialSpanMemoryTask(withIdentifier: String(describing:Identifier.spatialSpanMemoryTask), intendedUseDescription: exampleDescription, initialSpan: 3, minimumSpan: 2, maximumSpan: 15, playSpeed: 1.0, maximumTests: 5, maximumConsecutiveFailures: 3, customTargetImage: nil, customTargetPluralName: nil, requireReversal: false, options: [])
}
/// This task presents the Stroop pre-defined active task.
private var stroopTask: ORKTask {
return ORKOrderedTask.stroopTask(withIdentifier: String(describing:Identifier.stroopTask), intendedUseDescription: exampleDescription, numberOfAttempts: 10, options: [])
}
/// This task presents the Timed Walk pre-defined active task.
private var timedWalkTask: ORKTask {
return ORKOrderedTask.timedWalk(withIdentifier: String(describing:Identifier.timedWalkTask), intendedUseDescription: exampleDescription, distanceInMeters: 100.0, timeLimit: 180.0, includeAssistiveDeviceForm: true, options: [])
}
/// This task presents the Timed Walk with turn around pre-defined active task.
private var timedWalkWithTurnAroundTask: ORKTask {
return ORKOrderedTask.timedWalk(withIdentifier: String(describing:Identifier.timedWalkWithTurnAroundTask), intendedUseDescription: exampleDescription, distanceInMeters: 100.0, timeLimit: 180.0, turnAroundTimeLimit: 60.0, includeAssistiveDeviceForm: true, options: [])
}
/// This task presents the Tone Audiometry pre-defined active task.
private var toneAudiometryTask: ORKTask {
return ORKOrderedTask.toneAudiometryTask(withIdentifier: String(describing:Identifier.toneAudiometryTask), intendedUseDescription: exampleDescription, speechInstruction: nil, shortSpeechInstruction: nil, toneDuration: 20, options: [])
}
private var towerOfHanoiTask: ORKTask {
return ORKOrderedTask.towerOfHanoiTask(withIdentifier: String(describing:Identifier.towerOfHanoi), intendedUseDescription: exampleDescription, numberOfDisks: 5, options: [])
}
/// This task presents the Two Finger Tapping pre-defined active task.
private var twoFingerTappingIntervalTask: ORKTask {
return ORKOrderedTask.twoFingerTappingIntervalTask(withIdentifier: String(describing:Identifier.twoFingerTappingIntervalTask), intendedUseDescription: exampleDescription, duration: 10,
handOptions: [.both], options: [])
}
/// This task presents a walk back-and-forth task
private var walkBackAndForthTask: ORKTask {
return ORKOrderedTask.walkBackAndForthTask(withIdentifier: String(describing:Identifier.walkBackAndForthTask), intendedUseDescription: exampleDescription, walkDuration: 30, restDuration: 30, options: [])
}
/// This task presents the Tremor Test pre-defined active task.
private var tremorTestTask: ORKTask {
return ORKOrderedTask.tremorTest(withIdentifier: String(describing:Identifier.tremorTestTask),
intendedUseDescription: exampleDescription,
activeStepDuration: 10,
activeTaskOptions: [],
handOptions: [.both],
options: [])
}
/// This task presents a knee range of motion task
private var kneeRangeOfMotion: ORKTask {
return ORKOrderedTask.kneeRangeOfMotionTask(withIdentifier: String(describing: Identifier.kneeRangeOfMotion), limbOption: .right, intendedUseDescription: exampleDescription, options: [])
}
/// This task presents a shoulder range of motion task
private var shoulderRangeOfMotion: ORKTask {
return ORKOrderedTask.shoulderRangeOfMotionTask(withIdentifier: String(describing: Identifier.shoulderRangeOfMotion), limbOption: .left, intendedUseDescription: exampleDescription, options: [])
}
/// This task presents a trail making task
private var trailMaking: ORKTask {
let intendedUseDescription = "Tests visual attention and task switching"
return ORKOrderedTask.trailmakingTask(withIdentifier: String(describing: Identifier.trailMaking), intendedUseDescription: intendedUseDescription, trailmakingInstruction: nil, trailType:.B, options: [])
}
/// This task presents a video instruction step
private var videoInstruction: ORKTask {
let videoInstructionStep = ORKVideoInstructionStep(identifier: String(describing: Identifier.videoInstructionStep))
videoInstructionStep.title = NSLocalizedString("Video Instruction Step", comment: "")
videoInstructionStep.videoURL = URL(string: "https://www.apple.com/media/us/researchkit/2016/a63aa7d4_e6fd_483f_a59d_d962016c8093/films/carekit/researchkit-carekit-cc-us-20160321_r848-9dwc.mov")
videoInstructionStep.thumbnailTime = 2 // Customizable thumbnail timestamp
return ORKOrderedTask(identifier: String(describing: Identifier.videoInstructionTask), steps: [videoInstructionStep])
}
/// This task presents a web view step
private var webView: ORKTask {
let webViewStep = ORKWebViewStep.init(identifier: String(describing: Identifier.webViewStep), html: exampleHtml)
return ORKOrderedTask(identifier: String(describing: Identifier.webViewTask), steps: [webViewStep])
}
// MARK: Consent Document Creation Convenience
/**
A consent document provides the content for the visual consent and consent
review steps. This helper sets up a consent document with some dummy
content. You should populate your consent document to suit your study.
*/
private var consentDocument: ORKConsentDocument {
let consentDocument = ORKConsentDocument()
/*
This is the title of the document, displayed both for review and in
the generated PDF.
*/
consentDocument.title = NSLocalizedString("Example Consent", comment: "")
// This is the title of the signature page in the generated document.
consentDocument.signaturePageTitle = NSLocalizedString("Consent", comment: "")
/*
This is the line shown on the signature page of the generated document,
just above the signatures.
*/
consentDocument.signaturePageContent = NSLocalizedString("I agree to participate in this research study.", comment: "")
/*
Add the participant signature, which will be filled in during the
consent review process. This signature initially does not have a
signature image or a participant name; these are collected during
the consent review step.
*/
let participantSignatureTitle = NSLocalizedString("Participant", comment: "")
let participantSignature = ORKConsentSignature(forPersonWithTitle: participantSignatureTitle, dateFormatString: nil, identifier: String(describing:Identifier.consentDocumentParticipantSignature))
consentDocument.addSignature(participantSignature)
/*
Add the investigator signature. This is pre-populated with the
investigator's signature image and name, and the date of their
signature. If you need to specify the date as now, you could generate
a date string with code here.
This signature is only used for the generated PDF.
*/
let signatureImage = UIImage(named: "signature")!
let investigatorSignatureTitle = NSLocalizedString("Investigator", comment: "")
let investigatorSignatureGivenName = NSLocalizedString("Jonny", comment: "")
let investigatorSignatureFamilyName = NSLocalizedString("Appleseed", comment: "")
let investigatorSignatureDateString = "3/10/15"
let investigatorSignature = ORKConsentSignature(forPersonWithTitle: investigatorSignatureTitle, dateFormatString: nil, identifier: String(describing:Identifier.consentDocumentInvestigatorSignature), givenName: investigatorSignatureGivenName, familyName: investigatorSignatureFamilyName, signatureImage: signatureImage, dateString: investigatorSignatureDateString)
consentDocument.addSignature(investigatorSignature)
/*
This is the HTML content for the "Learn More" page for each consent
section. In a real consent, this would be your content, and you would
have different content for each section.
If your content is just text, you can use the `content` property
instead of the `htmlContent` property of `ORKConsentSection`.
*/
let htmlContentString = "<ul><li>Lorem</li><li>ipsum</li><li>dolor</li></ul><p>\(loremIpsumLongText)</p><p>\(loremIpsumMediumText)</p>"
/*
These are all the consent section types that have pre-defined animations
and images. We use them in this specific order, so we see the available
animated transitions.
*/
let consentSectionTypes: [ORKConsentSectionType] = [
.overview,
.dataGathering,
.privacy,
.dataUse,
.timeCommitment,
.studySurvey,
.studyTasks,
.withdrawing
]
/*
For each consent section type in `consentSectionTypes`, create an
`ORKConsentSection` that represents it.
In a real app, you would set specific content for each section.
*/
var consentSections: [ORKConsentSection] = consentSectionTypes.map { contentSectionType in
let consentSection = ORKConsentSection(type: contentSectionType)
consentSection.summary = loremIpsumShortText
if contentSectionType == .overview {
consentSection.htmlContent = htmlContentString
}
else {
consentSection.content = loremIpsumLongText
}
return consentSection
}
/*
This is an example of a section that is only in the review document
or only in the generated PDF, and is not displayed in `ORKVisualConsentStep`.
*/
let consentSection = ORKConsentSection(type: .onlyInDocument)
consentSection.summary = NSLocalizedString(".OnlyInDocument Scene Summary", comment: "")
consentSection.title = NSLocalizedString(".OnlyInDocument Scene", comment: "")
consentSection.content = loremIpsumLongText
consentSections += [consentSection]
// Set the sections on the document after they've been created.
consentDocument.sections = consentSections
return consentDocument
}
// MARK: `ORKTask` Reused Text Convenience
private var exampleDescription: String {
return NSLocalizedString("Your description goes here.", comment: "")
}
private var exampleSpeechInstruction: String {
return NSLocalizedString("Your more specific voice instruction goes here. For example, say 'Aaaah'.", comment: "")
}
private var exampleQuestionText: String {
return NSLocalizedString("Your question goes here.", comment: "")
}
private var exampleHighValueText: String {
return NSLocalizedString("High Value", comment: "")
}
private var exampleLowValueText: String {
return NSLocalizedString("Low Value", comment: "")
}
private var exampleDetailText: String {
return NSLocalizedString("Additional text can go here.", comment: "")
}
private var exampleEmailText: String {
return NSLocalizedString("[email protected]", comment: "")
}
private var loremIpsumText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
private var loremIpsumShortText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
private var loremIpsumMediumText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo?"
}
private var loremIpsumLongText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo? An potest, inquit ille, quicquam esse suavius quam nihil dolere? Cave putes quicquam esse verius. Quonam, inquit, modo?"
}
private var exampleHtml: String {
return """
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=400, user-scalable=no">
<meta charset="utf-8" />
<style type="text/css">
body
{
background: #FFF;
font-family: Helvetica, sans-serif;
text-align: center;
}
.container
{
width: 100%;
padding: 10px;
box-sizing: border-box;
}
.answer-box
{
width: 100%;
box-sizing: border-box;
padding: 10px;
border: solid 1px #ddd;
border-radius: 2px;
-webkit-appearance: none;
}
.continue-button
{
width: 140px;
text-align: center;
padding-top: 10px;
padding-bottom: 10px;
font-size: 16px;
color: #2e6e9e;
border-radius: 2px;
border: solid 1px #2e6e9e;
background: #FFF;
cursor: pointer;
margin-top: 40px;
}
</style>
<script type="text/javascript">
function completeStep() {
var answer = document.getElementById("answer").value;
window.webkit.messageHandlers.ResearchKit.postMessage(answer);
}
</script>
</head>
<body>
<div class="container">
<input type="text" id="answer" class="answer-box" placeholder="Answer" />
<button onclick="completeStep();" class="continue-button">Continue</button>
</div>
</body>
</html>
"""
}
}
| 46.129855 | 469 | 0.671011 |
720887607185fc7d4ff63d1f42a7e48e9f1272ca
| 10,472 |
//
// RecordWhistleViewController.swift
// Project33
//
// Created by Giang Bb on 10/29/18.
// Copyright © 2018 Giang Bb. All rights reserved.
//
import AVFoundation
import UIKit
class RecordWhistleViewController: UIViewController,AVAudioRecorderDelegate {
var stackView: UIStackView!
var recordButton: UIButton!
var recordingSession: AVAudioSession!
var whistleRecorder: AVAudioRecorder!
var playButton: UIButton!
var whistlePlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//we're going to be doing all the view layout in code to make it easier to follow
view.backgroundColor = UIColor.gray
stackView = UIStackView()
stackView.spacing = 30
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.distribution = UIStackView.Distribution.fillEqually
stackView.alignment = .center
stackView.axis = .vertical
view.addSubview(stackView)
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
//setting up the recording environment
//We'll use the requestRecordPermission() method of the audio session to ask the user whether we can record or not, and give that a trailing closure to execute when the user makes a choice
//As with reading photos, we also need to add a string to the Info.plist file explaining to the user what we intend to do with the audio. So, open the Info.plist file now, select any row, then click the + next that appears next to it. Select the key name “Privacy - Microphone Usage Description” then give it the value “We need to record your whistle.”
recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(.playAndRecord, mode: .default, options: .defaultToSpeaker)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission() { [unowned self] allowed in
DispatchQueue.main.async {
if allowed {
self.loadRecordingUI()
} else {
self.loadFailUI()
}
}
}
} catch {
self.loadFailUI()
}
}
func loadRecordingUI() {
recordButton = UIButton()
recordButton.translatesAutoresizingMaskIntoConstraints = false
recordButton.setTitle("Tap to Record", for: .normal)
recordButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .title1)
recordButton.addTarget(self, action: #selector(recordTapped), for: .touchUpInside)
stackView.addArrangedSubview(recordButton) //you should also be aware that you never add a subview to a UIStackView directly. Instead, you use its addArrangedSubview() method, which is what triggers the layout work
playButton = UIButton()
playButton.translatesAutoresizingMaskIntoConstraints = false
playButton.setTitle("Tap to Play", for: .normal)
playButton.isHidden = true
playButton.alpha = 0 //By setting the button to be hidden and have alpha 0, we're saying "don't show it to the user, and don't let it take up any space in the stack view.
playButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .title1)
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
stackView.addArrangedSubview(playButton)
}
func loadFailUI() {
let failLabel = UILabel()
failLabel.font = UIFont.preferredFont(forTextStyle: .headline)
failLabel.text = "Recording failed: please ensure the app has access to your microphone."
failLabel.numberOfLines = 0 //numberOfLines to 0 means "wrap over as many lines as you need."
stackView.addArrangedSubview(failLabel)
}
@objc func recordTapped() {
if whistleRecorder == nil {
startRecording()
if !playButton.isHidden { //The isHidden property of any UIView subclass is a simple boolean, meaning that it's either true or false: a view is either hidden or it's not
UIView.animate(withDuration: 0.35) { [unowned self] in
self.playButton.isHidden = true
self.playButton.alpha = 0
}
}
} else {
finishRecording(success: true)
}
}
@objc func playTapped() {
let audioURL = RecordWhistleViewController.getWhistleURL()
do {
whistlePlayer = try AVAudioPlayer(contentsOf: audioURL)
whistlePlayer.play()
} catch {
let ac = UIAlertController(title: "Playback failed", message: "There was a problem playing your whistle; please try re-recording.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
//You need to tell iOS where to save the recording. This is done when you create the AVAudioRecorder object because iOS streams the audio to the file as it goes so it can write large files
// class keyword at the beginning, which means you call them on the class not on instances of the class.This is important, because it means we can find the whistle URL from anywhere in our app rather than typing it in everywhere
class func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
class func getWhistleURL() -> URL {
return getDocumentsDirectory().appendingPathComponent("whistle.m4a")
}
func startRecording() {
// When we want to start recording, the app needs to do a few things:
// 1. Make the view have a red background color so the user knows they are in recording mode.
// 2. Change the title of the record button to say "Tap to Stop".
// 3. Use the getWhistleURL() method we just wrote to find where to save the whistle.
// 4. Create a settings dictionary describing the format, sample rate, channels and quality.
// 5. Create an AVAudioRecorder object pointing at our whistle URL, set ourselves as the delegate, then call its record() method.
// 1
view.backgroundColor = UIColor(red: 0.6, green: 0, blue: 0, alpha: 1)
// 2
recordButton.setTitle("Tap to Stop", for: .normal)
// 3
let audioURL = RecordWhistleViewController.getWhistleURL()
print(audioURL.absoluteString)
// 4
//We'll be using Apple's AAC format because it gets the most quality for the lowest bitrate. For bitrate we'll use 12,000Hz, which, when combined with the High AAC quality, sounds good in my testing. We'll specify 1 for the number of channels, because iPhones only have mono input
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
// 5
whistleRecorder = try AVAudioRecorder(url: audioURL, settings: settings)
whistleRecorder.delegate = self
whistleRecorder.record()
} catch {
finishRecording(success: false)
}
}
//once recording has started, we naturally want to stop it at some point. For that, we're going to create a finishRecording() method, which will take one boolean parameter saying whether the recording was successful or not. It will make the view's background color green to show that recording is finished, then it will destroy the AVAudioRecorder object
//The special part of this method lies in whether the recording was a success or not. If it was a success, we're going to set the record button's title to be "Tap to Re-record", but then show a new right bar button item in the navigation bar, letting users progress to the next stage of submission. So, they can submit what they have, or re-record as often as they want. If the record wasn't a success, we'll put the button's title back to being "Tap to Record" then show an error message
func finishRecording(success: Bool) {
view.backgroundColor = UIColor(red: 0, green: 0.6, blue: 0, alpha: 1)
whistleRecorder.stop()
whistleRecorder = nil
if success {
recordButton.setTitle("Tap to Re-record", for: .normal)
if playButton.isHidden {
UIView.animate(withDuration: 0.35) { [unowned self] in
self.playButton.isHidden = false
self.playButton.alpha = 1
}
}
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(nextTapped))
} else {
recordButton.setTitle("Tap to Record", for: .normal)
let ac = UIAlertController(title: "Record failed", message: "There was a problem recording your whistle; please try again.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
@objc func nextTapped() {
let vc = SelectGenreViewController()
navigationController?.pushViewController(vc, animated: true)
}
//MARK: IMPLEMENT AVAudioRecorderDelegate
// We already set our view controller to be the delegate of our AVAudioRecorder object, so we'll get sent a audioRecorderDidFinishRecording() message when recording finished. If the recording wasn't a success, we'll call finishRecording() so it can clean up and restore the view to its pre-recording state
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if !flag {
finishRecording(success: false)
}
}
}
| 49.164319 | 492 | 0.656513 |
298cb8e7293c7aff0eca43769e7354f795a6171c
| 224 |
//
// Agency.swift
// Fema
//
// Created by Sujata Das on 5/5/19.
// Copyright © 2019 Sujata Das. All rights reserved.
//
import Foundation
struct Agency : Codable {
var legalAgencyName: String
var id: String
}
| 16 | 53 | 0.660714 |
fe651434afccb0bcdae4f458c0cb7132da3a12cf
| 2,797 |
//
// AddressService.swift
// martkurly
//
// Created by 천지운 on 2020/10/03.
// Copyright © 2020 Team3x3. All rights reserved.
//
import Foundation
import Alamofire
struct AddressService {
static let shared = AddressService()
private init() { }
private let decoder = JSONDecoder()
// MARK: - 배송지 등록
func registerAddress(delivery: DeliverySpaceModel, completion: @escaping(Bool) -> Void) {
guard let currentUser = UserService.shared.currentUser else { return completion(false) }
let registerRef = REF_ADDRESS + "/\(currentUser.id)" + "/address/order"
let headers: HTTPHeaders = ["Authorization": currentUser.token]
let parameters = [
"address": delivery.address,
"detail_address": delivery.detail_address,
"status": delivery.status,
"receiving_place": delivery.receiving_place,
"entrance_password": delivery.entrance_password ?? "False",
"free_pass": delivery.free_pass,
"etc": delivery.etc ?? "False",
"message": delivery.message ?? true,
"extra_message": delivery.extra_message ?? "False"
] as [String: Any]
AF.request(registerRef, method: .post,
parameters: parameters,
encoding: JSONEncoding.default,
headers: headers).responseJSON { response in
switch response.result {
case .success:
if let status = response.response?.statusCode,
status >= 400 {
completion(false)
} else {
completion(true)
}
case .failure: completion(false)
}
}
}
// MARK: - 배송지 목록 가져오기
func requestAddressList(userPK: Int, completion: @escaping([AddressModel]) -> Void) {
var userAddressList = [AddressModel]()
let requestRef = REF_ADDRESS + "/\(userPK)" + "/address"
AF.request(requestRef, method: .get).responseJSON { response in
guard let jsonData = response.data else { return completion(userAddressList) }
do {
userAddressList = try decoder.decode([AddressModel].self, from: jsonData)
} catch {
print("DEBUG: Request Address List Error => ", error.localizedDescription)
}
completion(userAddressList)
}
}
// MARK: - 배송지 삭제
func deleteAddress(addressID: Int, completion: @escaping() -> Void) {
let deleteRef = REF_ADDRESS + "/1" + "/address" + "/\(addressID)"
AF.request(deleteRef, method: .delete).responseJSON { _ in
completion()
}
}
}
| 33.698795 | 96 | 0.559886 |
cc391c52124b23ee6620b4a391e8bac5e2567029
| 3,593 |
//
// ClangTranslationUnit.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-12.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
#if !os(Linux)
#if SWIFT_PACKAGE
import Clang_C
#endif
import Foundation
extension Sequence where Iterator.Element: Hashable {
fileprivate func distinct() -> [Iterator.Element] {
return Array(Set(self))
}
}
extension Sequence {
fileprivate func grouped<U>(by transform: (Iterator.Element) -> U) -> [U: [Iterator.Element]] {
return reduce([:]) { dictionary, element in
var dictionary = dictionary
let key = transform(element)
dictionary[key] = (dictionary[key] ?? []) + [element]
return dictionary
}
}
}
extension Dictionary {
fileprivate init(_ pairs: [Element]) {
self.init()
for (key, value) in pairs {
self[key] = value
}
}
fileprivate func map<OutValue>(transform: (Value) throws -> (OutValue)) rethrows -> [Key: OutValue] {
return [Key: OutValue](try map { ($0.key, try transform($0.value)) })
}
}
/// Represents a group of CXTranslationUnits.
public struct ClangTranslationUnit {
/// Array of CXTranslationUnits.
private let clangTranslationUnits: [CXTranslationUnit]
public let declarations: [String: [SourceDeclaration]]
/**
Create a ClangTranslationUnit by passing Objective-C header files and clang compiler arguments.
- parameter headerFiles: Objective-C header files to document.
- parameter compilerArguments: Clang compiler arguments.
*/
public init(headerFiles: [String], compilerArguments: [String]) {
let cStringCompilerArguments = compilerArguments.map { ($0 as NSString).utf8String }
let clangIndex = ClangIndex()
clangTranslationUnits = headerFiles.map { clangIndex.open(file: $0, args: cStringCompilerArguments) }
declarations = clangTranslationUnits
.flatMap { $0.cursor().compactMap({ SourceDeclaration(cursor: $0, compilerArguments: compilerArguments) }) }
.rejectEmptyDuplicateEnums()
.distinct()
.sorted()
.grouped { $0.location.file }
.map { insertMarks(declarations: $0) }
}
/**
Failable initializer to create a ClangTranslationUnit by passing Objective-C header files and
`xcodebuild` arguments. Optionally pass in a `path`.
- parameter headerFiles: Objective-C header files to document.
- parameter xcodeBuildArguments: The arguments necessary pass in to `xcodebuild` to link these header files.
- parameter path: Path to run `xcodebuild` from. Uses current path by default.
*/
public init?(headerFiles: [String], xcodeBuildArguments: [String], inPath path: String = FileManager.default.currentDirectoryPath) {
let xcodeBuildOutput = runXcodeBuild(arguments: xcodeBuildArguments + ["-dry-run"], inPath: path) ?? ""
guard let clangArguments = parseCompilerArguments(xcodebuildOutput: xcodeBuildOutput as NSString, language: .objc, moduleName: nil) else {
fputs("could not parse compiler arguments\n\(xcodeBuildOutput)\n", stderr)
return nil
}
self.init(headerFiles: headerFiles, compilerArguments: clangArguments)
}
}
// MARK: CustomStringConvertible
extension ClangTranslationUnit: CustomStringConvertible {
/// A textual JSON representation of `ClangTranslationUnit`.
public var description: String {
return declarationsToJSON(declarations) + "\n"
}
}
#endif
| 35.93 | 146 | 0.67047 |
dd991bd2e44e666bc72dccc7c7c0ad126d63356c
| 2,742 |
@testable import KsApi
import Prelude
import XCTest
final class BackingTests: XCTestCase {
func testJSONDecoding_WithCompleteData() {
let backing = Backing.decodeJSONDictionary([
"amount": 1.0,
"backer_id": 1,
"cancelable": true,
"id": 1,
"location_id": 1,
"location_name": "United States",
"payment_source": [
"expiration_date": "2019-09-23",
"id": "20",
"last_four": "1234",
"payment_type": "CREDIT_CARD",
"state": "ACTIVE",
"type": "VISA"
],
"pledged_at": 1_000,
"project_country": "US",
"project_id": 1,
"sequence": 1,
"status": "pledged"
])
XCTAssertNil(backing.error)
XCTAssertEqual(1.0, backing.value?.amount)
XCTAssertEqual(1, backing.value?.backerId)
XCTAssertEqual(true, backing.value?.cancelable)
XCTAssertEqual(1, backing.value?.id)
XCTAssertEqual("2019-09-23", backing.value?.paymentSource?.expirationDate)
XCTAssertEqual("20", backing.value?.paymentSource?.id)
XCTAssertEqual("1234", backing.value?.paymentSource?.lastFour)
XCTAssertEqual("CREDIT_CARD", backing.value?.paymentSource?.paymentType.rawValue)
XCTAssertEqual("ACTIVE", backing.value?.paymentSource?.state)
XCTAssertEqual(CreditCardType.visa, backing.value?.paymentSource?.type)
XCTAssertEqual(1, backing.value?.locationId)
XCTAssertEqual("United States", backing.value?.locationName)
XCTAssertEqual(1_000, backing.value?.pledgedAt)
XCTAssertEqual("US", backing.value?.projectCountry)
XCTAssertEqual(1, backing.value?.projectId)
XCTAssertEqual(1, backing.value?.sequence)
XCTAssertEqual(Backing.Status.pledged, backing.value?.status)
}
func testJSONDecoding_IncompletePaymentSource() {
let backing = Backing.decodeJSONDictionary([
"amount": 1.0,
"backer_id": 1,
"cancelable": true,
"id": 1,
"location_id": 1,
"location_name": "United States",
"payment_source": [],
"pledged_at": 1_000,
"project_country": "US",
"project_id": 1,
"sequence": 1,
"status": "pledged"
])
XCTAssertNil(backing.error)
XCTAssertEqual(1.0, backing.value?.amount)
XCTAssertEqual(1, backing.value?.backerId)
XCTAssertEqual(1, backing.value?.id)
XCTAssertNil(backing.value?.paymentSource)
XCTAssertEqual(1, backing.value?.locationId)
XCTAssertEqual("United States", backing.value?.locationName)
XCTAssertEqual(1_000, backing.value?.pledgedAt)
XCTAssertEqual("US", backing.value?.projectCountry)
XCTAssertEqual(1, backing.value?.projectId)
XCTAssertEqual(1, backing.value?.sequence)
XCTAssertEqual(Backing.Status.pledged, backing.value?.status)
}
}
| 33.851852 | 85 | 0.676513 |
46f55dcf6fe860cca55e4b4eb96548d73a101254
| 6,275 |
import Foundation
#if canImport(Combine)
import Combine
#endif
protocol ParsePointer: Encodable {
var __type: String { get } // swiftlint:disable:this identifier_name
var className: String { get }
var objectId: String { get set }
}
extension ParsePointer {
/**
Determines if two objects have the same objectId.
- parameter as: Object to compare.
- returns: Returns a `true` if the other object has the same `objectId` or `false` if unsuccessful.
*/
public func hasSameObjectId(as other: ParsePointer) -> Bool {
return other.className == className && other.objectId == objectId
}
}
private func getObjectId<T: ParseObject>(target: T) throws -> String {
guard let objectId = target.objectId else {
throw ParseError(code: .missingObjectId, message: "Cannot set a pointer to an unsaved object")
}
return objectId
}
private func getObjectId(target: Objectable) throws -> String {
guard let objectId = target.objectId else {
throw ParseError(code: .missingObjectId, message: "Cannot set a pointer to an unsaved object")
}
return objectId
}
/// A Pointer referencing a ParseObject.
public struct Pointer<T: ParseObject>: ParsePointer, Fetchable, Encodable, Hashable {
internal let __type: String = "Pointer" // swiftlint:disable:this identifier_name
/**
The id of the object.
*/
public var objectId: String
/**
The class name of the object.
*/
public var className: String
/**
Create a Pointer type.
- parameter target: Object to point to.
*/
public init(_ target: T) throws {
self.objectId = try getObjectId(target: target)
self.className = target.className
}
/**
Create a Pointer type.
- parameter objectId: The id of the object.
*/
public init(objectId: String) {
self.className = T.className
self.objectId = objectId
}
private enum CodingKeys: String, CodingKey {
case __type, objectId, className // swiftlint:disable:this identifier_name
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
objectId = try values.decode(String.self, forKey: .objectId)
className = try values.decode(String.self, forKey: .className)
}
}
public extension Pointer {
/**
Fetches the `ParseObject` *synchronously* with the current data from the server and sets an error if one occurs.
- parameter includeKeys: The name(s) of the key(s) to include that are
`ParseObject`s. Use `["*"]` to include all keys. This is similar to `include` and
`includeAll` for `Query`.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- throws: An error of `ParseError` type.
*/
func fetch(includeKeys: [String]? = nil,
options: API.Options = []) throws -> T {
let path = API.Endpoint.object(className: className, objectId: objectId)
return try API.NonParseBodyCommand<NoBody, T>(method: .GET,
path: path) { (data) -> T in
try ParseCoding.jsonDecoder().decode(T.self, from: data)
}.execute(options: options)
}
/**
Fetches the `ParseObject` *asynchronously* and executes the given callback block.
- parameter includeKeys: The name(s) of the key(s) to include. Use `["*"]` to include
all keys.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- parameter callbackQueue: The queue to return to after completion. Default
value of .main.
- parameter completion: The block to execute when completed.
It should have the following argument signature: `(Result<Self, ParseError>)`.
*/
func fetch(includeKeys: [String]? = nil,
options: API.Options = [],
callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<T, ParseError>) -> Void) {
let path = API.Endpoint.object(className: className, objectId: objectId)
API.NonParseBodyCommand<NoBody, T>(method: .GET,
path: path) { (data) -> T in
try ParseCoding.jsonDecoder().decode(T.self, from: data)
}.executeAsync(options: options) { result in
callbackQueue.async {
completion(result)
}
}
}
#if canImport(Combine)
/**
Fetches the `ParseObject` *aynchronously* with the current data from the server and sets an error if one occurs.
Publishes when complete.
- parameter includeKeys: The name(s) of the key(s) to include that are
`ParseObject`s. Use `["*"]` to include all keys. This is similar to `include` and
`includeAll` for `Query`.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: A publisher that eventually produces a single value and then finishes or fails.
*/
func fetchPublisher(includeKeys: [String]? = nil,
options: API.Options = []) -> Future<T, ParseError> {
Future { promise in
self.fetch(includeKeys: includeKeys,
options: options,
completion: promise)
}
}
#endif
}
// MARK: CustomDebugStringConvertible
extension Pointer: CustomDebugStringConvertible {
public var debugDescription: String {
guard let descriptionData = try? ParseCoding.jsonEncoder().encode(self),
let descriptionString = String(data: descriptionData, encoding: .utf8) else {
return "PointerType ()"
}
return "PointerType (\(descriptionString))"
}
}
// MARK: CustomStringConvertible
extension Pointer: CustomStringConvertible {
public var description: String {
debugDescription
}
}
internal struct PointerType: ParsePointer, Encodable {
var __type: String = "Pointer" // swiftlint:disable:this identifier_name
var objectId: String
var className: String
init(_ target: Objectable) throws {
self.objectId = try getObjectId(target: target)
self.className = target.className
}
}
| 34.861111 | 117 | 0.643665 |
140b5150a5fc8db7610efee20b411bbdda0ad524
| 23,826 |
/*
The MIT License (MIT)
Copyright (c) 2017-2018 Dalton Hinterscher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import SnapKit
import MarqueeLabel
public protocol NotificationBannerDelegate: class {
func notificationBannerWillAppear(_ banner: BaseNotificationBanner)
func notificationBannerDidAppear(_ banner: BaseNotificationBanner)
func notificationBannerWillDisappear(_ banner: BaseNotificationBanner)
func notificationBannerDidDisappear(_ banner: BaseNotificationBanner)
}
@objcMembers
open class BaseNotificationBanner: UIView {
/// Notification that will be posted when a notification banner will appear
public static let BannerWillAppear: Notification.Name = Notification.Name(rawValue: "NotificationBannerWillAppear")
/// Notification that will be posted when a notification banner did appear
public static let BannerDidAppear: Notification.Name = Notification.Name(rawValue: "NotificationBannerDidAppear")
/// Notification that will be posted when a notification banner will appear
public static let BannerWillDisappear: Notification.Name = Notification.Name(rawValue: "NotificationBannerWillDisappear")
/// Notification that will be posted when a notification banner did appear
public static let BannerDidDisappear: Notification.Name = Notification.Name(rawValue: "NotificationBannerDidDisappear")
/// Notification banner object key that is included with each Notification
public static let BannerObjectKey: String = "NotificationBannerObjectKey"
/// The delegate of the notification banner
public weak var delegate: NotificationBannerDelegate?
/// The style of the notification banner
public let style: BannerStyle
/// The height of the banner when it is presented
public var bannerHeight: CGFloat {
get {
if let customBannerHeight = customBannerHeight {
return customBannerHeight
} else {
return shouldAdjustForNotchFeaturedIphone() ? 88.0 : 64.0 + heightAdjustment
}
} set {
customBannerHeight = newValue
}
}
/// The topmost label of the notification if a custom view is not desired
public internal(set) var titleLabel: UILabel?
/// The time before the notificaiton is automatically dismissed
public var duration: TimeInterval = 5.0 {
didSet {
updateMarqueeLabelsDurations()
}
}
/// If false, the banner will not be dismissed until the developer programatically dismisses it
public var autoDismiss: Bool = true {
didSet {
if !autoDismiss {
dismissOnTap = false
dismissOnSwipeUp = false
}
}
}
/// The transparency of the background of the notification banner
public var transparency: CGFloat = 1.0 {
didSet {
if let customView = customView {
customView.backgroundColor = customView.backgroundColor?.withAlphaComponent(transparency)
} else {
let color = backgroundColor
self.backgroundColor = color
}
}
}
/// The type of haptic to generate when a banner is displayed
public var haptic: BannerHaptic = .heavy
/// If true, notification will dismissed when tapped
public var dismissOnTap: Bool = true
/// If true, notification will dismissed when swiped up
public var dismissOnSwipeUp: Bool = true
/// Closure that will be executed if the notification banner is tapped
public var onTap: (() -> Void)?
/// Closure that will be executed if the notification banner is swiped up
public var onSwipeUp: (() -> Void)?
/// Responsible for positioning and auto managing notification banners
public var bannerQueue: NotificationBannerQueue = NotificationBannerQueue.default
/// Banner show and dimiss animation duration
public var animationDuration: TimeInterval = 0.5
/// Wether or not the notification banner is currently being displayed
public var isDisplaying: Bool = false
/// The view that the notification layout is presented on. The constraints/frame of this should not be changed
internal var contentView: UIView!
/// A view that helps the spring animation look nice when the banner appears
internal var spacerView: UIView!
// The custom view inside the notification banner
internal var customView: UIView?
/// The default offset for spacerView top or bottom
internal var spacerViewDefaultOffset: CGFloat = 10.0
/// The maximum number of banners simultaneously visible on screen
internal var maximumVisibleBanners: Int = 1
/// The default padding between edges and views
internal var padding: CGFloat = 15.0
/// The view controller to display the banner on. This is useful if you are wanting to display a banner underneath a navigation bar
internal weak var parentViewController: UIViewController?
/// If this is not nil, then this height will be used instead of the auto calculated height
internal var customBannerHeight: CGFloat?
/// Used by the banner queue to determine wether a notification banner was placed in front of it in the queue
var isSuspended: Bool = false
/// The main window of the application which banner views are placed on
private let appWindow: UIWindow? = {
if #available(iOS 13.0, *) {
return UIApplication.shared.windows.filter { $0.isKeyWindow }.first
}
return UIApplication.shared.delegate?.window ?? nil
}()
/// The position the notification banner should slide in from
private(set) var bannerPosition: BannerPosition!
/// The notification banner sides edges insets from superview. If presented - spacerView color will be transparent
internal var bannerEdgeInsets: UIEdgeInsets? = nil {
didSet {
if bannerEdgeInsets != nil {
spacerView.backgroundColor = .clear
}
}
}
/// Object that stores the start and end frames for the notification banner based on the provided banner position
internal var bannerPositionFrame: BannerPositionFrame!
/// The user info that gets passed to each notification
private var notificationUserInfo: [String: BaseNotificationBanner] {
return [BaseNotificationBanner.BannerObjectKey: self]
}
open override var backgroundColor: UIColor? {
get {
return contentView.backgroundColor
} set {
guard style != .customView else { return }
let color = newValue?.withAlphaComponent(transparency)
contentView.backgroundColor = color
spacerView.backgroundColor = color
}
}
init(style: BannerStyle, colors: BannerColorsProtocol? = nil) {
self.style = style
super.init(frame: .zero)
spacerView = UIView()
addSubview(spacerView)
contentView = UIView()
addSubview(contentView)
if let colors = colors {
backgroundColor = colors.color(for: style)
} else {
backgroundColor = BannerColors().color(for: style)
}
let swipeUpGesture = UISwipeGestureRecognizer(target: self, action: #selector(onSwipeUpGestureRecognizer))
swipeUpGesture.direction = .up
addGestureRecognizer(swipeUpGesture)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self,
name: UIDevice.orientationDidChangeNotification,
object: nil)
}
/**
Creates the proper banner constraints based on the desired banner position
*/
private func createBannerConstraints(for bannerPosition: BannerPosition) {
spacerView.snp.remakeConstraints { (make) in
if bannerPosition == .top {
make.top.equalToSuperview().offset(-spacerViewDefaultOffset)
} else {
make.bottom.equalToSuperview().offset(spacerViewDefaultOffset)
}
make.left.equalToSuperview()
make.right.equalToSuperview()
updateSpacerViewHeight(make: make)
}
contentView.snp.remakeConstraints { (make) in
if bannerPosition == .top {
make.top.equalTo(spacerView.snp.bottom)
make.bottom.equalToSuperview()
} else {
make.top.equalToSuperview()
make.bottom.equalTo(spacerView.snp.top)
}
make.left.equalToSuperview()
make.right.equalToSuperview()
}
}
/**
Updates the spacer view height. Specifically used for orientation changes.
*/
private func updateSpacerViewHeight(make: ConstraintMaker? = nil) {
let finalHeight = spacerViewHeight()
if let make = make {
make.height.equalTo(finalHeight)
} else {
spacerView.snp.updateConstraints({ (make) in
make.height.equalTo(finalHeight)
})
}
}
internal func spacerViewHeight() -> CGFloat {
return NotificationBannerUtilities.isNotchFeaturedIPhone()
&& UIApplication.shared.statusBarOrientation.isPortrait
&& (parentViewController?.navigationController?.isNavigationBarHidden ?? true) ? 40.0 : 10.0
}
private func finishBannerYOffset() -> CGFloat {
let bannerIndex = (bannerQueue.banners.firstIndex(of: self) ?? bannerQueue.banners.filter { $0.isDisplaying }.count)
return bannerQueue.banners.prefix(bannerIndex).reduce(0) { $0
+ $1.bannerHeight
- (bannerPosition == .top ? spacerViewHeight() : 0) // notch spacer height for top position only
+ (bannerPosition == .top ? spacerViewDefaultOffset : -spacerViewDefaultOffset) // to reduct additions in createBannerConstraints (it's needed for proper shadow framing)
+ (bannerPosition == .top ? spacerViewDefaultOffset : -spacerViewDefaultOffset) // default space between banners
// this calculations are made only for banners except first one, for first banner it'll be 0
}
}
internal func updateBannerPositionFrames() {
guard let window = appWindow else { return }
bannerPositionFrame = BannerPositionFrame(bannerPosition: bannerPosition,
bannerWidth: window.width,
bannerHeight: bannerHeight,
maxY: maximumYPosition(),
finishYOffset: finishBannerYOffset(),
edgeInsets: bannerEdgeInsets)
}
internal func animateUpdatedBannerPositionFrames() {
UIView.animate(withDuration: animationDuration,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 1,
options: [.curveLinear, .allowUserInteraction],animations: {
self.frame = self.bannerPositionFrame.endFrame
})
}
/**
Places a NotificationBanner on the queue and shows it if its the first one in the queue
- parameter queuePosition: The position to show the notification banner. If the position is .front, the
banner will be displayed immediately
- parameter bannerPosition: The position the notification banner should slide in from
- parameter queue: The queue to display the notification banner on. It is up to the developer
to manage multiple banner queues and prevent any conflicts that may occur.
- parameter viewController: The view controller to display the notifification banner on. If nil, it will
be placed on the main app window
*/
public func show(queuePosition: QueuePosition = .back,
bannerPosition: BannerPosition = .top,
queue: NotificationBannerQueue = NotificationBannerQueue.default,
on viewController: UIViewController? = nil) {
parentViewController = viewController
bannerQueue = queue
show(placeOnQueue: true, queuePosition: queuePosition, bannerPosition: bannerPosition)
}
/**
Places a NotificationBanner on the queue and shows it if its the first one in the queue
- parameter placeOnQueue: If false, banner will not be placed on the queue and will be showed/resumed immediately
- parameter queuePosition: The position to show the notification banner. If the position is .front, the
banner will be displayed immediately
- parameter bannerPosition: The position the notification banner should slide in from
*/
func show(placeOnQueue: Bool,
queuePosition: QueuePosition = .back,
bannerPosition: BannerPosition = .top) {
guard !isDisplaying else {
return
}
self.bannerPosition = bannerPosition
createBannerConstraints(for: bannerPosition)
updateBannerPositionFrames()
NotificationCenter.default.removeObserver(self,
name: UIDevice.orientationDidChangeNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(onOrientationChanged),
name: UIDevice.orientationDidChangeNotification,
object: nil)
if placeOnQueue {
bannerQueue.addBanner(self,
bannerPosition: bannerPosition,
queuePosition: queuePosition)
} else {
guard let bannerPositionFrame = bannerPositionFrame else { return }
self.frame = bannerPositionFrame.startFrame
if let parentViewController = parentViewController {
parentViewController.view.addSubview(self)
if statusBarShouldBeShown() {
appWindow?.windowLevel = UIWindow.Level.normal
}
} else {
appWindow?.addSubview(self)
if statusBarShouldBeShown() && !(parentViewController == nil && bannerPosition == .top) {
appWindow?.windowLevel = UIWindow.Level.normal
} else {
appWindow?.windowLevel = UIWindow.Level.statusBar + 1
}
}
NotificationCenter.default.post(name: BaseNotificationBanner.BannerWillAppear, object: self, userInfo: notificationUserInfo)
delegate?.notificationBannerWillAppear(self)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onTapGestureRecognizer))
self.addGestureRecognizer(tapGestureRecognizer)
self.isDisplaying = true
let bannerIndex = Double(bannerQueue.banners.firstIndex(of: self) ?? 0) + 1
UIView.animate(withDuration: animationDuration * bannerIndex,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 1,
options: [.curveLinear, .allowUserInteraction],
animations: {
BannerHapticGenerator.generate(self.haptic)
self.frame = self.bannerPositionFrame.endFrame
}) { (completed) in
NotificationCenter.default.post(name: BaseNotificationBanner.BannerDidAppear, object: self, userInfo: self.notificationUserInfo)
self.delegate?.notificationBannerDidAppear(self)
/* We don't want to add the selector if another banner was queued in front of it
before it finished animating or if it is meant to be shown infinitely
*/
if !self.isSuspended && self.autoDismiss {
self.perform(#selector(self.dismiss), with: nil, afterDelay: self.duration)
}
}
}
}
/**
Suspends a notification banner so it will not be dismissed. This happens because a new notification banner was placed in front of it on the queue.
*/
func suspend() {
if autoDismiss {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dismiss), object: nil)
isSuspended = true
isDisplaying = false
}
}
/**
Resumes a notification banner immediately.
*/
func resume() {
if autoDismiss {
self.perform(#selector(dismiss), with: nil, afterDelay: self.duration)
isSuspended = false
isDisplaying = true
}
}
/**
Resets a notification banner's elapsed duration to zero.
*/
public func resetDuration() {
if autoDismiss {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dismiss), object: nil)
self.perform(#selector(dismiss), with: nil, afterDelay: self.duration)
}
}
/**
The height adjustment needed in order for the banner to look properly displayed.
*/
internal var heightAdjustment: CGFloat {
// iOS 13 does not allow covering the status bar on non-notch iPhones
// The banner needs to be moved further down under the status bar in this case
guard #available(iOS 13.0, *), !NotificationBannerUtilities.isNotchFeaturedIPhone() else {
return 0
}
return UIApplication.shared.statusBarFrame.height
}
/**
Update banner height, it's necessary after banner labels font update
*/
internal func updateBannerHeight() {
onOrientationChanged()
}
/**
Changes the frame of the notification banner when the orientation of the device changes
*/
@objc private dynamic func onOrientationChanged() {
guard let window = appWindow else { return }
updateSpacerViewHeight()
let edgeInsets = bannerEdgeInsets ?? .zero
let newY = (bannerPosition == .top) ? (frame.origin.y) : (window.height - bannerHeight + edgeInsets.top - edgeInsets.bottom)
frame = CGRect(x: frame.origin.x,
y: newY,
width: window.width - edgeInsets.left - edgeInsets.right,
height: bannerHeight)
bannerPositionFrame = BannerPositionFrame(bannerPosition: bannerPosition,
bannerWidth: window.width,
bannerHeight: bannerHeight,
maxY: maximumYPosition(),
finishYOffset: finishBannerYOffset(),
edgeInsets: bannerEdgeInsets)
}
/**
Dismisses the NotificationBanner and shows the next one if there is one to show on the queue
*/
@objc public func dismiss(forced: Bool = false) {
guard isDisplaying else {
return
}
NSObject.cancelPreviousPerformRequests(withTarget: self,
selector: #selector(dismiss),
object: nil)
NotificationCenter.default.post(name: BaseNotificationBanner.BannerWillDisappear, object: self, userInfo: notificationUserInfo)
delegate?.notificationBannerWillDisappear(self)
isDisplaying = false
remove()
UIView.animate(withDuration: forced ? animationDuration / 2 : animationDuration,
animations: {
self.frame = self.bannerPositionFrame.startFrame
}) { (completed) in
self.removeFromSuperview()
NotificationCenter.default.post(name: BaseNotificationBanner.BannerDidDisappear, object: self, userInfo: self.notificationUserInfo)
self.delegate?.notificationBannerDidDisappear(self)
self.bannerQueue.showNext(callback: { (isEmpty) in
if isEmpty || self.statusBarShouldBeShown() {
self.appWindow?.windowLevel = UIWindow.Level.normal
}
})
}
}
/**
Removes the NotificationBanner from the queue if not displaying
*/
public func remove() {
guard !isDisplaying else {
return
}
bannerQueue.removeBanner(self)
}
/**
Called when a notification banner is tapped
*/
@objc private dynamic func onTapGestureRecognizer() {
if dismissOnTap {
dismiss()
}
onTap?()
}
/**
Called when a notification banner is swiped up
*/
@objc private dynamic func onSwipeUpGestureRecognizer() {
if dismissOnSwipeUp {
dismiss()
}
onSwipeUp?()
}
/**
Determines wether or not the status bar should be shown when displaying a banner underneath
the navigation bar
*/
private func statusBarShouldBeShown() -> Bool {
for banner in bannerQueue.banners {
if (banner.parentViewController == nil && banner.bannerPosition == .top) {
return false
}
}
return true
}
/**
Calculates the maximum `y` position that a notification banner can slide in from
*/
private func maximumYPosition() -> CGFloat {
if let parentViewController = parentViewController {
return parentViewController.view.frame.height
} else {
return appWindow?.height ?? 0
}
}
/**
Determines wether or not we should adjust the banner for notch featured iPhone
*/
internal func shouldAdjustForNotchFeaturedIphone() -> Bool {
return NotificationBannerUtilities.isNotchFeaturedIPhone()
&& UIApplication.shared.statusBarOrientation.isPortrait
&& (self.parentViewController?.navigationController?.isNavigationBarHidden ?? true)
}
/**
Updates the scrolling marquee label duration
*/
internal func updateMarqueeLabelsDurations() {
(titleLabel as? MarqueeLabel)?.speed = .duration(CGFloat(duration <= 3 ? 0.5 : duration - 3))
}
}
| 39.909548 | 181 | 0.630026 |
ebf3862ac30b2117410c2428c085d7baeb6cf2ff
| 1,441 |
// MIT License
//
// Copyright (c) 2020 Anton Yereshchenko
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension CGFloat {
static var twoPi: CGFloat { return .pi * 2 }
var rad2deg: CGFloat { return degrees }
var deg2rad: CGFloat { return radians }
private var degrees: CGFloat { return self * 180 / CGFloat.pi }
private var radians: CGFloat { return self * CGFloat.pi / 180 }
}
| 41.171429 | 81 | 0.746704 |
f8579f8fd05c5e4cff311d6b68ace02075a3ccc7
| 1,089 |
import Foundation
import SnapKit
/**
* A view for captions.
*/
class CaptionView: UIView {
var text: String = "" {
didSet {
updateText()
}
}
private lazy var label: UILabel = {
let label = UILabel()
label.font = AppTheme.shared.fontForSize(size: AppConstants.Font.LabelMedium, bolded: true)
label.textColor = UIColor.applicationColor(TextPrimary)
label.numberOfLines = 1
return label
}()
init(text: String = "") {
super.init(frame: CGRect.zero)
self.text = text
configureLabel()
}
override init(frame: CGRect) {
super.init(frame: frame)
configureLabel()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configureLabel()
}
private func configureLabel() {
addSubview(label)
label.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
updateText()
}
private func updateText() {
label.text = text
label.sizeToFit()
}
}
| 19.105263 | 99 | 0.568411 |
5b09167db961cb86963fb95de2d92a5f8ff30aba
| 1,065 |
//
// 377-CombinationSum4.swift
// DynamicProgramming
//
// Created by Csy on 2019/2/19.
// Copyright © 2019 CXL. All rights reserved.
//
/**
给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
示例
nums = [1, 2, 3]
target = 4
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
请注意,顺序不同的序列被视作不同的组合。
因此输出为 7
思路一
dp[i]表示和是i的组合数
dp[i] = Sum{dp[i-num1],dp[i-num2],dp[i-num3]...}
*/
import Foundation
class CombinationSum4 {
// 对于target=10000,有数据溢出的问题。
// leetcode自己的计算结果也会溢出
func combinationSum4(_ nums: [Int], _ target: Int) -> Int {
let numCount = nums.count
if numCount == 0 || target <= 0{
return 0
}
// 初始化dp。dp[i]表示target是i的组合数
var dp = Array(repeating: 0, count: target+1)
dp[0] = 1
// 根据状态方程进行计算
for i in 1...target {
for num in nums {
if i - num >= 0 {
dp[i] += dp[i-num]
}
}
}
return dp[target]
}
}
| 17.75 | 63 | 0.493897 |
4b45b86e1143214d82abd8980b0eb52c0c7c96b4
| 1,169 |
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// swiftlint:disable all
import Amplify
import Foundation
extension OwnerPublicUPIAMPost {
// MARK: - CodingKeys
public enum CodingKeys: String, ModelKey {
case id
case name
case createdAt
case updatedAt
}
public static let keys = CodingKeys.self
// MARK: - ModelSchema
public static let schema = defineSchema { model in
let ownerPublicUPIAMPost = OwnerPublicUPIAMPost.keys
model.authRules = [
rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]),
rule(allow: .public, provider: .iam, operations: [.create, .update, .delete, .read])
]
model.pluralName = "OwnerPublicUPIAMPosts"
model.fields(
.id(),
.field(ownerPublicUPIAMPost.name, is: .required, ofType: .string),
.field(ownerPublicUPIAMPost.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime),
.field(ownerPublicUPIAMPost.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime)
)
}
}
| 27.833333 | 152 | 0.687767 |
160490c605be82d75a4b802c39bd276aed5cfbd4
| 4,992 |
//
// PageTitleView.swift
// HuyZB
//
// Created by mac on 2018/5/26.
// Copyright © 2018年 come.huy. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate: class {
func pageTitleView(titleView: PageTitleView, selectedIndex index : Int)
}
private let scrollLineH : CGFloat = 2
private let normalColor : (CGFloat, CGFloat, CGFloat) = (85,85,85)
private let selectColor : (CGFloat, CGFloat, CGFloat) = (255,128,0)
class PageTitleView: UIView {
private var currentIndex : Int = 0
private var titles : [String]
weak var delegate: PageTitleViewDelegate?
// MARK: - 记录数组
private lazy var labels : [UILabel] = [UILabel]()
private lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false;
scrollView.bounces = false
return scrollView
}()
private lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
init(frame: CGRect, titles : [String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
private func setupUI(){
addSubview(scrollView)
scrollView.frame = bounds
setupTitleLabels()
setupBottomLineAndScrollLine()
}
private func setupTitleLabels(){
print(titles.count)
let labelW : CGFloat = frame.width / CGFloat(titles.count)
print(frame.width,labelW)
let labelH : CGFloat = frame.height - scrollLineH
let labelY : CGFloat = 0
for(index, title) in titles.enumerated() {
print(title,index)
let label = UILabel()
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor(r: normalColor.0, g: normalColor.1, b: normalColor.2)
label.textAlignment = .center
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
labels.append(label)
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottomLineAndScrollLine(){
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
guard let firstLabel = labels.first else {return}
firstLabel.textColor = UIColor(r: selectColor.0, g: selectColor.1, b: selectColor.2)
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - scrollLineH, width: firstLabel.frame.width, height: scrollLineH)
}
}
extension PageTitleView {
@objc private func titleLabelClick(tapGes : UITapGestureRecognizer){
guard let currentLabel = tapGes.view as? UILabel else { return }
let oldLabel = labels[currentIndex]
currentLabel.textColor = UIColor(r: selectColor.0, g: selectColor.1, b: selectColor.2)
oldLabel.textColor = UIColor(r: normalColor.0, g: normalColor.1, b: normalColor.2)
currentIndex = currentLabel.tag
let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width
UIView.animate(withDuration: 0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
//通知代理做事情
delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex)
}
}
extension PageTitleView {
func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int){
let sourceLabel = labels[sourceIndex]
let targetLabel = labels[targetIndex]
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
let colorDelta = (selectColor.0 - normalColor.0, selectColor.1 - normalColor.1, selectColor.2 - normalColor.2)
sourceLabel.textColor = UIColor(r: selectColor.0 - colorDelta.0 * progress, g: selectColor.1 - colorDelta.1 * progress, b: selectColor.2 - colorDelta.2 * progress)
targetLabel.textColor = UIColor(r: normalColor.0 + colorDelta.0 * progress, g: normalColor.1 + colorDelta.1 * progress, b: normalColor.2 + colorDelta.2 * progress)
}
}
| 36.705882 | 171 | 0.642829 |
ac24f41f7c4cceb8cef1e592ca7819bc089dce1f
| 1,004 |
//
// FXVersionCheckDemoTests.swift
// FXVersionCheckDemoTests
//
// Created by bailun on 2018/3/1.
// Copyright © 2018年 bailun. All rights reserved.
//
import XCTest
@testable import FXVersionCheckDemo
class FXVersionCheckDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.135135 | 111 | 0.646414 |
61417be0535337eb88c7a868e5f9b72aea1378fc
| 1,224 |
//
// VisitorView.swift
// Weibo
//
// Created by dwt on 17/2/26.
// Copyright © 2017年 Dwt. All rights reserved.
//
import UIKit
class VisitorView: UIView {
class func visitorView() -> VisitorView {
return NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).first as! VisitorView
}
@IBOutlet weak var rotationView: UIImageView!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var registerBtn: UIButton!
@IBOutlet weak var loginBtn: UIButton!
//自定义函数
func resetVisitorView(iconName:String, title:String){
rotationView.hidden = true
iconView.image = UIImage(named: iconName)
titleLabel.text = title
}
//旋转动画方法
func setRotationAnimation(){
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = 0
animation.toValue = M_PI * 2
animation.repeatCount = MAXFLOAT
animation.duration = 5
//需要设置这个属性 不然退回后台或者切换页面动画会消失
animation.removedOnCompletion = false
rotationView.layer.addAnimation(animation, forKey: nil)
}
}
| 26.042553 | 112 | 0.643791 |
8704ad6625dae4f2ade72e71f69750b74dfac474
| 843 |
//
// IPaKeyChainKey.swift
// IPaKeyChain
//
// Created by IPa Chen on 2015/10/12.
// Copyright © 2015年 A Magic Studio. All rights reserved.
//
import Foundation
class IPaKeyChainKey :IPaKeyChainKeyIdentity {
override init () {
super.init()
self.keychainItemData[String(kSecClass)] = kSecClassKey as NSString
}
/*
kSecClassKey item attributes:
kSecAttrAccessible
kSecAttrAccessControl
kSecAttrAccessGroup
kSecAttrKeyClass
kSecAttrLabel
kSecAttrApplicationLabel
kSecAttrIsPermanent
kSecAttrApplicationTag
kSecAttrKeyType
kSecAttrKeySizeInBits
kSecAttrEffectiveKeySize
kSecAttrCanEncrypt
kSecAttrCanDecrypt
kSecAttrCanDerive
kSecAttrCanSign
kSecAttrCanVerify
kSecAttrCanWrap
kSecAttrCanUnwrap
kSecAttrSynchronizable
*/
}
| 20.071429 | 75 | 0.724792 |
22f3d6c8b202359cb85059dbf37a6a7904b43508
| 45 |
let AdzerkDecisionSDKVersionString = "2.1.0"
| 22.5 | 44 | 0.8 |
b992a75fc183bb17aedf22839990b8e262f31567
| 121,334 |
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import RealmSwift
import XCTest
#if canImport(RealmTestSupport)
import RealmTestSupport
#endif
// MARK: Test objects definitions
enum IntegerEnum: Int, PersistableEnum {
case value1 = 1
case value2 = 3
}
class AllTypesPrimitiveProjection: Projection<ModernAllTypesObject> {
@Projected(\ModernAllTypesObject.pk) var pk
@Projected(\ModernAllTypesObject.boolCol) var boolCol
@Projected(\ModernAllTypesObject.intCol) var intCol
@Projected(\ModernAllTypesObject.int8Col) var int8Col
@Projected(\ModernAllTypesObject.int16Col) var int16Col
@Projected(\ModernAllTypesObject.int32Col) var int32Col
@Projected(\ModernAllTypesObject.int64Col) var int64Col
@Projected(\ModernAllTypesObject.floatCol) var floatCol
@Projected(\ModernAllTypesObject.doubleCol) var doubleCol
@Projected(\ModernAllTypesObject.stringCol) var stringCol
@Projected(\ModernAllTypesObject.binaryCol) var binaryCol
@Projected(\ModernAllTypesObject.dateCol) var dateCol
@Projected(\ModernAllTypesObject.decimalCol) var decimalCol
@Projected(\ModernAllTypesObject.objectIdCol) var objectIdCol
@Projected(\ModernAllTypesObject.objectCol) var objectCol
@Projected(\ModernAllTypesObject.arrayCol) var arrayCol
@Projected(\ModernAllTypesObject.setCol) var setCol
@Projected(\ModernAllTypesObject.anyCol) var anyCol
@Projected(\ModernAllTypesObject.uuidCol) var uuidCol
@Projected(\ModernAllTypesObject.intEnumCol) var intEnumCol
@Projected(\ModernAllTypesObject.stringEnumCol) var stringEnumCol
@Projected(\ModernAllTypesObject.optIntCol) var optIntCol
@Projected(\ModernAllTypesObject.optInt8Col) var optInt8Col
@Projected(\ModernAllTypesObject.optInt16Col) var optInt16Col
@Projected(\ModernAllTypesObject.optInt32Col) var optInt32Col
@Projected(\ModernAllTypesObject.optInt64Col) var optInt64Col
@Projected(\ModernAllTypesObject.optFloatCol) var optFloatCol
@Projected(\ModernAllTypesObject.optDoubleCol) var optDoubleCol
@Projected(\ModernAllTypesObject.optBoolCol) var optBoolCol
@Projected(\ModernAllTypesObject.optStringCol) var optStringCol
@Projected(\ModernAllTypesObject.optBinaryCol) var optBinaryCol
@Projected(\ModernAllTypesObject.optDateCol) var optDateCol
@Projected(\ModernAllTypesObject.optDecimalCol) var optDecimalCol
@Projected(\ModernAllTypesObject.optObjectIdCol) var optObjectIdCol
@Projected(\ModernAllTypesObject.optUuidCol) var optUuidCol
@Projected(\ModernAllTypesObject.optIntEnumCol) var optIntEnumCol
@Projected(\ModernAllTypesObject.optStringEnumCol) var optStringEnumCol
@Projected(\ModernAllTypesObject.arrayBool) var arrayBool
@Projected(\ModernAllTypesObject.arrayInt) var arrayInt
@Projected(\ModernAllTypesObject.arrayInt8) var arrayInt8
@Projected(\ModernAllTypesObject.arrayInt16) var arrayInt16
@Projected(\ModernAllTypesObject.arrayInt32) var arrayInt32
@Projected(\ModernAllTypesObject.arrayInt64) var arrayInt64
@Projected(\ModernAllTypesObject.arrayFloat) var arrayFloat
@Projected(\ModernAllTypesObject.arrayDouble) var arrayDouble
@Projected(\ModernAllTypesObject.arrayString) var arrayString
@Projected(\ModernAllTypesObject.arrayBinary) var arrayBinary
@Projected(\ModernAllTypesObject.arrayDate) var arrayDate
@Projected(\ModernAllTypesObject.arrayDecimal) var arrayDecimal
@Projected(\ModernAllTypesObject.arrayObjectId) var arrayObjectId
@Projected(\ModernAllTypesObject.arrayAny) var arrayAny
@Projected(\ModernAllTypesObject.arrayUuid) var arrayUuid
@Projected(\ModernAllTypesObject.arrayOptBool) var arrayOptBool
@Projected(\ModernAllTypesObject.arrayOptInt) var arrayOptInt
@Projected(\ModernAllTypesObject.arrayOptInt8) var arrayOptInt8
@Projected(\ModernAllTypesObject.arrayOptInt16) var arrayOptInt16
@Projected(\ModernAllTypesObject.arrayOptInt32) var arrayOptInt32
@Projected(\ModernAllTypesObject.arrayOptInt64) var arrayOptInt64
@Projected(\ModernAllTypesObject.arrayOptFloat) var arrayOptFloat
@Projected(\ModernAllTypesObject.arrayOptDouble) var arrayOptDouble
@Projected(\ModernAllTypesObject.arrayOptString) var arrayOptString
@Projected(\ModernAllTypesObject.arrayOptBinary) var arrayOptBinary
@Projected(\ModernAllTypesObject.arrayOptDate) var arrayOptDate
@Projected(\ModernAllTypesObject.arrayOptDecimal) var arrayOptDecimal
@Projected(\ModernAllTypesObject.arrayOptObjectId) var arrayOptObjectId
@Projected(\ModernAllTypesObject.arrayOptUuid) var arrayOptUuid
@Projected(\ModernAllTypesObject.setBool) var setBool
@Projected(\ModernAllTypesObject.setInt) var setInt
@Projected(\ModernAllTypesObject.setInt8) var setInt8
@Projected(\ModernAllTypesObject.setInt16) var setInt16
@Projected(\ModernAllTypesObject.setInt32) var setInt32
@Projected(\ModernAllTypesObject.setInt64) var setInt64
@Projected(\ModernAllTypesObject.setFloat) var setFloat
@Projected(\ModernAllTypesObject.setDouble) var setDouble
@Projected(\ModernAllTypesObject.setString) var setString
@Projected(\ModernAllTypesObject.setBinary) var setBinary
@Projected(\ModernAllTypesObject.setDate) var setDate
@Projected(\ModernAllTypesObject.setDecimal) var setDecimal
@Projected(\ModernAllTypesObject.setObjectId) var setObjectId
@Projected(\ModernAllTypesObject.setAny) var setAny
@Projected(\ModernAllTypesObject.setUuid) var setUuid
@Projected(\ModernAllTypesObject.setOptBool) var setOptBool
@Projected(\ModernAllTypesObject.setOptInt) var setOptInt
@Projected(\ModernAllTypesObject.setOptInt8) var setOptInt8
@Projected(\ModernAllTypesObject.setOptInt16) var setOptInt16
@Projected(\ModernAllTypesObject.setOptInt32) var setOptInt32
@Projected(\ModernAllTypesObject.setOptInt64) var setOptInt64
@Projected(\ModernAllTypesObject.setOptFloat) var setOptFloat
@Projected(\ModernAllTypesObject.setOptDouble) var setOptDouble
@Projected(\ModernAllTypesObject.setOptString) var setOptString
@Projected(\ModernAllTypesObject.setOptBinary) var setOptBinary
@Projected(\ModernAllTypesObject.setOptDate) var setOptDate
@Projected(\ModernAllTypesObject.setOptDecimal) var setOptDecimal
@Projected(\ModernAllTypesObject.setOptObjectId) var setOptObjectId
@Projected(\ModernAllTypesObject.setOptUuid) var setOptUuid
@Projected(\ModernAllTypesObject.mapBool) var mapBool
@Projected(\ModernAllTypesObject.mapInt) var mapInt
@Projected(\ModernAllTypesObject.mapInt8) var mapInt8
@Projected(\ModernAllTypesObject.mapInt16) var mapInt16
@Projected(\ModernAllTypesObject.mapInt32) var mapInt32
@Projected(\ModernAllTypesObject.mapInt64) var mapInt64
@Projected(\ModernAllTypesObject.mapFloat) var mapFloat
@Projected(\ModernAllTypesObject.mapDouble) var mapDouble
@Projected(\ModernAllTypesObject.mapString) var mapString
@Projected(\ModernAllTypesObject.mapBinary) var mapBinary
@Projected(\ModernAllTypesObject.mapDate) var mapDate
@Projected(\ModernAllTypesObject.mapDecimal) var mapDecimal
@Projected(\ModernAllTypesObject.mapObjectId) var mapObjectId
@Projected(\ModernAllTypesObject.mapAny) var mapAny
@Projected(\ModernAllTypesObject.mapUuid) var mapUuid
@Projected(\ModernAllTypesObject.mapOptBool) var mapOptBool
@Projected(\ModernAllTypesObject.mapOptInt) var mapOptInt
@Projected(\ModernAllTypesObject.mapOptInt8) var mapOptInt8
@Projected(\ModernAllTypesObject.mapOptInt16) var mapOptInt16
@Projected(\ModernAllTypesObject.mapOptInt32) var mapOptInt32
@Projected(\ModernAllTypesObject.mapOptInt64) var mapOptInt64
@Projected(\ModernAllTypesObject.mapOptFloat) var mapOptFloat
@Projected(\ModernAllTypesObject.mapOptDouble) var mapOptDouble
@Projected(\ModernAllTypesObject.mapOptString) var mapOptString
@Projected(\ModernAllTypesObject.mapOptBinary) var mapOptBinary
@Projected(\ModernAllTypesObject.mapOptDate) var mapOptDate
@Projected(\ModernAllTypesObject.mapOptDecimal) var mapOptDecimal
@Projected(\ModernAllTypesObject.mapOptObjectId) var mapOptObjectId
@Projected(\ModernAllTypesObject.mapOptUuid) var mapOptUuid
@Projected(\ModernAllTypesObject.linkingObjects) var linkingObjects
}
class AdvancedObject: Object {
@Persisted(primaryKey: true) var pk: ObjectId
@Persisted var commonArray: RealmSwift.List<Int>
@Persisted var objectsArray: RealmSwift.List<SimpleObject>
@Persisted var commonSet: MutableSet<Int>
@Persisted var objectsSet: MutableSet<SimpleObject>
}
extension SimpleObject {
var stringify: String {
"\(int) - \(bool)"
}
}
class AdvancedProjection: Projection<AdvancedObject> {
@Projected(\AdvancedObject.commonArray.count) var arrayLen
@Projected(\AdvancedObject.commonArray) var renamedArray
@Projected(\AdvancedObject.objectsArray.projectTo.stringify) var projectedArray: ProjectedCollection<String>
@Projected(\AdvancedObject.commonSet.first) var firstElement
@Projected(\AdvancedObject.objectsSet.projectTo.bool) var projectedSet: ProjectedCollection<Bool>
}
class FailedProjection: Projection<ModernAllTypesObject> {
@Projected(\ModernAllTypesObject.ignored) var ignored
}
public class AddressSwift: EmbeddedObject {
@Persisted var city: String = ""
@Persisted var country = ""
}
public class CommonPerson: Object {
@Persisted var firstName: String
@Persisted var lastName = ""
@Persisted var birthday: Date
@Persisted var address: AddressSwift?
@Persisted public var friends: RealmSwift.List<CommonPerson>
@Persisted var reviews: RealmSwift.List<String>
@Persisted var money: Decimal128
}
public final class PersonProjection: Projection<CommonPerson> {
@Projected(\CommonPerson.firstName) var firstName
@Projected(\CommonPerson.lastName.localizedUppercase) var lastNameCaps
@Projected(\CommonPerson.birthday.timeIntervalSince1970) var birthdayAsEpochtime
@Projected(\CommonPerson.address?.city) var homeCity
@Projected(\CommonPerson.friends.projectTo.firstName) var firstFriendsName: ProjectedCollection<String>
}
public class SimpleObject: Object {
@Persisted var int: Int
@Persisted var bool: Bool
}
public final class SimpleProjection: Projection<SimpleObject> {
@Projected(\SimpleObject.int) var int
}
public final class AltSimpleProjection: Projection<SimpleObject> {
@Projected(\SimpleObject.int) var int
}
// MARK: Tests
class ProjectionTests: TestCase {
func assertSetEquals<T: RealmCollectionValue>(_ set: MutableSet<T>, _ expected: Array<T>) {
XCTAssertEqual(set.count, Set(expected).count)
XCTAssertEqual(Set(set), Set(expected))
}
func assertEquivalent(_ actual: AnyRealmCollection<ModernAllTypesObject>,
_ expected: Array<ModernAllTypesObject>,
expectedShouldBeCopy: Bool) {
XCTAssertEqual(actual.count, expected.count)
for obj in expected {
if expectedShouldBeCopy {
XCTAssertTrue(actual.contains { $0.pk == obj.pk })
} else {
XCTAssertTrue(actual.contains(obj))
}
}
}
func assertMapEquals<T: RealmCollectionValue>(_ actual: Map<String, T>, _ expected: Dictionary<String, T>) {
XCTAssertEqual(actual.count, expected.count)
for (key, value) in expected {
XCTAssertEqual(actual[key], value)
}
}
var allTypeValues: [String: Any] {
return [
"boolCol": true,
"intCol": 10,
"int8Col": 11 as Int8,
"int16Col": 12 as Int16,
"int32Col": 13 as Int32,
"int64Col": 14 as Int64,
"floatCol": 15 as Float,
"doubleCol": 16 as Double,
"stringCol": "a",
"binaryCol": "b".data(using: .utf8)!,
"dateCol": Date(timeIntervalSince1970: 17),
"decimalCol": 18 as Decimal128,
"objectIdCol": ObjectId("6058f12b957ba06156586a7c"),
"objectCol": ModernAllTypesObject(value: ["intCol": 1]),
"arrayCol": [
ModernAllTypesObject(value: ["pk": ObjectId("6058f12682b2fbb1f334ef1d"), "intCol": 2]),
ModernAllTypesObject(value: ["pk": ObjectId("6058f12d42e5a393e67538d0"), "intCol": 3])
],
"setCol": [
ModernAllTypesObject(value: ["pk": ObjectId("6058f12d42e5a393e67538d1"), "intCol": 4]),
ModernAllTypesObject(value: ["pk": ObjectId("6058f12682b2fbb1f334ef1f"), "intCol": 5]),
ModernAllTypesObject(value: ["pk": ObjectId("507f1f77bcf86cd799439011"), "intCol": 6])
],
"anyCol": AnyRealmValue.int(20),
"uuidCol": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fd")!,
"intEnumCol": ModernIntEnum.value2,
"stringEnumCol": ModernStringEnum.value3,
"optBoolCol": false,
"optIntCol": 30,
"optInt8Col": 31 as Int8,
"optInt16Col": 32 as Int16,
"optInt32Col": 33 as Int32,
"optInt64Col": 34 as Int64,
"optFloatCol": 35 as Float,
"optDoubleCol": 36 as Double,
"optStringCol": "c",
"optBinaryCol": "d".data(using: .utf8)!,
"optDateCol": Date(timeIntervalSince1970: 37),
"optDecimalCol": 38 as Decimal128,
"optObjectIdCol": ObjectId("6058f12b957ba06156586a7c"),
"optUuidCol": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fd")!,
"optIntEnumCol": ModernIntEnum.value1,
"optStringEnumCol": ModernStringEnum.value1,
"arrayBool": [true, false] as [Bool],
"arrayInt": [1, 1, 2, 3] as [Int],
"arrayInt8": [1, 2, 3, 1] as [Int8],
"arrayInt16": [1, 2, 3, 1] as [Int16],
"arrayInt32": [1, 2, 3, 1] as [Int32],
"arrayInt64": [1, 2, 3, 1] as [Int64],
"arrayFloat": [1 as Float, 2 as Float, 3 as Float, 1 as Float],
"arrayDouble": [1 as Double, 2 as Double, 3 as Double, 1 as Double],
"arrayString": ["a", "b", "c"] as [String],
"arrayBinary": ["a".data(using: .utf8)!] as [Data],
"arrayDate": [Date(timeIntervalSince1970: 0), Date(timeIntervalSince1970: 1)] as [Date],
"arrayDecimal": [1 as Decimal128, 2 as Decimal128],
"arrayObjectId": [ObjectId("6058f12b957ba06156586a7c"), ObjectId("6058f12682b2fbb1f334ef1d")],
"arrayAny": [.none, .int(1), .string("a"), .none] as [AnyRealmValue],
"arrayUuid": [UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fd")!, UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fe")!],
"arrayOptBool": [true, false, nil] as [Bool?],
"arrayOptInt": [1, 1, 2, 3, nil] as [Int?],
"arrayOptInt8": [1, 2, 3, 1, nil] as [Int8?],
"arrayOptInt16": [1, 2, 3, 1, nil] as [Int16?],
"arrayOptInt32": [1, 2, 3, 1, nil] as [Int32?],
"arrayOptInt64": [1, 2, 3, 1, nil] as [Int64?],
"arrayOptFloat": [1 as Float, 2 as Float, 3 as Float, 1 as Float, nil],
"arrayOptDouble": [1 as Double, 2 as Double, 3 as Double, 1 as Double, nil],
"arrayOptString": ["a", "b", "c", nil],
"arrayOptBinary": ["a".data(using: .utf8)!, nil],
"arrayOptDate": [Date(timeIntervalSince1970: 0), Date(timeIntervalSince1970: 1), nil],
"arrayOptDecimal": [1 as Decimal128, 2 as Decimal128, nil],
"arrayOptObjectId": [ObjectId("6058f12b957ba06156586a7c"), ObjectId("6058f12682b2fbb1f334ef1d"), nil],
"arrayOptUuid": [UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fd")!, UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fe")!, nil],
"setBool": [true] as [Bool],
"setInt": [1, 1, 2, 3] as [Int],
"setInt8": [1, 2, 3, 1] as [Int8],
"setInt16": [1, 2, 3, 1] as [Int16],
"setInt32": [1, 2, 3, 1] as [Int32],
"setInt64": [1, 2, 3, 1] as [Int64],
"setFloat": [1 as Float, 2 as Float, 3 as Float, 1 as Float],
"setDouble": [1 as Double, 2 as Double, 3 as Double, 1 as Double],
"setString": ["a", "b", "c"] as [String],
"setBinary": ["a".data(using: .utf8)!] as [Data],
"setDate": [Date(timeIntervalSince1970: 1), Date(timeIntervalSince1970: 2)] as [Date],
"setDecimal": [1 as Decimal128, 2 as Decimal128],
"setObjectId": [ObjectId("6058f12b957ba06156586a7c"),
ObjectId("6058f12682b2fbb1f334ef1d")],
"setAny": [.none, .int(1), .string("a"), .none] as [AnyRealmValue],
"setUuid": [UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fd")!,
UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fe")!,
UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90ff")!],
"setOptBool": [true, false, nil] as [Bool?],
"setOptInt": [1, 1, 2, 3, nil] as [Int?],
"setOptInt8": [1, 2, 3, 1, nil] as [Int8?],
"setOptInt16": [1, 2, 3, 1, nil] as [Int16?],
"setOptInt32": [1, 2, 3, 1, nil] as [Int32?],
"setOptInt64": [1, 2, 3, 1, nil] as [Int64?],
"setOptFloat": [1 as Float, 2 as Float, 3 as Float, 1 as Float, nil],
"setOptDouble": [1 as Double, 2 as Double, 3 as Double, 1 as Double, nil],
"setOptString": ["a", "b", "c", nil],
"setOptBinary": ["a".data(using: .utf8)!, nil],
"setOptDate": [Date(timeIntervalSince1970: 1), Date(timeIntervalSince1970: 2), nil],
"setOptDecimal": [1 as Decimal128, 2 as Decimal128, nil],
"setOptObjectId": [ObjectId("6058f12b957ba06156586a7c"), ObjectId("6058f12682b2fbb1f334ef1d"), nil],
"setOptUuid": [UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fd")!,
UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fe")!,
UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90ff")!,
nil],
"mapBool": ["1": true, "2": false] as [String: Bool],
"mapInt": ["1": 1, "2": 1, "3": 2, "4": 3] as [String: Int],
"mapInt8": ["1": 1, "2": 2, "3": 3, "4": 1] as [String: Int8],
"mapInt16": ["1": 1, "2": 2, "3": 3, "4": 1] as [String: Int16],
"mapInt32": ["1": 1, "2": 2, "3": 3, "4": 1] as [String: Int32],
"mapInt64": ["1": 1, "2": 2, "3": 3, "4": 1] as [String: Int64],
"mapFloat": ["1": 1 as Float, "2": 2 as Float, "3": 3 as Float, "4": 1 as Float],
"mapDouble": ["1": 1 as Double, "2": 2 as Double, "3": 3 as Double, "4": 1 as Double],
"mapString": ["1": "a", "2": "b", "3": "c"] as [String: String],
"mapBinary": ["1": "a".data(using: .utf8)!] as [String: Data],
"mapDate": ["1": Date(timeIntervalSince1970: 1), "2": Date(timeIntervalSince1970: 2)] as [String: Date],
"mapDecimal": ["1": 1 as Decimal128, "2": 2 as Decimal128],
"mapObjectId": ["1": ObjectId("6058f12b957ba06156586a7c"),
"2": ObjectId("6058f12682b2fbb1f334ef1d")],
"mapAny": ["1": .none, "2": .int(1), "3": .string("a"), "4": .none] as [String: AnyRealmValue],
"mapUuid": ["1": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fd")!,
"2": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fe")!,
"3": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90ff")!],
"mapOptBool": ["1": true, "2": false, "3": nil] as [String: Bool?],
"mapOptInt": ["1": 1, "2": 1, "3": 2, "4": 3, "5": nil] as [String: Int?],
"mapOptInt8": ["1": 1, "2": 2, "3": 3, "4": 1, "5": nil] as [String: Int8?],
"mapOptInt16": ["1": 1, "2": 2, "3": 3, "4": 1, "5": nil] as [String: Int16?],
"mapOptInt32": ["1": 1, "2": 2, "3": 3, "4": 1, "5": nil] as [String: Int32?],
"mapOptInt64": ["1": 1, "2": 2, "3": 3, "4": 1, "5": nil] as [String: Int64?],
"mapOptFloat": ["1": 1 as Float, "2": 2 as Float, "3": 3 as Float, "4": 1 as Float, "5": nil],
"mapOptDouble": ["1": 1 as Double, "2": 2 as Double, "3": 3 as Double, "4": 1 as Double, "5": nil],
"mapOptString": ["1": "a", "2": "b", "3": "c", "4": nil],
"mapOptBinary": ["1": "a".data(using: .utf8)!, "2": nil],
"mapOptDate": ["1": Date(timeIntervalSince1970: 1), "2": Date(timeIntervalSince1970: 2), "3": nil],
"mapOptDecimal": ["1": 1 as Decimal128, "2": 2 as Decimal128, "3": nil],
"mapOptObjectId": ["1": ObjectId("6058f12b957ba06156586a7c"),
"2": ObjectId("6058f12682b2fbb1f334ef1d"),
"3": nil],
"mapOptUuid": ["1": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fd")!,
"2": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fe")!,
"3": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90ff")!,
"4": nil],
] as [String: Any]
}
override func setUp() {
super.setUp()
let realm = realmWithTestPath()
try! realm.write {
let js = realm.create(CommonPerson.self, value: ["firstName": "John",
"lastName": "Snow",
"birthday": Date(timeIntervalSince1970: 10),
"address": ["Winterfell", "Kingdom in the North"],
"money": Decimal128("2.22")])
let dt = realm.create(CommonPerson.self, value: ["firstName": "Daenerys",
"lastName": "Targaryen",
"birthday": Date(timeIntervalSince1970: 0),
"address": ["King's Landing", "Westeros"],
"money": Decimal128("2.22")])
js.friends.append(dt)
dt.friends.append(js)
realm.create(ModernAllTypesObject.self, value: allTypeValues)
realm.create(AdvancedObject.self, value: ["pk": ObjectId.generate(), "commonArray": [1, 2, 3], "objectsArray": [[1, true], [2, false]], "commonSet": [1, 2, 3], "objectsSet": [[1, true], [2, false]]])
}
}
func testProjectionManualInit() {
let realm = realmWithTestPath()
let johnSnow = realm.objects(CommonPerson.self).filter("lastName == 'Snow'").first!
// this step will happen under the hood
let pp = PersonProjection(projecting: johnSnow)
XCTAssertEqual(pp.homeCity, "Winterfell")
XCTAssertEqual(pp.birthdayAsEpochtime, Date(timeIntervalSince1970: 10).timeIntervalSince1970)
XCTAssertEqual(pp.firstFriendsName.first!, "Daenerys")
}
func testProjectionFromResult() {
let realm = realmWithTestPath()
let johnSnow: PersonProjection = realm.objects(PersonProjection.self).first!
XCTAssertEqual(johnSnow.homeCity, "Winterfell")
XCTAssertEqual(johnSnow.birthdayAsEpochtime, Date(timeIntervalSince1970: 10).timeIntervalSince1970)
XCTAssertEqual(johnSnow.firstFriendsName.first!, "Daenerys")
}
func testProjectionFromResultFiltered() {
let realm = realmWithTestPath()
let johnSnow: PersonProjection = realm.objects(PersonProjection.self).filter("lastName == 'Snow'").first!
XCTAssertEqual(johnSnow.homeCity, "Winterfell")
XCTAssertEqual(johnSnow.birthdayAsEpochtime, Date(timeIntervalSince1970: 10).timeIntervalSince1970)
XCTAssertEqual(johnSnow.firstFriendsName.first!, "Daenerys")
}
func testProjectionFromResultSorted() {
let realm = realmWithTestPath()
let dany: PersonProjection = realm.objects(PersonProjection.self).sorted(byKeyPath: "firstName").first!
XCTAssertEqual(dany.homeCity, "King's Landing")
XCTAssertEqual(dany.birthdayAsEpochtime, Date(timeIntervalSince1970: 0).timeIntervalSince1970)
XCTAssertEqual(dany.firstFriendsName.first!, "John")
}
func testProjectionEnumeration() {
let realm = realmWithTestPath()
XCTAssertGreaterThan(realm.objects(PersonProjection.self).count, 0)
for proj in realm.objects(PersonProjection.self) {
_ = proj
}
}
func testProjectionEquality() {
let realm = realmWithTestPath()
let johnObject = realm.objects(CommonPerson.self).filter("lastName == 'Snow'").first!
let johnDefaultInit = PersonProjection(projecting: johnObject)
let johnMapped = realm.objects(PersonProjection.self).filter("lastName == 'Snow'").first!
let notJohn = realm.objects(PersonProjection.self).filter("lastName != 'Snow'").first!
XCTAssertEqual(johnMapped, johnDefaultInit)
XCTAssertNotEqual(johnMapped, notJohn)
}
func testDescription() {
let actual = realmWithTestPath().objects(PersonProjection.self).filter("lastName == 'Snow'").first!.description
let expected = "PersonProjection<CommonPerson> <0x[0-9a-f]+> \\{\n\t\tfirstName\\(\\\\.firstName\\) = John;\n\tlastNameCaps\\(\\\\.lastName\\) = SNOW;\n\tbirthdayAsEpochtime\\(\\\\.birthday\\) = 10.0;\n\thomeCity\\(\\\\.address.city\\) = Optional\\(\"Winterfell\"\\);\n\tfirstFriendsName\\(\\\\.friends\\) = ProjectedCollection<String> \\{\n\t\\[0\\] Daenerys\n\\};\n\\}"
assertMatches(actual, expected)
}
func testProjectionsRealmShouldNotBeNil() {
XCTAssertNotNil(realmWithTestPath().objects(PersonProjection.self).first!.realm)
}
func testProjectionFromResultSortedBirthday() {
let realm = realmWithTestPath()
let dany: PersonProjection = realm.objects(PersonProjection.self).sorted(byKeyPath: "birthday").first!
XCTAssertEqual(dany.homeCity, "King's Landing")
XCTAssertEqual(dany.birthdayAsEpochtime, Date(timeIntervalSince1970: 0).timeIntervalSince1970)
XCTAssertEqual(dany.firstFriendsName.first!, "John")
}
func testProjectionForAllRealmTypes() {
let allTypesModel = realmWithTestPath().objects(AllTypesPrimitiveProjection.self).first!
XCTAssertEqual(allTypesModel.boolCol, allTypeValues["boolCol"] as! Bool)
XCTAssertEqual(allTypesModel.intCol, allTypeValues["intCol"] as! Int)
XCTAssertEqual(allTypesModel.int8Col, allTypeValues["int8Col"] as! Int8)
XCTAssertEqual(allTypesModel.int16Col, allTypeValues["int16Col"] as! Int16)
XCTAssertEqual(allTypesModel.int32Col, allTypeValues["int32Col"] as! Int32)
XCTAssertEqual(allTypesModel.int64Col, allTypeValues["int64Col"] as! Int64)
XCTAssertEqual(allTypesModel.floatCol, allTypeValues["floatCol"] as! Float)
XCTAssertEqual(allTypesModel.doubleCol, allTypeValues["doubleCol"] as! Double)
XCTAssertEqual(allTypesModel.stringCol, allTypeValues["stringCol"] as! String)
XCTAssertEqual(allTypesModel.binaryCol, allTypeValues["binaryCol"] as! Data)
XCTAssertEqual(allTypesModel.dateCol, allTypeValues["dateCol"] as! Date)
XCTAssertEqual(allTypesModel.decimalCol, allTypeValues["decimalCol"] as! Decimal128)
assertEquivalent(AnyRealmCollection(allTypesModel.arrayCol),
allTypeValues["arrayCol"] as! [ModernAllTypesObject],
expectedShouldBeCopy: true)
assertEquivalent(AnyRealmCollection(allTypesModel.setCol),
allTypeValues["setCol"] as! [ModernAllTypesObject],
expectedShouldBeCopy: true)
XCTAssertEqual(allTypesModel.anyCol, allTypeValues["anyCol"] as! AnyRealmValue)
XCTAssertEqual(allTypesModel.uuidCol, allTypeValues["uuidCol"] as! UUID)
XCTAssertEqual(allTypesModel.intEnumCol, allTypeValues["intEnumCol"] as! ModernIntEnum)
XCTAssertEqual(allTypesModel.stringEnumCol, allTypeValues["stringEnumCol"] as! ModernStringEnum)
XCTAssertEqual(allTypesModel.optBoolCol, allTypeValues["optBoolCol"] as! Bool?)
XCTAssertEqual(allTypesModel.optIntCol, allTypeValues["optIntCol"] as! Int?)
XCTAssertEqual(allTypesModel.optInt8Col, allTypeValues["optInt8Col"] as! Int8?)
XCTAssertEqual(allTypesModel.optInt16Col, allTypeValues["optInt16Col"] as! Int16?)
XCTAssertEqual(allTypesModel.optInt32Col, allTypeValues["optInt32Col"] as! Int32?)
XCTAssertEqual(allTypesModel.optInt64Col, allTypeValues["optInt64Col"] as! Int64?)
XCTAssertEqual(allTypesModel.optFloatCol, allTypeValues["optFloatCol"] as! Float?)
XCTAssertEqual(allTypesModel.optDoubleCol, allTypeValues["optDoubleCol"] as! Double?)
XCTAssertEqual(allTypesModel.optStringCol, allTypeValues["optStringCol"] as! String?)
XCTAssertEqual(allTypesModel.optBinaryCol, allTypeValues["optBinaryCol"] as! Data?)
XCTAssertEqual(allTypesModel.optDateCol, allTypeValues["optDateCol"] as! Date?)
XCTAssertEqual(allTypesModel.optDecimalCol, allTypeValues["optDecimalCol"] as! Decimal128?)
XCTAssertEqual(allTypesModel.optObjectIdCol, allTypeValues["optObjectIdCol"] as! ObjectId?)
XCTAssertEqual(allTypesModel.optUuidCol, allTypeValues["optUuidCol"] as! UUID?)
XCTAssertEqual(allTypesModel.optIntEnumCol, allTypeValues["optIntEnumCol"] as! ModernIntEnum?)
XCTAssertEqual(allTypesModel.optStringEnumCol, allTypeValues["optStringEnumCol"] as! ModernStringEnum?)
XCTAssertEqual(Array(allTypesModel.arrayBool), allTypeValues["arrayBool"] as! [Bool])
XCTAssertEqual(Array(allTypesModel.arrayInt), allTypeValues["arrayInt"] as! [Int])
XCTAssertEqual(Array(allTypesModel.arrayInt8), allTypeValues["arrayInt8"] as! [Int8])
XCTAssertEqual(Array(allTypesModel.arrayInt16), allTypeValues["arrayInt16"] as! [Int16])
XCTAssertEqual(Array(allTypesModel.arrayInt32), allTypeValues["arrayInt32"] as! [Int32])
XCTAssertEqual(Array(allTypesModel.arrayInt64), allTypeValues["arrayInt64"] as! [Int64])
XCTAssertEqual(Array(allTypesModel.arrayFloat), allTypeValues["arrayFloat"] as! [Float])
XCTAssertEqual(Array(allTypesModel.arrayDouble), allTypeValues["arrayDouble"] as! [Double])
XCTAssertEqual(Array(allTypesModel.arrayString), allTypeValues["arrayString"] as! [String])
XCTAssertEqual(Array(allTypesModel.arrayBinary), allTypeValues["arrayBinary"] as! [Data])
XCTAssertEqual(Array(allTypesModel.arrayDate), allTypeValues["arrayDate"] as! [Date])
XCTAssertEqual(Array(allTypesModel.arrayDecimal), allTypeValues["arrayDecimal"] as! [Decimal128])
XCTAssertEqual(Array(allTypesModel.arrayObjectId), allTypeValues["arrayObjectId"] as! [ObjectId])
XCTAssertEqual(Array(allTypesModel.arrayAny), allTypeValues["arrayAny"] as! [AnyRealmValue])
XCTAssertEqual(Array(allTypesModel.arrayUuid), allTypeValues["arrayUuid"] as! [UUID])
XCTAssertEqual(Array(allTypesModel.arrayOptBool), allTypeValues["arrayOptBool"] as! [Bool?])
XCTAssertEqual(Array(allTypesModel.arrayOptInt), allTypeValues["arrayOptInt"] as! [Int?])
XCTAssertEqual(Array(allTypesModel.arrayOptInt8), allTypeValues["arrayOptInt8"] as! [Int8?])
XCTAssertEqual(Array(allTypesModel.arrayOptInt16), allTypeValues["arrayOptInt16"] as! [Int16?])
XCTAssertEqual(Array(allTypesModel.arrayOptInt32), allTypeValues["arrayOptInt32"] as! [Int32?])
XCTAssertEqual(Array(allTypesModel.arrayOptInt64), allTypeValues["arrayOptInt64"] as! [Int64?])
XCTAssertEqual(Array(allTypesModel.arrayOptFloat), allTypeValues["arrayOptFloat"] as! [Float?])
XCTAssertEqual(Array(allTypesModel.arrayOptDouble), allTypeValues["arrayOptDouble"] as! [Double?])
XCTAssertEqual(Array(allTypesModel.arrayOptString), allTypeValues["arrayOptString"] as! [String?])
XCTAssertEqual(Array(allTypesModel.arrayOptBinary), allTypeValues["arrayOptBinary"] as! [Data?])
XCTAssertEqual(Array(allTypesModel.arrayOptDate), allTypeValues["arrayOptDate"] as! [Date?])
XCTAssertEqual(Array(allTypesModel.arrayOptDecimal), allTypeValues["arrayOptDecimal"] as! [Decimal128?])
XCTAssertEqual(Array(allTypesModel.arrayOptObjectId), allTypeValues["arrayOptObjectId"] as! [ObjectId?])
XCTAssertEqual(Array(allTypesModel.arrayOptUuid), allTypeValues["arrayOptUuid"] as! [UUID?])
assertSetEquals(allTypesModel.setBool, allTypeValues["setBool"] as! [Bool])
assertSetEquals(allTypesModel.setInt, allTypeValues["setInt"] as! [Int])
assertSetEquals(allTypesModel.setInt8, allTypeValues["setInt8"] as! [Int8])
assertSetEquals(allTypesModel.setInt16, allTypeValues["setInt16"] as! [Int16])
assertSetEquals(allTypesModel.setInt32, allTypeValues["setInt32"] as! [Int32])
assertSetEquals(allTypesModel.setInt64, allTypeValues["setInt64"] as! [Int64])
assertSetEquals(allTypesModel.setFloat, allTypeValues["setFloat"] as! [Float])
assertSetEquals(allTypesModel.setDouble, allTypeValues["setDouble"] as! [Double])
assertSetEquals(allTypesModel.setString, allTypeValues["setString"] as! [String])
assertSetEquals(allTypesModel.setBinary, allTypeValues["setBinary"] as! [Data])
assertSetEquals(allTypesModel.setDate, allTypeValues["setDate"] as! [Date])
assertSetEquals(allTypesModel.setDecimal, allTypeValues["setDecimal"] as! [Decimal128])
assertSetEquals(allTypesModel.setObjectId, allTypeValues["setObjectId"] as! [ObjectId])
assertSetEquals(allTypesModel.setAny, allTypeValues["setAny"] as! [AnyRealmValue])
assertSetEquals(allTypesModel.setUuid, allTypeValues["setUuid"] as! [UUID])
assertSetEquals(allTypesModel.setOptBool, allTypeValues["setOptBool"] as! [Bool?])
assertSetEquals(allTypesModel.setOptInt, allTypeValues["setOptInt"] as! [Int?])
assertSetEquals(allTypesModel.setOptInt8, allTypeValues["setOptInt8"] as! [Int8?])
assertSetEquals(allTypesModel.setOptInt16, allTypeValues["setOptInt16"] as! [Int16?])
assertSetEquals(allTypesModel.setOptInt32, allTypeValues["setOptInt32"] as! [Int32?])
assertSetEquals(allTypesModel.setOptInt64, allTypeValues["setOptInt64"] as! [Int64?])
assertSetEquals(allTypesModel.setOptFloat, allTypeValues["setOptFloat"] as! [Float?])
assertSetEquals(allTypesModel.setOptDouble, allTypeValues["setOptDouble"] as! [Double?])
assertSetEquals(allTypesModel.setOptString, allTypeValues["setOptString"] as! [String?])
assertSetEquals(allTypesModel.setOptBinary, allTypeValues["setOptBinary"] as! [Data?])
assertSetEquals(allTypesModel.setOptDate, allTypeValues["setOptDate"] as! [Date?])
assertSetEquals(allTypesModel.setOptDecimal, allTypeValues["setOptDecimal"] as! [Decimal128?])
assertSetEquals(allTypesModel.setOptObjectId, allTypeValues["setOptObjectId"] as! [ObjectId?])
assertSetEquals(allTypesModel.setOptUuid, allTypeValues["setOptUuid"] as! [UUID?])
assertMapEquals(allTypesModel.mapBool, allTypeValues["mapBool"] as! [String: Bool])
assertMapEquals(allTypesModel.mapInt, allTypeValues["mapInt"] as! [String: Int])
assertMapEquals(allTypesModel.mapInt8, allTypeValues["mapInt8"] as! [String: Int8])
assertMapEquals(allTypesModel.mapInt16, allTypeValues["mapInt16"] as! [String: Int16])
assertMapEquals(allTypesModel.mapInt32, allTypeValues["mapInt32"] as! [String: Int32])
assertMapEquals(allTypesModel.mapInt64, allTypeValues["mapInt64"] as! [String: Int64])
assertMapEquals(allTypesModel.mapFloat, allTypeValues["mapFloat"] as! [String: Float])
assertMapEquals(allTypesModel.mapDouble, allTypeValues["mapDouble"] as! [String: Double])
assertMapEquals(allTypesModel.mapString, allTypeValues["mapString"] as! [String: String])
assertMapEquals(allTypesModel.mapBinary, allTypeValues["mapBinary"] as! [String: Data])
assertMapEquals(allTypesModel.mapDate, allTypeValues["mapDate"] as! [String: Date])
assertMapEquals(allTypesModel.mapDecimal, allTypeValues["mapDecimal"] as! [String: Decimal128])
assertMapEquals(allTypesModel.mapObjectId, allTypeValues["mapObjectId"] as! [String: ObjectId])
assertMapEquals(allTypesModel.mapAny, allTypeValues["mapAny"] as! [String: AnyRealmValue])
assertMapEquals(allTypesModel.mapUuid, allTypeValues["mapUuid"] as! [String: UUID])
assertMapEquals(allTypesModel.mapOptBool, allTypeValues["mapOptBool"] as! [String: Bool?])
assertMapEquals(allTypesModel.mapOptInt, allTypeValues["mapOptInt"] as! [String: Int?])
assertMapEquals(allTypesModel.mapOptInt8, allTypeValues["mapOptInt8"] as! [String: Int8?])
assertMapEquals(allTypesModel.mapOptInt16, allTypeValues["mapOptInt16"] as! [String: Int16?])
assertMapEquals(allTypesModel.mapOptInt32, allTypeValues["mapOptInt32"] as! [String: Int32?])
assertMapEquals(allTypesModel.mapOptInt64, allTypeValues["mapOptInt64"] as! [String: Int64?])
assertMapEquals(allTypesModel.mapOptFloat, allTypeValues["mapOptFloat"] as! [String: Float?])
assertMapEquals(allTypesModel.mapOptDouble, allTypeValues["mapOptDouble"] as! [String: Double?])
assertMapEquals(allTypesModel.mapOptString, allTypeValues["mapOptString"] as! [String: String?])
assertMapEquals(allTypesModel.mapOptBinary, allTypeValues["mapOptBinary"] as! [String: Data?])
assertMapEquals(allTypesModel.mapOptDate, allTypeValues["mapOptDate"] as! [String: Date?])
assertMapEquals(allTypesModel.mapOptDecimal, allTypeValues["mapOptDecimal"] as! [String: Decimal128?])
assertMapEquals(allTypesModel.mapOptObjectId, allTypeValues["mapOptObjectId"] as! [String: ObjectId?])
assertMapEquals(allTypesModel.mapOptUuid, allTypeValues["mapOptUuid"] as! [String: UUID?])
}
func observeKeyPathChange<Root: ObjectBase, P: Projection<Root>, E: Equatable>(_ obj: Object, _ obs: P, _ keyPath: PartialKeyPath<P>,
_ old: E?, _ new: E?,
fileName: StaticString = #file, lineNumber: UInt = #line, _ block: () -> Void) {
let ex = expectation(description: "observeKeyPathChange")
let token = obs.observe(keyPaths: [keyPath]) { changes in
ex.fulfill()
if case .change(_, let properties) = changes {
XCTAssertEqual(properties.count, 1)
let actualOld = properties[0].oldValue as? E
let actualNew = properties[0].newValue as? E
XCTAssert(actualOld != actualNew, "Old value \(String(describing: actualOld)) should not be equal to New value \(String(describing: actualNew))",
file: (fileName), line: lineNumber)
XCTAssert(new == actualNew,
"New value: expected \(String(describing: new)), got \(String(describing: actualNew))",
file: (fileName), line: lineNumber)
if actualOld != nil {
XCTAssert(old == actualOld,
"Old value: expected \(String(describing: old)), got \(String(describing: actualOld))",
file: (fileName), line: lineNumber)
}
} else {
XCTFail("Expected .change but got \(changes)")
}
}
try! obj.realm!.write {
block()
}
waitForExpectations(timeout: 2, handler: nil)
token.invalidate()
}
func observeArrayKeyPathChange<Root: ObjectBase, P: Projection<Root>, E: Equatable & RealmCollectionValue>(_ obj: Object, _ obs: P, _ keyPath: PartialKeyPath<P>,
_ new: [E]?,
fileName: StaticString = #file, lineNumber: UInt = #line, _ block: () -> Void) {
let ex = expectation(description: "observeKeyPathChange")
let token = obs.observe(keyPaths: [keyPath]) { changes in
ex.fulfill()
if case .change(let object, let properties) = changes {
XCTAssertEqual(properties.count, 1)
let observedOld = properties[0].oldValue as? [E]
let observedNew = properties[0].newValue as? [E]
XCTAssertNil(observedOld)
XCTAssertNil(observedNew)
guard let projectedNew = object[keyPath: keyPath] as? RealmSwift.List<E>,
let newVals = new else {
XCTFail("Expected new array to be [\(String(describing: E.self))] and projected array to be \(String(describing: RealmSwift.List<E>.self)), got \(String(describing: new)) and \(String(describing: obs[keyPath: keyPath]))",
file: (fileName), line: lineNumber)
return
}
if projectedNew.count != newVals.count {
XCTAssertEqual(projectedNew.count, newVals.count, "Expected \(projectedNew) and \(newVals) to be equal", file: (fileName), line: lineNumber)
} else {
for (index, element) in projectedNew.enumerated() {
XCTAssertEqual(element, newVals[index], "Element \(element) at index \(index) should be equal to \(newVals[index])", file: (fileName), line: lineNumber)
}
}
} else {
XCTFail("Expected .change but got \(changes)", file: (fileName), line: lineNumber)
}
}
try! obj.realm!.write {
block()
}
waitForExpectations(timeout: 2, handler: nil)
token.invalidate()
}
func observeSetKeyPathChange<Root: ObjectBase, P: Projection<Root>, E: Equatable & RealmCollectionValue>(_ obj: Object, _ obs: P, _ keyPath: PartialKeyPath<P>,
_ new: [E],
fileName: StaticString = #file, lineNumber: UInt = #line, _ block: () -> Void) {
let ex = expectation(description: "observeKeyPathChange")
let token = obs.observe(keyPaths: [keyPath]) { changes in
ex.fulfill()
if case .change(let object, let properties) = changes {
XCTAssertEqual(properties.count, 1)
let observedOld = properties[0].oldValue as? Set<E>
let observedNew = properties[0].newValue as? Set<E>
XCTAssertNil(observedOld)
XCTAssertNil(observedNew)
guard let projectedNew = object[keyPath: keyPath] as? MutableSet<E> else {
XCTFail("Expected new set to be \(String(describing: Set<E>.self)) and projected set to be \(String(describing: MutableSet<E>.self)), got \(String(describing: new)) and \(String(describing: obs[keyPath: keyPath]))",
file: (fileName), line: lineNumber)
return
}
self.assertSetEquals(projectedNew, new)
} else {
XCTFail("Expected .change but got \(changes)", file: (fileName), line: lineNumber)
}
}
try! obj.realm!.write {
block()
}
waitForExpectations(timeout: 2, handler: nil)
token.invalidate()
}
func observeMapKeyPathChange<Root: ObjectBase, P: Projection<Root>, E: Equatable & RealmCollectionValue>(_ obj: Object, _ obs: P, _ keyPath: PartialKeyPath<P>,
_ new: Dictionary<String, E>,
fileName: StaticString = #file, lineNumber: UInt = #line, _ block: () -> Void) {
let ex = expectation(description: "observeKeyPathChange")
let token = obs.observe(keyPaths: [keyPath]) { changes in
ex.fulfill()
if case .change(let object, let properties) = changes {
XCTAssertEqual(properties.count, 1)
let observedOld = properties[0].oldValue as? MutableSet<E>
let observedNew = properties[0].newValue as? MutableSet<E>
XCTAssertNil(observedOld)
XCTAssertNil(observedNew)
guard let projectedNew = object[keyPath: keyPath] as? Map<String, E> else {
XCTFail("Expected new set to be \(String(describing: Dictionary<String, E>.self)) and projected set to be \(String(describing: Map<String, E>.self)), got \(String(describing: new)) and \(String(describing: obs[keyPath: keyPath]))",
file: (fileName), line: lineNumber)
return
}
if projectedNew.count != new.count {
XCTAssertEqual(projectedNew.count, new.count, "Expected \(projectedNew) and \(new) to be equal", file: (fileName), line: lineNumber)
} else {
for (key, value) in new {
XCTAssertEqual(projectedNew[key], value, "Projected set should contain (\(key), \(value))", file: (fileName), line: lineNumber)
}
}
} else {
XCTFail("Expected .change but got \(changes)", file: (fileName), line: lineNumber)
}
}
try! obj.realm!.write {
block()
}
waitForExpectations(timeout: 2, handler: nil)
token.invalidate()
}
func testAllPropertyTypesNotifications() {
let realm = realmWithTestPath()
let obj = realm.objects(ModernAllTypesObject.self).first!
let obs = realm.objects(AllTypesPrimitiveProjection.self).first!
let data = "b".data(using: String.Encoding.utf8)!
let date = Date(timeIntervalSince1970: 7)
let decimal = Decimal128(number: 3)
let objectId = ObjectId()
let uuid = UUID()
let object = ModernAllTypesObject(value: ["intCol": 2])
let anyValue = AnyRealmValue.int(22)
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.boolCol, obj.boolCol, false, { obj.boolCol = false })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.intCol, obj.intCol, 2, { obj.intCol = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.int8Col, obj.int8Col, 2, { obj.int8Col = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.int16Col, obj.int16Col, 2, { obj.int16Col = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.int32Col, obj.int32Col, 2, { obj.int32Col = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.int64Col, obj.int64Col, 2, { obj.int64Col = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.floatCol, obj.floatCol, 2.0, { obj.floatCol = 2.0 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.doubleCol, obj.doubleCol, 2.0, { obj.doubleCol = 2.0 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.stringCol, obj.stringCol, "def", { obj.stringCol = "def" })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.binaryCol, obj.binaryCol, data, { obj.binaryCol = data })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.dateCol, obj.dateCol, date, { obj.dateCol = date })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.decimalCol, obj.decimalCol, decimal, { obj.decimalCol = decimal })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.objectIdCol, obj.objectIdCol, objectId, { obj.objectIdCol = objectId })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.objectCol, obj.objectCol, object, { obj.objectCol = object })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.anyCol, obj.anyCol, anyValue, { obj.anyCol = anyValue })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.uuidCol, obj.uuidCol, uuid, { obj.uuidCol = uuid })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.intEnumCol, obj.intEnumCol, .value2, { obj.intEnumCol = .value2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.stringEnumCol, obj.stringEnumCol, .value2, { obj.stringEnumCol = .value2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optIntCol, obj.optIntCol, 2, { obj.optIntCol = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optInt8Col, obj.optInt8Col, 2, { obj.optInt8Col = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optInt16Col, obj.optInt16Col, 2, { obj.optInt16Col = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optInt32Col, obj.optInt32Col, 2, { obj.optInt32Col = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optInt64Col, obj.optInt64Col, 2, { obj.optInt64Col = 2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optFloatCol, obj.optFloatCol, 2.0, { obj.optFloatCol = 2.0 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optDoubleCol, obj.optDoubleCol, 2.0, { obj.optDoubleCol = 2.0 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optBoolCol, obj.optBoolCol, false, { obj.optBoolCol = false })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optStringCol, obj.optStringCol, "def", { obj.optStringCol = "def" })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optBinaryCol, obj.optBinaryCol, data, { obj.optBinaryCol = data })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optDateCol, obj.optDateCol, date, { obj.optDateCol = date })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optDecimalCol, obj.optDecimalCol, decimal, { obj.optDecimalCol = decimal })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optObjectIdCol, obj.optObjectIdCol, objectId, { obj.optObjectIdCol = objectId })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optUuidCol, obj.optUuidCol, uuid, { obj.optUuidCol = uuid })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optIntEnumCol, obj.optIntEnumCol, .value2, { obj.optIntEnumCol = .value2 })
observeKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.optStringEnumCol, obj.optStringEnumCol, .value2, { obj.optStringEnumCol = .value2 })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayBool, allTypeValues["arrayBool"] as! [Bool] + [false]) { obj.arrayBool.append(false) }
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayInt, allTypeValues["arrayInt"] as! [Int] + [4], { obj.arrayInt.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayInt8, allTypeValues["arrayInt8"] as! [Int8] + [4], { obj.arrayInt8.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayInt16, allTypeValues["arrayInt16"] as! [Int16] + [4], { obj.arrayInt16.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayInt32, allTypeValues["arrayInt32"] as! [Int32] + [4], { obj.arrayInt32.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayInt64, allTypeValues["arrayInt64"] as! [Int64] + [4], { obj.arrayInt64.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayFloat, allTypeValues["arrayFloat"] as! [Float] + [4], { obj.arrayFloat.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayDouble, allTypeValues["arrayDouble"] as! [Double] + [4], { obj.arrayDouble.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayString, allTypeValues["arrayString"] as! [String] + ["d"], { obj.arrayString.append("d") })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayBinary, allTypeValues["arrayBinary"] as! [Data] + [data], { obj.arrayBinary.append(data) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayDate, allTypeValues["arrayDate"] as! [Date] + [date], { obj.arrayDate.append(date) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayDecimal, allTypeValues["arrayDecimal"] as! [Decimal128] + [decimal], { obj.arrayDecimal.append(decimal) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayObjectId, allTypeValues["arrayObjectId"] as! [ObjectId] + [objectId], { obj.arrayObjectId.append(objectId) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayAny, allTypeValues["arrayAny"] as! [AnyRealmValue] + [anyValue], { obj.arrayAny.append(anyValue) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayUuid, allTypeValues["arrayUuid"] as! [UUID] + [uuid], { obj.arrayUuid.append(uuid) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptBool, allTypeValues["arrayOptBool"] as! [Bool?] + [true], { obj.arrayOptBool.append(true) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptInt, allTypeValues["arrayOptInt"] as! [Int?] + [4], { obj.arrayOptInt.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptInt8, allTypeValues["arrayOptInt8"] as! [Int8?] + [4], { obj.arrayOptInt8.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptInt16, allTypeValues["arrayOptInt16"] as! [Int16?] + [4], { obj.arrayOptInt16.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptInt32, allTypeValues["arrayOptInt32"] as! [Int32?] + [4], { obj.arrayOptInt32.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptInt64, allTypeValues["arrayOptInt64"] as! [Int64?] + [4], { obj.arrayOptInt64.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptFloat, allTypeValues["arrayOptFloat"] as! [Float?] + [4], { obj.arrayOptFloat.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptDouble, allTypeValues["arrayOptDouble"] as! [Double?] + [4], { obj.arrayOptDouble.append(4) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptString, allTypeValues["arrayOptString"] as! [String?] + ["d"], { obj.arrayOptString.append("d") })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptBinary, allTypeValues["arrayOptBinary"] as! [Data?] + [data], { obj.arrayOptBinary.append(data) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptDate, allTypeValues["arrayOptDate"] as! [Date?] + [date], { obj.arrayOptDate.append(date) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptDecimal, allTypeValues["arrayOptDecimal"] as! [Decimal128?] + [decimal], { obj.arrayOptDecimal.append(decimal) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptObjectId, allTypeValues["arrayOptObjectId"] as! [ObjectId?] + [objectId], { obj.arrayOptObjectId.append(objectId) })
observeArrayKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.arrayOptUuid, allTypeValues["arrayOptUuid"] as! [UUID?] + [uuid], { obj.arrayOptUuid.append(uuid) })
try! realmWithTestPath().write {
obj.setBool.removeAll()
obj.setBool.insert(objectsIn: [true])
obj.setOptBool.removeAll()
obj.setOptBool.insert(objectsIn: [true, nil])
}
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setBool, allTypeValues["setBool"] as! [Bool] + [false], { obj.setBool.insert(false) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setInt, allTypeValues["setInt"] as! [Int] + [4], { obj.setInt.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setInt8, allTypeValues["setInt8"] as! [Int8] + [4], { obj.setInt8.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setInt16, allTypeValues["setInt16"] as! [Int16] + [4], { obj.setInt16.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setInt32, allTypeValues["setInt32"] as! [Int32] + [4], { obj.setInt32.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setInt64, allTypeValues["setInt64"] as! [Int64] + [4], { obj.setInt64.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setFloat, allTypeValues["setFloat"] as! [Float] + [4], { obj.setFloat.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setDouble, allTypeValues["setDouble"] as! [Double] + [4], { obj.setDouble.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setString, allTypeValues["setString"] as! [String] + ["d"], { obj.setString.insert("d") })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setBinary, allTypeValues["setBinary"] as! [Data] + [data], { obj.setBinary.insert(data) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setDate, allTypeValues["setDate"] as! [Date] + [date], { obj.setDate.insert(date) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setDecimal, allTypeValues["setDecimal"] as! [Decimal128] + [decimal], { obj.setDecimal.insert(decimal) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setObjectId, allTypeValues["setObjectId"] as! [ObjectId] + [objectId], { obj.setObjectId.insert(objectId) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setAny, allTypeValues["setAny"] as! [AnyRealmValue] + [anyValue], { obj.setAny.insert(anyValue) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setUuid, allTypeValues["setUuid"] as! [UUID] + [uuid], { obj.setUuid.insert(uuid) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptBool, allTypeValues["setOptBool"] as! [Bool?] + [false], { obj.setOptBool.insert(false) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptInt, allTypeValues["setOptInt"] as! [Int?] + [4], { obj.setOptInt.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptInt8, allTypeValues["setOptInt8"] as! [Int8?] + [4], { obj.setOptInt8.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptInt16, allTypeValues["setOptInt16"] as! [Int16?] + [4], { obj.setOptInt16.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptInt32, allTypeValues["setOptInt32"] as! [Int32?] + [4], { obj.setOptInt32.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptInt64, allTypeValues["setOptInt64"] as! [Int64?] + [4], { obj.setOptInt64.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptFloat, allTypeValues["setOptFloat"] as! [Float?] + [4], { obj.setOptFloat.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptDouble, allTypeValues["setOptDouble"] as! [Double?] + [4], { obj.setOptDouble.insert(4) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptString, allTypeValues["setOptString"] as! [String?] + ["d"], { obj.setOptString.insert("d") })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptBinary, allTypeValues["setOptBinary"] as! [Data?] + [data], { obj.setOptBinary.insert(data) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptDate, allTypeValues["setOptDate"] as! [Date?] + [date], { obj.setOptDate.insert(date) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptDecimal, allTypeValues["setOptDecimal"] as! [Decimal128?] + [decimal], { obj.setOptDecimal.insert(decimal) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptObjectId, allTypeValues["setOptObjectId"] as! [ObjectId?] + [objectId], { obj.setOptObjectId.insert(objectId) })
observeSetKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.setOptUuid, allTypeValues["setOptUuid"] as! [UUID?] + [uuid], { obj.setOptUuid.insert(uuid) })
let newValues: [String: Any] = [
"mapBool": ["1": false, "2": false] as [String: Bool],
"mapInt": ["1": 4, "2": 1, "3": 2, "4": 3] as [String: Int],
"mapInt8": ["1": 4, "2": 2, "3": 3, "4": 1] as [String: Int8],
"mapInt16": ["1": 4, "2": 2, "3": 3, "4": 1] as [String: Int16],
"mapInt32": ["1": 4, "2": 2, "3": 3, "4": 1] as [String: Int32],
"mapInt64": ["1": 4, "2": 2, "3": 3, "4": 1] as [String: Int64],
"mapFloat": ["1": 4 as Float, "2": 2 as Float, "3": 3 as Float, "4": 1 as Float],
"mapDouble": ["1": 4 as Double, "2": 2 as Double, "3": 3 as Double, "4": 1 as Double],
"mapString": ["1": "d", "2": "b", "3": "c"] as [String: String],
"mapBinary": ["1": data] as [String: Data],
"mapDate": ["1": date, "2": Date(timeIntervalSince1970: 2)] as [String: Date],
"mapDecimal": ["1": decimal, "2": 2 as Decimal128],
"mapObjectId": ["1": objectId,
"2": ObjectId("6058f12682b2fbb1f334ef1d")],
"mapAny": ["1": anyValue, "2": .int(1), "3": .string("a"), "4": .none] as [String: AnyRealmValue],
"mapUuid": ["1": uuid,
"2": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fe")!,
"3": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90ff")!],
"mapOptBool": ["1": false, "2": false, "3": nil] as [String: Bool?],
"mapOptInt": ["1": 4, "2": 1, "3": 2, "4": 3, "5": nil] as [String: Int?],
"mapOptInt8": ["1": 4, "2": 2, "3": 3, "4": 1, "5": nil] as [String: Int8?],
"mapOptInt16": ["1": 4, "2": 2, "3": 3, "4": 1, "5": nil] as [String: Int16?],
"mapOptInt32": ["1": 4, "2": 2, "3": 3, "4": 1, "5": nil] as [String: Int32?],
"mapOptInt64": ["1": 4, "2": 2, "3": 3, "4": 1, "5": nil] as [String: Int64?],
"mapOptFloat": ["1": 4 as Float, "2": 2 as Float, "3": 3 as Float, "4": 1 as Float, "5": nil],
"mapOptDouble": ["1": 4 as Double, "2": 2 as Double, "3": 3 as Double, "4": 1 as Double, "5": nil],
"mapOptString": ["1": "d", "2": "b", "3": "c", "4": nil],
"mapOptBinary": ["1": data, "2": nil],
"mapOptDate": ["1": date, "2": Date(timeIntervalSince1970: 2), "3": nil],
"mapOptDecimal": ["1": decimal, "2": 2 as Decimal128, "3": nil],
"mapOptObjectId": ["1": objectId,
"2": ObjectId("6058f12682b2fbb1f334ef1d"),
"3": nil],
"mapOptUuid": ["1": uuid,
"2": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90fe")!,
"3": UUID(uuidString: "6b28ec45-b29a-4b0a-bd6a-343c7f6d90ff")!,
"4": nil],
]
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapBool, newValues["mapBool"] as! Dictionary<String, Bool>, { obj.mapBool["1"] = false })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapInt, newValues["mapInt"] as! Dictionary<String, Int>, { obj.mapInt["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapInt8, newValues["mapInt8"] as! Dictionary<String, Int8>, { obj.mapInt8["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapInt16, newValues["mapInt16"] as! Dictionary<String, Int16>, { obj.mapInt16["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapInt32, newValues["mapInt32"] as! Dictionary<String, Int32>, { obj.mapInt32["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapInt64, newValues["mapInt64"] as! Dictionary<String, Int64>, { obj.mapInt64["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapFloat, newValues["mapFloat"] as! Dictionary<String, Float>, { obj.mapFloat["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapDouble, newValues["mapDouble"] as! Dictionary<String, Double>, { obj.mapDouble["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapString, newValues["mapString"] as! Dictionary<String, String>, { obj.mapString["1"] = "d" })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapBinary, newValues["mapBinary"] as! Dictionary<String, Data>, { obj.mapBinary["1"] = data })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapDate, newValues["mapDate"] as! Dictionary<String, Date>, { obj.mapDate["1"] = date })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapDecimal, newValues["mapDecimal"] as! Dictionary<String, Decimal128>, { obj.mapDecimal["1"] = decimal })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapObjectId, newValues["mapObjectId"] as! Dictionary<String, ObjectId>, { obj.mapObjectId["1"] = objectId })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapAny, newValues["mapAny"] as! Dictionary<String, AnyRealmValue>, { obj.mapAny["1"] = anyValue })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapUuid, newValues["mapUuid"] as! Dictionary<String, UUID>, { obj.mapUuid["1"] = uuid })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptBool, newValues["mapOptBool"] as! Dictionary<String, Bool?>, { obj.mapOptBool["1"] = false })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptInt, newValues["mapOptInt"] as! Dictionary<String, Int?>, { obj.mapOptInt["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptInt8, newValues["mapOptInt8"] as! Dictionary<String, Int8?>, { obj.mapOptInt8["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptInt16, newValues["mapOptInt16"] as! Dictionary<String, Int16?>, { obj.mapOptInt16["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptInt32, newValues["mapOptInt32"] as! Dictionary<String, Int32?>, { obj.mapOptInt32["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptInt64, newValues["mapOptInt64"] as! Dictionary<String, Int64?>, { obj.mapOptInt64["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptFloat, newValues["mapOptFloat"] as! Dictionary<String, Float?>, { obj.mapOptFloat["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptDouble, newValues["mapOptDouble"] as! Dictionary<String, Double?>, { obj.mapOptDouble["1"] = 4 })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptString, newValues["mapOptString"] as! Dictionary<String, String?>, { obj.mapOptString["1"] = "d" })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptBinary, newValues["mapOptBinary"] as! Dictionary<String, Data?>, { obj.mapOptBinary["1"] = data })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptDate, newValues["mapOptDate"] as! Dictionary<String, Date?>, { obj.mapOptDate["1"] = date })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptDecimal, newValues["mapOptDecimal"] as! Dictionary<String, Decimal128?>, { obj.mapOptDecimal["1"] = decimal })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptObjectId, newValues["mapOptObjectId"] as! Dictionary<String, ObjectId?>, { obj.mapOptObjectId["1"] = objectId })
observeMapKeyPathChange(obj, obs, \AllTypesPrimitiveProjection.mapOptUuid, newValues["mapOptUuid"] as! Dictionary<String, UUID?>, { obj.mapOptUuid["1"] = uuid })
}
func testObserveKeyPath() {
let realm = realmWithTestPath()
let johnProjection = realm.objects(PersonProjection.self).filter("lastName == 'Snow'").first!
let ex = expectation(description: "testProjectionNotification")
let token = johnProjection.observe(keyPaths: ["lastName"], on: nil) { _ in
ex.fulfill()
}
dispatchSyncNewThread {
let realm = self.realmWithTestPath()
try! realm.write {
let johnObject = realm.objects(CommonPerson.self).filter("lastName == 'Snow'").first!
johnObject.lastName = "Targaryen"
}
}
waitForExpectations(timeout: 1, handler: nil)
token.invalidate()
}
var changeDictionary: [NSKeyValueChangeKey: Any]?
override class func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
// noop
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
changeDictionary = change
}
// swiftlint:disable:next cyclomatic_complexity
func observeChange<T: Equatable>(_ obj: AllTypesPrimitiveProjection, _ key: String, _ old: T?, _ new: T?,
fileName: StaticString = #file, lineNumber: UInt = #line, _ block: () -> Void) {
let kvoOptions: NSKeyValueObservingOptions = [.old, .new]
obj.addObserver(self, forKeyPath: key, options: kvoOptions, context: nil)
try! obj.realm!.write {
block()
}
obj.removeObserver(self, forKeyPath: key)
XCTAssert(changeDictionary != nil, "Did not get a notification", file: (fileName), line: lineNumber)
guard changeDictionary != nil else { return }
let actualOld = changeDictionary![.oldKey] as? T
let actualNew = changeDictionary![.newKey] as? T
XCTAssert(old == actualOld,
"Old value: expected \(String(describing: old)), got \(String(describing: actualOld))",
file: (fileName), line: lineNumber)
XCTAssert(new == actualNew,
"New value: expected \(String(describing: new)), got \(String(describing: actualNew))",
file: (fileName), line: lineNumber)
changeDictionary = nil
}
func observeListChange(_ obj: AllTypesPrimitiveProjection, _ key: String, _ kind: NSKeyValueChange, _ indexes: NSIndexSet = NSIndexSet(index: 0),
fileName: StaticString = #file, lineNumber: UInt = #line, _ block: () -> Void) {
obj.addObserver(self, forKeyPath: key, options: [.old, .new], context: nil)
obj.realm?.beginWrite()
block()
try! obj.realm?.commitWrite()
obj.removeObserver(self, forKeyPath: key)
XCTAssert(changeDictionary != nil, "Did not get a notification", file: (fileName), line: lineNumber)
guard changeDictionary != nil else { return }
let actualKind = NSKeyValueChange(rawValue: (changeDictionary![NSKeyValueChangeKey.kindKey] as! NSNumber).uintValue)!
let actualIndexes = changeDictionary![NSKeyValueChangeKey.indexesKey]! as! NSIndexSet
XCTAssert(actualKind == kind, "Change kind: expected \(kind), got \(actualKind)", file: (fileName),
line: lineNumber)
XCTAssert(actualIndexes.isEqual(indexes), "Changed indexes: expected \(indexes), got \(actualIndexes)",
file: (fileName), line: lineNumber)
changeDictionary = nil
}
func newObjects(_ defaultValues: [String: Any] = [:]) -> (ModernAllTypesObject, AllTypesPrimitiveProjection) {
let realm = realmWithTestPath()
realm.beginWrite()
realm.delete( realm.objects(ModernAllTypesObject.self))
let obj = realm.create(ModernAllTypesObject.self, value: defaultValues)
let obs = AllTypesPrimitiveProjection(projecting: obj)
try! realm.commitWrite()
return (obj, obs)
}
func observeSetChange(_ obj: AllTypesPrimitiveProjection, _ key: String,
fileName: StaticString = #file, lineNumber: UInt = #line, _ block: () -> Void) {
obj.addObserver(self, forKeyPath: key, options: [], context: nil)
obj.realm!.beginWrite()
block()
try! obj.realm!.commitWrite()
obj.removeObserver(self, forKeyPath: key)
XCTAssert(changeDictionary != nil, "Did not get a notification", file: (fileName), line: lineNumber)
guard changeDictionary != nil else { return }
let actualKind = NSKeyValueChange(rawValue: (changeDictionary![NSKeyValueChangeKey.kindKey] as! NSNumber).uintValue)!
XCTAssert(actualKind == NSKeyValueChange.setting, "Change kind: expected NSKeyValueChange.setting, got \(actualKind)", file: (fileName),
line: lineNumber)
changeDictionary = nil
}
func testAllPropertyTypes() {
var (obj, obs) = newObjects(allTypeValues)
let data = "b".data(using: String.Encoding.utf8)!
let date = Date(timeIntervalSince1970: 2)
let decimal = Decimal128(number: 3)
let objectId = ObjectId()
let uuid = UUID()
observeChange(obs, "boolCol", true, false) { obj.boolCol = false }
observeChange(obs, "int8Col", 11 as Int8, 10) { obj.int8Col = 10 }
observeChange(obs, "int16Col", 12 as Int16, 10) { obj.int16Col = 10 }
observeChange(obs, "int32Col", 13 as Int32, 10) { obj.int32Col = 10 }
observeChange(obs, "int64Col", 14 as Int64, 10) { obj.int64Col = 10 }
observeChange(obs, "floatCol", 15 as Float, 10) { obj.floatCol = 10 }
observeChange(obs, "doubleCol", 16 as Double, 10) { obj.doubleCol = 10 }
observeChange(obs, "stringCol", "a", "abc") { obj.stringCol = "abc" }
observeChange(obs, "objectCol", obj.objectCol, obj) { obj.objectCol = obj }
observeChange(obs, "binaryCol", obj.binaryCol, data) { obj.binaryCol = data }
observeChange(obs, "dateCol", obj.dateCol, date) { obj.dateCol = date }
observeChange(obs, "decimalCol", obj.decimalCol, decimal) { obj.decimalCol = decimal }
observeChange(obs, "objectIdCol", obj.objectIdCol, objectId) { obj.objectIdCol = objectId }
observeChange(obs, "uuidCol", obj.uuidCol, uuid) { obj.uuidCol = uuid }
observeChange(obs, "anyCol", 20, 1) { obj.anyCol = .int(1) }
(obj, obs) = newObjects()
observeListChange(obs, "arrayCol", .insertion) { obj.arrayCol.append(obj) }
observeListChange(obs, "arrayCol", .removal) { obj.arrayCol.removeAll() }
observeSetChange(obs, "setCol") { obj.setCol.insert(obj) }
observeSetChange(obs, "setCol") { obj.setCol.remove(obj) }
observeChange(obs, "optIntCol", nil, 10) { obj.optIntCol = 10 }
observeChange(obs, "optFloatCol", nil, 10.0) { obj.optFloatCol = 10 }
observeChange(obs, "optDoubleCol", nil, 10.0) { obj.optDoubleCol = 10 }
observeChange(obs, "optBoolCol", nil, true) { obj.optBoolCol = true }
observeChange(obs, "optStringCol", nil, "abc") { obj.optStringCol = "abc" }
observeChange(obs, "optBinaryCol", nil, data) { obj.optBinaryCol = data }
observeChange(obs, "optDateCol", nil, date) { obj.optDateCol = date }
observeChange(obs, "optDecimalCol", nil, decimal) { obj.optDecimalCol = decimal }
observeChange(obs, "optObjectIdCol", nil, objectId) { obj.optObjectIdCol = objectId }
observeChange(obs, "optUuidCol", nil, uuid) { obj.optUuidCol = uuid }
observeChange(obs, "optIntCol", 10, nil) { obj.optIntCol = nil }
observeChange(obs, "optFloatCol", 10.0, nil) { obj.optFloatCol = nil }
observeChange(obs, "optDoubleCol", 10.0, nil) { obj.optDoubleCol = nil }
observeChange(obs, "optBoolCol", true, nil) { obj.optBoolCol = nil }
observeChange(obs, "optStringCol", "abc", nil) { obj.optStringCol = nil }
observeChange(obs, "optBinaryCol", data, nil) { obj.optBinaryCol = nil }
observeChange(obs, "optDateCol", date, nil) { obj.optDateCol = nil }
observeChange(obs, "optDecimalCol", decimal, nil) { obj.optDecimalCol = nil }
observeChange(obs, "optObjectIdCol", objectId, nil) { obj.optObjectIdCol = nil }
observeChange(obs, "optUuidCol", uuid, nil) { obj.optUuidCol = nil }
// .insertion append
observeListChange(obs, "arrayBool", .insertion) { obj.arrayBool.append(true) }
observeListChange(obs, "arrayInt", .insertion) { obj.arrayInt.append(10) }
observeListChange(obs, "arrayInt8", .insertion) { obj.arrayInt8.append(10) }
observeListChange(obs, "arrayInt16", .insertion) { obj.arrayInt16.append(10) }
observeListChange(obs, "arrayInt32", .insertion) { obj.arrayInt32.append(10) }
observeListChange(obs, "arrayInt64", .insertion) { obj.arrayInt64.append(10) }
observeListChange(obs, "arrayFloat", .insertion) { obj.arrayFloat.append(10.0) }
observeListChange(obs, "arrayDouble", .insertion) { obj.arrayDouble.append(10.0) }
observeListChange(obs, "arrayString", .insertion) { obj.arrayString.append("10") }
observeListChange(obs, "arrayBinary", .insertion) { obj.arrayBinary.append(data) }
observeListChange(obs, "arrayDate", .insertion) { obj.arrayDate.append(date) }
observeListChange(obs, "arrayDecimal", .insertion) { obj.arrayDecimal.append(decimal) }
observeListChange(obs, "arrayObjectId", .insertion) { obj.arrayObjectId.append(objectId) }
observeListChange(obs, "arrayAny", .insertion) { obj.arrayAny.append(.int(10)) }
observeListChange(obs, "arrayUuid", .insertion) { obj.arrayUuid.append(uuid) }
observeListChange(obs, "arrayOptBool", .insertion) { obj.arrayOptBool.append(true) }
observeListChange(obs, "arrayOptInt", .insertion) { obj.arrayOptInt.append(10) }
observeListChange(obs, "arrayOptInt8", .insertion) { obj.arrayOptInt8.append(10) }
observeListChange(obs, "arrayOptInt16", .insertion) { obj.arrayOptInt16.append(10) }
observeListChange(obs, "arrayOptInt32", .insertion) { obj.arrayOptInt32.append(10) }
observeListChange(obs, "arrayOptInt64", .insertion) { obj.arrayOptInt64.append(10) }
observeListChange(obs, "arrayOptFloat", .insertion) { obj.arrayOptFloat.append(10.0) }
observeListChange(obs, "arrayOptDouble", .insertion) { obj.arrayOptDouble.append(10.0) }
observeListChange(obs, "arrayOptString", .insertion) { obj.arrayOptString.append("10") }
observeListChange(obs, "arrayOptBinary", .insertion) { obj.arrayOptBinary.append(data) }
observeListChange(obs, "arrayOptDate", .insertion) { obj.arrayOptDate.append(date) }
observeListChange(obs, "arrayOptDecimal", .insertion) { obj.arrayOptDecimal.append(decimal) }
observeListChange(obs, "arrayOptObjectId", .insertion) { obj.arrayOptObjectId.append(objectId) }
observeListChange(obs, "arrayOptUuid", .insertion) { obj.arrayOptUuid.append(uuid) }
(obj, obs) = newObjects()
observeListChange(obs, "arrayOptBool", .insertion) { obj.arrayOptBool.append(nil) }
observeListChange(obs, "arrayOptInt", .insertion) { obj.arrayOptInt.append(nil) }
observeListChange(obs, "arrayOptInt8", .insertion) { obj.arrayOptInt8.append(nil) }
observeListChange(obs, "arrayOptInt16", .insertion) { obj.arrayOptInt16.append(nil) }
observeListChange(obs, "arrayOptInt32", .insertion) { obj.arrayOptInt32.append(nil) }
observeListChange(obs, "arrayOptInt64", .insertion) { obj.arrayOptInt64.append(nil) }
observeListChange(obs, "arrayOptFloat", .insertion) { obj.arrayOptFloat.append(nil) }
observeListChange(obs, "arrayOptDouble", .insertion) { obj.arrayOptDouble.append(nil) }
observeListChange(obs, "arrayOptString", .insertion) { obj.arrayOptString.append(nil) }
observeListChange(obs, "arrayOptBinary", .insertion) { obj.arrayOptBinary.append(nil) }
observeListChange(obs, "arrayOptDate", .insertion) { obj.arrayOptDate.append(nil) }
observeListChange(obs, "arrayOptDecimal", .insertion) { obj.arrayOptDecimal.append(nil) }
observeListChange(obs, "arrayOptObjectId", .insertion) { obj.arrayOptObjectId.append(nil) }
observeListChange(obs, "arrayOptUuid", .insertion) { obj.arrayOptUuid.append(nil) }
// .insertion insert at
observeListChange(obs, "arrayBool", .insertion) { obj.arrayBool.insert(true, at: 0) }
observeListChange(obs, "arrayInt", .insertion) { obj.arrayInt.append(10) }
observeListChange(obs, "arrayInt8", .insertion) { obj.arrayInt8.insert(10, at: 0) }
observeListChange(obs, "arrayInt16", .insertion) { obj.arrayInt16.insert(10, at: 0) }
observeListChange(obs, "arrayInt32", .insertion) { obj.arrayInt32.insert(10, at: 0) }
observeListChange(obs, "arrayInt64", .insertion) { obj.arrayInt64.insert(10, at: 0) }
observeListChange(obs, "arrayFloat", .insertion) { obj.arrayFloat.insert(10, at: 0) }
observeListChange(obs, "arrayDouble", .insertion) { obj.arrayDouble.insert(10, at: 0) }
observeListChange(obs, "arrayString", .insertion) { obj.arrayString.insert("abc", at: 0) }
observeListChange(obs, "arrayBinary", .insertion) { obj.arrayBinary.append(data) }
observeListChange(obs, "arrayDate", .insertion) { obj.arrayDate.append(date) }
observeListChange(obs, "arrayDecimal", .insertion) { obj.arrayDecimal.insert(decimal, at: 0) }
observeListChange(obs, "arrayObjectId", .insertion) { obj.arrayObjectId.insert(objectId, at: 0) }
observeListChange(obs, "arrayUuid", .insertion) { obj.arrayUuid.insert(uuid, at: 0) }
observeListChange(obs, "arrayAny", .insertion) { obj.arrayAny.insert(.string("a"), at: 0) }
observeListChange(obs, "arrayOptBool", .insertion) { obj.arrayOptBool.insert(true, at: 0) }
observeListChange(obs, "arrayOptInt", .insertion) { obj.arrayOptInt.insert(10, at: 0) }
observeListChange(obs, "arrayOptInt8", .insertion) { obj.arrayOptInt8.insert(10, at: 0) }
observeListChange(obs, "arrayOptInt16", .insertion) { obj.arrayOptInt16.insert(10, at: 0) }
observeListChange(obs, "arrayOptInt32", .insertion) { obj.arrayOptInt32.insert(10, at: 0) }
observeListChange(obs, "arrayOptInt64", .insertion) { obj.arrayOptInt64.insert(10, at: 0) }
observeListChange(obs, "arrayOptFloat", .insertion) { obj.arrayOptFloat.insert(10, at: 0) }
observeListChange(obs, "arrayOptDouble", .insertion) { obj.arrayOptDouble.insert(10, at: 0) }
observeListChange(obs, "arrayOptString", .insertion) { obj.arrayOptString.insert("abc", at: 0) }
observeListChange(obs, "arrayOptBinary", .insertion) { obj.arrayOptBinary.insert(data, at: 0) }
observeListChange(obs, "arrayOptDate", .insertion) { obj.arrayOptDate.insert(date, at: 0) }
observeListChange(obs, "arrayOptDecimal", .insertion) { obj.arrayOptDecimal.insert(decimal, at: 0) }
observeListChange(obs, "arrayOptObjectId", .insertion) { obj.arrayOptObjectId.insert(objectId, at: 0) }
observeListChange(obs, "arrayOptUuid", .insertion) { obj.arrayOptUuid.insert(uuid, at: 0) }
observeListChange(obs, "arrayOptBool", .insertion) { obj.arrayOptBool.insert(nil, at: 0) }
observeListChange(obs, "arrayOptInt", .insertion) { obj.arrayOptInt.insert(nil, at: 0) }
observeListChange(obs, "arrayOptInt8", .insertion) { obj.arrayOptInt8.insert(nil, at: 0) }
observeListChange(obs, "arrayOptInt16", .insertion) { obj.arrayOptInt16.insert(nil, at: 0) }
observeListChange(obs, "arrayOptInt32", .insertion) { obj.arrayOptInt32.insert(nil, at: 0) }
observeListChange(obs, "arrayOptInt64", .insertion) { obj.arrayOptInt64.insert(nil, at: 0) }
observeListChange(obs, "arrayOptFloat", .insertion) { obj.arrayOptFloat.insert(nil, at: 0) }
observeListChange(obs, "arrayOptDouble", .insertion) { obj.arrayOptDouble.insert(nil, at: 0) }
observeListChange(obs, "arrayOptString", .insertion) { obj.arrayOptString.insert(nil, at: 0) }
observeListChange(obs, "arrayOptDate", .insertion) { obj.arrayOptDate.insert(nil, at: 0) }
observeListChange(obs, "arrayOptBinary", .insertion) { obj.arrayOptBinary.insert(nil, at: 0) }
observeListChange(obs, "arrayOptDecimal", .insertion) { obj.arrayOptDecimal.insert(nil, at: 0) }
observeListChange(obs, "arrayOptObjectId", .insertion) { obj.arrayOptObjectId.insert(nil, at: 0) }
observeListChange(obs, "arrayOptUuid", .insertion) { obj.arrayOptUuid.insert(nil, at: 0) }
// .replacement
observeListChange(obs, "arrayBool", .replacement) { obj.arrayBool[0] = true }
observeListChange(obs, "arrayInt", .replacement) { obj.arrayInt[0] = 10 }
observeListChange(obs, "arrayInt8", .replacement) { obj.arrayInt8[0] = 10 }
observeListChange(obs, "arrayInt16", .replacement) { obj.arrayInt16[0] = 10 }
observeListChange(obs, "arrayInt32", .replacement) { obj.arrayInt32[0] = 10 }
observeListChange(obs, "arrayInt64", .replacement) { obj.arrayInt64[0] = 10 }
observeListChange(obs, "arrayFloat", .replacement) { obj.arrayFloat[0] = 10 }
observeListChange(obs, "arrayDouble", .replacement) { obj.arrayDouble[0] = 10 }
observeListChange(obs, "arrayString", .replacement) { obj.arrayString[0] = "abc" }
observeListChange(obs, "arrayBinary", .replacement) { obj.arrayBinary[0] = data }
observeListChange(obs, "arrayDate", .replacement) { obj.arrayDate[0] = date }
observeListChange(obs, "arrayDecimal", .replacement) { obj.arrayDecimal[0] = decimal }
observeListChange(obs, "arrayObjectId", .replacement) { obj.arrayObjectId[0] = objectId }
observeListChange(obs, "arrayUuid", .replacement) { obj.arrayUuid[0] = uuid }
observeListChange(obs, "arrayAny", .replacement) { obj.arrayAny[0] = .string("a") }
observeListChange(obs, "arrayOptBool", .replacement) { obj.arrayOptBool[0] = true }
observeListChange(obs, "arrayOptInt", .replacement) { obj.arrayOptInt[0] = 10 }
observeListChange(obs, "arrayOptInt8", .replacement) { obj.arrayOptInt8[0] = 10 }
observeListChange(obs, "arrayOptInt16", .replacement) { obj.arrayOptInt16[0] = 10 }
observeListChange(obs, "arrayOptInt32", .replacement) { obj.arrayOptInt32[0] = 10 }
observeListChange(obs, "arrayOptInt64", .replacement) { obj.arrayOptInt64[0] = 10 }
observeListChange(obs, "arrayOptFloat", .replacement) { obj.arrayOptFloat[0] = 10 }
observeListChange(obs, "arrayOptDouble", .replacement) { obj.arrayOptDouble[0] = 10 }
observeListChange(obs, "arrayOptString", .replacement) { obj.arrayOptString[0] = "abc" }
observeListChange(obs, "arrayOptBinary", .replacement) { obj.arrayOptBinary[0] = data }
observeListChange(obs, "arrayOptDate", .replacement) { obj.arrayOptDate[0] = date }
observeListChange(obs, "arrayOptBinary", .replacement) { obj.arrayOptBinary[0] = data }
observeListChange(obs, "arrayOptDate", .replacement) { obj.arrayOptDate[0] = date }
observeListChange(obs, "arrayOptDecimal", .replacement) { obj.arrayOptDecimal[0] = decimal }
observeListChange(obs, "arrayOptObjectId", .replacement) { obj.arrayOptObjectId[0] = objectId }
observeListChange(obs, "arrayOptUuid", .replacement) { obj.arrayOptUuid[0] = uuid }
observeListChange(obs, "arrayOptBool", .replacement) { obj.arrayOptBool[0] = nil }
observeListChange(obs, "arrayOptInt", .replacement) { obj.arrayOptInt[0] = nil }
observeListChange(obs, "arrayOptInt8", .replacement) { obj.arrayOptInt8[0] = nil }
observeListChange(obs, "arrayOptInt16", .replacement) { obj.arrayOptInt16[0] = nil }
observeListChange(obs, "arrayOptInt32", .replacement) { obj.arrayOptInt32[0] = nil }
observeListChange(obs, "arrayOptInt64", .replacement) { obj.arrayOptInt64[0] = nil }
observeListChange(obs, "arrayOptFloat", .replacement) { obj.arrayOptFloat[0] = nil }
observeListChange(obs, "arrayOptDouble", .replacement) { obj.arrayOptDouble[0] = nil }
observeListChange(obs, "arrayOptString", .replacement) { obj.arrayOptString[0] = nil }
observeListChange(obs, "arrayOptBinary", .replacement) { obj.arrayOptBinary[0] = nil }
observeListChange(obs, "arrayOptDate", .replacement) { obj.arrayOptDate[0] = nil }
observeListChange(obs, "arrayOptDate", .replacement) { obj.arrayOptDate[0] = nil }
observeListChange(obs, "arrayOptBinary", .replacement) { obj.arrayOptBinary[0] = nil }
observeListChange(obs, "arrayOptDecimal", .replacement) { obj.arrayOptDecimal[0] = nil }
observeListChange(obs, "arrayOptObjectId", .replacement) { obj.arrayOptObjectId[0] = nil }
observeListChange(obs, "arrayOptUuid", .replacement) { obj.arrayOptUuid[0] = nil }
// .removal removeAll
observeListChange(obs, "arrayBool", .removal) { obj.arrayBool.removeAll() }
observeListChange(obs, "arrayInt", .removal) { obj.arrayInt.removeAll() }
observeListChange(obs, "arrayInt8", .removal) { obj.arrayInt8.removeAll() }
observeListChange(obs, "arrayInt16", .removal) { obj.arrayInt16.removeAll() }
observeListChange(obs, "arrayInt32", .removal) { obj.arrayInt32.removeAll() }
observeListChange(obs, "arrayInt64", .removal) { obj.arrayInt64.removeAll() }
observeListChange(obs, "arrayFloat", .removal) { obj.arrayFloat.removeAll() }
observeListChange(obs, "arrayDouble", .removal) { obj.arrayDouble.removeAll() }
observeListChange(obs, "arrayString", .removal) { obj.arrayString.removeAll() }
observeListChange(obs, "arrayBinary", .removal) { obj.arrayBinary.removeAll() }
observeListChange(obs, "arrayDate", .removal) { obj.arrayDate.removeAll() }
observeListChange(obs, "arrayDecimal", .removal) { obj.arrayDecimal.removeAll() }
observeListChange(obs, "arrayObjectId", .removal) { obj.arrayObjectId.removeAll() }
observeListChange(obs, "arrayUuid", .removal) { obj.arrayUuid.removeAll() }
observeListChange(obs, "arrayAny", .removal) { obj.arrayAny.removeAll() }
let indices = NSIndexSet(indexesIn: NSRange(location: 0, length: 3))
observeListChange(obs, "arrayOptBool", .removal, indices) { obj.arrayOptBool.removeAll() }
observeListChange(obs, "arrayOptInt", .removal, indices) { obj.arrayOptInt.removeAll() }
observeListChange(obs, "arrayOptInt8", .removal, indices) { obj.arrayOptInt8.removeAll() }
observeListChange(obs, "arrayOptInt16", .removal, indices) { obj.arrayOptInt16.removeAll() }
observeListChange(obs, "arrayOptInt32", .removal, indices) { obj.arrayOptInt32.removeAll() }
observeListChange(obs, "arrayOptInt64", .removal, indices) { obj.arrayOptInt64.removeAll() }
observeListChange(obs, "arrayOptFloat", .removal, indices) { obj.arrayOptFloat.removeAll() }
observeListChange(obs, "arrayOptDouble", .removal, indices) { obj.arrayOptDouble.removeAll() }
observeListChange(obs, "arrayOptString", .removal, indices) { obj.arrayOptString.removeAll() }
observeListChange(obs, "arrayOptBinary", .removal, indices) { obj.arrayOptBinary.removeAll() }
observeListChange(obs, "arrayOptDate", .removal, indices) { obj.arrayOptDate.removeAll() }
observeListChange(obs, "arrayOptDecimal", .removal, indices) { obj.arrayOptDecimal.removeAll() }
observeListChange(obs, "arrayOptObjectId", .removal, indices) { obj.arrayOptObjectId.removeAll() }
observeListChange(obs, "arrayOptUuid", .removal, indices) { obj.arrayOptUuid.removeAll() }
// .removal remove at
(obj, obs) = newObjects(allTypeValues)
observeListChange(obs, "arrayBool", .removal) { obj.arrayBool.remove(at: 0) }
observeListChange(obs, "arrayInt", .removal) { obj.arrayInt.remove(at: 0) }
observeListChange(obs, "arrayInt8", .removal) { obj.arrayInt8.remove(at: 0) }
observeListChange(obs, "arrayInt16", .removal) { obj.arrayInt16.remove(at: 0) }
observeListChange(obs, "arrayInt32", .removal) { obj.arrayInt32.remove(at: 0) }
observeListChange(obs, "arrayInt64", .removal) { obj.arrayInt64.remove(at: 0) }
observeListChange(obs, "arrayFloat", .removal) { obj.arrayFloat.remove(at: 0) }
observeListChange(obs, "arrayDouble", .removal) { obj.arrayDouble.remove(at: 0) }
observeListChange(obs, "arrayString", .removal) { obj.arrayString.remove(at: 0) }
observeListChange(obs, "arrayBinary", .removal) { obj.arrayBinary.remove(at: 0) }
observeListChange(obs, "arrayDate", .removal) { obj.arrayDate.remove(at: 0) }
observeListChange(obs, "arrayDecimal", .removal) { obj.arrayDecimal.remove(at: 0) }
observeListChange(obs, "arrayObjectId", .removal) { obj.arrayObjectId.remove(at: 0) }
observeListChange(obs, "arrayUuid", .removal) { obj.arrayUuid.remove(at: 0) }
observeListChange(obs, "arrayAny", .removal) { obj.arrayAny.remove(at: 0) }
observeListChange(obs, "arrayOptBool", .removal) { obj.arrayOptBool.remove(at: 0) }
observeListChange(obs, "arrayOptInt", .removal) { obj.arrayOptInt.remove(at: 0) }
observeListChange(obs, "arrayOptInt8", .removal) { obj.arrayOptInt8.remove(at: 0) }
observeListChange(obs, "arrayOptInt16", .removal) { obj.arrayOptInt16.remove(at: 0) }
observeListChange(obs, "arrayOptInt32", .removal) { obj.arrayOptInt32.remove(at: 0) }
observeListChange(obs, "arrayOptInt64", .removal) { obj.arrayOptInt64.remove(at: 0) }
observeListChange(obs, "arrayOptFloat", .removal) { obj.arrayOptFloat.remove(at: 0) }
observeListChange(obs, "arrayOptDouble", .removal) { obj.arrayOptDouble.remove(at: 0) }
observeListChange(obs, "arrayOptString", .removal) { obj.arrayOptString.remove(at: 0) }
observeListChange(obs, "arrayOptBinary", .removal) { obj.arrayOptBinary.remove(at: 0) }
observeListChange(obs, "arrayOptDate", .removal) { obj.arrayOptDate.remove(at: 0) }
observeListChange(obs, "arrayOptDecimal", .removal) { obj.arrayOptDecimal.remove(at: 0) }
observeListChange(obs, "arrayOptObjectId", .removal) { obj.arrayOptObjectId.remove(at: 0) }
observeListChange(obs, "arrayOptUuid", .removal) { obj.arrayOptUuid.remove(at: 0) }
// insert
observeSetChange(obs, "setBool") { obj.setBool.insert(true) }
observeSetChange(obs, "setInt") { obj.setInt.insert(10) }
observeSetChange(obs, "setInt8") { obj.setInt8.insert(10) }
observeSetChange(obs, "setInt16") { obj.setInt16.insert(10) }
observeSetChange(obs, "setInt32") { obj.setInt32.insert(10) }
observeSetChange(obs, "setInt64") { obj.setInt64.insert(10) }
observeSetChange(obs, "setFloat") { obj.setFloat.insert(10.0) }
observeSetChange(obs, "setDouble") { obj.setDouble.insert(10.0) }
observeSetChange(obs, "setString") { obj.setString.insert("10") }
observeSetChange(obs, "setBinary") { obj.setBinary.insert(data) }
observeSetChange(obs, "setDate") { obj.setDate.insert(date) }
observeSetChange(obs, "setDecimal") { obj.setDecimal.insert(decimal) }
observeSetChange(obs, "setObjectId") { obj.setObjectId.insert(objectId) }
observeSetChange(obs, "setAny") { obj.setAny.insert(.string("a")) }
observeSetChange(obs, "setUuid") { obj.setUuid.insert(uuid) }
observeSetChange(obs, "setOptBool") { obj.setOptBool.insert(true) }
observeSetChange(obs, "setOptInt") { obj.setOptInt.insert(10) }
observeSetChange(obs, "setOptInt8") { obj.setOptInt8.insert(10) }
observeSetChange(obs, "setOptInt16") { obj.setOptInt16.insert(10) }
observeSetChange(obs, "setOptInt32") { obj.setOptInt32.insert(10) }
observeSetChange(obs, "setOptInt64") { obj.setOptInt64.insert(10) }
observeSetChange(obs, "setOptFloat") { obj.setOptFloat.insert(10.0) }
observeSetChange(obs, "setOptDouble") { obj.setOptDouble.insert(10.0) }
observeSetChange(obs, "setOptString") { obj.setOptString.insert("10") }
observeSetChange(obs, "setOptBinary") { obj.setOptBinary.insert(data) }
observeSetChange(obs, "setOptDate") { obj.setOptDate.insert(date) }
observeSetChange(obs, "setOptDecimal") { obj.setOptDecimal.insert(decimal) }
observeSetChange(obs, "setOptObjectId") { obj.setOptObjectId.insert(objectId) }
observeSetChange(obs, "setOptUuid") { obj.setOptUuid.insert(uuid) }
observeSetChange(obs, "setOptBool") { obj.setOptBool.insert(nil) }
observeSetChange(obs, "setOptInt") { obj.setOptInt.insert(nil) }
observeSetChange(obs, "setOptInt8") { obj.setOptInt8.insert(nil) }
observeSetChange(obs, "setOptInt16") { obj.setOptInt16.insert(nil) }
observeSetChange(obs, "setOptInt32") { obj.setOptInt32.insert(nil) }
observeSetChange(obs, "setOptInt64") { obj.setOptInt64.insert(nil) }
observeSetChange(obs, "setOptFloat") { obj.setOptFloat.insert(nil) }
observeSetChange(obs, "setOptDouble") { obj.setOptDouble.insert(nil) }
observeSetChange(obs, "setOptString") { obj.setOptString.insert(nil) }
observeSetChange(obs, "setOptBinary") { obj.setOptBinary.insert(nil) }
observeSetChange(obs, "setOptDate") { obj.setOptDate.insert(nil) }
observeSetChange(obs, "setOptDecimal") { obj.setOptDecimal.insert(nil) }
observeSetChange(obs, "setOptObjectId") { obj.setOptObjectId.insert(nil) }
observeSetChange(obs, "setOptUuid") { obj.setOptUuid.insert(nil) }
// insert objectsIn
observeSetChange(obs, "setBool") { obj.setBool.insert(objectsIn: [true]) }
observeSetChange(obs, "setInt") { obj.setInt.insert(objectsIn: [10]) }
observeSetChange(obs, "setInt8") { obj.setInt8.insert(objectsIn: [10]) }
observeSetChange(obs, "setInt16") { obj.setInt16.insert(objectsIn: [10]) }
observeSetChange(obs, "setInt32") { obj.setInt32.insert(objectsIn: [10]) }
observeSetChange(obs, "setInt64") { obj.setInt64.insert(objectsIn: [10]) }
observeSetChange(obs, "setFloat") { obj.setFloat.insert(objectsIn: [10.0]) }
observeSetChange(obs, "setDouble") { obj.setDouble.insert(objectsIn: [10.0]) }
observeSetChange(obs, "setString") { obj.setString.insert(objectsIn: ["10"]) }
observeSetChange(obs, "setBinary") { obj.setBinary.insert(objectsIn: [data]) }
observeSetChange(obs, "setDate") { obj.setDate.insert(objectsIn: [date]) }
observeSetChange(obs, "setDecimal") { obj.setDecimal.insert(objectsIn: [decimal]) }
observeSetChange(obs, "setObjectId") { obj.setObjectId.insert(objectsIn: [objectId]) }
observeSetChange(obs, "setAny") { obj.setAny.insert(objectsIn: [.string("a")]) }
observeSetChange(obs, "setUuid") { obj.setUuid.insert(objectsIn: [uuid]) }
observeSetChange(obs, "setOptBool") { obj.setOptBool.insert(objectsIn: [true, nil]) }
observeSetChange(obs, "setOptInt") { obj.setOptInt.insert(objectsIn: [10, nil]) }
observeSetChange(obs, "setOptInt8") { obj.setOptInt8.insert(objectsIn: [10, nil]) }
observeSetChange(obs, "setOptInt16") { obj.setOptInt16.insert(objectsIn: [10, nil]) }
observeSetChange(obs, "setOptInt32") { obj.setOptInt32.insert(objectsIn: [10, nil]) }
observeSetChange(obs, "setOptInt64") { obj.setOptInt64.insert(objectsIn: [10, nil]) }
observeSetChange(obs, "setOptFloat") { obj.setOptFloat.insert(objectsIn: [10.0, nil]) }
observeSetChange(obs, "setOptDouble") { obj.setOptDouble.insert(objectsIn: [10.0, nil]) }
observeSetChange(obs, "setOptString") { obj.setOptString.insert(objectsIn: ["10", nil]) }
observeSetChange(obs, "setOptBinary") { obj.setOptBinary.insert(objectsIn: [data, nil]) }
observeSetChange(obs, "setOptDate") { obj.setOptDate.insert(objectsIn: [date, nil]) }
observeSetChange(obs, "setOptDecimal") { obj.setOptDecimal.insert(objectsIn: [decimal, nil]) }
observeSetChange(obs, "setOptObjectId") { obj.setOptObjectId.insert(objectsIn: [objectId, nil]) }
observeSetChange(obs, "setOptUuid") { obj.setOptUuid.insert(objectsIn: [uuid, nil]) }
// delete
observeSetChange(obs, "setBool") { obj.setBool.remove(true) }
observeSetChange(obs, "setInt") { obj.setInt.remove(10) }
observeSetChange(obs, "setInt8") { obj.setInt8.remove(10) }
observeSetChange(obs, "setInt16") { obj.setInt16.remove(10) }
observeSetChange(obs, "setInt32") { obj.setInt32.remove(10) }
observeSetChange(obs, "setInt64") { obj.setInt64.remove(10) }
observeSetChange(obs, "setFloat") { obj.setFloat.remove(10.0) }
observeSetChange(obs, "setDouble") { obj.setDouble.remove(10.0) }
observeSetChange(obs, "setString") { obj.setString.remove("10") }
observeSetChange(obs, "setBinary") { obj.setBinary.remove(data) }
observeSetChange(obs, "setDate") { obj.setDate.remove(date) }
observeSetChange(obs, "setDecimal") { obj.setDecimal.remove(decimal) }
observeSetChange(obs, "setObjectId") { obj.setObjectId.remove(objectId) }
observeSetChange(obs, "setAny") { obj.setAny.remove(.string("a")) }
observeSetChange(obs, "setUuid") { obj.setUuid.remove(uuid) }
observeSetChange(obs, "setOptBool") { obj.setOptBool.remove(true) }
observeSetChange(obs, "setOptInt") { obj.setOptInt.remove(10) }
observeSetChange(obs, "setOptInt8") { obj.setOptInt8.remove(10) }
observeSetChange(obs, "setOptInt16") { obj.setOptInt16.remove(10) }
observeSetChange(obs, "setOptInt32") { obj.setOptInt32.remove(10) }
observeSetChange(obs, "setOptInt64") { obj.setOptInt64.remove(10) }
observeSetChange(obs, "setOptFloat") { obj.setOptFloat.remove(10.0) }
observeSetChange(obs, "setOptDouble") { obj.setOptDouble.remove(10.0) }
observeSetChange(obs, "setOptString") { obj.setOptString.remove("10") }
observeSetChange(obs, "setOptBinary") { obj.setOptBinary.remove(data) }
observeSetChange(obs, "setOptDate") { obj.setOptDate.remove(date) }
observeSetChange(obs, "setOptDecimal") { obj.setOptDecimal.remove(decimal) }
observeSetChange(obs, "setOptObjectId") { obj.setOptObjectId.remove(objectId) }
observeSetChange(obs, "setOptUuid") { obj.setOptUuid.remove(uuid) }
observeSetChange(obs, "setOptBool") { obj.setOptBool.remove(nil) }
observeSetChange(obs, "setOptInt") { obj.setOptInt.remove(nil) }
observeSetChange(obs, "setOptInt8") { obj.setOptInt8.remove(nil) }
observeSetChange(obs, "setOptInt16") { obj.setOptInt16.remove(nil) }
observeSetChange(obs, "setOptInt32") { obj.setOptInt32.remove(nil) }
observeSetChange(obs, "setOptInt64") { obj.setOptInt64.remove(nil) }
observeSetChange(obs, "setOptFloat") { obj.setOptFloat.remove(nil) }
observeSetChange(obs, "setOptDouble") { obj.setOptDouble.remove(nil) }
observeSetChange(obs, "setOptString") { obj.setOptString.remove(nil) }
observeSetChange(obs, "setOptDate") { obj.setOptDate.remove(nil) }
observeSetChange(obs, "setOptBinary") { obj.setOptBinary.remove(nil) }
observeSetChange(obs, "setOptDecimal") { obj.setOptDecimal.remove(nil) }
observeSetChange(obs, "setOptObjectId") { obj.setOptObjectId.remove(nil) }
observeSetChange(obs, "setOptUuid") { obj.setOptUuid.remove(nil) }
// delete all
observeSetChange(obs, "setBool") { obj.setBool.removeAll() }
observeSetChange(obs, "setInt") { obj.setInt.removeAll() }
observeSetChange(obs, "setInt8") { obj.setInt8.removeAll() }
observeSetChange(obs, "setInt16") { obj.setInt16.removeAll() }
observeSetChange(obs, "setInt32") { obj.setInt32.removeAll() }
observeSetChange(obs, "setInt64") { obj.setInt64.removeAll() }
observeSetChange(obs, "setFloat") { obj.setFloat.removeAll() }
observeSetChange(obs, "setDouble") { obj.setDouble.removeAll() }
observeSetChange(obs, "setString") { obj.setString.removeAll() }
observeSetChange(obs, "setBinary") { obj.setBinary.removeAll() }
observeSetChange(obs, "setDate") { obj.setDate.removeAll() }
observeSetChange(obs, "setDecimal") { obj.setDecimal.removeAll() }
observeSetChange(obs, "setObjectId") { obj.setObjectId.removeAll() }
observeSetChange(obs, "setAny") { obj.setAny.removeAll() }
observeSetChange(obs, "setUuid") { obj.setUuid.removeAll() }
observeSetChange(obs, "setOptBool") { obj.setOptBool.removeAll() }
observeSetChange(obs, "setOptInt") { obj.setOptInt.removeAll() }
observeSetChange(obs, "setOptInt8") { obj.setOptInt8.removeAll() }
observeSetChange(obs, "setOptInt16") { obj.setOptInt16.removeAll() }
observeSetChange(obs, "setOptInt32") { obj.setOptInt32.removeAll() }
observeSetChange(obs, "setOptInt64") { obj.setOptInt64.removeAll() }
observeSetChange(obs, "setOptFloat") { obj.setOptFloat.removeAll() }
observeSetChange(obs, "setOptDouble") { obj.setOptDouble.removeAll() }
observeSetChange(obs, "setOptString") { obj.setOptString.removeAll() }
observeSetChange(obs, "setOptBinary") { obj.setOptBinary.removeAll() }
observeSetChange(obs, "setOptDate") { obj.setOptDate.removeAll() }
observeSetChange(obs, "setOptDecimal") { obj.setOptDecimal.removeAll() }
observeSetChange(obs, "setOptObjectId") { obj.setOptObjectId.removeAll() }
observeSetChange(obs, "setOptUuid") { obj.setOptUuid.removeAll() }
observeSetChange(obs, "mapBool") { obj.mapBool["key"] = true }
observeSetChange(obs, "mapInt") { obj.mapInt["key"] = 10 }
observeSetChange(obs, "mapInt8") { obj.mapInt8["key"] = 10 }
observeSetChange(obs, "mapInt16") { obj.mapInt16["key"] = 10 }
observeSetChange(obs, "mapInt32") { obj.mapInt32["key"] = 10 }
observeSetChange(obs, "mapInt64") { obj.mapInt64["key"] = 10 }
observeSetChange(obs, "mapFloat") { obj.mapFloat["key"] = 10.0 }
observeSetChange(obs, "mapDouble") { obj.mapDouble["key"] = 10.0 }
observeSetChange(obs, "mapString") { obj.mapString["key"] = "10" }
observeSetChange(obs, "mapBinary") { obj.mapBinary["key"] = data }
observeSetChange(obs, "mapDate") { obj.mapDate["key"] = date }
observeSetChange(obs, "mapDecimal") { obj.mapDecimal["key"] = decimal }
observeSetChange(obs, "mapObjectId") { obj.mapObjectId["key"] = objectId }
observeSetChange(obs, "mapAny") { obj.mapAny["key"] = .string("a") }
observeSetChange(obs, "mapUuid") { obj.mapUuid["key"] = uuid }
observeSetChange(obs, "mapOptBool") { obj.mapOptBool["key"] = true }
observeSetChange(obs, "mapOptInt") { obj.mapOptInt["key"] = 10 }
observeSetChange(obs, "mapOptInt8") { obj.mapOptInt8["key"] = 10 }
observeSetChange(obs, "mapOptInt16") { obj.mapOptInt16["key"] = 10 }
observeSetChange(obs, "mapOptInt32") { obj.mapOptInt32["key"] = 10 }
observeSetChange(obs, "mapOptInt64") { obj.mapOptInt64["key"] = 10 }
observeSetChange(obs, "mapOptFloat") { obj.mapOptFloat["key"] = 10.0 }
observeSetChange(obs, "mapOptDouble") { obj.mapOptDouble["key"] = 10.0 }
observeSetChange(obs, "mapOptString") { obj.mapOptString["key"] = "10" }
observeSetChange(obs, "mapOptBinary") { obj.mapOptBinary["key"] = data }
observeSetChange(obs, "mapOptDate") { obj.mapOptDate["key"] = date }
observeSetChange(obs, "mapOptDecimal") { obj.mapOptDecimal["key"] = decimal }
observeSetChange(obs, "mapOptObjectId") { obj.mapOptObjectId["key"] = objectId }
observeSetChange(obs, "mapOptUuid") { obj.mapOptUuid["key"] = uuid }
observeSetChange(obs, "mapBool") { obj.mapBool["key"] = nil }
observeSetChange(obs, "mapInt") { obj.mapInt["key"] = nil }
observeSetChange(obs, "mapInt8") { obj.mapInt8["key"] = nil }
observeSetChange(obs, "mapInt16") { obj.mapInt16["key"] = nil }
observeSetChange(obs, "mapInt32") { obj.mapInt32["key"] = nil }
observeSetChange(obs, "mapInt64") { obj.mapInt64["key"] = nil }
observeSetChange(obs, "mapFloat") { obj.mapFloat["key"] = nil }
observeSetChange(obs, "mapDouble") { obj.mapDouble["key"] = nil }
observeSetChange(obs, "mapString") { obj.mapString["key"] = nil }
observeSetChange(obs, "mapBinary") { obj.mapBinary["key"] = nil }
observeSetChange(obs, "mapDate") { obj.mapDate["key"] = nil }
observeSetChange(obs, "mapDecimal") { obj.mapDecimal["key"] = nil }
observeSetChange(obs, "mapObjectId") { obj.mapObjectId["key"] = nil }
observeSetChange(obs, "mapAny") { obj.mapAny["key"] = nil }
observeSetChange(obs, "mapUuid") { obj.mapUuid["key"] = nil }
observeSetChange(obs, "mapOptBool") { obj.mapOptBool["key"] = nil }
observeSetChange(obs, "mapOptInt") { obj.mapOptInt["key"] = nil }
observeSetChange(obs, "mapOptInt8") { obj.mapOptInt8["key"] = nil }
observeSetChange(obs, "mapOptInt16") { obj.mapOptInt16["key"] = nil }
observeSetChange(obs, "mapOptInt32") { obj.mapOptInt32["key"] = nil }
observeSetChange(obs, "mapOptInt64") { obj.mapOptInt64["key"] = nil }
observeSetChange(obs, "mapOptFloat") { obj.mapOptFloat["key"] = nil }
observeSetChange(obs, "mapOptDouble") { obj.mapOptDouble["key"] = nil }
observeSetChange(obs, "mapOptString") { obj.mapOptString["key"] = nil }
observeSetChange(obs, "mapOptBinary") { obj.mapOptBinary["key"] = nil }
observeSetChange(obs, "mapOptDate") { obj.mapOptDate["key"] = nil }
observeSetChange(obs, "mapOptDecimal") { obj.mapOptDecimal["key"] = nil }
observeSetChange(obs, "mapOptObjectId") { obj.mapOptObjectId["key"] = nil }
observeSetChange(obs, "mapOptUuid") { obj.mapOptUuid["key"] = nil }
observeSetChange(obs, "mapOptBool") { obj.mapOptBool.removeObject(for: "key") }
observeSetChange(obs, "mapOptInt") { obj.mapOptInt.removeObject(for: "key") }
observeSetChange(obs, "mapOptInt8") { obj.mapOptInt8.removeObject(for: "key") }
observeSetChange(obs, "mapOptInt16") { obj.mapOptInt16.removeObject(for: "key") }
observeSetChange(obs, "mapOptInt32") { obj.mapOptInt32.removeObject(for: "key") }
observeSetChange(obs, "mapOptInt64") { obj.mapOptInt64.removeObject(for: "key") }
observeSetChange(obs, "mapOptFloat") { obj.mapOptFloat.removeObject(for: "key") }
observeSetChange(obs, "mapOptDouble") { obj.mapOptDouble.removeObject(for: "key") }
observeSetChange(obs, "mapOptString") { obj.mapOptString.removeObject(for: "key") }
observeSetChange(obs, "mapOptBinary") { obj.mapOptBinary.removeObject(for: "key") }
observeSetChange(obs, "mapOptDate") { obj.mapOptDate.removeObject(for: "key") }
observeSetChange(obs, "mapOptDecimal") { obj.mapOptDecimal.removeObject(for: "key") }
observeSetChange(obs, "mapOptObjectId") { obj.mapOptObjectId.removeObject(for: "key") }
observeSetChange(obs, "mapOptUuid") { obj.mapOptUuid.removeObject(for: "key") }
}
// MARK: Frozen Objects
func simpleProjection() -> SimpleProjection {
let realm = realmWithTestPath()
var obj: SimpleObject!
try! realm.write {
obj = realm.create(SimpleObject.self)
}
return SimpleProjection(projecting: obj)
}
func testIsFrozen() {
let projection = simpleProjection()
let frozen = projection.freeze()
XCTAssertFalse(projection.isFrozen)
XCTAssertTrue(frozen.isFrozen)
}
func testFreezingFrozenObjectReturnsSelf() {
let projection = simpleProjection()
let frozen = projection.freeze()
XCTAssertNotEqual(projection, frozen)
XCTAssertFalse(projection.freeze() === frozen)
XCTAssertEqual(frozen, frozen.freeze())
}
func testFreezingDeletedObject() {
let projection = simpleProjection()
let object = projection.rootObject
try! projection.realm!.write({
projection.realm!.delete(object)
})
assertThrows(projection.freeze(), "Object has been deleted or invalidated.")
}
func testFreezeFromWrongThread() {
let projection = simpleProjection()
dispatchSyncNewThread {
self.assertThrows(projection.freeze(), "Realm accessed from incorrect thread")
}
}
func testAccessFrozenObjectFromDifferentThread() {
let projection = simpleProjection()
let frozen = projection.freeze()
dispatchSyncNewThread {
XCTAssertEqual(frozen.int, 0)
}
}
func testMutateFrozenObject() {
let projection = simpleProjection()
let frozen = projection.freeze()
XCTAssertTrue(frozen.isFrozen)
assertThrows(try! frozen.realm!.write { }, "Can't perform transactions on a frozen Realm")
}
func testObserveFrozenObject() {
let frozen = simpleProjection().freeze()
assertThrows(frozen.observe(keyPaths: [String](), { _ in }), "Frozen Realms do not change and do not have change notifications.")
}
func testFrozenObjectEquality() {
let projectionA = simpleProjection()
let frozenA1 = projectionA.freeze()
let frozenA2 = projectionA.freeze()
XCTAssertEqual(frozenA1, frozenA2)
let projectionB = simpleProjection()
let frozenB = projectionB.freeze()
XCTAssertNotEqual(frozenA1, frozenB)
}
func testFreezeInsideWriteTransaction() {
let realm = realmWithTestPath()
var object: SimpleObject!
var projection: SimpleProjection!
try! realm.write {
object = realm.create(SimpleObject.self)
projection = SimpleProjection(projecting: object)
self.assertThrows(projection.freeze(), "Cannot freeze an object in the same write transaction as it was created in.")
}
try! realm.write {
object.int = 2
// Frozen objects have the value of the object at the start of the transaction
XCTAssertEqual(projection.freeze().int, 0)
}
}
func testThaw() {
let frozen = simpleProjection().freeze()
XCTAssertTrue(frozen.isFrozen)
let live = frozen.thaw()!
XCTAssertFalse(live.isFrozen)
try! live.realm!.write {
live.int = 2
}
XCTAssertNotEqual(live.int, frozen.int)
}
func testThawDeleted() {
let projection = simpleProjection()
let frozen = projection.freeze()
let realm = realmWithTestPath()
XCTAssertTrue(frozen.isFrozen)
try! realm.write {
realm.deleteAll()
}
let thawed = frozen.thaw()
XCTAssertNil(thawed, "Thaw should return nil when object was deleted")
}
func testThawPreviousVersion() {
let projection = simpleProjection()
let frozen = projection.freeze()
XCTAssertTrue(frozen.isFrozen)
XCTAssertEqual(projection.int, frozen.int)
try! projection.realm!.write {
projection.int = 1
}
XCTAssertNotEqual(projection.int, frozen.int, "Frozen object shouldn't mutate")
let thawed = frozen.thaw()!
XCTAssertFalse(thawed.isFrozen)
XCTAssertEqual(thawed.int, projection.int, "Thawed object should reflect transactions since the original reference was frozen.")
}
func testThawUpdatedOnDifferentThread() {
let realm = realmWithTestPath()
let projection = simpleProjection()
let tsr = ThreadSafeReference(to: projection)
var frozen: SimpleProjection!
dispatchSyncNewThread {
let realm = self.realmWithTestPath()
let resolvedProjection: SimpleProjection = realm.resolve(tsr)!
try! realm.write {
resolvedProjection.int = 1
}
frozen = resolvedProjection.freeze()
}
let thawed = frozen.thaw()!
XCTAssertEqual(thawed.int, 0, "Thaw shouldn't reflect background transactions until main thread realm is refreshed")
realm.refresh()
XCTAssertEqual(thawed.int, 1)
}
func testThawCreatedOnDifferentThread() {
let realm = realmWithTestPath()
try! realm.write {
realm.deleteAll()
}
var frozen: SimpleProjection!
dispatchSyncNewThread {
let projection = self.simpleProjection()
frozen = projection.freeze()
}
XCTAssertNil(frozen.thaw())
XCTAssertEqual(realm.objects(SimpleProjection.self).count, 0)
realm.refresh()
XCTAssertEqual(realm.objects(SimpleProjection.self).count, 1)
}
func testObserveComputedChange() throws {
let realm = realmWithTestPath()
let johnProjection = realm.objects(PersonProjection.self).first!
XCTAssertEqual(johnProjection.lastNameCaps, "SNOW")
let ex = expectation(description: "values will be observed")
let token = johnProjection.observe(keyPaths: [\PersonProjection.lastNameCaps]) { chg in
if case let .change(_, change) = chg {
XCTAssertEqual(change.first!.name, "lastNameCaps")
XCTAssertEqual(change.first!.oldValue as! String, "SNOW")
XCTAssertEqual(change.first!.newValue as! String, "ALI")
ex.fulfill()
}
}
dispatchSyncNewThread {
let realm = self.realmWithTestPath()
let johnObject = realm.objects(CommonPerson.self).filter("lastName == 'Snow'").first!
try! realm.write {
johnObject.lastName = "Ali"
}
}
waitForExpectations(timeout: 2)
token.invalidate()
}
func testFailedProjection() {
let realm = realmWithTestPath()
XCTAssertGreaterThan(realm.objects(FailedProjection.self).count, 0)
assertThrows(realm.objects(FailedProjection.self).first, reason: "@Projected property")
}
func testAdvancedProjection() throws {
let realm = realmWithTestPath()
let proj = realm.objects(AdvancedProjection.self).first!
XCTAssertEqual(proj.arrayLen, 3)
XCTAssertTrue(proj.projectedArray.elementsEqual(["1 - true", "2 - false"]), "'\(proj.projectedArray)' should be equal to '[\"1 - true\", \"2 - false\"]'")
XCTAssertTrue(proj.renamedArray.elementsEqual([1, 2, 3]))
XCTAssertEqual(proj.firstElement, 1)
XCTAssertTrue(proj.projectedSet.elementsEqual([true, false]), "'\(proj.projectedArray)' should be equal to '[true, false]'")
}
}
| 67.860179 | 379 | 0.663268 |
223cb9649488b623aadc28f5958e423e46444538
| 7,480 |
//
// BreakpointTests.swift
//
//
// Created by Sergej Jaskiewicz on 03.12.2019.
//
#if !WASI
import XCTest
#if OPENCOMBINE_COMPATIBILITY_TEST
import Combine
#else
import OpenCombine
#endif
@available(macOS 10.15, iOS 13.0, *)
final class BreakpointTests: XCTestCase {
func testReceiveSubscription() {
var shouldStop = false
var counter = 0
let helper = OperatorTestHelper(publisherType: CustomPublisher.self,
initialDemand: nil,
receiveValueDemand: .max(1)) {
$0.breakpoint(receiveSubscription: { _ in counter += 1; return shouldStop })
}
XCTAssertNotNil(helper.sut.receiveSubscription)
XCTAssertNil(helper.sut.receiveOutput)
XCTAssertNil(helper.sut.receiveCompletion)
XCTAssertEqual(helper.publisher.send(12), .max(1))
helper.publisher.send(completion: .finished)
helper.publisher.send(completion: .failure(.oops))
XCTAssertEqual(helper.publisher.send(21), .max(1))
helper.publisher.send(subscription: CustomSubscription())
XCTAssertEqual(helper.tracking.history, [.subscription("CustomSubscription"),
.value(12),
.completion(.finished),
.completion(.failure(.oops)),
.value(21),
.subscription("CustomSubscription")])
XCTAssertEqual(helper.subscription.history, [])
shouldStop = true
XCTAssertEqual(counter, 2)
assertCrashes {
helper.publisher.send(subscription: CustomSubscription())
}
}
func testReceiveValue() {
var counter = 0
let helper = OperatorTestHelper(publisherType: CustomPublisher.self,
initialDemand: nil,
receiveValueDemand: .max(1)) {
$0.breakpoint(receiveOutput: { counter += 1; return $0 < 0 })
}
XCTAssertNil(helper.sut.receiveSubscription)
XCTAssertNotNil(helper.sut.receiveOutput)
XCTAssertNil(helper.sut.receiveCompletion)
XCTAssertEqual(helper.publisher.send(12), .max(1))
helper.publisher.send(completion: .finished)
helper.publisher.send(completion: .failure(.oops))
XCTAssertEqual(helper.publisher.send(21), .max(1))
helper.publisher.send(subscription: CustomSubscription())
XCTAssertEqual(helper.tracking.history, [.subscription("CustomSubscription"),
.value(12),
.completion(.finished),
.completion(.failure(.oops)),
.value(21),
.subscription("CustomSubscription")])
XCTAssertEqual(helper.subscription.history, [])
XCTAssertEqual(counter, 2)
assertCrashes {
_ = helper.publisher.send(-1)
}
}
func testReceiveCompletion() {
var counter = 0
let helper = OperatorTestHelper(publisherType: CustomPublisher.self,
initialDemand: nil,
receiveValueDemand: .max(1)) {
$0.breakpoint(receiveCompletion: { counter += 1; return $0 == .finished })
}
XCTAssertNil(helper.sut.receiveSubscription)
XCTAssertNil(helper.sut.receiveOutput)
XCTAssertNotNil(helper.sut.receiveCompletion)
XCTAssertEqual(helper.publisher.send(12), .max(1))
helper.publisher.send(completion: .failure(.oops))
helper.publisher.send(completion: .failure(.oops))
XCTAssertEqual(helper.publisher.send(21), .max(1))
helper.publisher.send(subscription: CustomSubscription())
XCTAssertEqual(helper.tracking.history, [.subscription("CustomSubscription"),
.value(12),
.completion(.failure(.oops)),
.completion(.failure(.oops)),
.value(21),
.subscription("CustomSubscription")])
XCTAssertEqual(counter, 2)
assertCrashes {
helper.publisher.send(completion: .finished)
}
}
func testBreakpointOnError() throws {
let helper = OperatorTestHelper(publisherType: CustomPublisher.self,
initialDemand: nil,
receiveValueDemand: .max(1)) {
$0.breakpointOnError()
}
XCTAssertNil(helper.sut.receiveSubscription)
XCTAssertNil(helper.sut.receiveOutput)
XCTAssertNotNil(helper.sut.receiveCompletion)
XCTAssertEqual(helper.publisher.send(12), .max(1))
helper.publisher.send(completion: .finished)
helper.publisher.send(completion: .finished)
XCTAssertEqual(helper.publisher.send(21), .max(1))
helper.publisher.send(subscription: CustomSubscription())
XCTAssertEqual(helper.tracking.history, [.subscription("CustomSubscription"),
.value(12),
.completion(.finished),
.completion(.finished),
.value(21),
.subscription("CustomSubscription")])
XCTAssertEqual(helper.sut.receiveCompletion?(.finished), false)
XCTAssertEqual(helper.sut.receiveCompletion?(.failure(.oops)), true)
assertCrashes {
helper.publisher.send(completion: .failure(.oops))
}
}
func testCancelAlreadyCancelled() throws {
let helper = OperatorTestHelper(publisherType: CustomPublisher.self,
initialDemand: .unlimited,
receiveValueDemand: .none) {
$0.breakpointOnError()
}
try XCTUnwrap(helper.downstreamSubscription).request(.max(14))
try XCTUnwrap(helper.downstreamSubscription).cancel()
try XCTUnwrap(helper.downstreamSubscription).request(.max(100))
try XCTUnwrap(helper.downstreamSubscription).cancel()
XCTAssertEqual(helper.subscription.history, [.requested(.unlimited),
.requested(.max(14)),
.cancelled,
.requested(.max(100)),
.cancelled])
}
func testBreakpointReflection() throws {
try testReflection(parentInput: Int.self,
parentFailure: Error.self,
description: "Breakpoint",
customMirror: childrenIsEmpty,
playgroundDescription: "Breakpoint",
subscriberIsAlsoSubscription: false,
{ $0.breakpointOnError() })
}
}
#endif // !WASI
| 42.259887 | 88 | 0.525668 |
f79c5fe0567602981c588a1928eee73ecb717fde
| 8,896 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
#if compiler(>=5.5) && canImport(_Concurrency)
import SotoCore
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
extension MediaPackageVod {
// MARK: Async API Calls
/// Changes the packaging group's properities to configure log subscription
public func configureLogs(_ input: ConfigureLogsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ConfigureLogsResponse {
return try await self.client.execute(operation: "ConfigureLogs", path: "/packaging_groups/{id}/configure_logs", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new MediaPackage VOD Asset resource.
public func createAsset(_ input: CreateAssetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateAssetResponse {
return try await self.client.execute(operation: "CreateAsset", path: "/assets", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new MediaPackage VOD PackagingConfiguration resource.
public func createPackagingConfiguration(_ input: CreatePackagingConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreatePackagingConfigurationResponse {
return try await self.client.execute(operation: "CreatePackagingConfiguration", path: "/packaging_configurations", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new MediaPackage VOD PackagingGroup resource.
public func createPackagingGroup(_ input: CreatePackagingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreatePackagingGroupResponse {
return try await self.client.execute(operation: "CreatePackagingGroup", path: "/packaging_groups", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes an existing MediaPackage VOD Asset resource.
public func deleteAsset(_ input: DeleteAssetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteAssetResponse {
return try await self.client.execute(operation: "DeleteAsset", path: "/assets/{id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a MediaPackage VOD PackagingConfiguration resource.
public func deletePackagingConfiguration(_ input: DeletePackagingConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeletePackagingConfigurationResponse {
return try await self.client.execute(operation: "DeletePackagingConfiguration", path: "/packaging_configurations/{id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a MediaPackage VOD PackagingGroup resource.
public func deletePackagingGroup(_ input: DeletePackagingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeletePackagingGroupResponse {
return try await self.client.execute(operation: "DeletePackagingGroup", path: "/packaging_groups/{id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a description of a MediaPackage VOD Asset resource.
public func describeAsset(_ input: DescribeAssetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeAssetResponse {
return try await self.client.execute(operation: "DescribeAsset", path: "/assets/{id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a description of a MediaPackage VOD PackagingConfiguration resource.
public func describePackagingConfiguration(_ input: DescribePackagingConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribePackagingConfigurationResponse {
return try await self.client.execute(operation: "DescribePackagingConfiguration", path: "/packaging_configurations/{id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a description of a MediaPackage VOD PackagingGroup resource.
public func describePackagingGroup(_ input: DescribePackagingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribePackagingGroupResponse {
return try await self.client.execute(operation: "DescribePackagingGroup", path: "/packaging_groups/{id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a collection of MediaPackage VOD Asset resources.
public func listAssets(_ input: ListAssetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListAssetsResponse {
return try await self.client.execute(operation: "ListAssets", path: "/assets", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a collection of MediaPackage VOD PackagingConfiguration resources.
public func listPackagingConfigurations(_ input: ListPackagingConfigurationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListPackagingConfigurationsResponse {
return try await self.client.execute(operation: "ListPackagingConfigurations", path: "/packaging_configurations", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a collection of MediaPackage VOD PackagingGroup resources.
public func listPackagingGroups(_ input: ListPackagingGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListPackagingGroupsResponse {
return try await self.client.execute(operation: "ListPackagingGroups", path: "/packaging_groups", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of the tags assigned to the specified resource.
public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListTagsForResourceResponse {
return try await self.client.execute(operation: "ListTagsForResource", path: "/tags/{resource-arn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Adds tags to the specified resource. You can specify one or more tags to add.
public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws {
return try await self.client.execute(operation: "TagResource", path: "/tags/{resource-arn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Removes tags from the specified resource. You can specify one or more tags to remove.
public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws {
return try await self.client.execute(operation: "UntagResource", path: "/tags/{resource-arn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates a specific packaging group. You can't change the id attribute or any other system-generated attributes.
public func updatePackagingGroup(_ input: UpdatePackagingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdatePackagingGroupResponse {
return try await self.client.execute(operation: "UpdatePackagingGroup", path: "/packaging_groups/{id}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
#endif // compiler(>=5.5) && canImport(_Concurrency)
| 79.428571 | 227 | 0.744379 |
09e3f09e5a7c4ab85267ee219738803acb9e6bca
| 29,160 |
/*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import func Foundation.NSUserName
import TSCLibc
import TSCBasic
import TSCUtility
import PackageModel
import PackageGraph
import SourceControl
import Build
import Workspace
typealias Diagnostic = TSCBasic.Diagnostic
private class ToolWorkspaceDelegate: WorkspaceDelegate {
/// The stream to use for reporting progress.
private let stdoutStream: ThreadSafeOutputByteStream
init(_ stdoutStream: OutputByteStream) {
// FIXME: Implement a class convenience initializer that does this once they are supported
// https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924
self.stdoutStream = stdoutStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(stdoutStream)
}
func fetchingWillBegin(repository: String) {
stdoutStream <<< "Fetching \(repository)"
stdoutStream <<< "\n"
stdoutStream.flush()
}
func fetchingDidFinish(repository: String, diagnostic: Diagnostic?) {
}
func repositoryWillUpdate(_ repository: String) {
stdoutStream <<< "Updating \(repository)"
stdoutStream <<< "\n"
stdoutStream.flush()
}
func repositoryDidUpdate(_ repository: String) {
}
func dependenciesUpToDate() {
stdoutStream <<< "Everything is already up-to-date"
stdoutStream <<< "\n"
stdoutStream.flush()
}
func cloning(repository: String) {
stdoutStream <<< "Cloning \(repository)"
stdoutStream <<< "\n"
stdoutStream.flush()
}
func checkingOut(repository: String, atReference reference: String, to path: AbsolutePath) {
stdoutStream <<< "Resolving \(repository) at \(reference)"
stdoutStream <<< "\n"
stdoutStream.flush()
}
func removing(repository: String) {
stdoutStream <<< "Removing \(repository)"
stdoutStream <<< "\n"
stdoutStream.flush()
}
func warning(message: String) {
// FIXME: We should emit warnings through the diagnostic engine.
stdoutStream <<< "warning: " <<< message
stdoutStream <<< "\n"
stdoutStream.flush()
}
}
protocol ToolName {
static var toolName: String { get }
}
extension ToolName {
static func otherToolNames() -> String {
let allTools: [ToolName.Type] = [SwiftBuildTool.self, SwiftRunTool.self, SwiftPackageTool.self, SwiftTestTool.self]
return allTools.filter({ $0 != self }).map({ $0.toolName }).joined(separator: ", ")
}
}
/// Handler for the main DiagnosticsEngine used by the SwiftTool class.
private final class DiagnosticsEngineHandler {
/// The standard output stream.
var stdoutStream = TSCBasic.stdoutStream
/// The default instance.
static let `default` = DiagnosticsEngineHandler()
private init() {}
func diagnosticsHandler(_ diagnostic: Diagnostic) {
print(diagnostic: diagnostic, stdoutStream: stderrStream)
}
}
public class SwiftTool<Options: ToolOptions> {
/// The original working directory.
let originalWorkingDirectory: AbsolutePath
/// The options of this tool.
let options: Options
/// Path to the root package directory, nil if manifest is not found.
let packageRoot: AbsolutePath?
/// Helper function to get package root or throw error if it is not found.
func getPackageRoot() throws -> AbsolutePath {
guard let packageRoot = packageRoot else {
throw Error.rootManifestFileNotFound
}
return packageRoot
}
/// Get the current workspace root object.
func getWorkspaceRoot() throws -> PackageGraphRootInput {
let packages: [AbsolutePath]
if let workspace = options.multirootPackageDataFile {
packages = try XcodeWorkspaceLoader(diagnostics: diagnostics).load(workspace: workspace)
} else {
packages = [try getPackageRoot()]
}
return PackageGraphRootInput(packages: packages)
}
/// Path to the build directory.
let buildPath: AbsolutePath
/// Reference to the argument parser.
let parser: ArgumentParser
/// The process set to hold the launched processes. These will be terminated on any signal
/// received by the swift tools.
let processSet: ProcessSet
/// The current build system reference. The actual reference is present only during an active build.
let buildSystemRef: BuildSystemRef
/// The interrupt handler.
let interruptHandler: InterruptHandler
/// The diagnostics engine.
let diagnostics: DiagnosticsEngine = DiagnosticsEngine(
handlers: [DiagnosticsEngineHandler.default.diagnosticsHandler])
/// The execution status of the tool.
var executionStatus: ExecutionStatus = .success
/// The stream to print standard output on.
fileprivate(set) var stdoutStream: OutputByteStream = TSCBasic.stdoutStream
/// Create an instance of this tool.
///
/// - parameter args: The command line arguments to be passed to this tool.
public init(toolName: String, usage: String, overview: String, args: [String], seeAlso: String? = nil) {
// Capture the original working directory ASAP.
guard let cwd = localFileSystem.currentWorkingDirectory else {
diagnostics.emit(error: "couldn't determine the current working directory")
SwiftTool.exit(with: .failure)
}
originalWorkingDirectory = cwd
// Create the parser.
parser = ArgumentParser(
commandName: "swift \(toolName)",
usage: usage,
overview: overview,
seeAlso: seeAlso)
// Create the binder.
let binder = ArgumentBinder<Options>()
// Bind the common options.
binder.bindArray(
parser.add(
option: "-Xcc", kind: [String].self, strategy: .oneByOne,
usage: "Pass flag through to all C compiler invocations"),
parser.add(
option: "-Xswiftc", kind: [String].self, strategy: .oneByOne,
usage: "Pass flag through to all Swift compiler invocations"),
parser.add(
option: "-Xlinker", kind: [String].self, strategy: .oneByOne,
usage: "Pass flag through to all linker invocations"),
to: {
$0.buildFlags.cCompilerFlags = $1
$0.buildFlags.swiftCompilerFlags = $2
$0.buildFlags.linkerFlags = $3
})
binder.bindArray(
option: parser.add(
option: "-Xcxx", kind: [String].self, strategy: .oneByOne,
usage: "Pass flag through to all C++ compiler invocations"),
to: { $0.buildFlags.cxxCompilerFlags = $1 })
binder.bind(
option: parser.add(
option: "--configuration", shortName: "-c", kind: BuildConfiguration.self,
usage: "Build with configuration (debug|release) [default: debug]"),
to: { $0.configuration = $1 })
binder.bind(
option: parser.add(
option: "--build-path", kind: PathArgument.self,
usage: "Specify build/cache directory [default: ./.build]"),
to: { $0.buildPath = $1.path })
binder.bind(
option: parser.add(
option: "--chdir", shortName: "-C", kind: PathArgument.self),
to: { $0.chdir = $1.path })
binder.bind(
option: parser.add(
option: "--package-path", kind: PathArgument.self,
usage: "Change working directory before any other operation"),
to: { $0.packagePath = $1.path })
binder.bind(
option: parser.add(
option: "--multiroot-data-file", kind: PathArgument.self, usage: nil),
to: { $0.multirootPackageDataFile = $1.path })
binder.bindArray(
option: parser.add(option: "--sanitize", kind: [Sanitizer].self,
strategy: .oneByOne, usage: "Turn on runtime checks for erroneous behavior"),
to: { $0.sanitizers = EnabledSanitizers(Set($1)) })
binder.bind(
option: parser.add(option: "--disable-prefetching", kind: Bool.self, usage: ""),
to: { $0.shouldEnableResolverPrefetching = !$1 })
binder.bind(
option: parser.add(option: "--skip-update", kind: Bool.self, usage: "Skip updating dependencies from their remote during a resolution"),
to: { $0.skipDependencyUpdate = $1 })
binder.bind(
option: parser.add(option: "--disable-sandbox", kind: Bool.self,
usage: "Disable using the sandbox when executing subprocesses"),
to: { $0.shouldDisableSandbox = $1 })
binder.bind(
option: parser.add(option: "--disable-package-manifest-caching", kind: Bool.self,
usage: "Disable caching Package.swift manifests"),
to: { $0.shouldDisableManifestCaching = $1 })
binder.bind(
option: parser.add(option: "--version", kind: Bool.self),
to: { $0.shouldPrintVersion = $1 })
binder.bind(
option: parser.add(option: "--destination", kind: PathArgument.self),
to: { $0.customCompileDestination = $1.path })
// FIXME: We need to allow -vv type options for this.
binder.bind(
option: parser.add(option: "--verbose", shortName: "-v", kind: Bool.self,
usage: "Increase verbosity of informational output"),
to: { $0.verbosity = $1 ? 1 : 0 })
binder.bind(
option: parser.add(option: "--no-static-swift-stdlib", kind: Bool.self,
usage: "Do not link Swift stdlib statically [default]"),
to: { $0.shouldLinkStaticSwiftStdlib = !$1 })
binder.bind(
option: parser.add(option: "--static-swift-stdlib", kind: Bool.self,
usage: "Link Swift stdlib statically"),
to: { $0.shouldLinkStaticSwiftStdlib = $1 })
binder.bind(
option: parser.add(option: "--force-resolved-versions", kind: Bool.self),
to: { $0.forceResolvedVersions = $1 })
binder.bind(
option: parser.add(option: "--disable-automatic-resolution", kind: Bool.self,
usage: "Disable automatic resolution if Package.resolved file is out-of-date"),
to: { $0.forceResolvedVersions = $1 })
binder.bind(
option: parser.add(option: "--enable-index-store", kind: Bool.self,
usage: "Enable indexing-while-building feature"),
to: { if $1 { $0.indexStoreMode = .on } })
binder.bind(
option: parser.add(option: "--disable-index-store", kind: Bool.self,
usage: "Disable indexing-while-building feature"),
to: { if $1 { $0.indexStoreMode = .off } })
binder.bind(
option: parser.add(option: "--enable-pubgrub-resolver", kind: Bool.self,
usage: "Enable the new Pubgrub dependency resolver"),
to: { $0.enablePubgrubResolver = $1 })
binder.bind(
option: parser.add(option: "--use-legacy-resolver", kind: Bool.self,
usage: "Use the legacy dependency resolver"),
to: { $0.enablePubgrubResolver = !$1 })
binder.bind(
option: parser.add(option: "--enable-parseable-module-interfaces", kind: Bool.self),
to: { $0.shouldEnableParseableModuleInterfaces = $1 })
binder.bind(
option: parser.add(option: "--trace-resolver", kind: Bool.self),
to: { $0.enableResolverTrace = $1 })
binder.bind(
option: parser.add(option: "--jobs", shortName: "-j", kind: Int.self,
usage: "The number of jobs to spawn in parallel during the build process"),
to: { $0.jobs = UInt32($1) })
binder.bind(
option: parser.add(option: "--enable-test-discovery", kind: Bool.self,
usage: "Enable test discovery on platforms without Objective-C runtime"),
to: { $0.enableTestDiscovery = $1 })
binder.bind(
option: parser.add(option: "--enable-build-manifest-caching", kind: Bool.self, usage: nil),
to: { $0.enableBuildManifestCaching = $1 })
binder.bind(
option: parser.add(option: "--emit-swift-module-separately", kind: Bool.self, usage: nil),
to: { $0.emitSwiftModuleSeparately = $1 })
// Let subclasses bind arguments.
type(of: self).defineArguments(parser: parser, binder: binder)
do {
// Parse the result.
let result = try parser.parse(args)
try Self.postprocessArgParserResult(result: result, diagnostics: diagnostics)
var options = Options()
try binder.fill(parseResult: result, into: &options)
self.options = options
// Honor package-path option is provided.
if let packagePath = options.packagePath ?? options.chdir {
try ProcessEnv.chdir(packagePath)
}
let processSet = ProcessSet()
let buildSystemRef = BuildSystemRef()
interruptHandler = try InterruptHandler {
// Terminate all processes on receiving an interrupt signal.
processSet.terminate()
buildSystemRef.buildOp?.cancel()
#if os(Windows)
// Exit as if by signal()
TerminateProcess(GetCurrentProcess(), 3)
#elseif os(macOS)
// Install the default signal handler.
var action = sigaction()
action.__sigaction_u.__sa_handler = SIG_DFL
sigaction(SIGINT, &action, nil)
kill(getpid(), SIGINT)
#elseif os(Android)
// Install the default signal handler.
var action = sigaction()
action.sa_handler = SIG_DFL
sigaction(SIGINT, &action, nil)
kill(getpid(), SIGINT)
#else
var action = sigaction()
action.__sigaction_handler = unsafeBitCast(
SIG_DFL,
to: sigaction.__Unnamed_union___sigaction_handler.self)
sigaction(SIGINT, &action, nil)
kill(getpid(), SIGINT)
#endif
}
self.processSet = processSet
self.buildSystemRef = buildSystemRef
} catch {
handle(error: error)
SwiftTool.exit(with: .failure)
}
// Create local variables to use while finding build path to avoid capture self before init error.
let customBuildPath = options.buildPath
let packageRoot = findPackageRoot()
self.packageRoot = packageRoot
self.buildPath = getEnvBuildPath(workingDir: cwd) ??
customBuildPath ??
(packageRoot ?? cwd).appending(component: ".build")
}
static func postprocessArgParserResult(result: ArgumentParser.Result, diagnostics: DiagnosticsEngine) throws {
if result.exists(arg: "--chdir") || result.exists(arg: "-C") {
diagnostics.emit(warning: "'--chdir/-C' option is deprecated; use '--package-path' instead")
}
if result.exists(arg: "--multiroot-data-file") {
diagnostics.emit(.unsupportedFlag("--multiroot-data-file"))
}
}
class func defineArguments(parser: ArgumentParser, binder: ArgumentBinder<Options>) {
fatalError("Must be implemented by subclasses")
}
func editablesPath() throws -> AbsolutePath {
if let multiRootPackageDataFile = options.multirootPackageDataFile {
return multiRootPackageDataFile.appending(component: "Packages")
}
return try getPackageRoot().appending(component: "Packages")
}
func resolvedFilePath() throws -> AbsolutePath {
if let multiRootPackageDataFile = options.multirootPackageDataFile {
return multiRootPackageDataFile.appending(components: "xcshareddata", "swiftpm", "Package.resolved")
}
return try getPackageRoot().appending(component: "Package.resolved")
}
func configFilePath() throws -> AbsolutePath {
// Look for the override in the environment.
if let envPath = ProcessEnv.vars["SWIFTPM_MIRROR_CONFIG"] {
return try AbsolutePath(validating: envPath)
}
// Otherwise, use the default path.
if let multiRootPackageDataFile = options.multirootPackageDataFile {
return multiRootPackageDataFile.appending(components: "xcshareddata", "swiftpm", "config")
}
return try getPackageRoot().appending(components: ".swiftpm", "config")
}
func getSwiftPMConfig() throws -> SwiftPMConfig {
return try _swiftpmConfig.get()
}
private lazy var _swiftpmConfig: Result<SwiftPMConfig, AnyError> = {
return Result(anyError: { SwiftPMConfig(path: try configFilePath()) })
}()
/// Holds the currently active workspace.
///
/// It is not initialized in init() because for some of the commands like package init , usage etc,
/// workspace is not needed, infact it would be an error to ask for the workspace object
/// for package init because the Manifest file should *not* present.
private var _workspace: Workspace?
/// Returns the currently active workspace.
func getActiveWorkspace() throws -> Workspace {
if let workspace = _workspace {
return workspace
}
let delegate = ToolWorkspaceDelegate(self.stdoutStream)
let provider = GitRepositoryProvider(processSet: processSet)
let workspace = Workspace(
dataPath: buildPath,
editablesPath: try editablesPath(),
pinsFile: try resolvedFilePath(),
manifestLoader: try getManifestLoader(),
toolsVersionLoader: ToolsVersionLoader(),
delegate: delegate,
config: try getSwiftPMConfig(),
repositoryProvider: provider,
isResolverPrefetchingEnabled: options.shouldEnableResolverPrefetching,
enablePubgrubResolver: options.enablePubgrubResolver,
skipUpdate: options.skipDependencyUpdate,
enableResolverTrace: options.enableResolverTrace
)
_workspace = workspace
return workspace
}
/// Execute the tool.
public func run() {
do {
// Setup the globals.
verbosity = Verbosity(rawValue: options.verbosity)
Process.verbose = verbosity != .concise
// Call the implementation.
try runImpl()
if diagnostics.hasErrors {
throw Diagnostics.fatalError
}
} catch {
// Set execution status to failure in case of errors.
executionStatus = .failure
handle(error: error)
}
SwiftTool.exit(with: executionStatus)
}
/// Exit the tool with the given execution status.
private static func exit(with status: ExecutionStatus) -> Never {
switch status {
case .success: TSCLibc.exit(0)
case .failure: TSCLibc.exit(1)
}
}
/// Run method implementation to be overridden by subclasses.
func runImpl() throws {
fatalError("Must be implemented by subclasses")
}
/// Start redirecting the standard output stream to the standard error stream.
func redirectStdoutToStderr() {
self.stdoutStream = TSCBasic.stderrStream
DiagnosticsEngineHandler.default.stdoutStream = TSCBasic.stderrStream
}
/// Resolve the dependencies.
func resolve() throws {
let workspace = try getActiveWorkspace()
let root = try getWorkspaceRoot()
if options.forceResolvedVersions {
workspace.resolveToResolvedVersion(root: root, diagnostics: diagnostics)
} else {
workspace.resolve(root: root, diagnostics: diagnostics)
}
// Throw if there were errors when loading the graph.
// The actual errors will be printed before exiting.
guard !diagnostics.hasErrors else {
throw Diagnostics.fatalError
}
}
/// Fetch and load the complete package graph.
@discardableResult
func loadPackageGraph(
createREPLProduct: Bool = false
) throws -> PackageGraph {
do {
let workspace = try getActiveWorkspace()
// Fetch and load the package graph.
let graph = try workspace.loadPackageGraph(
root: getWorkspaceRoot(),
createREPLProduct: createREPLProduct,
forceResolvedVersions: options.forceResolvedVersions,
diagnostics: diagnostics
)
// Throw if there were errors when loading the graph.
// The actual errors will be printed before exiting.
guard !diagnostics.hasErrors else {
throw Diagnostics.fatalError
}
return graph
} catch {
throw error
}
}
/// Returns the user toolchain to compile the actual product.
func getToolchain() throws -> UserToolchain {
return try _destinationToolchain.get()
}
func getManifestLoader() throws -> ManifestLoader {
return try _manifestLoader.get()
}
private func canUseBuildManifestCaching() throws -> Bool {
let buildParameters = try self.buildParameters()
let haveBuildManifestAndDescription =
localFileSystem.exists(buildParameters.llbuildManifest) &&
localFileSystem.exists(buildParameters.buildDescriptionPath)
// Perform steps for build manifest caching if we can enabled it.
//
// FIXME: We don't add edited packages in the package structure command yet (SR-11254).
let hasEditedPackages = try getActiveWorkspace().managedDependencies.values.contains{ $0.isEdited }
return options.enableBuildManifestCaching && haveBuildManifestAndDescription && !hasEditedPackages
}
func createBuildOperation(useBuildManifestCaching: Bool = true) throws -> BuildOperation {
// Load a custom package graph which has a special product for REPL.
let graphLoader = { try self.loadPackageGraph() }
// Construct the build operation.
let buildOp = try BuildOperation(
buildParameters: buildParameters(),
useBuildManifestCaching: useBuildManifestCaching && canUseBuildManifestCaching(),
packageGraphLoader: graphLoader,
diags: diagnostics,
stdoutStream: self.stdoutStream
)
// Save the instance so it can be cancelled from the int handler.
buildSystemRef.buildOp = buildOp
return buildOp
}
/// Return the build parameters.
func buildParameters() throws -> BuildParameters {
return try _buildParameters.get()
}
private lazy var _buildParameters: Result<BuildParameters, AnyError> = {
return Result(anyError: {
let toolchain = try self.getToolchain()
let triple = toolchain.destination.target
return BuildParameters(
dataPath: buildPath.appending(component: toolchain.destination.target.tripleString),
configuration: options.configuration,
toolchain: toolchain,
destinationTriple: triple,
flags: options.buildFlags,
shouldLinkStaticSwiftStdlib: options.shouldLinkStaticSwiftStdlib,
sanitizers: options.sanitizers,
enableCodeCoverage: options.shouldEnableCodeCoverage,
indexStoreMode: options.indexStoreMode,
enableParseableModuleInterfaces: options.shouldEnableParseableModuleInterfaces,
enableTestDiscovery: options.enableTestDiscovery,
emitSwiftModuleSeparately: options.emitSwiftModuleSeparately
)
})
}()
/// Lazily compute the destination toolchain.
private lazy var _destinationToolchain: Result<UserToolchain, AnyError> = {
// Create custom toolchain if present.
if let customDestination = self.options.customCompileDestination {
return Result(anyError: {
try UserToolchain(destination: Destination(fromFile: customDestination))
})
}
// Otherwise use the host toolchain.
return self._hostToolchain
}()
/// Lazily compute the host toolchain used to compile the package description.
private lazy var _hostToolchain: Result<UserToolchain, AnyError> = {
return Result(anyError: {
try UserToolchain(destination: Destination.hostDestination(
originalWorkingDirectory: self.originalWorkingDirectory))
})
}()
private lazy var _manifestLoader: Result<ManifestLoader, AnyError> = {
return Result(anyError: {
try ManifestLoader(
// Always use the host toolchain's resources for parsing manifest.
manifestResources: self._hostToolchain.get().manifestResources,
isManifestSandboxEnabled: !self.options.shouldDisableSandbox,
cacheDir: self.options.shouldDisableManifestCaching ? nil : self.buildPath
)
})
}()
/// An enum indicating the execution status of run commands.
enum ExecutionStatus {
case success
case failure
}
}
/// Returns path of the nearest directory containing the manifest file w.r.t
/// current working directory.
private func findPackageRoot() -> AbsolutePath? {
guard var root = localFileSystem.currentWorkingDirectory else {
return nil
}
// FIXME: It would be nice to move this to a generalized method which takes path and predicate and
// finds the lowest path for which the predicate is true.
while !localFileSystem.isFile(root.appending(component: Manifest.filename)) {
root = root.parentDirectory
guard !root.isRoot else {
return nil
}
}
return root
}
/// Returns the build path from the environment, if present.
private func getEnvBuildPath(workingDir: AbsolutePath) -> AbsolutePath? {
// Don't rely on build path from env for SwiftPM's own tests.
guard ProcessEnv.vars["SWIFTPM_TESTS_MODULECACHE"] == nil else { return nil }
guard let env = ProcessEnv.vars["SWIFTPM_BUILD_DIR"] else { return nil }
return AbsolutePath(env, relativeTo: workingDir)
}
/// Returns the sandbox profile to be used when parsing manifest on macOS.
private func sandboxProfile(allowedDirectories: [AbsolutePath]) -> String {
let stream = BufferedOutputByteStream()
stream <<< "(version 1)" <<< "\n"
// Deny everything by default.
stream <<< "(deny default)" <<< "\n"
// Import the system sandbox profile.
stream <<< "(import \"system.sb\")" <<< "\n"
// Allow reading all files.
stream <<< "(allow file-read*)" <<< "\n"
// These are required by the Swift compiler.
stream <<< "(allow process*)" <<< "\n"
stream <<< "(allow sysctl*)" <<< "\n"
// Allow writing in temporary locations.
stream <<< "(allow file-write*" <<< "\n"
for directory in Platform.darwinCacheDirectories() {
// For compiler module cache.
stream <<< " (regex #\"^\(directory.pathString)/org\\.llvm\\.clang.*\")" <<< "\n"
// For archive tool.
stream <<< " (regex #\"^\(directory.pathString)/ar.*\")" <<< "\n"
// For xcrun cache.
stream <<< " (regex #\"^\(directory.pathString)/xcrun.*\")" <<< "\n"
// For autolink files.
stream <<< " (regex #\"^\(directory.pathString)/.*\\.(swift|c)-[0-9a-f]+\\.autolink\")" <<< "\n"
}
for directory in allowedDirectories {
stream <<< " (subpath \"\(directory.pathString)\")" <<< "\n"
}
stream <<< ")" <<< "\n"
return stream.bytes.description
}
extension BuildConfiguration: StringEnumArgument {
public static var completion: ShellCompletion = .values([
(debug.rawValue, "build with DEBUG configuration"),
(release.rawValue, "build with RELEASE configuration"),
])
}
/// A wrapper to hold the build system so we can use it inside
/// the int. handler without requiring to initialize it.
final class BuildSystemRef {
var buildOp: BuildOperation?
}
extension Diagnostic.Message {
static func unsupportedFlag(_ flag: String) -> Diagnostic.Message {
.warning("\(flag) is an *unsupported* option which can be removed at any time; do not rely on it")
}
}
| 38.7251 | 148 | 0.622634 |
e6596708066578a8fd3d12800b57c94d90c7ad89
| 2,105 |
// Copyright 2016 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TulsiGenerator
class CommandLineSplitterTests: XCTestCase {
var splitter: CommandLineSplitter! = nil
override func setUp() {
super.setUp()
splitter = CommandLineSplitter()
}
func testSimpleArgs() {
checkSplit("", [])
checkSplit("'broken \"", nil)
checkSplit("\"broken ", nil)
checkSplit("\"\"", [""])
checkSplit("Single", ["Single"])
checkSplit("one two", ["one", "two"])
}
func testQuotedArgs() {
checkSplit("one 'two single quoted'", ["one", "two single quoted"])
checkSplit("one \"two double quoted\"", ["one", "two double quoted"])
checkSplit("one \"two double quoted\"", ["one", "two double quoted"])
checkSplit("one=one \"two double quoted\"", ["one=one", "two double quoted"])
checkSplit("\"a=b=c\" \"two double quoted\"", ["a=b=c", "two double quoted"])
checkSplit("\"a=\\\"b = c\\\"\" \"two double quoted\"", ["a=\"b = c\"", "two double quoted"])
checkSplit("\"quoted text \"", ["quoted text "])
checkSplit("'quoted text '", ["quoted text "])
}
// MARK: - Private methods
private func checkSplit(_ commandLine: String, _ expected: [String]?, line: UInt = #line) {
let split = splitter.splitCommandLine(commandLine)
if expected == nil {
XCTAssertNil(split, line: line)
return
}
XCTAssertNotNil(split, line: line)
if let split = split {
XCTAssertEqual(split, expected!, line: line)
}
}
}
| 32.384615 | 97 | 0.644181 |
482c5c2badcea3c55a9c8a3b11518f701dd0e0cb
| 2,113 |
//
// KingfisherOptionsInfo.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/23.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
* KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoKey: Any]. You can use the key-value pairs to control some behaviors of Kingfisher.
*/
public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoKey: Any]
/**
Key for KingfisherOptionsInfo
- Options: Key for options. The value for this key should be a KingfisherOptions.
- TargetCache: Key for target cache. The value for this key should be an ImageCache object.Kingfisher will use this cache when handling the related operation, including trying to retrieve the cached images and store the downloaded image to it.
- Downloader: Key for downloader to use. The value for this key should be an ImageDownloader object. Kingfisher will use this downloader to download the images.
*/
public enum KingfisherOptionsInfoKey {
case Options
case TargetCache
case Downloader
}
| 45.934783 | 243 | 0.764789 |
1cd2e2448630050df3306d89bc9729984c3dc55a
| 353 |
class UnlinkService {
let account: Account
private let accountManager: AccountManager
init(account: Account, accountManager: AccountManager) {
self.account = account
self.accountManager = accountManager
}
}
extension UnlinkService {
func deleteAccount() {
accountManager.delete(account: account)
}
}
| 18.578947 | 60 | 0.685552 |
fc5156598405f0c884b920d59a72d130a0cffbf5
| 546 |
//
// LaunchScreenViewController.swift
// BBPhobia
//
// Created by Martin Weber on 05/02/2017.
// Copyright © 2017 Martin Weber. All rights reserved.
//
import Foundation
import UIKit
class LaunchScreenViewController: UIViewController {
override var prefersStatusBarHidden: Bool {
get {
return true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setNeedsStatusBarAppearanceUpdate()
}
}
| 21.84 | 80 | 0.663004 |
1a0e148c12e53dbaf8ccb000402e5c5abfc02cf9
| 343 |
//
// Bundle+Utils.h
// BadasSwift
//
// Created by Morgan Berger on 14/10/2018.
//
public extension Bundle {
var versionNumber:String? {
return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
}
var buildVersionNumber: String? {
return infoDictionary?["CFBundleVersion"] as? String
}
}
| 21.4375 | 83 | 0.670554 |
1807d80210d5f32f832acc7de15479018a97419b
| 1,614 |
//
// ImageType.swift
// RemoteImage
//
// Copyright (c) 2021 Rocket Insights, Inc.
//
// 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.
//
// Typealias an `ImageType` to either `UIImage` or `NSImage` depending on our platform.
import SwiftUI
#if os(iOS)
import UIKit
public typealias ImageType = UIImage
extension ImageType {
var swiftUIImage: Image {
Image(uiImage: self)
}
}
#elseif os(macOS)
import AppKit
public typealias ImageType = NSImage
extension ImageType {
var swiftUIImage: Image {
Image(nsImage: self)
}
}
#endif
| 30.45283 | 87 | 0.730483 |
016578f312a748db5c539738eaa1c421a405d96b
| 213 |
//
// TrackRelationship.swift
//
//
// Created by Quentin Zervaas on 24/2/2022.
//
import Foundation
extension AppleMusicAPI {
public struct TrackRelationship: Codable {
let data: [Song]
}
}
| 14.2 | 46 | 0.652582 |
89beeeb966b86611be72d740c0dbe5dd2e9572fb
| 3,842 |
//
// MissionTotalizer.swift
// Park Observer
//
// Created by Regan E. Sarwas on 4/23/20.
// Copyright © 2020 Alaska Region GIS Team. All rights reserved.
//
/// Immutable structs and decoders for representing a portion of the configuration file (see SurveyProtocol.swift)
/// An object used to define the text summarizing the mission so far.
struct MissionTotalizer: Codable {
/// The names of attributes that are 'watched'. When one of them changes, the totalizer resets.
let fields: [String]?
/// The size (in points) of the font used for the totalizer text.
let fontSize: Double
/// Indicate if the total distance/time while not 'observing' should be displayed.
let includeOff: Bool
/// Indicate if the total distance/time while 'observing' should be displayed.
let includeOn: Bool
/// Indicate if the total distance/time regardless of 'observing' status should be displayed.
let includeTotal: Bool
/// The units for the quantities displayed in the totalizer.
let units: TotalizerUnits
enum CodingKeys: String, CodingKey {
case fields = "fields"
case fontSize = "fontsize"
case includeOff = "includeoff"
case includeOn = "includeon"
case includeTotal = "includetotal"
case units = "units"
}
/// The units for the quantities displayed in the totalizer.
enum TotalizerUnits: String, Codable {
case kilometers = "kilometers"
case miles = "miles"
case minutes = "minutes"
}
}
//MARK: - MissionTotalizer Codable
// Custom decoding to do array checking:
// Fields must have at least one element,
// and all elements must be unique
// Also a good time to set default values
extension MissionTotalizer {
init(from decoder: Decoder) throws {
var validationEnabled = true
if let options = decoder.userInfo[SurveyProtocolCodingOptions.key]
as? SurveyProtocolCodingOptions
{
validationEnabled = !options.skipValidation
}
let container = try decoder.container(keyedBy: CodingKeys.self)
let fields = try container.decodeIfPresent([String].self, forKey: .fields)
let fontSize = try container.decodeIfPresent(Double.self, forKey: .fontSize) ?? 14.0
let includeOff = try container.decodeIfPresent(Bool.self, forKey: .includeOff) ?? false
let includeOn = try container.decodeIfPresent(Bool.self, forKey: .includeOn) ?? true
let includeTotal = try container.decodeIfPresent(Bool.self, forKey: .includeTotal) ?? false
let units = try container.decodeIfPresent(TotalizerUnits.self, forKey: .units) ?? .kilometers
if validationEnabled {
// Validate fields and fontSize
if let fields = fields {
if fields.count == 0 {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize fields with an empty list"
)
)
}
// Validate fields; ensure unique with case insensitive compare
let fieldNames = fields.map { $0.lowercased() }
if Set(fieldNames).count != fieldNames.count {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription:
"Cannot initialize fields with duplicate values in the list \(fields)"
)
)
}
}
if fontSize < 0 {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize fontsize with a negative value \(fontSize)"
)
)
}
}
self.init(
fields: fields,
fontSize: fontSize,
includeOff: includeOff,
includeOn: includeOn,
includeTotal: includeTotal,
units: units)
}
}
| 32.837607 | 114 | 0.673347 |
f998f7f406a837f680936c4287b60edeba18d6b9
| 2,633 |
//
// SceneDelegate.swift
// TestGRPC
//
// Created by Yoseph Wijaya on 2019/12/15.
// Copyright © 2019 curcifer. 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.
}
}
| 40.507692 | 143 | 0.73984 |
3aef68c99b4c7c48c448d80b500ba09ec1db208f
| 3,028 |
// Copyright 2017-2020 Fitbit, Inc
// SPDX-License-Identifier: Apache-2.0
//
// CentralManagerSink.swift
// GoldenGate
//
// Created by Marcel Jackwerth on 10/24/17.
//
import CoreBluetooth
import Foundation
import RxBluetoothKit
import RxSwift
/// On platforms that support `canSendWriteWithoutResponse`, it will communicate back-pressure.
public class CentralManagerSink: NSObject, DataSink {
fileprivate let listenerScheduler: ImmediateSchedulerType
fileprivate let characteristic: CharacteristicType
fileprivate let writeType: CBCharacteristicWriteType
fileprivate weak var dataSinkListener: DataSinkListener?
fileprivate var reportedFailure = false
fileprivate var waitingForReponse = false
public init(listenerScheduler: ImmediateSchedulerType, characteristic: CharacteristicType) {
self.listenerScheduler = listenerScheduler
self.characteristic = characteristic
self.writeType = characteristic.properties.contains(.writeWithoutResponse) ?
.withoutResponse : .withResponse
super.init()
}
public func put(_ buffer: Buffer, metadata: Metadata?) throws {
switch writeType {
case .withResponse:
guard !waitingForReponse else {
reportedFailure = true
throw BluetoothConnectionError.wouldBlock
}
waitingForReponse = true
case .withoutResponse:
// TODO: IPD-81539 Hack to make it work for now. It should be removed once we implement the support for peripheralIsReadyToSendWriteWithoutResponse.
// if #available(iOS 11, OSX 10.13, *) {
// guard peripheral.cbPeripheral.canSendWriteWithoutResponse else {
// reportedFailure = true
// throw BluetoothConnectionError.wouldBlock
// }
// }
_ = ()
@unknown default:
break
}
// Log header of outbound packet
LogBluetoothVerbose("CentralManagerSink: \(buffer.debugDescription)")
_ = characteristic.service().peripheral().writeValue(buffer.data, for: characteristic, type: writeType, canSendWriteWithoutResponseCheckEnabled: false)
.catchErrorJustReturn(characteristic)
.do(onSuccess: { _ in self.waitingForReponse = false })
.observeOn(listenerScheduler)
.subscribe(onSuccess: { _ in
switch self.writeType {
case .withResponse:
self.notify()
case .withoutResponse:
// nothing to do
break
@unknown default:
break
}
})
}
public func setDataSinkListener(_ dataSinkListener: DataSinkListener?) throws {
self.dataSinkListener = dataSinkListener
}
private func notify() {
guard reportedFailure else { return }
reportedFailure = false
dataSinkListener?.onCanPut()
}
}
| 34.804598 | 160 | 0.640357 |
3853e6f50a2e138fceb5868b986bb4a0662be1ef
| 281 |
import UIKit
/// Used to load assets from Lightbox bundle
class AssetManagerLightbox {
static func image(_ named: String) -> UIImage? {
let bundle = Bundle(for: AssetManager.self)
return UIImage(named: "Lightbox.bundle/\(named)", in: bundle, compatibleWith: nil)
}
}
| 25.545455 | 86 | 0.711744 |
ed4b5a43beca9676f463307b0885a7ce47957ccc
| 823 |
//
// PhotoCell.swift
// Instagram
//
// Created by Hoang on 2/25/18.
// Copyright © 2018 Hoang. All rights reserved.
//
import Foundation
import UIKit
class PhotoCell: UICollectionViewCell {
@IBOutlet weak var photoImageView: UIImageView!
override var isSelected: Bool {
willSet {
onSelected(newValue)
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
func setImage(image: UIImage) {
photoImageView.image = image
}
func turnonShade() {
photoImageView.alpha = 0.5
}
func turnoffShade() {
photoImageView.alpha = 1.0
}
func onSelected(_ newValue: Bool) {
if newValue {
turnonShade()
}
else {
turnoffShade()
}
}
}
| 17.891304 | 51 | 0.55407 |
edd68deb90ef537c37b42a4a7ebb876d4e0e763a
| 580 |
//
// WishlistViewModel.swift
// RoutingExample
//
// Created by Cassius Pacheco on 8/3/20.
// Copyright © 2020 Cassius Pacheco. All rights reserved.
//
import Foundation
final class WishlistViewModel {
typealias Routes = LoginRoute & ProductRoute
private let router: Routes
init(router: Routes) {
self.router = router
}
func productButtonTouchUpInside() {
print("Product Button pressed")
router.openProduct()
}
func loginButtonTouchUpInside() {
print("Login Button pressed")
router.openLogin()
}
}
| 20 | 58 | 0.656897 |
160ff774aa5a6ab0cfb0321c5c7c2f13866bc131
| 589 |
import Foundation
struct PusherEncryptionHelpers {
public static func shouldDecryptMessage(eventName: String, channelName: String?) -> Bool {
return isEncryptedChannel(channelName: channelName) && !isPusherSystemEvent(eventName: eventName)
}
public static func isEncryptedChannel(channelName: String?) -> Bool {
return channelName?.starts(with: "private-encrypted-") ?? false
}
public static func isPusherSystemEvent(eventName: String) -> Bool {
return eventName.starts(with: "pusher:") || eventName.starts(with: "pusher_internal:")
}
}
| 34.647059 | 105 | 0.716469 |
db4687865db725075685712a7320bbe348f5fdf1
| 27,138 |
public enum ColorStyle: String, CaseIterable {
// MARK: - Basic Palette Colors
/// Standard base color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: 354A5F
/// (light variant)  Hex color: 2C3D4F
case shell
/// Standard background color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: EDEFF0
/// (light variant)  Hex color: 1C2228
case background1
/// Standard background color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: F7F7F7
/// (light variant)  Hex color: 232A31
case background2
/// Standard line color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: 89919A
/// (light variant)  Hex value: 8696A9
case line
/// Standard line color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: 89919A69 (alpha: 41%)
/// (light variant)  Hex value: 8696A945 (alpha: 27%)
case separator
/// Standard text color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: 32636A
/// (light variant)  Hex color: FAFAFA
case primary1
/// Standard secondary text color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: 515456
/// (light variant)  Hex color: EEF0F1
case primary2
/// Standard secondary text color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: 6A6D70
/// (light variant)  Hex color: D3D7D9
case primary3
/// Standard background and accent color, used in any color scheme.
/// (dark variant)  Hex color: CCCCCC
/// (light variant)  Hex color: 687D94
case primary4
/// Standard background and accent color, used in any color scheme.
/// (dark variant)  Hex color: FAFAFA
/// (light variant)  Hex color: 23303E
case primary5
/// Standard background and accent color, for use in header and cell background.
/// (dark variant)  Hex color: FFFFFF
/// (light variant)  Hex color: 29313A
case primary6
/// Standard background and accent color that is used in tag outline.
/// (dark variant)  Hex color: 74777A
/// (light variant)  Hex color: B8BEC1
case primary7
/// Background and accent color that is mainly used with dark color scheme.
///  Hex color: 2F3943
case primary8
/// Standard background and accent color.
/// (dark variant)  Hex color: E5E5E5
/// (light variant)  Hex color: 3A4552
case primary9
/// Standard background and accent color.
/// (dark variant)  Hex color: 89919A
/// (light variant)  Hex color: 8696A9
case primary10
/// Standard shadow color.
///  Hex color: 000000
case shadow
// MARK: - Grouped Background Colors
/// Primary grouped background colors, with variants for base and elevated UI schemes.
/// (base dark variant)  Hex color: EDEFF0
/// (base light variant)  Hex color: 1C2228
/// (elevated dark variant)  Hex color: EDEFF0
/// (elevated light variant)  Hex color: 232A31
case primaryGroupedBackground
/// Secondary grouped background colors, with variants for base and elevated UI schemes.
/// (base dark variant)  Hex color: FFFFFF
/// (base light variant)  Hex color: 232A31
/// (elevated dark variant)  Hex color: FFFFFF
/// (elevated light variant)  Hex color: 29313A
case secondaryGroupedBackground
/// Secondary grouped background colors, with variants for base and elevated UI schemes.
/// (base dark variant)  Hex color: FFFFFF
/// (base light variant)  Hex color: 29313A
/// (elevated dark variant)  Hex color: FFFFFF
/// (elevated light variant)  Hex color: 2F3943
case tertiaryGroupedBackground
// MARK: - Background Colors
/// Primary grouped background colors, with variants for base and elevated UI schemes.
/// (base dark variant)  Hex color: FFFFFF
/// (base light variant)  Hex color: 232A31
/// (elevated dark variant)  Hex color: FFFFFF
/// (elevated light variant)  Hex color: 29313A
case primaryBackground
/// Secondary grouped background colors, with variants for base and elevated UI schemes.
/// (base dark variant)  Hex color: F7F7F7
/// (base light variant)  Hex color: 1C2228
/// (elevated dark variant)  Hex color: F7F7F7
/// (elevated light variant)  Hex color: 232A31
case secondaryBackground
/// Secondary grouped background colors, with variants for base and elevated UI schemes.
/// (base dark variant)  Hex color: FFFFFF
/// (base light variant)  Hex color: 29313A
/// (elevated dark variant)  Hex color: FFFFFF
/// (elevated light variant)  Hex color: 2F3943
case tertiaryBackground
// MARK: - Label Colors
/// Standard color for primary label.
/// (dark variant - normal)  Hex value: 32363A
/// (light variant - normal)  Hex value: FAFAFA
/// (dark variant - contrast)  Hex value: FAFAFA
/// (light variant - contrast)  Hex value: FAFAFAB8 (alpha: 72%)
case primaryLabel
/// Standard color for secondary label.
/// (dark variant - normal)  Hex value: 32363AD9 (alpha: 85%)
/// (light variant - normal)  Hex value: FAFAFAD9 (alpha: 85%)
/// (dark variant - contrast)  Hex value: FAFAFAD9 (alpha: 85%)
/// (light variant - contrast)  Hex value: FAFAFAD9 (alpha: 85%)
case secondaryLabel
/// Standard color for tertiary label.
/// (dark variant - normal)  Hex value: 32363AB8 (alpha: 72%)
/// (light variant - normal)  Hex value: FAFAFAB8 (alpha: 72%)
/// (dark variant - contrast)  Hex value: FAFAFAB8 (alpha: 72%)
/// (light variant - contrast)  Hex value: FAFAFAB8 (alpha: 72%)
case tertiaryLabel
/// Standard color for quarternary label.
/// (dark variant - normal)  Hex value: 32363A8C (alpha: 55%)
/// (light variant - normal)  Hex value: FAFAFA8C (alpha: 55%)
/// (dark variant - contrast)  Hex value: FAFAFA8C (alpha: 55%)
/// (light variant - contrast)  Hex value: FAFAFA8C (alpha: 55%)
case quarternaryLabel
// MARK: - Fill Colors
/// Standard color for primary fill.
/// (dark variant - normal)  Hex value: 89919A29 (alpha: 16%)
/// (light variant - normal)  Hex value: 8696A948 (alpha: 28%)
/// (dark variant - contrast)  Hex value: 8696A948 (alpha: 28%)
/// (light variant - contrast)  Hex value: 8696A948 (alpha: 28%)
case primaryFill
/// Standard color for secondary fill.
/// (dark variant - normal)  Hex value: 89919A1F (alpha: 12%)
/// (light variant - normal)  Hex value: 8696A933 (alpha: 20%)
/// (dark variant - contrast)  Hex value: 8696A933 (alpha: 20%)
/// (light variant - contrast)  Hex value: 8696A933 (alpha: 20%)
case secondaryFill
/// Standard color for tertiary fill.
/// (dark variant - normal)  Hex value: 89919A14 (alpha: 8%)
/// (light variant - normal)  Hex value: 89919A1F (alpha: 12%)
/// (dark variant - contrast)  Hex value: 89919A1F (alpha: 12%)
/// (light variant - contrast)  Hex value: 8696A91F (alpha: 12%)
case tertiaryFill
/// Standard color for quarternary fill.
/// (dark variant - normal)  Hex value: 89919A0A (alpha: 4%)
/// (light variant - normal)  Hex value: 89919A0A (alpha: 4%)
/// (dark variant - contrast)  Hex value: 89919A0A (alpha: 4%)
/// (light variant - contrast)  Hex value: 8696A90A (alpha: 4%)
case quarternaryFill
// MARK: - Specific UI Materials Colors
/// Standard background color for navigation bar or headers.
/// (dark variant)  Hex value: 354A5F
/// (light variant)  Hex value: 2C3D4F
case header
/// Blended color for navigation bar or headers.
/// (dark variant)  Hex value: FFFFFFCD (alpha: 80%)
/// (light variant)  Hex value: 29313ACD (alpha: 80%)
/// (elevated dark variant)  Hex color: FFFFFFA6 (alpha: 65%)
/// (elevated light variant)  Hex color: 232A31A6 (alpha: 65%)
case headerBlended
/// Transparent color for navigation bar or tap bar.
/// (dark variant)  Hex value: 23303EDA (alpha: 85%)
/// (light variant)  Hex value: 23303EDA (alpha: 85%)
case barTransparent
/// Color for contrast element.
/// (dark variant)  Hex value: 2C3D4F
/// (light variant)  Hex value: FAFAFA
case contrastElement
/// Standard background color for toolbar, tab bar or footers.
/// (dark variant)  Hex value: FAFAFAEB (alpha: 92%)
/// (light variant)  Hex value: 23303EEB (alpha: 92%)
case footer
/// Standard cell background color, with variants for light and dark color schemes.
/// (dark variant)  Hex color: FFFFFF00 (alpha: 0%)
/// (light variant)  Hex color: FFFFFF00 (alpha: 0%)
case cellBackground
/// Standard cell background color when being tapped, with variants for light and dark color schemes.
/// (dark variant)  Hex color: 89919A1C (alpha: 11%)
/// (light variant)  Hex color: 8696A91C (alpha: 11%)
case cellBackgroundTapState
/// Wraps `tintColorLight` and `tintColorDark`.
/// Use `Color.preferredColor(forStyle:background:)` to select appropriate variant.
/// (dark variant)  Hex color: 0A6ED1
/// (light variant)  Hex color: 91C8F6
case tintColor
/// Default light `tintColor`.
/// (dark variant)  Hex color: 91C8F6
/// (light variant)  Hex color: 91C8F6
case tintColorLight
/// Default dark `tintColor`.
/// (dark variant)  Hex color: 0A6ED1
/// (light variant)  Hex color: 0A6ED1
case tintColorDark
/// Wraps `tintColorTapStateLight` and `tintColorTapStateDark`.
/// Use `Color.preferredColor(forStyle:background:)` to select appropriate variant.
/// (dark variant)  Hex color: 0854A1
/// (light variant)  Hex color: 0A84FF66 (alpha: 40%)
case tintColorTapState
/// Tap state (`UIControlState.highlighted`) color for control with `tintColor` equal to `tintColorLight`. Should not be used as text color.
/// (dark variant)  Hex color: 74A5D5
/// (light variant)  Hex color: 0A84FF66 (alpha: 40%)
case tintColorTapStateLight
/// Tap state (`UIControlState.highlighted`) color for control with `tintColor` equal to `tintColorDark`. May be used as text color.
/// (dark variant)  Hex color: 0854A1
/// (light variant)  Hex color: 0A84FF66 (alpha: 40%)
case tintColorTapStateDark
/// Standard background color for `UINavigationBar`.
/// (dark variant)  Hex value: 354A5F
/// (light variant)  Hex value: 2C3D4F
@available(*, deprecated, renamed: "header")
public static let navigationBar = ColorStyle.header
/// Top gradient color, originating at SAP Fiori `UINavigationBar`.  Hex color: 445E75
@available(*, deprecated, renamed: "header")
public static let backgroundGradientTop = ColorStyle.header
/// Bottom gradient color, originating at SAP Fiori `UINavigationBar`.  Hex color: 3F566B
@available(*, deprecated, renamed: "header")
public static let backgroundGradientBottom = ColorStyle.header
/// Standard background color, with variants for light and dark color schemes.
/// (dark variant)  Hex value: F3F3F3
/// (light variant)  Hex value: 000000
@available(*, deprecated, renamed: "background2")
public static let backgroundBase = ColorStyle.background2
// MARK: - Chart Colors
/// Standard text color, with variants for light and dark color variants.
/// Use `UIColor.preferredFioriColor(forStyle: background:)` to select appropriate variant.
/// (dark variant)  Hex color: 5899DA
/// (light variant)  Hex color: 74B3F0
case chart1
///  Hex color: E8743B
case chart2
///  Hex color: 19A979
case chart3
///  Hex color: ED4A7B
case chart4
///  Hex color: 945ECF
case chart5
///  Hex color: 13A4B4
case chart6
///  Hex color: 525DF4
case chart7
///  Hex color: BF399E
case chart8
///  Hex color: 6C8893
case chart9
///  Hex color: EE6868
case chart10
///  Hex color: 2F6497
case chart11
/// Semantic stroke color for line when stock goes up.
/// (light variant)  Hex color: 19A979
case stockUpStroke
/// Semantic stroke color for line when stock goes down.
/// (light variant)  Hex color: AB2217
case stockDownStroke
// MARK: - Map Colors
///  Hex color: 2E4A62
case map1
///  Hex color: 56840E
case map2
///  Hex color: A63788
case map3
///  Hex color: 0079C6
case map4
///  Hex color: 6B4EA0
case map5
///  Hex color: A16B00
case map6
///  Hex color: 0B6295
case map7
///  Hex color: D0R774
case map8
///  Hex color: 1C857A
case map9
///  Hex color: C45300
case map10
///  Hex color: 1B6DD2
case esriEdit
// MARK: - Semantic Colors
/// Semantic color for "negative" (bad) value, with light and dark color variants.
/// (dark variant)  Hex color: BB0000
/// (light variant)  Hex color: FF453A
case negative
/// Semantic color for "positive" (good) value, with light and dark color variants.
/// (dark variant)  Hex color: 107E3E
/// (light variant)  Hex color: 32D74B
case positive
/// Semantic color for "critical" (risky) value, with light and dark color variants.
/// (dark variant)  Hex color: E9730C
/// (light variant)  Hex color: FF9F0A
case critical
/// Semantic color for "negative" (bad) label, with light and dark color variants.
/// (dark variant - normal)  Hex color: BB0000
/// (light variant - normal)  Hex color: FF8888
/// (dark variant - contrast)  Hex color: FF8888
/// (light variant - contrast)  Hex color: FF8888
case negativeLabel
/// Semantic color for "positive" (good) label, with light and dark color variants.
/// (dark variant - normal)  Hex color: 107E3E
/// (light variant - normal)  Hex color: ABE2AB
/// (dark variant - contrast)  Hex color: ABE2AB
/// (light variant - contrast)  Hex color: ABE2AB
case positiveLabel
/// Semantic color for "critical" (risky) label, with light and dark color variants.
/// (dark variant - normal)  Hex color: E9730C
/// (light variant - normal)  Hex color: FABD64
/// (dark variant - contrast)  Hex color: FABD64
/// (light variant - contrast)  Hex color: FABD64
case criticalLabel
/// Semantic color for "negative" (bad) background, with light and dark color variants.
/// (dark variant - normal)  Hex color: BB000014 (alpha: 8%)
/// (light variant - normal)  Hex color: FF888824 (alpha: 14%)
/// (dark variant - contrast)  Hex color: BB000024 (alpha: 14%)
/// (light variant - contrast)  Hex color: FF888824 (alpha: 14%)
case negativeBackground
/// Semantic color for "positive" (good) background, with light and dark color variants.
/// (dark variant - normal)  Hex color: 107E3E14 (alpha: 8%)
/// (light variant - normal)  Hex color: ABE2AB24 (alpha: 14%)
/// (dark variant - contrast)  Hex color: 107E3E24 (alpha: 14%)
/// (light variant - contrast)  Hex color: ABE2AB24 (alpha: 14%)
case positiveBackground
/// Semantic color for "critical" (risky) background, with light and dark color variants.
/// (dark variant - normal)  Hex color: E9730C14 (alpha: 8%)
/// (light variant - normal)  Hex color: FABD6424 (alpha: 14%)
/// (dark variant - contrast)  Hex color: E9730C24 (alpha: 14%)
/// (light variant - contrast)  Hex color: FABD6424 (alpha: 14%)
case criticalBackground
/// Semantic color for "information" (neutral) background, with light and dark color variants.
/// (dark variant - normal)  Hex color: 0A6ED114 (alpha: 8%)
/// (light variant - normal)  Hex color: 91C8F624 (alpha: 14%)
/// (dark variant - contrast)  Hex color: 0A6ED124 (alpha: 14%)
/// (light variant - contrast)  Hex color: 91C8F624 (alpha: 14%)
case informationBackground
// MARK: - Accent Colors
case accent1
case accent1b
case accent2
case accent2b
case accent3
case accent4
case accent5
case accent6
case accent6b
case accent7
case accent7b
case accent8
case accent9
case accent10
case accent10b
}
| 64.308057 | 145 | 0.630076 |
75c788c4f23aab2f25a8bfddf6ba84997780bb31
| 2,627 |
//
// SwiftSumTests.swift
// SwiftMultihash
//
// Created by Matteo Sartori on 31/05/15.
// Licensed under MIT See LICENCE for details
//
import Foundation
import XCTest
@testable
import SwiftMultihash
struct SumTestCase {
let code: Int
let length: Int
let input: String
let hex: String
}
let sumTestCases = [
SumTestCase(code: SHA1, length: -1, input: "foo", hex: "11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"),
SumTestCase(code: SHA1, length: 10, input: "foo", hex: "110a0beec7b5ea3f0fdbc95d"),
SumTestCase(code: SHA2_256, length: -1, input: "foo", hex: "12202c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"),
SumTestCase(code: SHA2_256, length: 16, input: "foo", hex: "12102c26b46b68ffc68ff99b453c1d304134"),
SumTestCase(code: SHA2_512, length: -1, input: "foo", hex: "1340f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7"),
SumTestCase(code: SHA2_512, length: 32, input: "foo", hex: "1320f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc663832")
]
class SwiftSumTests: XCTestCase {
func testSum() {
for tc in sumTestCases {
do {
let m1: Multihash = try fromHexString(tc.hex)
let m2: Multihash = try sum(Array(tc.input.utf8), tc.code, tc.length)
if m1 != m2 {
XCTFail("sum failed: \(m1.value) \(m2.value)")
}
let hexStr = m1.hexString()
if hexStr != tc.hex {
XCTFail("Hex strings not the same.")
}
let b58Str = b58String(m1)
do {
let m3 = try fromB58String(b58Str)
if m3 != m1 {
XCTFail("b58 failing bytes.")
} else if b58Str != b58String(m3) {
XCTFail("b58 failing string.")
}
} catch {
let error = error as! MultihashError
XCTFail("Failed to decode b58.\(error.description)")
continue
}
} catch {
let error = error as! MultihashError
XCTFail(error.description)
continue
}
}
}
func testSumPerformance() {
let tc = sumTestCases[0]
self.measure {
do {
try _ = sum(Array(tc.input.utf8), tc.code, tc.length)
} catch {}
}
}
}
| 34.116883 | 199 | 0.553102 |
d540e79c42ba6ec4f3f91df1137338fa0d9b9e1b
| 3,525 |
//
// Test.swift
// SDKNetwork
//
// Created by Felipe Andrade on 22/02/21.
//
import Foundation
public enum HTTPMethod: String {
case get = "GET"
case post = "POST"
}
public enum Timeout: TimeInterval {
case short = 15
case medium = 30
case long = 60
}
public enum RequestError: Error {
case network
case serverError(Error)
case parseError
case unknown
}
public protocol ServiceRequest {
var url: String { get }
var httpMethod: HTTPMethod { get }
var header: [String: String]? { get }
var data: DataTask.RequestContent { get }
}
open class Service<U: ServiceRequest> {
public var requester: Request = Requester()
var timeout = Timeout.medium
public init() {}
public func request<T: Decodable>(_ flow: U, model: T.Type,
completion: @escaping (Result<T, RequestError>, URLResponse?) -> Void) {
guard let service = setupEnvirnment(flow) else {
completion(.failure(.network), nil)
return
}
Log.isMock(requester)
requester.makeRequest(service) { (data, response, error) in
Log.request(data: data, response: response, error: error)
if let error = error {
completion(.failure(.serverError(error)), response)
} else if let model = self.decodeBody(data: data, model: model) {
completion(.success(model), response)
} else {
completion(.failure(.parseError), response)
}
}
}
public func request(_ flow: U, completion: @escaping (Result<Data?, RequestError>, URLResponse?) -> Void) {
guard let service = setupEnvirnment(flow) else {
completion(.failure(.network), nil)
return
}
Log.isMock(requester)
requester.makeRequest(service) { data, response, error in
Log.request(data: data, response: response, error: error)
if let error = error {
completion(.failure(.serverError(error)), response)
} else {
completion(.success(data), response)
}
}
}
func setupEnvirnment(_ flow: U) -> URLRequest? {
if let url = URL(string: flow.url) {
var service = URLRequest(url: url)
service.timeoutInterval = timeout.rawValue
service.httpMethod = flow.httpMethod.rawValue
service.allHTTPHeaderFields = flow.header
switch flow.data {
case .httpBody(let data):
service.httpBody = data
case .urlandbody(let url, let body):
service.url = URL(string: "\(service.url?.absoluteString ?? "")\(url)")
service.httpBody = body
case .urlEncoded(let url):
service.url = URL(string: "\(service.url?.absoluteString ?? "")\(url)")
default: break
}
return service
}
Log.defaultLogs(.requestFailed)
return nil
}
func decodeBody<T: Decodable>(data: Data?, model: T.Type) -> T? {
if let data = data {
do {
let model = try JSONDecoder().decode(T.self, from: data)
return model
} catch {
Log.defaultLogs(.parseError, error: error)
return nil
}
} else {
Log.defaultLogs(.dataIsNull)
return nil
}
}
}
| 30.652174 | 111 | 0.548936 |
2fec7693eb9dcb958d765012833457e3a5aa1520
| 670 |
//
// Utilities.swift
// Modularity1
//
// Created by Narasannagari Krishna Prakash on 13/09/20.
// Copyright © 2020 Narasannagari Krishna Prakash. All rights reserved.
//
import Foundation
struct Utilites {
static func dataToObject<T>(type: T.Type, from data: Data, completion:@escaping((T?, Error?) -> Void)) where T : Decodable {
do{
let dataModel = try JSONDecoder().decode(type, from: data)
completion(dataModel,nil)
}
catch DecodingError.dataCorrupted(let context){
completion(nil, context.underlyingError)
}
catch let err {
completion(nil, err)
}
}
}
| 24.814815 | 128 | 0.61791 |
62e32fb5a04f0d78a72d12f7c596fb8d5fd05de8
| 5,028 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
import SotoCore
// MARK: Waiters
extension MachineLearning {
/// Poll resource until it reaches a desired state
///
/// Parameters:
/// - input: Input for request
/// - maxWaitTime: Maximum amount of time to wait for waiter to be successful
/// - logger: Logger for logging output
/// - eventLoop: EventLoop to run waiter code on
public func waitUntilBatchPredictionAvailable(
_ input: DescribeBatchPredictionsInput,
maxWaitTime: TimeAmount? = nil,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> EventLoopFuture<Void> {
let waiter = AWSClient.Waiter(
acceptors: [
.init(state: .success, matcher: try! JMESAllPathMatcher("results[].status", expected: "COMPLETED")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("results[].status", expected: "FAILED")),
],
minDelayTime: .seconds(30),
command: describeBatchPredictions
)
return self.client.waitUntil(input, waiter: waiter, maxWaitTime: maxWaitTime, logger: logger, on: eventLoop)
}
/// Poll resource until it reaches a desired state
///
/// Parameters:
/// - input: Input for request
/// - maxWaitTime: Maximum amount of time to wait for waiter to be successful
/// - logger: Logger for logging output
/// - eventLoop: EventLoop to run waiter code on
public func waitUntilDataSourceAvailable(
_ input: DescribeDataSourcesInput,
maxWaitTime: TimeAmount? = nil,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> EventLoopFuture<Void> {
let waiter = AWSClient.Waiter(
acceptors: [
.init(state: .success, matcher: try! JMESAllPathMatcher("results[].status", expected: "COMPLETED")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("results[].status", expected: "FAILED")),
],
minDelayTime: .seconds(30),
command: describeDataSources
)
return self.client.waitUntil(input, waiter: waiter, maxWaitTime: maxWaitTime, logger: logger, on: eventLoop)
}
/// Poll resource until it reaches a desired state
///
/// Parameters:
/// - input: Input for request
/// - maxWaitTime: Maximum amount of time to wait for waiter to be successful
/// - logger: Logger for logging output
/// - eventLoop: EventLoop to run waiter code on
public func waitUntilEvaluationAvailable(
_ input: DescribeEvaluationsInput,
maxWaitTime: TimeAmount? = nil,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> EventLoopFuture<Void> {
let waiter = AWSClient.Waiter(
acceptors: [
.init(state: .success, matcher: try! JMESAllPathMatcher("results[].status", expected: "COMPLETED")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("results[].status", expected: "FAILED")),
],
minDelayTime: .seconds(30),
command: describeEvaluations
)
return self.client.waitUntil(input, waiter: waiter, maxWaitTime: maxWaitTime, logger: logger, on: eventLoop)
}
/// Poll resource until it reaches a desired state
///
/// Parameters:
/// - input: Input for request
/// - maxWaitTime: Maximum amount of time to wait for waiter to be successful
/// - logger: Logger for logging output
/// - eventLoop: EventLoop to run waiter code on
public func waitUntilMLModelAvailable(
_ input: DescribeMLModelsInput,
maxWaitTime: TimeAmount? = nil,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> EventLoopFuture<Void> {
let waiter = AWSClient.Waiter(
acceptors: [
.init(state: .success, matcher: try! JMESAllPathMatcher("results[].status", expected: "COMPLETED")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("results[].status", expected: "FAILED")),
],
minDelayTime: .seconds(30),
command: describeMLModels
)
return self.client.waitUntil(input, waiter: waiter, maxWaitTime: maxWaitTime, logger: logger, on: eventLoop)
}
}
| 41.9 | 117 | 0.615354 |
f5ffd8ebea9ea113bd083c385f78b611db30f34e
| 4,103 |
//
// StoryCell.swift
// InstagramStoriesClone
//
// Created by Jerome Isaacs on 8/5/18.
// Copyright © 2018 Jerome Isaacs. All rights reserved.
//
import UIKit
import IGListKit
protocol TappedPictureDelegate: class {
func didTapPicture(_ picture: UIImageView, cell: StoryCell)
}
class StoryCell: UICollectionViewCell {
public weak var tappedPictureDelegate: TappedPictureDelegate?
// Outer circle view for the purple Instagram border
private let containerView: UIView = {
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
return containerView
}()
private let profilePicImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.isUserInteractionEnabled = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
private let handleLabel: UILabel = {
let handle = UILabel()
handle.textAlignment = .center
handle.font = UIFont.systemFont(ofSize: 12, weight: .light)
handle.text = "Jeromeythehomie"
handle.translatesAutoresizingMaskIntoConstraints = false
return handle
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(containerView)
containerView.addSubview(profilePicImageView)
contentView.addSubview(handleLabel)
setupConstraints()
setupCircles()
profilePicImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedProfilePicture)))
}
@objc private func tappedProfilePicture() {
tappedPictureDelegate?.didTapPicture(profilePicImageView, cell: self)
}
private func setupCircles() {
let height = contentView.bounds.height.rounded(.down)
containerView.layer.borderColor = UIColor(red:0.76, green:0.16, blue:0.64, alpha:1.0).cgColor
containerView.layer.borderWidth = 2
containerView.layer.cornerRadius = (height - 15)/2
profilePicImageView.layer.cornerRadius = (height - 25)/2
}
private func setupConstraints() {
let height = contentView.bounds.height.rounded(.down)
containerView.heightAnchor.constraint(equalToConstant: height - 15).isActive = true
containerView.widthAnchor.constraint(equalToConstant: height - 15).isActive = true
profilePicImageView.heightAnchor.constraint(equalToConstant: height - 25).isActive = true
profilePicImageView.widthAnchor.constraint(equalToConstant: height - 25).isActive = true
profilePicImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
profilePicImageView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
handleLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
handleLabel.topAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 2).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: ListBindable
/*
If it's our story, set the container view border to a clear color and remove our handle since it's redundant.
*/
extension StoryCell: ListBindable {
func bindViewModel(_ viewModel: Any) {
guard let story = viewModel as? Story else { return }
containerView.layer.borderColor = story.isRead ? UIColor.lightGray.cgColor: UIColor(red:0.76, green:0.16, blue:0.64, alpha:1.0).cgColor
if story.user.handle == "jeromeythehomie" {
handleLabel.text = "Your Story"
containerView.layer.borderColor = UIColor.clear.cgColor
}
else {
handleLabel.text = story.user.handle
}
let urlString: String = story.user.profilePic.lastPathComponent
profilePicImageView.image = UIImage(named: urlString, in: Bundle.main, compatibleWith: nil)
}
}
| 39.451923 | 143 | 0.700951 |
e48fd9e345b8739bb39fd3713a207493f6165d73
| 1,399 |
import Foundation
extension Service {
open class OccupancySensor: Service {
// Required Characteristics
public let occupancyDetected: GenericCharacteristic<Enums.OccupancyDetected>
// Optional Characteristics
public let name: GenericCharacteristic<String>?
public let statusActive: GenericCharacteristic<Bool>?
public let statusFault: GenericCharacteristic<UInt8>?
public let statusLowBattery: GenericCharacteristic<Enums.StatusLowBattery>?
public let statusTampered: GenericCharacteristic<UInt8>?
public init(characteristics: [AnyCharacteristic] = []) {
var unwrapped = characteristics.map { $0.wrapped }
occupancyDetected = getOrCreateAppend(
type: .occupancyDetected,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.occupancyDetected() })
name = get(type: .name, characteristics: unwrapped)
statusActive = get(type: .statusActive, characteristics: unwrapped)
statusFault = get(type: .statusFault, characteristics: unwrapped)
statusLowBattery = get(type: .statusLowBattery, characteristics: unwrapped)
statusTampered = get(type: .statusTampered, characteristics: unwrapped)
super.init(type: .occupancySensor, characteristics: unwrapped)
}
}
}
| 46.633333 | 87 | 0.683345 |
26502579e41eea23285e30b9dfd0643c5f998932
| 895 |
//
// Chaining.swift
// ExampleChaining
//
// Created by iDeveloper on 7/18/19.
// Copyright © 2019 iDeveloper. All rights reserved.
//
import Foundation
public typealias ChainOperationCompletion<T> = (T) -> Void
public typealias ChainOperation<T, U> = (T, @escaping ChainOperationCompletion<U>) -> Void
public enum ChainOperationResult<T> {
case success(T)
case failure(Error)
}
infix operator ==>: AdditionPrecedence
func ==> <T, U, V>(f: @escaping ChainOperation<T, ChainOperationResult<U>>,
g: @escaping ChainOperation<U, ChainOperationResult<V>>)
-> ChainOperation<T, ChainOperationResult<V>> {
return { input, combineCompletion in
f(input) { (u: ChainOperationResult<U>) in
switch u {
case .success(let unwrappedU): g(unwrappedU, combineCompletion)
case .failure(let error): combineCompletion(.failure(error))
}
}
}
}
| 27.121212 | 90 | 0.686034 |
182d686a99a7aac414dfd06e74ac9b0709e85971
| 1,446 |
//
// DateExtension.swift
// r2-shared-swift
//
// Created by Alexandre Camilleri on 3/22/17.
//
// Copyright 2018 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
public extension Date {
/// Computed property turning an ISO8601 Date to a String?.
var iso8601: String {
return Formatter.iso8601.string(from: self)
}
}
public extension Formatter {
/// Format from the ISO8601 format to a Date format.
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
}
public extension String {
/// Date string (ISO8601) to Date object.
var dateFromISO8601: Date? {
// Removing .SSSS precision if found.
var string = self
let regexp = "[.][0-9]+"
if let range = string.range(of: regexp, options: .regularExpression) {
string.replaceSubrange(range, with: "")
}
return Formatter.iso8601.date(from: string) // 2012-01-20T12:47:00.SSSZ -> "Mar 22, 2017, 10:22 AM"
}
}
| 30.125 | 110 | 0.656985 |
20882c8de6d9e16259da25a6b468af99a4fc328d
| 5,956 |
//
// PVGameLibraryViewController+CollectionView.swift
// Provenance
//
// Created by Joseph Mattiello on 5/26/18.
// Copyright © 2018 Provenance. All rights reserved.
//
import Foundation
import PVLibrary
import PVSupport
import RxCocoa
import RxSwift
// tvOS
let tvOSCellUnit: CGFloat = 224.0 // org 256.0 = 6, base subtract 32 for 1 more column. 224= 7, 192 = 8
// MARK: - UICollectionViewDelegateFlowLayout
extension PVGameLibraryViewController: UICollectionViewDelegateFlowLayout {
var minimumInteritemSpacing: CGFloat {
#if os(tvOS)
return 24.0
#else
return 10.0
#endif
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
#if os(tvOS)
return tvos_collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)
#else
return ios_collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)
#endif
}
#if os(iOS)
private func ios_collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var height: CGFloat = PVSettingsModel.shared.showGameTitles ? 144 : 100
let viewWidth = transitioningToSize?.width ?? collectionView.bounds.size.width
let itemsPerRow: CGFloat = viewWidth > 800 ? 6 : 3
var width: CGFloat = (viewWidth / itemsPerRow) - (minimumInteritemSpacing * itemsPerRow * 0.67)
let item: Section.Item = try! collectionView.rx.model(at: indexPath)
switch item {
case .game:
width *= collectionViewZoom
height *= collectionViewZoom
case .saves, .favorites, .recents:
// TODO: Multirow?
let numberOfRows = 1
width = viewWidth
height = (height + PageIndicatorHeight + 24) * CGFloat(numberOfRows)
}
return .init(width: width, height: height)
}
#endif
#if os(tvOS)
private func tvos_collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let item: Section.Item = try! collectionView.rx.model(at: indexPath)
let viewWidth = transitioningToSize?.width ?? collectionView.bounds.size.width
switch item {
case .game(let game):
let boxartSize = CGSize(width: tvOSCellUnit, height: tvOSCellUnit / game.boxartAspectRatio.rawValue)
return PVGameLibraryCollectionViewCell.cellSize(forImageSize: boxartSize)
case .saves:
// TODO: Multirow?
let numberOfRows: CGFloat = 1.0
let width = viewWidth //- collectionView.contentInset.left - collectionView.contentInset.right / 4
let height = tvOSCellUnit * numberOfRows + PageIndicatorHeight
return PVSaveStateCollectionViewCell.cellSize(forImageSize: CGSize(width: width, height: height))
case .favorites, .recents:
let numberOfRows: CGFloat = 1.0
let width = viewWidth //- collectionView.contentInset.left - collectionView.contentInset.right / 5
let height: CGFloat = tvOSCellUnit * numberOfRows + PageIndicatorHeight
return PVSaveStateCollectionViewCell.cellSize(forImageSize: CGSize(width: width, height: height))
}
}
#endif
#if os(tvOS)
func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
let item: Section.Item? = firstModel(in: collectionView, at: section)
switch item {
case .none:
return .zero
case .game:
return 40
case .saves, .favorites, .recents:
return 0
}
}
#endif
func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
let item: Section.Item? = firstModel(in: collectionView, at: section)
switch item {
case .none:
return .zero
case .some(.game):
return minimumInteritemSpacing
case .saves, .favorites, .recents:
return 0
}
}
func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
#if os(tvOS)
let item: Section.Item? = firstModel(in: collectionView, at: section)
switch item {
case .none:
return .zero
case .some(.game):
return .init(top: 20, left: 20, bottom: 25, right: 20)
case .saves:
return .init(top: -20, left: 0, bottom: 45, right: 0)
case .favorites:
return .init(top: 0, left: 20, bottom: 20, right: 20)
case .recents:
return .init(top: 0, left: 20, bottom: 20, right: 20)
}
#else
let item: Section.Item? = firstModel(in: collectionView, at: section)
switch item {
case .none:
return .zero
case .some(.game):
return .init(top: section == 0 ? 5 : 15, left: 10, bottom: 5, right: 10)
case .saves, .favorites, .recents:
return .zero
}
#endif
}
private func firstModel(in collectionView: UICollectionView, at section: Int) -> Section.Item? {
guard collectionView.numberOfItems(inSection: section) > 0 else { return nil }
return try? collectionView.rx.model(at: IndexPath(item: 0, section: section))
}
}
| 41.943662 | 160 | 0.61904 |
230c2a7d5dd44ae0dbd2decb14bf4d1bee90ef5d
| 1,860 |
//
// ViewController.swift
// ytk-swift
//
// Created by 王树军(金融壹账通客户端研发团队) on 2018/11/15.
// Copyright © 2018 王树军(金融壹账通客户端研发团队). All rights reserved.
//
import UIKit
class ViewController: UIViewController {
lazy var actionBtn: UIButton = {
let btn = UIButton.init(type: .roundedRect)
btn.frame = CGRect(x: 0, y: 0, width: 150, height: 60)
btn.center = view.center
btn.backgroundColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
btn.setTitleColor(.white, for: .normal)
btn.setTitle("Send Request", for: .normal)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.addSubview(actionBtn)
actionBtn.addTarget(self, action: #selector(loadData), for: .touchUpInside)
}
//network demo
@objc func loadData() {
view.makeToastActivity(.center)
DispatchQueue.main.asyncAfter(deadline: .now()+2, execute:
{
// let request: GetRequest = GetRequest()
// request.loadCacheWithSuccess(success: { (request) in
// print("\(request.responseString)")
// self.view.hideToastActivity()
// })
let request: GetRequest = GetRequest()
request.startWithCompletionBlockWithSuccess(success: { (request) in
print("\(request.responseString)")
self.view.hideToastActivity()
}) { (request) in
self.view.hideToastActivity()
self.view.makeToast("网络异常或返回数据异常")
}
})
}
}
| 31.525424 | 113 | 0.57043 |
3342f19ac3f757833d72be3a39a6ebf205b09c51
| 1,602 |
extension Bundle {
func decode<T: Decodable>(_ type: T.Type, from file: String, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = dateDecodingStrategy
decoder.keyDecodingStrategy = keyDecodingStrategy
do {
return try decoder.decode(T.self, from: data)
} catch DecodingError.keyNotFound(let key, let context) {
fatalError("Failed to decode \(file) from bundle due to missing key '\(key.stringValue)' not found – \(context.debugDescription)")
} catch DecodingError.typeMismatch(_, let context) {
fatalError("Failed to decode \(file) from bundle due to type mismatch – \(context.debugDescription)")
} catch DecodingError.valueNotFound(let type, let context) {
fatalError("Failed to decode \(file) from bundle due to missing \(type) value – \(context.debugDescription)")
} catch DecodingError.dataCorrupted(_) {
fatalError("Failed to decode \(file) from bundle because it appears to be invalid JSON")
} catch {
fatalError("Failed to decode \(file) from bundle: \(error.localizedDescription)")
}
}
}
| 53.4 | 217 | 0.661673 |
5d2e9b6afb38c5cf611c6569550eb13e976f080a
| 6,809 |
//===--- Builtins.swift - Tests for our Builtin wrappers ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: rm -rf %t && mkdir -p %t
// note: building with -Onone to test debug-mode-only safety checks
// RUN: %target-build-swift %s -parse-stdlib -Xfrontend -disable-access-control -Onone -o %t/Builtins
// RUN: %target-run %t/Builtins
// REQUIRES: executable_test
import Swift
import SwiftShims
import StdlibUnittest
#if _runtime(_ObjC)
import Foundation
#endif
var tests = TestSuite("Builtins")
class X {}
tests.test("_isUnique/NativeObject") {
var a: Builtin.NativeObject = Builtin.castToNativeObject(X())
expectNotEqual(false, _isUnique_native(&a))
var b = a
expectFalse(_isUnique_native(&a))
expectFalse(_isUnique_native(&b))
}
tests.test("_isUniquelyReferenced/OptionalNativeObject") {
var a: Builtin.NativeObject? = Builtin.castToNativeObject(X())
StdlibUnittest.expectTrue(_getBool(Builtin.isUnique(&a)))
var b = a
expectFalse(_getBool(Builtin.isUnique(&a)))
expectFalse(_getBool(Builtin.isUnique(&b)))
var x: Builtin.NativeObject? = nil
expectFalse(_getBool(Builtin.isUnique(&x)))
}
#if _runtime(_ObjC)
class XObjC : NSObject {}
tests.test("_isUnique_native/SpareBitTrap")
.skip(.custom(
{ !_isStdlibInternalChecksEnabled() },
reason: "sanity checks are disabled in this build of stdlib"))
.code {
// Fake an ObjC pointer.
var b = _makeObjCBridgeObject(X())
expectCrashLater()
_ = _isUnique_native(&b)
}
tests.test("_isUniqueOrPinned_native/SpareBitTrap")
.skip(.custom(
{ !_isStdlibInternalChecksEnabled() },
reason: "sanity checks are disabled in this build of stdlib"))
.code {
// Fake an ObjC pointer.
var b = _makeObjCBridgeObject(X())
expectCrashLater()
_ = _isUniqueOrPinned_native(&b)
}
tests.test("_isUnique_native/NonNativeTrap")
.skip(.custom(
{ !_isStdlibInternalChecksEnabled() },
reason: "sanity checks are disabled in this build of stdlib"))
.code {
var x = XObjC()
expectCrashLater()
_ = _isUnique_native(&x)
}
tests.test("_isUniqueOrPinned_native/NonNativeTrap")
.skip(.custom(
{ !_isStdlibInternalChecksEnabled() },
reason: "sanity checks are disabled in this build of stdlib"))
.code {
var x = XObjC()
expectCrashLater()
_ = _isUniqueOrPinned_native(&x)
}
#endif // _ObjC
var x = 27
@inline(never)
func genint() -> Int {
return x
}
tests.test("_assumeNonNegative") {
let r = _assumeNonNegative(genint())
expectEqual(r, 27)
}
var NoisyLifeCount = 0
var NoisyDeathCount = 0
protocol P {}
class Noisy : P {
init() { NoisyLifeCount += 1 }
deinit { NoisyDeathCount += 1}
}
struct Large : P {
var a, b, c, d: Noisy
init() {
self.a = Noisy()
self.b = Noisy()
self.c = Noisy()
self.d = Noisy()
}
}
struct ContainsP { var p: P }
func exerciseArrayValueWitnesses<T>(_ value: T) {
let buf = UnsafeMutablePointer<T>.allocate(capacity: 5)
(buf + 0).initialize(to: value)
(buf + 1).initialize(to: value)
Builtin.copyArray(T.self, (buf + 2)._rawValue, buf._rawValue, 2._builtinWordValue)
Builtin.takeArrayBackToFront(T.self, (buf + 1)._rawValue, buf._rawValue, 4._builtinWordValue)
Builtin.takeArrayFrontToBack(T.self, buf._rawValue, (buf + 1)._rawValue, 4._builtinWordValue)
Builtin.destroyArray(T.self, buf._rawValue, 4._builtinWordValue)
buf.deallocate(capacity: 5)
}
tests.test("array value witnesses") {
NoisyLifeCount = 0
NoisyDeathCount = 0
do {
exerciseArrayValueWitnesses(44)
exerciseArrayValueWitnesses(Noisy())
exerciseArrayValueWitnesses(Noisy() as P)
exerciseArrayValueWitnesses(Large())
exerciseArrayValueWitnesses(Large() as P)
exerciseArrayValueWitnesses(ContainsP(p: Noisy()))
exerciseArrayValueWitnesses(ContainsP(p: Large()))
}
expectEqual(NoisyLifeCount, NoisyDeathCount)
}
protocol Classy : class {}
class A : Classy {}
class B : A {}
class C : B {}
tests.test("_getSuperclass") {
expectEmpty(_getSuperclass(A.self))
expectEmpty(_getSuperclass(Classy.self))
expectNotEmpty(_getSuperclass(B.self))
expectNotEmpty(_getSuperclass(C.self))
expectTrue(_getSuperclass(B.self)! == A.self)
expectTrue(_getSuperclass(C.self)! == B.self)
}
tests.test("type comparison") {
class B {}
class D : B {}
let t1 = B.self
let t1o = Optional(t1)
let t2 = D.self
let t2o = Optional(t2)
expectTrue(t1 == t1)
expectFalse(t1 != t1)
expectTrue(t2 == t2)
expectFalse(t2 != t2)
expectFalse(t1 == t2)
expectFalse(t2 == t1)
expectTrue(t1 != t2)
expectTrue(t2 != t1)
expectTrue(t1 == t1o)
expectFalse(t1 != t1o)
expectTrue(t2 == t2o)
expectFalse(t2 != t2o)
expectFalse(t1 == t2o)
expectFalse(t2 == t1o)
expectTrue(t1 != t2o)
expectTrue(t2 != t1o)
expectTrue(t1o == t1)
expectFalse(t1o != t1)
expectTrue(t2o == t2)
expectFalse(t2o != t2)
expectFalse(t1o == t2)
expectFalse(t2o == t1)
expectTrue(t1o != t2)
expectTrue(t2o != t1)
expectTrue(t1o == t1o)
expectFalse(t1o != t1o)
expectTrue(t2o == t2o)
expectFalse(t2o != t2o)
expectFalse(t1o == t2o)
expectFalse(t2o == t1o)
expectTrue(t1o != t2o)
expectTrue(t2o != t1o)
let nil1 : B.Type? = nil
let nil2 : D.Type? = nil
expectTrue(nil1 == nil2)
expectTrue(nil1 == nil1)
expectTrue(nil1 == nil)
expectTrue(nil == nil1)
expectTrue(nil2 == nil)
expectTrue(nil == nil2)
expectFalse(t1 == nil1)
expectFalse(nil1 == t1)
expectFalse(t2 == nil1)
expectFalse(nil1 == t2)
expectFalse(t1 == nil2)
expectFalse(nil2 == t1)
expectFalse(t2 == nil2)
expectFalse(nil2 == t2)
expectFalse(t1o == nil)
expectFalse(nil == t1o)
expectFalse(t2o == nil)
expectFalse(nil == t2o)
expectFalse(t1o == nil1)
expectFalse(nil1 == t1o)
expectFalse(t2o == nil1)
expectFalse(nil1 == t2o)
expectFalse(t1o == nil2)
expectFalse(nil2 == t1o)
expectFalse(t2o == nil2)
expectFalse(nil2 == t2o)
}
tests.test("_isPOD") {
expectTrue(_isPOD(Int.self))
expectFalse(_isPOD(X.self))
expectFalse(_isPOD(P.self))
}
tests.test("_isOptional") {
expectTrue(_isOptional(Optional<Int>.self))
expectTrue(_isOptional(Optional<X>.self))
expectTrue(_isOptional(Optional<P>.self))
expectTrue(_isOptional(ImplicitlyUnwrappedOptional<P>.self))
expectFalse(_isOptional(Int.self))
expectFalse(_isOptional(X.self))
expectFalse(_isOptional(P.self))
}
runAllTests()
| 24.14539 | 101 | 0.680864 |
22a9d1cd94bcf10ec0a829576dc5689f66f9332f
| 2,138 |
//
// PopGesture.swift
// Pods-PopGesture_Example
//
// Created by linhey on 2018/1/17.
//
import UIKit
typealias PopGes_Closure = ((_ vc: UIViewController,_ animated: Bool) -> ())
struct RunTime {
/// 交换方法
///
/// - Parameters:
/// - selector: 被交换的方法
/// - replace: 用于交换的方法
/// - classType: 所属类型
static func exchangeMethod(selector: Selector,
replace: Selector,
class classType: AnyClass) {
let select1 = selector
let select2 = replace
let select1Method = class_getInstanceMethod(classType, select1)
let select2Method = class_getInstanceMethod(classType, select2)
let didAddMethod = class_addMethod(classType,
select1,
method_getImplementation(select2Method!),
method_getTypeEncoding(select2Method!))
if didAddMethod {
class_replaceMethod(classType,
select2,
method_getImplementation(select1Method!),
method_getTypeEncoding(select1Method!))
}else {
method_exchangeImplementations(select1Method!, select2Method!)
}
}
}
public class PopGesture {
static var once = false
public class func begin() {
if once { return }
once = true
RunTime.exchangeMethod(selector: #selector(UIViewController.viewWillAppear(_:)),
replace: #selector(UIViewController.popGes_viewWillAppear(_:)),
class: UIViewController.self)
RunTime.exchangeMethod(selector: #selector(UIViewController.viewWillDisappear(_:)),
replace: #selector(UIViewController.popGes_viewWillDisappear(_:)),
class: UIViewController.self)
RunTime.exchangeMethod(selector: #selector(UINavigationController.pushViewController(_:animated:)),
replace: #selector(UINavigationController.popGes_pushViewController(_:animated:)),
class: UINavigationController.self)
}
}
| 33.936508 | 109 | 0.599158 |
39ec853e3e8cec3be96d046cf2782b2f26c5894e
| 561 |
//
// CNMapPinModel.swift
// CNMap
//
// Created by Igor Smirnov on 08/10/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import Foundation
import CoreLocation
open class CNMapPinModel {
open var coordinate: CLLocationCoordinate2D!
open var count: Int = 1
public init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
}
public convenience init(coordinate: CLLocationCoordinate2D, count: Int) {
self.init(coordinate: coordinate)
self.count = count
}
}
| 20.777778 | 77 | 0.672014 |
0a14967a87909577721be052f933dddd1f35bee2
| 3,215 |
//
// RecipeTableViewCell.swift
// UponShef
//
// Created by cgtn on 2018/7/27.
// Copyright © 2018年 houcong. All rights reserved.
//
import UIKit
import SnapKit
import Then
import Kingfisher
class RecipeTableViewCell: UITableViewCell {
var isForceTouchRegistered = false
fileprivate let recipeImgView = UIImageView()
fileprivate let recipeName = UILabel().then { (nameL) in
nameL.font = UIFont.boldSystemFont(ofSize: 15.0)
}
fileprivate let recipeBrowse = UILabel().then { (browseL) in
browseL.font = UIFont.systemFont(ofSize: 15.0)
}
fileprivate let recipeCollection = UILabel().then { (collectionL) in
collectionL.font = UIFont.systemFont(ofSize: 15.0)
}
fileprivate let recipeVideo = UIImageView().then { (imgV) in
imgV.image = UIImage(named: "play_btn")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setup() {
contentView.addSubview(recipeImgView)
contentView.addSubview(recipeName)
contentView.addSubview(recipeBrowse)
contentView.addSubview(recipeCollection)
recipeImgView.addSubview(recipeVideo)
recipeImgView.snp.makeConstraints { (make) in
make.left.equalTo(contentView.snp.left).offset(10)
make.top.equalTo(contentView.snp.top).offset(10)
make.bottom.equalTo(contentView.snp.bottom).offset(-10)
make.width.equalTo(160.0)
}
recipeVideo.snp.makeConstraints { (make) in
make.centerX.equalTo(recipeImgView.snp.centerX)
make.centerY.equalTo(recipeImgView.snp.centerY)
make.width.height.equalTo(40)
}
recipeName.snp.makeConstraints { (make) in
make.left.equalTo(recipeImgView.snp.right).offset(10)
make.top.equalTo(recipeImgView.snp.top)
make.height.equalTo(35)
make.right.equalTo(contentView.snp.right).offset(-10)
}
recipeBrowse.snp.makeConstraints { (make) in
make.left.equalTo(recipeName.snp.left)
make.bottom.equalTo(recipeImgView.snp.bottom)
make.height.equalTo(30)
}
recipeCollection.snp.makeConstraints { (make) in
make.bottom.equalTo(recipeBrowse.snp.bottom)
make.height.equalTo(recipeBrowse.snp.height)
make.right.equalTo(contentView.snp.right).offset(-10)
make.left.equalTo(recipeBrowse.snp.right).offset(-10)
}
}
func configureCell(content: RecipeOutlineModel) {
recipeImgView.kf.setImage(with: URL(string: content.recipe_imgsrc), placeholder: UIImage(named: "placeholder"))
recipeBrowse.text = Tools.toFormat(item: content.recipe_browse) + "浏览"
recipeCollection.text = Tools.toFormat(item: content.recipe_collection) + "收藏"
recipeName.text = content.recipe_name
recipeVideo.isHidden = !content.recipe_isvideo
}
}
| 36.534091 | 119 | 0.652877 |
8f06db6f557e14a5710d625df1d38d713ac17f05
| 958 |
//
// 🦠 Corona-Warn-App
//
import Foundation
class HealthCertificateQRCodeParser: QRCodeParsable {
// MARK: - Init
init(
healthCertificateService: HealthCertificateService,
markAsNew: Bool
) {
self.healthCertificateService = healthCertificateService
self.markAsNew = markAsNew
}
// MARK: - Protocol QRCodeParsable
func parse(
qrCode: String,
completion: @escaping (Result<QRCodeResult, QRCodeParserError>) -> Void
) {
let result = healthCertificateService.registerHealthCertificate(base45: qrCode, markAsNew: markAsNew)
switch result {
case let .success(certificateResult):
completion(.success(.certificate(certificateResult)))
case .failure(let registrationError):
// wrap RegistrationError into an QRScannerError.other error
completion(.failure(.certificateQrError(registrationError)))
}
}
// MARK: - Private
private let healthCertificateService: HealthCertificateService
private let markAsNew: Bool
}
| 23.365854 | 103 | 0.762004 |
9c05de206dda9faf15f3b02f9b2887877cf4bac1
| 2,459 |
import Foundation
// type infer helper
fileprivate func substrUSS(_ us: String.UnicodeScalarView, _ l: String.Index, _ r: String.Index) -> String {
let range: Range<String.Index> = l..<r
let susv: Substring.UnicodeScalarView = us[range]
return String(susv)
}
extension String {
public func splitLines() -> [String] {
var result: [String] = []
let view: String.UnicodeScalarView = self.unicodeScalars
var pos: String.Index = startIndex
var lineStart: String.Index = pos
while true {
if pos == endIndex {
if lineStart != pos {
result.append(substrUSS(view, lineStart, pos))
lineStart = pos
}
break
}
let c0: Unicode.Scalar = view[pos]
if c0 == .cr {
pos = view.index(after: pos)
if pos == endIndex {
result.append(substrUSS(view, lineStart, pos))
lineStart = pos
break
}
let c1: Unicode.Scalar = view[pos]
if c1 == .lf {
pos = view.index(after: pos)
result.append(substrUSS(view, lineStart, pos))
lineStart = pos
} else {
result.append(substrUSS(view, lineStart, pos))
lineStart = pos
}
} else if c0 == .lf {
pos = view.index(after: pos)
result.append(substrUSS(view, lineStart, pos))
lineStart = pos
} else {
pos = view.index(after: pos)
}
}
return result
}
public var lastNewLineIndex: String.Index {
let view = self.unicodeScalars
var index = endIndex
while true {
if index == startIndex {
break
}
let leftIndex = view.index(before: index)
let c0 = view[leftIndex]
if c0 == .lf || c0 == .cr {
index = leftIndex
} else {
break
}
}
return index
}
internal mutating func appendIfPresent(_ str: String?) {
guard let str = str else {
return
}
self.append(str)
}
}
| 29.27381 | 108 | 0.452216 |
0ed3bc5ca9b00cb92aa4a93e5f0b84bf09156228
| 1,761 |
/**
* https://leetcode.com/problems/single-number/
*
*
*/
class Solution {
/// - Complexity:
/// - Time: O(n), where n is the number of elements in the array
/// - Space: O(1).
func singleNumber(_ nums: [Int]) -> Int {
var sum = 0
for n in nums {
sum ^= n
}
return sum
}
}
class Solution {
func singleNumber(_ nums: [Int]) -> Int {
return self.singleNumber(nums, with: 2)
}
fileprivate func singleNumber(_ nums: [Int], with repeatNumber: Int) -> Int {
var ret = 0
for bit in 0 ..< 64 {
var count = 0
for n in nums {
if ((n >> bit) & 1) == 1 { count += 1 }
}
count %= repeatNumber
ret |= (count << bit)
}
return ret
}
}
class Solution {
/// Go through every element in the array.
/// When first met a number, insert it to the Set,
/// Otherwise, it's not the first time, just remove it from Set.
/// Return the only one left in the Set.
///
/// - Complexity: O(n), where n is the number of elements in the array.
///
func singleNumber(_ nums: [Int]) -> Int {
var num: Set<Int> = []
for n in nums {
if num.contains(n) {
num.remove(n)
} else {
num.insert(n)
}
}
return Array(num).first!
}
}
/**
* https://leetcode.com/problems/single-number/
*
*
*/
// Date: Sun May 3 09:39:26 PDT 2020
class Solution {
func singleNumber(_ nums: [Int]) -> Int {
return nums.reduce(0) { $0 ^ $1 }
}
}
class Solution {
func singleNumber(_ nums: [Int]) -> Int {
return nums.reduce(0, ^)
}
}
| 23.171053 | 81 | 0.491766 |
1401e94d5b8aa840a6f798c5aa3db1333cd151c3
| 1,958 |
//
// CanteenTests.swift
// OpenMensaKit
//
// Created by Kilian Koeltzsch on 10.07.17.
// Copyright © 2017 OpenMensaKit. All rights reserved.
//
import Foundation
import XCTest
import struct CoreLocation.CLLocationCoordinate2D
import OpenMensaKit
class CanteenTests: XCTestCase {
func testGetSingleCanteen() {
let e = expectation(description: "Get a result for a single canteen")
let alteMensa = 79
Canteen.get(withID: alteMensa) { result in
switch result {
case .failure(let error):
XCTFail("Failed with error: \(error)")
case .success(_):
e.fulfill()
}
}
waitForExpectations(timeout: 5)
}
func testGetMultipleCanteens() {
let e = expectation(description: "Get a result for multiple canteens")
let dresden = [78,79,80,81,82,83,84,85,86,87,88,89,90,91,92]
Canteen.get(withIDs: dresden) { result in
switch result {
case .failure(let error):
XCTFail("Failed with error: \(error)")
case .success(_):
e.fulfill()
}
}
waitForExpectations(timeout: 5)
}
func testFindNear() {
let e = expectation(description: "Get a result for finding canteens near a coordinate")
let nuernbergerPlatz = CLLocationCoordinate2D(latitude: 51.0344374, longitude: 13.7279451)
Canteen.find(near: nuernbergerPlatz, distance: 0.5) { result in
switch result {
case .failure(let error):
XCTFail("Failed with error: \(error)")
case .success(_):
e.fulfill()
}
}
waitForExpectations(timeout: 5)
}
static var allTests = [
("testGetSingleCanteen", testGetSingleCanteen),
("testGetMultipleCanteens", testGetMultipleCanteens),
("testFindNear", testFindNear)
]
}
| 28.376812 | 98 | 0.588355 |
03626888763a26680419dd04757f5299f54bb349
| 2,552 |
import XCTest
import Tagged
enum Tag {}
struct Unit: Error {}
final class TaggedTests: XCTestCase {
func testCustomStringConvertible() {
XCTAssertEqual("1", Tagged<Tag, Int>(rawValue: 1).description)
}
func testComparable() {
XCTAssertTrue(Tagged<Tag, Int>(rawValue: 1) < Tagged<Tag, Int>(rawValue: 2))
}
func testDecodable() {
XCTAssertEqual(
[Tagged<Tag, Int>(rawValue: 1)],
try JSONDecoder().decode([Tagged<Tag, Int>].self, from: Data("[1]".utf8))
)
}
func testEncodable() {
XCTAssertEqual(
Data("[1]".utf8),
try JSONEncoder().encode([Tagged<Tag, Int>(rawValue: 1)])
)
}
func testEquatable() {
XCTAssertEqual(Tagged<Tag, Int>(rawValue: 1), Tagged<Tag, Int>(rawValue: 1))
}
func testError() {
XCTAssertThrowsError(try { throw Tagged<Tag, Unit>(rawValue: Unit()) }())
}
func testExpressibleByBooleanLiteral() {
XCTAssertEqual(true, Tagged<Tag, Bool>(rawValue: true))
}
func testExpressibleByFloatLiteral() {
XCTAssertEqual(1.0, Tagged<Tag, Double>(rawValue: 1.0))
}
func testExpressibleByIntegerLiteral() {
XCTAssertEqual(1, Tagged<Tag, Int>(rawValue: 1))
}
func testExpressibleByStringLiteral() {
XCTAssertEqual("Hello!", Tagged<Tag, String>(rawValue: "Hello!"))
}
func testLosslessStringConvertible() {
XCTAssertEqual(Tagged<Tag, Bool>(rawValue: true), Tagged<Tag, Bool>("true"))
}
func testNumeric() {
XCTAssertEqual(
Tagged<Tag, Int>(rawValue: 2),
Tagged<Tag, Int>(rawValue: 1) + Tagged<Tag, Int>(rawValue: 1)
)
}
func testHashable() {
XCTAssertEqual(Tagged<Tag, Int>(rawValue: 1).hashValue, Tagged<Tag, Int>(rawValue: 1).hashValue)
}
func testSignedNumeric() {
XCTAssertEqual(Tagged<Tag, Int>(rawValue: -1), -Tagged<Tag, Int>(rawValue: 1))
}
func testMap() {
let x: Tagged<Tag, Int> = 1
XCTAssertEqual("1!", x.map { "\($0)!" })
}
func testOptionalRawTypeAndNilValueDecodesCorrectly() {
struct Container: Decodable {
typealias Idenitifer = Tagged<Container, String?>
let id: Idenitifer
}
XCTAssertNoThrow(try {
let data = "[{\"id\":null}]".data(using: .utf8)!
let containers = try JSONDecoder().decode([Container].self, from: data)
XCTAssertEqual(containers.count, 1)
XCTAssertEqual(containers.first?.id.rawValue, nil)
}())
}
func testCoerce() {
let x: Tagged<Tag, Int> = 1
enum Tag2 {}
let x2: Tagged<Tag2, Int> = x.coerced(to: Tag2.self)
XCTAssertEqual(1, x2.rawValue)
}
}
| 25.267327 | 100 | 0.64616 |
23a9984d819feeac82e1e9e2f40f0a2e46448d78
| 1,839 |
//
// FMPatherPage.swift
// FMPather
//
// Created by Fantasy on 2017/9/20.
// Copyright © 2017年 fantasy. All rights reserved.
//
import UIKit
public class FMPatherPage {
fileprivate let restful: String
fileprivate let restfulRegex: String
fileprivate let builder: (FMPatherPage)->AnyObject
public init(restful path: String,
regex: String = ":[a-z,A-Z,0-9,_]+",
builder:@escaping (FMPatherPage)->AnyObject)
{
restful = path
restfulRegex = regex
self.builder = builder
}
public func canMatch(for path: String) -> Bool {
return path.isMatchRouter(restfulPath: restful,
dynamic: restfulRegex)
}
public func matchedObject(path: String) -> AnyObject? {
if !canMatch(for: path) {
return nil
}
let obj = builder(self)
if obj is FMPatherPathData {
(obj as! FMPatherPathData).querys = path.querys
(obj as! FMPatherPathData).dynamicNode = dynamicPathNode(for: path)
(obj as! FMPatherPathData).url = path
}
return obj
}
}
extension FMPatherPage {
func dynamicPathNode(for path: String) -> [String: String] {
if !path.isMatchRouter(restfulPath: restful,
dynamic: restfulRegex) {
return [:]
}
let pathNodes = path.pathComponents
let patternNodes = restful.pathComponents
let dNodes = patternNodes.flatMap {($0, pathNodes[patternNodes.index(of: $0)!])}
.filter {
[unowned self] in
$0.0.isDynamic(dynamic: self.restfulRegex)
}
var result = [String: String]()
dNodes.forEach {
result[$0.0] = $0.1
}
return result
}
}
| 29.190476 | 88 | 0.566069 |
bb412dbe4de9888d3cee2c0515097ad4720f6332
| 3,429 |
// RUN: %target-swift-frontend %s -emit-ir -gdwarf-types -o - | FileCheck %s
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s --check-prefix=AST
// CHECK-DAG: ![[SINODE:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Int64",{{.*}} identifier: [[SI:.*]])
// CHECK-DAG: ![[SFNODE:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Float",{{.*}} identifier: [[SF:.*]])
// CHECK-DAG: ![[VOIDNODE:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_TtT_",{{.*}} identifier: [[VOID:.*]])
func bar() {
print("bar()", terminator: "")
}
func baz(_ i: Float) -> Int64 { return 0; }
func barz(_ i: Float, _ j: Float) -> Int64 { return 0; }
func main() -> Int64 {
// CHECK-DAG: !DILocalVariable(name: "bar_fnptr",{{.*}} line: [[@LINE+3]],{{.*}} type: ![[BARPT:[0-9]+]]
// AST-DAG: !DILocalVariable(name: "bar_fnptr",{{.*}} line: [[@LINE+2]],{{.*}} type: ![[BAR_T:[0-9]+]]
// AST-DAG: ![[BAR_T]] = !DICompositeType({{.*}}, identifier: "_TtFT_T_")
var bar_fnptr = bar
// CHECK-DAG: ![[BARPT]] = !DICompositeType(tag: DW_TAG_structure_type, {{.*}} elements: ![[BARMEMBERS:[0-9]+]]
// CHECK-DAG: ![[BARMEMBERS]] = !{![[BARMEMBER:.*]], {{.*}}}
// CHECK-DAG: ![[BARMEMBER]] = !DIDerivedType(tag: DW_TAG_member,{{.*}} baseType: ![[BARPTR:[0-9]+]]
// CHECK-DAG: ![[BARPTR]] = !DIDerivedType(tag: DW_TAG_pointer_type,{{.*}} baseType: ![[BART:[0-9]+]]
// CHECK-DAG: ![[BART]] = !DISubroutineType(types: ![[BARARGS:[0-9]+]])
// CHECK-DAG: ![[BARARGS]] = !{![[VOID:.*]]}
// CHECK-DAG: ![[VOID]] = {{.*}}identifier: "_TtT_"
bar_fnptr();
// CHECK-DAG: !DILocalVariable(name: "baz_fnptr",{{.*}} type: ![[BAZPT:[0-9]+]]
// AST-DAG: !DILocalVariable(name: "baz_fnptr",{{.*}} type: ![[BAZ_T:[0-9]+]]
// AST-DAG: ![[BAZ_T]] = !DICompositeType({{.*}}, identifier: "_TtFSfVs5Int64")
// CHECK-DAG: ![[BAZPT]] = !DICompositeType(tag: DW_TAG_structure_type, {{.*}} elements: ![[BAZMEMBERS:[0-9]+]]
// CHECK-DAG: ![[BAZMEMBERS]] = !{![[BAZMEMBER:.*]], {{.*}}}
// CHECK-DAG: ![[BAZMEMBER]] = !DIDerivedType(tag: DW_TAG_member,{{.*}} baseType: ![[BAZPTR:[0-9]+]]
// CHECK-DAG: ![[BAZPTR]] = !DIDerivedType(tag: DW_TAG_pointer_type,{{.*}} baseType: ![[BAZT:[0-9]+]]
// CHECK-DAG: ![[BAZT]] = !DISubroutineType(types: ![[BAZARGS:.*]])
// CHECK-DAG: ![[BAZARGS]] = !{![[INT:.*]], ![[FLOAT:.*]]}
// CHECK-DAG: ![[INT]] = {{.*}}identifier: "_TtVs5Int64"
// CHECK-DAG: ![[FLOAT]] = {{.*}}identifier: "_TtSf"
var baz_fnptr = baz
baz_fnptr(2.89)
// CHECK-DAG: !DILocalVariable(name: "barz_fnptr",{{.*}} type: ![[BARZPT:[0-9]+]]
// AST_DAG: !DILocalVariable(name: "barz_fnptr",{{.*}} type: ![[BARZ_T:[0-9]+]]
// AST-DAG: ![[BARZ_T:[0-9]+]] = !DICompositeType({{.*}}, identifier: "_TtFTSfSf_Vs5Int64")
// CHECK-DAG: ![[BARZPT]] = !DICompositeType(tag: DW_TAG_structure_type,{{.*}} elements: ![[BARZMEMBERS:[0-9]+]]
// CHECK-DAG: ![[BARZMEMBERS]] = !{![[BARZMEMBER:.*]], {{.*}}}
// CHECK-DAG: ![[BARZMEMBER]] = !DIDerivedType(tag: DW_TAG_member,{{.*}} baseType: ![[BARZPTR:[0-9]+]]
// CHECK-DAG: ![[BARZPTR]] = !DIDerivedType(tag: DW_TAG_pointer_type,{{.*}} baseType: ![[BARZT:[0-9]+]]
// CHECK-DAG: ![[BARZT]] = !DISubroutineType(types: ![[BARZARGS:.*]])
// CHECK-DAG: ![[BARZARGS]] = !{![[INT]], ![[FLOAT]], ![[FLOAT]]}
var barz_fnptr = barz
return barz_fnptr(2.89, -1.0)
}
main()
| 63.5 | 123 | 0.564304 |
fc307a1c390791631cf9b83c83227e03ea620ab4
| 7,564 |
//
// StreamingSplitKillTest.swift
// SplitTests
//
// Created by Javier L. Avrudsky on 16/10/2020.
// Copyright © 2020 Split. All rights reserved.
//
import XCTest
@testable import Split
class StreamingSplitKillTest: XCTestCase {
var httpClient: HttpClient!
let apiKey = IntegrationHelper.dummyApiKey
let userKey = IntegrationHelper.dummyUserKey
var streamingBinding: TestStreamResponseBinding?
let sseConnExp = XCTestExpectation(description: "sseConnExp")
var splitsChangesHits = 0
var numbers = [500, 1000, 2000, 3000, 4000]
var changes = [String]()
var exps = [XCTestExpectation]()
let kInitialChangeNumber = 1000
var expIndex: Int = 0
var queue = DispatchQueue(label: "hol", qos: .userInteractive)
var exp1: XCTestExpectation!
var exp2: XCTestExpectation!
var exp3: XCTestExpectation!
var exp4: XCTestExpectation!
override func setUp() {
expIndex = 1
let session = HttpSessionMock()
let reqManager = HttpRequestManagerTestDispatcher(dispatcher: buildTestDispatcher(),
streamingHandler: buildStreamingHandler())
httpClient = DefaultHttpClient(session: session, requestManager: reqManager)
loadChanges()
}
func testSplitKill() {
let splitConfig: SplitClientConfig = SplitClientConfig()
splitConfig.featuresRefreshRate = 9999
splitConfig.segmentsRefreshRate = 9999
splitConfig.impressionRefreshRate = 999999
splitConfig.sdkReadyTimeOut = 60000
splitConfig.eventsPushRate = 999999
//splitConfig.isDebugModeEnabled = true
let key: Key = Key(matchingKey: userKey)
let builder = DefaultSplitFactoryBuilder()
_ = builder.setHttpClient(httpClient)
_ = builder.setReachabilityChecker(ReachabilityMock())
let factory = builder.setApiKey(apiKey).setKey(key)
.setConfig(splitConfig).build()!
let client = factory.client
let expTimeout: TimeInterval = 5
let sdkReadyExpectation = XCTestExpectation(description: "SDK READY Expectation")
exp1 = XCTestExpectation(description: "Exp1")
exp2 = XCTestExpectation(description: "Exp2")
exp3 = XCTestExpectation(description: "Exp3")
exp4 = XCTestExpectation(description: "Exp4")
client.on(event: SplitEvent.sdkReady) {
IntegrationHelper.tlog("READY")
sdkReadyExpectation.fulfill()
}
client.on(event: SplitEvent.sdkReadyTimedOut) {
IntegrationHelper.tlog("TIMEOUT")
}
wait(for: [sdkReadyExpectation, sseConnExp], timeout: expTimeout)
IntegrationHelper.tlog("KEEPAL")
streamingBinding?.push(message: ":keepalive") // send keep alive to confirm streaming connection ok
wait(for: [exp1], timeout: expTimeout)
waitForUpdate(secs: 1)
let splitName = "workm"
let treatmentReady = client.getTreatment(splitName)
streamingBinding?.push(message:
StreamingIntegrationHelper.splitKillMessagge(splitName: splitName, defaultTreatment: "conta",
timestamp: numbers[splitsChangesHits],
changeNumber: numbers[splitsChangesHits]))
wait(for: [exp2], timeout: expTimeout)
waitForUpdate(secs: 1)
let treatmentKill = client.getTreatment(splitName)
print("Updating split")
streamingBinding?.push(message:
StreamingIntegrationHelper.splitUpdateMessage(timestamp: numbers[splitsChangesHits],
changeNumber: numbers[splitsChangesHits]))
wait(for: [exp3], timeout: expTimeout)
waitForUpdate(secs: 1)
let treatmentNoKill = client.getTreatment(splitName)
streamingBinding?.push(message:
StreamingIntegrationHelper.splitKillMessagge(splitName: splitName, defaultTreatment: "conta",
timestamp: numbers[0],
changeNumber: numbers[0]))
ThreadUtils.delay(seconds: 2.0) // The server should not be hit here
let treatmentOldKill = client.getTreatment(splitName)
XCTAssertEqual("on", treatmentReady)
XCTAssertEqual("conta", treatmentKill)
XCTAssertEqual("on", treatmentNoKill)
XCTAssertEqual("on", treatmentOldKill)
}
private func getChanges(for hitNumber: Int) -> Data {
if hitNumber < 4 {
return Data(self.changes[hitNumber].utf8)
}
return Data(IntegrationHelper.emptySplitChanges(since: 999999, till: 999999).utf8)
}
private func buildTestDispatcher() -> HttpClientTestDispatcher {
return { request in
switch request.url.absoluteString {
case let(urlString) where urlString.contains("splitChanges"):
let hitNumber = self.getAndUpdateHit()
IntegrationHelper.tlog("sc hit: \(hitNumber)")
switch hitNumber {
case 1:
self.exp1.fulfill()
case 2:
self.exp2.fulfill()
case 3:
self.exp3.fulfill()
default:
IntegrationHelper.tlog("Exp no fired \(hitNumber)")
}
return TestDispatcherResponse(code: 200, data: self.getChanges(for: hitNumber))
case let(urlString) where urlString.contains("mySegments"):
return TestDispatcherResponse(code: 200, data: Data(IntegrationHelper.emptyMySegments.utf8))
case let(urlString) where urlString.contains("auth"):
return TestDispatcherResponse(code: 200, data: Data(IntegrationHelper.dummySseResponse().utf8))
default:
return TestDispatcherResponse(code: 500)
}
}
}
private func getAndUpdateHit() -> Int {
var hitNumber = 0
DispatchQueue.global().sync {
hitNumber = self.splitsChangesHits
self.splitsChangesHits+=1
}
return hitNumber
}
private func buildStreamingHandler() -> TestStreamResponseBindingHandler {
return { request in
self.streamingBinding = TestStreamResponseBinding.createFor(request: request, code: 200)
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
self.sseConnExp.fulfill()
}
return self.streamingBinding!
}
}
private func getChanges(killed: Bool, since: Int, till: Int) -> String {
let change = IntegrationHelper.getChanges(fileName: "simple_split_change")
change?.since = Int64(since)
change?.till = Int64(till)
let split = change?.splits[0]
split?.changeNumber = Int64(since)
if killed {
split?.killed = true
split?.defaultTreatment = "conta"
}
return (try? Json.encodeToJson(change)) ?? ""
}
private func loadChanges() {
for i in 0..<4 {
let change = getChanges(killed: (i == 2),
since: self.numbers[i],
till: self.numbers[i])
changes.insert(change, at: i)
}
}
private func waitForUpdate(secs: UInt32 = 2) {
sleep(secs)
}
}
| 37.631841 | 111 | 0.605368 |
79535c8f47b1b99a83c0e40a0d6ef19f6b6eb9b8
| 5,894 |
// Copyright © 2018 Stormbird PTE. LTD.
import Foundation
import BigInt
private typealias ContractTokenIdsAttributeValues = [TokenId: [AttributeId: CachedAssetAttribute]]
class AssetAttributesCache {
private var resolvedAttributesData: AssetAttributesCacheData
private var functionOriginAttributes: [AlphaWallet.Address: [AttributeId: AssetAttribute]] = .init()
private var functionOriginSubscribables: [AlphaWallet.Address: [TokenId: [AttributeId: Subscribable<AssetInternalValue>]]] = .init()
init() {
let decoder = JSONDecoder()
//TODO read from JSON file/database (if it exists)
self.resolvedAttributesData = (try? decoder.decode(AssetAttributesCacheData.self, from: Data())) ?? .init()
}
func clearCacheWhenTokenScriptChanges(forContract contract: AlphaWallet.Address) {
resolvedAttributesData.remove(contract: contract)
functionOriginAttributes.removeValue(forKey: contract)
functionOriginSubscribables.removeValue(forKey: contract)
}
func cache(attribute: AssetAttribute, attributeId: AttributeId, value: AssetInternalValue, forContract contract: AlphaWallet.Address, tokenId: TokenId) {
var contractData: ContractTokenIdsAttributeValues = resolvedAttributesData[contract] ?? .init()
defer { resolvedAttributesData[contract] = contractData }
let cachedAttribute = CachedAssetAttribute(type: .token, id: attributeId, value: value)
var tokenIdData = contractData[tokenId] ?? .init()
defer { contractData[tokenId] = tokenIdData }
tokenIdData[attributeId] = cachedAttribute
}
func cache(attributes: [AttributeId: AssetAttribute], values: [AttributeId: AssetInternalValue], forContract contract: AlphaWallet.Address, tokenId: TokenId) {
if functionOriginAttributes[contract] == nil {
functionOriginAttributes[contract] = attributes
}
var contractSubscribables = functionOriginSubscribables[contract] ?? .init()
defer { functionOriginSubscribables[contract] = contractSubscribables }
var tokenIdSubscribables = contractSubscribables[tokenId] ?? .init()
defer { contractSubscribables[tokenId] = tokenIdSubscribables }
for (attributeId, attribute) in attributes {
guard attribute.isFunctionOriginBased, let value = values[attributeId] else { continue }
switch value {
case .subscribable(let subscribable):
tokenIdSubscribables[attributeId] = subscribable
subscribable.subscribe { [weak self] value in
guard let strongSelf = self else { return }
guard let value = value else { return }
//We really expect the data to be available if the subscribable fires later. And not available if subscribable has already been resolved
guard var tokenData: [AttributeId: CachedAssetAttribute] = strongSelf.resolvedAttributesData[contract]?[tokenId] else { return }
defer {
if var contractData = strongSelf.resolvedAttributesData[contract] {
contractData[tokenId] = tokenData
strongSelf.resolvedAttributesData[contract] = contractData
//TODO good chance to write to disk? Maybe limit writing to every sec or 300msec?
}
}
tokenData[attributeId] = CachedAssetAttribute(type: .token, id: attributeId, value: value)
}
case .address, .string, .int, .uint, .generalisedTime, .bool, .bytes:
break
case .openSeaNonFungibleTraits:
break
}
}
var contractData: ContractTokenIdsAttributeValues = resolvedAttributesData[contract] ?? .init()
defer { resolvedAttributesData[contract] = contractData }
let tokenValues: [(AttributeId, CachedAssetAttribute)] = values.compactMap { each in
let attributeId = each.key
let value = each.value
//TODO this doesn't support action-level
return value.resolvedValue.flatMap { (attributeId, .init(type: .token, id: attributeId, value: $0)) }
}
contractData[tokenId] = Dictionary(tokenValues) { _, new in new }
}
func getValues(forContract contractAddress: AlphaWallet.Address, tokenId: TokenId) -> [AttributeId: AssetInternalValue]? {
//Explicitly typed so AppCode knows
guard let values: [AttributeId: CachedAssetAttribute] = resolvedAttributesData[contractAddress]?[tokenId] else { return nil }
let results = values.mapValues { $0.value }
let subscribablesOptional: [(AttributeId, AssetInternalValue)]? = functionOriginSubscribables[contractAddress]?[tokenId]?.map { each in
let attributeId = each.key
let subscribable = each.value
return (attributeId, .subscribable(subscribable))
}
if let subscribables = subscribablesOptional {
return results.merging(subscribables) { _, new in new }
} else {
return results
}
}
}
struct AssetAttributesCacheData: Codable {
private var contracts = [AlphaWallet.Address: ContractTokenIdsAttributeValues]()
fileprivate subscript(contract: AlphaWallet.Address) -> ContractTokenIdsAttributeValues? {
get {
return contracts[contract]
}
set {
contracts[contract] = newValue
}
}
mutating func remove(contract: AlphaWallet.Address) {
contracts.removeValue(forKey: contract)
}
}
enum CachedAssetAttributeType: Int, Codable {
case token
case action
}
struct CachedAssetAttribute: Codable {
let type: CachedAssetAttributeType
let id: AttributeId
let value: AssetInternalValue
}
| 47.532258 | 163 | 0.667967 |
1a04784b2c0e999645aadbc1af548ad429d4ec2f
| 3,766 |
//
// TransitionAnimator.swift
//
// Copyright (c) 2015 Teodor Patraş
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/**
* Protocol for defining custom animations for when switching the center view controller.
* By the time this method is called, the view of the new center view controller has been
* added to the center panel and resized. You only need to implement a custom animation.
*/
public protocol TransitionAnimatable {
static func performTransition(forView view: UIView, completion: @escaping () -> Void)
}
public struct FadeAnimator: TransitionAnimatable {
public static func performTransition(forView view: UIView, completion: @escaping () -> Void) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
let fadeAnimation = CABasicAnimation(keyPath: "opacity")
fadeAnimation.duration = 0.35
fadeAnimation.fromValue = 0
fadeAnimation.toValue = 1
fadeAnimation.fillMode = .forwards
fadeAnimation.isRemovedOnCompletion = true
view.layer.add(fadeAnimation, forKey: "fade")
CATransaction.commit()
}
}
public struct CircleMaskAnimator: TransitionAnimatable {
public static func performTransition(forView view: UIView, completion: @escaping () -> Void) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
let screenSize = UIScreen.main.bounds.size
let dim = max(screenSize.width, screenSize.height)
let circleDiameter : CGFloat = 50.0
let circleFrame = CGRect(x: (screenSize.width - circleDiameter) / 2, y: (screenSize.height - circleDiameter) / 2, width: circleDiameter, height: circleDiameter)
let circleCenter = CGPoint(x: circleFrame.origin.x + circleDiameter / 2, y: circleFrame.origin.y + circleDiameter / 2)
let circleMaskPathInitial = UIBezierPath(ovalIn: circleFrame)
let extremePoint = CGPoint(x: circleCenter.x - dim, y: circleCenter.y - dim)
let radius = sqrt((extremePoint.x * extremePoint.x) + (extremePoint.y * extremePoint.y))
let circleMaskPathFinal = UIBezierPath(ovalIn: circleFrame.insetBy(dx: -radius, dy: -radius))
let maskLayer = CAShapeLayer()
maskLayer.path = circleMaskPathFinal.cgPath
view.layer.mask = maskLayer
let maskLayerAnimation = CABasicAnimation(keyPath: "path")
maskLayerAnimation.fromValue = circleMaskPathInitial.cgPath
maskLayerAnimation.toValue = circleMaskPathFinal.cgPath
maskLayerAnimation.duration = 0.6
view.layer.mask?.add(maskLayerAnimation, forKey: "circleMask")
CATransaction.commit()
}
}
| 45.926829 | 168 | 0.71402 |
f93308d055305980d9736a60f0900658678cfbb2
| 2,090 |
//
// AppDelegate.swift
// ForestAdventures
//
// Created by Brandi Bailey on 4/27/20.
// Copyright © 2020 Brandi Bailey. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let inactiveColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
let activeColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: activeColor], for: .selected)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font:UIFont(name: "Menlo-Regular", size: 18),
NSAttributedString.Key.foregroundColor: inactiveColor],
for: .normal)
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.
}
}
| 45.434783 | 179 | 0.708612 |
4bffb5986d01efbced146ed0f013e94ef16bf24d
| 4,350 |
//
// LanguageHandler.swift
// test
//
// Created by Karim Mousa on 1/27/18.
// Copyright © 2018 Karim Mousa. All rights reserved.
//
import UIKit
// user defaults
private let languageUserDefaults = "languageUserDefaults"
private let currentLanguageUserDefaults = "currentLanguageUserDefaults"
private let currentDirectionUserDefaults = "currentDirectionUserDefaults"
public enum Language: Int {
case english = 0
case arabic = 1
}
public enum Direction: Int {
case ltr = 0
case rtl = 1
}
public class LanguageHandler: NSObject {
// singlton implementation
static var shared = LanguageHandler()
private override init() {
let userDefaults = UserDefaults(suiteName: languageUserDefaults)!
let savedLangId = userDefaults.integer(forKey: currentLanguageUserDefaults)
let savedDirection = userDefaults.integer(forKey: currentDirectionUserDefaults)
let languageId = Language(rawValue: savedLangId) ?? .english
self.currentLanguage = languageId
let direction = Direction(rawValue: savedDirection) ?? .ltr
self.currentDirection = direction
}
var currentLanguageModel: LanguageModel {
if self.currentLanguage == .english { // on for englush
return LanguageModel.english
} else { // off arabic
return LanguageModel.arabic
}
}
var currentLanguage: Language {
willSet {
let defaults: UserDefaults = UserDefaults(suiteName: languageUserDefaults)!
defaults.set(newValue.rawValue, forKey: currentLanguageUserDefaults)
defaults.synchronize()
}
}
var currentDirection: Direction {
willSet {
let defaults: UserDefaults = UserDefaults(suiteName: languageUserDefaults)!
defaults.set(newValue.rawValue, forKey: currentDirectionUserDefaults)
defaults.synchronize()
}
}
var localizedResourcesBundle: Bundle {
let lang: String = (currentLanguage == .arabic) ? "ar" : "en"
let bundlePath: String = Bundle.main.path(forResource: lang, ofType: "lproj")!
let bundle = Bundle(path: bundlePath)!
return bundle
}
func localizedNameForResourceWithName(_ resourceName: String) -> String {
return "\(resourceName)_" + ((self.currentDirection == .rtl) ? "RTL" : "LTR")
}
func stringForKey(_ key: String) -> String {
return self.localizedResourcesBundle.localizedString(forKey: key, value: "\(key)", table: nil)
}
}
// MARK: Helper Prefered methods
public extension LanguageHandler {
func getSupportedLanguages() -> [LanguageModel] {
let arabicLang = LanguageModel.arabic
let englishLang = LanguageModel.english
let languageList = [englishLang, arabicLang]
return languageList
}
func getPreferredLanguageCodePreferred() -> String {
let preferred = Bundle.main.preferredLocalizations.first ?? "en"
return preferred
}
func getCurrentLanguageCode() -> String {
let code = (currentLanguage == .arabic) ? "ar" : "en"
return code
}
func configureAppLanguage(_ code: String) {
if code == "en" {
currentLanguage = .english
currentDirection = .ltr
} else {
currentLanguage = .arabic
currentDirection = .rtl
}
UserDefaults.standard.set([code], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
debugPrint(Locale.autoupdatingCurrent.identifier)
}
}
///**
// reset app which will perform transition and call reset on appdelegate if it's MOLHResetable
// */
//open class func reset() {
// var transition = UIView.AnimationOptions.transitionFlipFromRight
// if !MOLHLanguage.isRTLLanguage() {
// transition = .transitionFlipFromLeft
// }
// reset(transition: transition)
//}
//
//open class func reset(transition: UIView.AnimationOptions) {
// if let delegate = UIApplication.shared.delegate {
// if delegate is MOLHResetable {
// (delegate as!MOLHResetable).reset()
// }
// UIView.transition(with: ((delegate.window)!)!, duration: 0.5, options: transition, animations: {}) { (f) in
// }
// }
//}
| 31.071429 | 117 | 0.644828 |
4ac775b6b3ab09f92471ad855c49094f1ee0a71b
| 2,960 |
//
// UITextfield + Extension.swift
// UIVIew_Reusable
//
// Created by Solulab on 2/10/20.
// Copyright © 2020 Solulab. All rights reserved.
//
import Foundation
import UIKit
//MARK:- EXTENSIONS
extension UITextField{
private static var datePickerInstance: UIDatePicker!
private static var dateStyle: DateFormatter.Style!
var datePickerProperty:UIDatePicker {
get {
return UITextField.datePickerInstance
}
set(newValue) {
UITextField.datePickerInstance = newValue
}
}
public func changeTextfieldPlaceholderColor(_ placeholderString: String, placeholder textColor:UIColor){
self.attributedPlaceholder = NSAttributedString(string: placeholderString, attributes: [.foregroundColor: textColor])
}
public func openDatePicker(dateFormateStyle: DateFormatter.Style = .medium){
UITextField.dateStyle = dateFormateStyle
let screenWidth = UIScreen.main.bounds.width
//Add DatePicker as inputView
var datePicker = UITextField.datePickerInstance
if datePicker == nil{
datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
UITextField.datePickerInstance = datePicker
}
datePicker?.datePickerMode = .date
datePicker?.addTarget(self, action: #selector(valueChanged(datepicker:)), for: .valueChanged)
self.inputView = datePicker
//Add Tool Bar as input AccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donePressed))
toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)
self.inputAccessoryView = toolBar
}
@objc func donePressed(){
self.text = formatter().string(from: UITextField.datePickerInstance.date)
self.accessibilityLabel = self.text
self.resignFirstResponder()
}
@objc
func valueChanged(datepicker: UIDatePicker){
UITextField.datePickerInstance = datepicker
self.text = formatter().string(from: datepicker.date)
}
func formatter() -> DateFormatter{
let formatter = DateFormatter()
formatter.dateStyle = UITextField.dateStyle
return formatter
}
@objc func cancelPressed(){
datePickerText()
self.resignFirstResponder()
}
func datePickerText(){
self.text = self.accessibilityLabel
UITextField.datePickerInstance.date = formatter().date(from: self.text ?? "") ?? Date()
}
}
| 34.022989 | 125 | 0.667568 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.