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
|
---|---|---|---|---|---|
cc4027708d579aa9b61e0b7ed6c36db52cb8f1a4 | 2,370 | //
// VideoSettingDetailedOptionCell.swift
// RCE
//
// Created by hanxiaoqing on 2021/11/29.
//
import UIKit
import Reusable
class VideoSettingDetailedOptionCell: UICollectionViewCell,Reusable {
private var normalBackgroundImage: UIImage = {
let size = CGSize(width: 157.5.resize, height: 48.resize)
let layer = CALayer()
layer.bounds = CGRect(origin: .zero, size: size)
layer.borderWidth = 0
layer.backgroundColor = UIColor.white.withAlphaComponent(0.16).cgColor
layer.cornerRadius = 6.resize
return UIGraphicsImageRenderer(size: size)
.image { renderer in
layer.render(in: renderer.cgContext)
}
}()
private var selectedBackgroundImage: UIImage = {
let size = CGSize(width: 157.5.resize, height: 48.resize)
let layer = CALayer()
layer.bounds = CGRect(origin: .zero, size: size)
layer.borderWidth = 1
layer.borderColor = UIColor(byteRed: 239, green: 73, blue: 154).cgColor
layer.backgroundColor = UIColor(byteRed: 239, green: 73, blue: 154, alpha: 0.06).cgColor
layer.cornerRadius = 6.resize
return UIGraphicsImageRenderer(size: size)
.image { renderer in
layer.render(in: renderer.cgContext)
}
}()
private lazy var centerItem: UIButton = {
let btn = UIButton(type: .custom)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btn.setBackgroundImage(normalBackgroundImage, for: .normal)
btn.setBackgroundImage(selectedBackgroundImage, for: .selected)
btn.setTitleColor(.white, for: .normal)
btn.setTitleColor(UIColor(byteRed: 239, green: 73, blue: 154), for: .selected)
btn.isUserInteractionEnabled = false
contentView.addSubview(btn)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(centerItem)
centerItem.snp.makeConstraints {
$0.edges.equalTo(contentView)
}
}
func update(_ option: String, selected: Bool) {
centerItem.setTitle(option, for: .normal)
centerItem.isSelected = selected
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 31.6 | 96 | 0.626582 |
c11fe5d8593b18b92fedbc4c13acd52350622fc3 | 456 | //
// SampleTableViewCell.swift
// PDFGenerator
//
// Created by Suguru Kishimoto on 2016/02/27.
//
//
import UIKit
class SampleTableViewCell: UITableViewCell {
@IBOutlet weak var leftLabel: UILabel!
@IBOutlet weak var rightLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 19 | 65 | 0.684211 |
f49cbb154e454bb7ed52379b4c92a4bf20688a0c | 6,514 | //
// NSLayoutConstraint-SKLBits.swift
// slidekey
//
// Created by Simeon Leifer on 7/10/16.
// Copyright © 2016 droolingcat.com. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
public typealias ViewType = UIView
#elseif os(OSX)
import AppKit
public typealias ViewType = NSView
#endif
#if !os(watchOS)
#if os(iOS) || os(tvOS)
private var barKey: UInt8 = 0
public class LayoutConstraintSizeClass {
public var horizontalSizeClass: UIUserInterfaceSizeClass = .unspecified
public var verticalSizeClass: UIUserInterfaceSizeClass = .unspecified
}
#endif
public extension NSLayoutConstraint {
#if os(iOS) || os(tvOS)
var sizeClass: LayoutConstraintSizeClass {
get {
return associatedObject(self, key: &barKey) {
return LayoutConstraintSizeClass()
}
}
set {
associateObject(self, key: &barKey, value: newValue)
}
}
#endif
public func referes(_ toView: ViewType) -> Bool {
if let view = self.firstItem as? ViewType, view == toView {
return true
}
if self.secondItem == nil {
return false
}
if let view = self.secondItem as? ViewType, view == toView {
return true
}
return false
}
@discardableResult public func install() -> NSLayoutConstraint {
let first = self.firstItem as? ViewType
let second = self.secondItem as? ViewType
let target = first?.nearestCommonAncestor(second)
if target != nil && target?.constraints.contains(self) == false {
if target != first {
first?.translatesAutoresizingMaskIntoConstraints = false
}
if target != second {
second?.translatesAutoresizingMaskIntoConstraints = false
}
target?.addConstraint(self)
}
return self
}
@discardableResult public func installWith(priority: Float) -> NSLayoutConstraint {
self.priority = priority
self.install()
return self
}
@discardableResult public func remove() -> NSLayoutConstraint {
if let owner = owner() {
owner.removeConstraint(self)
}
return self
}
public func likelyOwner() -> ViewType? {
let first = self.firstItem as? ViewType
let second = self.secondItem as? ViewType
let target = first?.nearestCommonAncestor(second)
return target
}
public func owner() -> ViewType? {
let first = self.firstItem as? ViewType
if first != nil && first?.constraints.contains(self) == true {
return first
}
let second = self.secondItem as? ViewType
if second != nil && second?.constraints.contains(self) == true {
return second
}
let target = first?.nearestCommonAncestor(second)
if target != nil && target != first && target != second && target?.constraints.contains(self) == true {
return target
}
if first != nil, let supers = first?.allSuperviews() {
for view in supers {
if view.constraints.contains(self) {
return view
}
}
}
if second != nil, let supers = second?.allSuperviews() {
for view in supers {
if view.constraints.contains(self) {
return view
}
}
}
return nil
}
}
public extension ViewType {
public func allSuperviews() -> [ViewType] {
var views = [ViewType]()
var view = self.superview
while view != nil {
views.append(view!)
view = view?.superview
}
return views
}
public func isParent(of view: ViewType) -> Bool {
if self == view {
return true
}
if view.allSuperviews().contains(self) {
return true
}
return false
}
public func allSubviews(_ includeSelf: Bool = true) -> [ViewType] {
var views: [ViewType] = []
for view in self.subviews {
views.append(view)
views.append(contentsOf: view.allSubviews())
}
if includeSelf {
views.append(self)
}
return views
}
public func referencingConstraintsInSuperviews() -> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
for view in allSuperviews() {
for constraint in view.constraints {
if type(of: constraint) != NSLayoutConstraint.self && constraint.shouldBeArchived == false {
continue
}
if constraint.referes(self) {
constraints.append(constraint)
}
}
}
return constraints
}
public func referencingConstraints() -> [NSLayoutConstraint] {
var constraints = referencingConstraintsInSuperviews()
for constraint in self.constraints {
if type(of: constraint) != NSLayoutConstraint.self && constraint.shouldBeArchived == false {
continue
}
if constraint.referes(self) {
constraints.append(constraint)
}
}
return constraints
}
public func referencingConstraint(withIdentifier identifier: String) -> NSLayoutConstraint? {
let constraints = self.referencingConstraints()
let slidables = constraints.filter { (item) -> Bool in
if item.identifier == identifier {
return true
}
return false
}
if slidables.count > 0 {
return slidables[0]
}
return nil
}
public func isAncestorOf(_ view: ViewType?) -> Bool {
if let view = view {
return view.allSuperviews().contains(self)
}
return false
}
public func nearestCommonAncestor(_ view: ViewType?) -> ViewType? {
if let view = view {
if self == view {
return self
}
if self.isAncestorOf(view) {
return self
}
if view.isAncestorOf(self) {
return view
}
let ancestors = self.allSuperviews()
for aView in view.allSuperviews() {
if ancestors.contains(aView) {
return aView
}
}
return nil
}
return self
}
}
public extension Array where Element: NSLayoutConstraint {
public func installConstraints() {
for constraint in self {
constraint.install()
}
}
public func removeConstraints() {
for constraint in self {
constraint.remove()
}
}
#if os(iOS) || os(tvOS)
public func installConstraintsFor(_ traits: UITraitCollection) {
let hSizeClass = traits.horizontalSizeClass
let vSizeClass = traits.verticalSizeClass
var install = [NSLayoutConstraint]()
var remove = [NSLayoutConstraint]()
for constraint in self {
let sizeClass = constraint.sizeClass
var add: Bool = false
if hSizeClass == .unspecified || sizeClass.horizontalSizeClass == .unspecified || hSizeClass == sizeClass.horizontalSizeClass {
if vSizeClass == .unspecified || sizeClass.verticalSizeClass == .unspecified || vSizeClass == sizeClass.verticalSizeClass {
add = true
}
}
if add == true {
if constraint.isActive == false {
install.append(constraint)
}
} else {
if constraint.isActive == true {
remove.append(constraint)
}
}
}
NSLayoutConstraint.deactivate(remove)
NSLayoutConstraint.activate(install)
}
#endif
}
#endif
| 22.696864 | 130 | 0.686061 |
e975ee8e01a6e97d7380cd1f12afc83193448f86 | 11,920 | //
// Copyright © 2020 Iterable. All rights reserved.
//
import XCTest
@testable import IterableSDK
class TaskProcessorTests: XCTestCase {
func testAPICallForTrackEventWithPersistence() throws {
let apiKey = "test-api-key"
let email = "[email protected]"
let eventName = "CustomEvent1"
let dataFields = ["var1": "val1", "var2": "val2"]
let expectation1 = expectation(description: #function)
let auth = Auth(userId: nil, email: email, authToken: nil)
let config = IterableConfig()
let networkSession = MockNetworkSession()
let internalAPI = InternalIterableAPI.initializeForTesting(apiKey: apiKey, config: config, networkSession: networkSession)
let requestCreator = RequestCreator(apiKey: apiKey,
auth: auth,
deviceMetadata: internalAPI.deviceMetadata)
guard case let Result.success(trackEventRequest) = requestCreator.createTrackEventRequest(eventName, dataFields: dataFields) else {
XCTFail("Could not create trackEvent request")
return
}
let apiCallRequest = IterableAPICallRequest(apiKey: apiKey,
endPoint: Endpoint.api,
auth: auth,
deviceMetadata: internalAPI.deviceMetadata,
iterableRequest: trackEventRequest)
let data = try JSONEncoder().encode(apiCallRequest)
// persist data
let taskId = IterableUtil.generateUUID()
try persistenceProvider.mainQueueContext().create(task: IterableTask(id: taskId,
type: .apiCall,
scheduledAt: Date(),
data: data,
requestedAt: Date()))
try persistenceProvider.mainQueueContext().save()
// load data
let found = try persistenceProvider.mainQueueContext().findTask(withId: taskId)!
// process data
let processor = IterableAPICallTaskProcessor(networkSession: internalAPI.networkSession)
try processor.process(task: found).onSuccess { _ in
let request = networkSession.getRequest(withEndPoint: Const.Path.trackEvent)!
let body = request.httpBody!.json() as! [String: Any]
TestUtils.validateMatch(keyPath: KeyPath(keys: JsonKey.email), value: email, inDictionary: body)
TestUtils.validateMatch(keyPath: KeyPath(keys: JsonKey.dataFields), value: dataFields, inDictionary: body)
expectation1.fulfill()
}
try persistenceProvider.mainQueueContext().delete(task: found)
try persistenceProvider.mainQueueContext().save()
wait(for: [expectation1], timeout: 15.0)
}
func testNetworkAvailable() throws {
let expectation1 = expectation(description: #function)
let task = try createSampleTask()!
let networkSession = MockNetworkSession(statusCode: 200)
// process data
let processor = IterableAPICallTaskProcessor(networkSession: networkSession)
try processor.process(task: task)
.onSuccess { taskResult in
switch taskResult {
case .success(detail: _):
expectation1.fulfill()
case .failureWithNoRetry(detail: _):
XCTFail("not expecting failure with no retry")
case .failureWithRetry(retryAfter: _, detail: _):
XCTFail("not expecting failure with retry")
}
}
.onError { _ in
XCTFail()
}
try persistenceProvider.mainQueueContext().delete(task: task)
try persistenceProvider.mainQueueContext().save()
wait(for: [expectation1], timeout: 15.0)
}
func testNetworkUnavailable() throws {
let expectation1 = expectation(description: #function)
let task = try createSampleTask()!
let networkError = IterableError.general(description: "The Internet connection appears to be offline.")
let networkSession = MockNetworkSession(statusCode: 0, data: nil, error: networkError)
// process data
let processor = IterableAPICallTaskProcessor(networkSession: networkSession)
try processor.process(task: task)
.onSuccess { taskResult in
switch taskResult {
case .success(detail: _):
XCTFail("not expecting success")
case .failureWithNoRetry(detail: _):
XCTFail("not expecting failure with no retry")
case .failureWithRetry(retryAfter: _, detail: _):
expectation1.fulfill()
}
}
.onError { _ in
XCTFail()
}
try persistenceProvider.mainQueueContext().delete(task: task)
try persistenceProvider.mainQueueContext().save()
wait(for: [expectation1], timeout: 15.0)
}
func testUnrecoverableError() throws {
let expectation1 = expectation(description: #function)
let task = try createSampleTask()!
let networkSession = MockNetworkSession(statusCode: 401, data: nil, error: nil)
// process data
let processor = IterableAPICallTaskProcessor(networkSession: networkSession)
try processor.process(task: task)
.onSuccess { taskResult in
switch taskResult {
case .success(detail: _):
XCTFail("not expecting success")
case .failureWithNoRetry(detail: _):
expectation1.fulfill()
case .failureWithRetry(retryAfter: _, detail: _):
XCTFail("not expecting failure with retry")
}
}
.onError { _ in
XCTFail()
}
try persistenceProvider.mainQueueContext().delete(task: task)
try persistenceProvider.mainQueueContext().save()
wait(for: [expectation1], timeout: 15.0)
}
func testSentAtInHeader() throws {
let expectation1 = expectation(description: #function)
let task = try createSampleTask()!
let date = Date()
let sentAtTime = "\(Int(date.timeIntervalSince1970))"
let dateProvider = MockDateProvider()
dateProvider.currentDate = date
let networkSession = MockNetworkSession()
networkSession.requestCallback = { request in
if request.allHTTPHeaderFields!.contains(where: { $0.key == "Sent-At" && $0.value == sentAtTime }) {
expectation1.fulfill()
}
}
// process data
let processor = IterableAPICallTaskProcessor(networkSession: networkSession, dateProvider: dateProvider)
try processor.process(task: task)
.onSuccess { taskResult in
switch taskResult {
case .success(detail: _):
break
case .failureWithNoRetry(detail: _):
XCTFail("not expecting failure with no retry")
case .failureWithRetry(retryAfter: _, detail: _):
XCTFail("not expecting failure with retry")
}
}
.onError { _ in
XCTFail()
}
try persistenceProvider.mainQueueContext().delete(task: task)
try persistenceProvider.mainQueueContext().save()
wait(for: [expectation1], timeout: 5.0)
}
func testCreatedAtInBody() throws {
let expectation1 = expectation(description: #function)
let date = Date()
let createdAtTime = Int(date.timeIntervalSince1970)
let task = try createSampleTask(scheduledAt: date)!
let networkSession = MockNetworkSession()
networkSession.requestCallback = { request in
if request.bodyDict.contains(where: { $0.key == "createdAt" && ($0.value as! Int) == createdAtTime }) {
expectation1.fulfill()
}
}
// process data
let processor = IterableAPICallTaskProcessor(networkSession: networkSession)
try processor.process(task: task)
.onSuccess { taskResult in
switch taskResult {
case .success(detail: _):
break
case .failureWithNoRetry(detail: _):
XCTFail("not expecting failure with no retry")
case .failureWithRetry(retryAfter: _, detail: _):
XCTFail("not expecting failure with retry")
}
}
.onError { _ in
XCTFail()
}
try persistenceProvider.mainQueueContext().delete(task: task)
try persistenceProvider.mainQueueContext().save()
wait(for: [expectation1], timeout: 5.0)
}
private func createSampleTask(scheduledAt: Date = Date(), requestedAt: Date = Date()) throws -> IterableTask? {
let apiKey = "test-api-key"
let email = "[email protected]"
let eventName = "CustomEvent1"
let dataFields = ["var1": "val1", "var2": "val2"]
let auth = Auth(userId: nil, email: email, authToken: nil)
let requestCreator = RequestCreator(apiKey: apiKey,
auth: auth,
deviceMetadata: deviceMetadata)
guard case let Result.success(trackEventRequest) = requestCreator.createTrackEventRequest(eventName, dataFields: dataFields) else {
XCTFail("Could not create trackEvent request")
return nil
}
let apiCallRequest = IterableAPICallRequest(apiKey: apiKey,
endPoint: Endpoint.api,
auth: auth,
deviceMetadata: deviceMetadata,
iterableRequest: trackEventRequest)
let data = try JSONEncoder().encode(apiCallRequest)
// persist data
let taskId = IterableUtil.generateUUID()
try persistenceProvider.mainQueueContext().create(task: IterableTask(id: taskId,
type: .apiCall,
scheduledAt: scheduledAt,
data: data,
requestedAt: requestedAt))
try persistenceProvider.mainQueueContext().save()
return try persistenceProvider.mainQueueContext().findTask(withId: taskId)
}
private let deviceMetadata = DeviceMetadata(deviceId: IterableUtil.generateUUID(),
platform: JsonValue.iOS,
appPackageName: Bundle.main.appPackageName ?? "")
private lazy var persistenceProvider: IterablePersistenceContextProvider = {
let provider = CoreDataPersistenceContextProvider(fromBundle: Bundle(for: PersistentContainer.self))!
try! provider.mainQueueContext().deleteAllTasks()
try! provider.mainQueueContext().save()
return provider
}()
}
| 45.151515 | 139 | 0.55193 |
0a9d9b5233d4d6ccc0673d7dee702a0938fd51c2 | 3,474 | //
// KMAUIUploadFilesTableViewCell.swift
// KMA EYES CITIZENS
//
// Created by Stanislav Rastvorov on 16.04.2020.
// Copyright © 2020 Stanislav Rastvorov. All rights reserved.
//
import UIKit
public class KMAUIUploadFilesTableViewCell: UITableViewCell {
// MARK: - IBOutlets
@IBOutlet public weak var bgView: UIView!
@IBOutlet public weak var circleView: UIView!
@IBOutlet public weak var cameraImageView: UIImageView!
@IBOutlet weak var arrowImageView: UIImageView!
@IBOutlet public weak var titleLabel: UILabel!
@IBOutlet public weak var infoLabel: UILabel!
// MARK: - Variables
public var rowData = KMAUIRowData() {
didSet {
setupCell()
}
}
// MARK: - Variables
public static let id = "KMAUIUploadFilesTableViewCell"
override public func awakeFromNib() {
super.awakeFromNib()
// Background color
contentView.backgroundColor = KMAUIConstants.shared.KMAUIViewBgColorReverse
// BgView
bgView.backgroundColor = KMAUIConstants.shared.KMAUILightButtonColor
bgView.layer.cornerRadius = 10
bgView.clipsToBounds = true
// Circle view
circleView.backgroundColor = KMAUIConstants.shared.KMAUIBlueDarkColorBarTint.withAlphaComponent(0.7)
circleView.layer.cornerRadius = 32
circleView.clipsToBounds = true
// Camera icon
cameraImageView.image = KMAUIConstants.shared.cameraIcon.withRenderingMode(.alwaysTemplate)
cameraImageView.tintColor = KMAUIConstants.shared.KMAUILightButtonColor
// Title label
titleLabel.font = KMAUIConstants.shared.KMAUIBoldFont.withSize(19)
// Info label
infoLabel.font = KMAUIConstants.shared.KMAUIRegularFont.withSize(12)
// Arrow image view
arrowImageView.backgroundColor = KMAUIConstants.shared.KMAUIDarkTextColor
arrowImageView.layer.cornerRadius = 12
arrowImageView.clipsToBounds = true
arrowImageView.image = KMAUIConstants.shared.arrowDown.withRenderingMode(.alwaysTemplate)
arrowImageView.tintColor = KMAUIConstants.shared.KMAUIMainBgColorReverse
// No standard selection required
selectionStyle = .none
}
override public func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
setupColors(highlight: selected)
}
override public func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
setupColors(highlight: highlighted)
}
public func setupColors(highlight: Bool) {
if highlight {
bgView.backgroundColor = KMAUIConstants.shared.KMAUILightButtonColor
} else {
bgView.backgroundColor = KMAUIConstants.shared.KMAUIMainBgColorReverse
}
}
public func setupCell() {
titleLabel.text = rowData.rowName
infoLabel.text = rowData.rowValue
infoLabel.setLineSpacing(lineSpacing: 1.2, lineHeightMultiple: 1.2)
if rowData.rowName == "Set a location" {
cameraImageView.image = KMAUIConstants.shared.pinIcon.withRenderingMode(.alwaysTemplate)
} else {
cameraImageView.image = KMAUIConstants.shared.cameraIcon.withRenderingMode(.alwaysTemplate)
}
}
}
| 34.74 | 108 | 0.675014 |
bb857b8aaca7d44e678c4def4c85848792a58112 | 434 | // RUN: %swift -typecheck %s -verify -D FOO -D BAR -target i386-apple-ios7.0 -D FOO -parse-stdlib
// RUN: %swift-ide-test -test-input-complete -source-filename=%s -target i386-apple-ios7.0
#if os(tvOS) || os(watchOS)
// This block should not parse.
// os(tvOS) or os(watchOS) does not imply os(iOS).
let i: Int = "Hello"
#endif
#if arch(i386) && os(iOS) && _runtime(_ObjC) && _endian(little)
class C {}
var x = C()
#endif
var y = x
| 28.933333 | 97 | 0.66129 |
562f9f28287ae517e8db064c59b028a1a75f671c | 1,403 | import XCTest
import class Foundation.Bundle
final class AutomaticTouchServiceTests: XCTestCase {
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
// Some of the APIs that we use below are available in macOS 10.13 and above.
guard #available(macOS 10.13, *) else {
return
}
let fooBinary = productsDirectory.appendingPathComponent("AutomaticTouchService")
let process = Process()
process.executableURL = fooBinary
let pipe = Pipe()
process.standardOutput = pipe
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
XCTAssertEqual(output, "Hello, world!\n")
}
/// Returns path to the built products directory.
var productsDirectory: URL {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return bundle.bundleURL.deletingLastPathComponent()
}
fatalError("couldn't find the products directory")
#else
return Bundle.main.bundleURL
#endif
}
static var allTests = [
("testExample", testExample),
]
}
| 29.229167 | 89 | 0.642195 |
22cd26112f755fa995c0d5f0f92390b7bfe39d92 | 895 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// ___COPYRIGHT___
//
// This file was generated by Project Xcode Templates
// Created by Wahyu Ady Prasetyo,
//
import Foundation
import UIKit
class AlertAppearance {
var titleColor = UIColor.black
var titleFont = UIFont.boldSystemFont(ofSize: 17)
var messageColor = UIColor.black
var messageFont = UIFont.systemFont(ofSize: 13)
var dismissText = "Cancel"
var dismissColor = UIColor(red: 0, green: 122/255, blue: 255/255, alpha: 1)
var okeText = "Submit"
var okeColor = UIColor(red: 0, green: 122/255, blue: 255/255, alpha: 1)
var buttonFont = UIFont.systemFont(ofSize: 17)
var backgroundColor = UIColor.white
var overlayColor = UIColor.black.withAlphaComponent(0.4)
var isBlurContainer = false
}
| 30.862069 | 82 | 0.675978 |
effa3a7cb008d71922a0d9dd8d96364b36da8c14 | 1,484 | //
// SettingsViewController.swift
// empatip
//
// Created by Nageshwar Bajamahal on 3/9/17.
// Copyright © 2017 Nageshwar Bajamahal. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var defaultTipControl: UISegmentedControl!
let defaults = UserDefaults.standard;
@IBAction func onTap(_ sender: AnyObject) {
defaults.set(defaultTipControl.selectedSegmentIndex, forKey: "defaultTipPercent")
defaults.synchronize()
//print("settings onTap index = %d",defaultTipControl.selectedSegmentIndex)
}
override func viewDidLoad() {
super.viewDidLoad()
defaultTipControl.selectedSegmentIndex =
defaults.integer(forKey: "defaultTipPercent")
//print("settings Load index= %d",
// defaults.integer(forKey: "defaultTipPercent"))
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 28.538462 | 106 | 0.674528 |
758173a4e530472c9aff12e55fa48295e0afa498 | 7,970 | // Copyright © 2018 Mindera. All rights reserved.
import Foundation
/// A type that logs messages with multiple possible severity levels, originating from configurable app modules.
public protocol ModuleLogger: Logger {
/// A type that represents any logical subsystems (modules) of your app you wish to log messages from.
/// Messages can be logged with or without a defined module. If defined, module filtering will be enabled for that
/// particular message (i.e. only messages whose log level is above a registered module's minumum log level will be
/// logged. Otherwise, no module filtering will be done.
associatedtype Module: LogModule
// MARK: - Logging
/// Logs a message from the specified module with the given level, alongside the file, function and line the log
/// originated from.
///
/// - Note:
/// The message should only be logged if the module is registered in the logger, and the log message's level is
/// *above* the module's registered minimum log level.
///
/// - Parameters:
/// - module: The module from which the message originated.
/// - level: The severity level of the message.
/// - message: The log message.
/// - file: The file from where the log was invoked.
/// - line: The line from where the log was invoked.
/// - function: The function from where the log was invoked.
func log(module: Module, // swiftlint:disable:this function_parameter_count
level: Log.Level,
message: @autoclosure () -> String,
file: StaticString,
line: UInt,
function: StaticString)
// MARK: - Modules
/// Registers a module in the logger with a minimum severity log level, taking it into account when filtering
/// any new log messages (if using the `ModuleLogger`'s `log` API, i.e. *with* `module` parameter).
///
/// - Note:
/// Module filtering works as follows:
///
/// A log message having a module parameter should only be logged _if the module is registered_ in the logger, and
/// the log message's level is *above* the module's registered minimum log level. On the other hand, if the message
/// is logged without module (i.e. using the `Logger`'s `log` API, i.e. *without* `module` parameter), no module
/// filtering should be made.
///
/// - Parameters:
/// - module: The module to be registered.
/// - minLevel: The minimum severity level required to be logged by the module.
func registerModule(_ module: Module, minLevel: Log.Level) throws
/// Unregisters a module from the logger, taking it into account when filtering any new log messages (if logged
/// using the `ModuleLogger`'s `log` API, i.e. *with* `module` parameter).
///
/// - SeeAlso: `registerModule(_:minLevel:)`
///
/// - Parameter module: The module to be unregistered.
func unregisterModule(_ module: Module) throws
}
public extension ModuleLogger {
/// Logs a `verbose` log level message from the specified module, alongside the file, function and line the log
/// originated from.
///
/// - Note:
/// The message should only be logged if the module is registered in the logger, and the log message's level is
/// *above* the module's registered minimum log level.
///
/// - Parameters:
/// - module: The module from which the message originated.
/// - message: The log message.
/// - file: The file from where the log was invoked.
/// - line: The line from where the log was invoked.
/// - function: The function from where the log was invoked.
func verbose(_ module: Module,
_ message: @autoclosure () -> String,
file: StaticString = #file,
line: UInt = #line,
function: StaticString = #function) {
log(module: module, level: .verbose, message: message, file: file, line: line, function: function)
}
/// Logs a `debug` log level message from the specified module, alongside the file, function and line the log
/// originated from.
///
/// - Note:
/// The message should only be logged if the module is registered in the logger, and the log message's level is
/// *above* the module's registered minimum log level.
///
/// - Parameters:
/// - module: The module from which the message originated.
/// - message: The log message.
/// - file: The file from where the log was invoked.
/// - line: The line from where the log was invoked.
/// - function: The function from where the log was invoked.
func debug(_ module: Module,
_ message: @autoclosure () -> String,
file: StaticString = #file,
line: UInt = #line,
function: StaticString = #function) {
log(module: module, level: .debug, message: message, file: file, line: line, function: function)
}
/// Logs an `info` log level message from the specified module, alongside the file, function and line the log
/// originated from.
///
/// - Note:
/// The message should only be logged if the module is registered in the logger, and the log message's level is
/// *above* the module's registered minimum log level.
///
/// - Parameters:
/// - module: The module from which the message originated.
/// - message: The log message.
/// - file: The file from where the log was invoked.
/// - line: The line from where the log was invoked.
/// - function: The function from where the log was invoked.
func info(_ module: Module,
_ message: @autoclosure () -> String,
file: StaticString = #file,
line: UInt = #line,
function: StaticString = #function) {
log(module: module, level: .info, message: message, file: file, line: line, function: function)
}
/// Logs a `warning` log level message from the specified module, alongside the file, function and line the log
/// originated from.
///
/// - Note:
/// The message should only be logged if the module is registered in the logger, and the log message's level is
/// *above* the module's registered minimum log level.
///
/// - Parameters:
/// - module: The module from which the message originated.
/// - message: The log message.
/// - file: The file from where the log was invoked.
/// - line: The line from where the log was invoked.
/// - function: The function from where the log was invoked.
func warning(_ module: Module,
_ message: @autoclosure () -> String,
file: StaticString = #file,
line: UInt = #line,
function: StaticString = #function) {
log(module: module, level: .warning, message: message, file: file, line: line, function: function)
}
/// Logs an `error` log level message from the specified module, alongside the file, function and line the log
/// originated from.
///
/// - Note:
/// The message should only be logged if the module is registered in the logger, and the log message's level is
/// *above* the module's registered minimum log level.
///
/// - Parameters:
/// - module: The module from which the message originated.
/// - message: The log message.
/// - file: The file from where the log was invoked.
/// - line: The line from where the log was invoked.
/// - function: The function from where the log was invoked.
func error(_ module: Module,
_ message: @autoclosure () -> String,
file: StaticString = #file,
line: UInt = #line,
function: StaticString = #function) {
log(module: module, level: .error, message: message, file: file, line: line, function: function)
}
}
| 45.284091 | 119 | 0.627854 |
f42e9837560c103d1678ceb3e470bb6880e4dcca | 5,264 | //
// Xcore
// Copyright © 2018 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
extension UIFont {
public enum LoaderError: Error {
case fontNotFound
case remoteFontUrlDetected
case failedToCreateFont
case failedToRegisterFont
case failedToUnregisterFont
}
/// Registers the font if it's not already registered with the font manager.
///
/// - Parameters:
/// - fontName: The font name to register.
/// - fontUrl: The local url where the font is located.
public static func registerIfNeeded(fontName: String, url fontUrl: URL) throws {
let name = fontName.deletingPathExtension
// Check if the given font is not already registered with font manager before
// attempting to register.
guard fontNames(forFamilyName: name).isEmpty else {
return
}
_ = try register(url: fontUrl, unregisterOldFirstIfExists: false)
}
/// Unregister the font if it's registered with the font manager.
///
/// - Parameters:
/// - fontName: The font name to unregister.
/// - fontUrl: The local url where the font is located.
public static func unregisterIfExists(fontName: String, url fontUrl: URL) throws {
let name = fontName.deletingPathExtension
// Check if the given font is registered with font manager before
// attempting to unregister.
guard !fontNames(forFamilyName: name).isEmpty else {
return
}
_ = try unregister(url: fontUrl)
}
/// Registers the font at given url with the font manager.
///
/// - Parameters:
/// - fontUrl: The font url to be registered.
/// - unregisterOldFirstIfExists: An option to unregister old font first if it exists.
/// This is useful if the same font is updated, then unregistering
/// the font from font manager first, then registering the new font again.
/// The default value is `false`.
/// - Returns: Returns the post script name of the font.
public static func register(url fontUrl: URL, unregisterOldFirstIfExists: Bool = false) throws -> String {
let (cgFont, fontName) = try metadata(from: fontUrl)
// Check if the given font is already registered with font manager.
let exists = !fontNames(forFamilyName: fontName).isEmpty
if exists {
if unregisterOldFirstIfExists {
try unregister(cgFont: cgFont, fontName: fontName)
} else {
Console.info("Font \"\(fontName)\" already registered.")
return fontName
}
}
var fontError: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(cgFont, &fontError) else {
if let fontError = fontError?.takeRetainedValue() {
let errorDescription = CFErrorCopyDescription(fontError)
Console.error("Failed to register font \"\(fontName)\" with font manager: \(String(describing: errorDescription))")
}
throw LoaderError.failedToRegisterFont
}
Console.info("Successfully registered font \"\(fontName)\".")
return fontName
}
/// Unregisters the font at given url with the font manager.
///
/// - Parameter fontUrl: The font url to be unregistered.
public static func unregister(url fontUrl: URL) throws {
let (cgFont, fontName) = try metadata(from: fontUrl)
try unregister(cgFont: cgFont, fontName: fontName)
}
/// Unregisters the specified font with the font manager.
///
/// - Parameter fontUrl: The font to be unregistered.
private static func unregister(cgFont: CGFont, fontName: String) throws {
// Check if the given font is registered with font manager before
// attempting to unregister.
guard !fontNames(forFamilyName: fontName).isEmpty else {
Console.info("Font \"\(fontName)\" isn't registered.")
return
}
var fontError: Unmanaged<CFError>?
CTFontManagerUnregisterGraphicsFont(cgFont, &fontError)
if let fontError = fontError?.takeRetainedValue() {
let errorDescription = CFErrorCopyDescription(fontError)
Console.error("Failed to unregister font \"\(fontName)\" with font manager: \(String(describing: errorDescription))")
throw LoaderError.failedToUnregisterFont
}
Console.info("Successfully unregistered font \"\(fontName)\".")
}
private static func metadata(from fontUrl: URL) throws -> (cgFont: CGFont, postScriptName: String) {
guard fontUrl.schemeType == .file else {
throw LoaderError.remoteFontUrlDetected
}
guard
let fontData = NSData(contentsOf: fontUrl),
let dataProvider = CGDataProvider(data: fontData),
let cgFont = CGFont(dataProvider),
let postScriptName = cgFont.postScriptName
else {
throw LoaderError.failedToCreateFont
}
let fontName = String(describing: postScriptName)
return (cgFont, fontName)
}
}
| 37.333333 | 131 | 0.628229 |
ccf67122f42ac17b093ec8204a659495b802615d | 862 | //
// marketDataLoader.swift
// MarketEats
//
// Created by Alexis Powell on 4/19/22.
//
import Foundation
public class marketDataLoader {
@Published var marketInfo = [MarketInfo]()
init(){
loadMarkets()
}
/*
Load the JSON Data
*/
func loadMarkets(){
if let fileLocation = Bundle.main.url(forResource: "markets", withExtension: "json"){
//do catch
do {
let marketData = try Data(contentsOf: fileLocation)
let jsonDecoder = JSONDecoder()
let dataFromJson = try jsonDecoder.decode([MarketInfo].self, from: marketData)
self.marketInfo = dataFromJson
}catch{
print(error)
}
}
}
}
| 20.52381 | 94 | 0.491879 |
50563f6a8480f4e1652deefaf027542b54331b4f | 2,948 | //
// TweetsViewController.swift
// Twitter
//
// Created by Luis Rocha on 4/16/17.
// Copyright © 2017 Luis Rocha. All rights reserved.
//
import UIKit
import MBProgressHUD
class TweetsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var tweets = [Tweet]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
// initialize a UIRefreshControl
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(TweetsViewController.refreshControlAction(_:)), for: UIControlEvents.valueChanged)
tableView.insertSubview(refreshControl, at: 0)
refreshControlAction(refreshControl)
}
func refreshControlAction(_ refreshControl: UIRefreshControl) {
MBProgressHUD.showAdded(to: self.view, animated: true)
TwitterClient.sharedInstance.homeTimeLine(success: { (tweets: [Tweet]) in
self.tweets = tweets
self.tableView.reloadData()
MBProgressHUD.hide(for: self.view, animated: true)
refreshControl.endRefreshing()
}) { (error: Error) in
print(error.localizedDescription)
MBProgressHUD.hide(for: self.view, animated: true)
refreshControl.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TweetCell
cell.tweet = tweets[indexPath.item]
// cell.selectionStyle = .none
return cell
}
@IBAction func onLogoutButton(_ sender: Any) {
TwitterClient.sharedInstance.logout()
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Pass the selected object to the new view controller.
let navigationController = segue.destination as! UINavigationController
// Pass the selected object to the new view controller.
if let tweetDetailsViewController = navigationController.topViewController as? TweetDetailsViewController {
// Set the model for the details view controller
let cel = sender as! TweetCell
tweetDetailsViewController.tweet = cel.tweet
}
}
}
| 36.395062 | 139 | 0.675373 |
fbb94fa7469df225353b1b31b24853dcd3ad9329 | 1,745 | // Copyright 2022 Pera Wallet, LDA
// 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.
//
// AssetDisplayViewModel.swift
import UIKit
import MacaroonUIKit
final class AssetDisplayViewModel: PairedViewModel {
private(set) var isVerified: Bool = false
private(set) var name: String?
private(set) var code: String?
init(
_ model: AssetDecoration?
) {
if let assetDetail = model {
bindVerified(assetDetail)
bindName(assetDetail)
bindCode(assetDetail)
}
}
}
extension AssetDisplayViewModel {
private func bindVerified(
_ assetDetail: AssetDecoration
) {
isVerified = assetDetail.isVerified
}
private func bindName(
_ assetDetail: AssetDecoration
) {
let displayNames = assetDetail.displayNames
if !displayNames.primaryName.isUnknown() {
name = displayNames.primaryName
}
}
private func bindCode(
_ assetDetail: AssetDecoration
) {
let displayNames = assetDetail.displayNames
if displayNames.primaryName.isUnknown() {
code = displayNames.primaryName
} else {
code = displayNames.secondaryName
}
}
}
| 26.846154 | 75 | 0.666476 |
e9c9b628e5cb63a53bb7dd201d9d06f197e84541 | 1,600 | //
// Formatter.swift
// Snack
//
// Created by Taylor Maxwell on 11/8/19.
// Copyright © 2019 Taylor Maxwell. All rights reserved.
//
import Foundation
// Handles issues with formatting dates
// Original Idea from this link: https://useyourloaf.com/blog/swift-codable-with-custom-dates/
extension Formatter {
// Handles normal dates with subseconds
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:ss.SSSZZZZZ"
return formatter
}()
// Handles dates with no sub seconds
// Notice the missing.SSS
static let missingSS: 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:ssZZZZZ"
return formatter
}()
/// Takes a date string and returns as date
/// - Parameter dateString: date string to be converted
static func stringToDate(dateString: String) -> Date {
if dateString.contains(".") {
if let date = Formatter.iso8601.date(from: dateString) as Date? {
return date
}
} else {
if let date = Formatter.missingSS.date(from: dateString) as Date? {
return date
}
}
return Date(timeIntervalSince1970: 0)
}
}
| 27.118644 | 94 | 0.669375 |
1c0d2e62837812056a4ed5b9a6ae413540e04b2c | 1,246 | /**
* Protocol for view events.
**/
public protocol IKViewEvent: IKDataObject {
/**
* The type of the view event.
**/
var type: String { set get }
/**
* The title of the view controller.
**/
var viewControllerTitle: String { set get }
/**
* The type of the view controller.
**/
var viewControllerType: String { set get }
/**
* The specific instance of the view controller.
**/
var viewControllerInstance: String { set get }
/**
* The width of the view.
**/
var viewWidth: Double { set get }
/**
* The height of the view.
**/
var viewHeight: Double { set get }
/**
* The origin x value of the view.
**/
var viewOriginX: Double { set get }
/**
* The origin y value of the view.
**/
var viewOriginY: Double { set get }
/**
* The global origin x value of the view.
**/
var globalViewOriginX: Double { set get }
/**
* The global origin x value of the view.
**/
var globalViewOriginY: Double { set get }
/**
* The amount of subviews.
**/
var subviewCount: Int { set get }
}
| 20.42623 | 54 | 0.516854 |
ff3fe75e68581b14099133d7901e0e43c59bbb74 | 1,972 | //
// UIScreenType.swift
// UIOnboarding Example
//
// Created by Lukman Aščić on 14.02.22.
//
import UIKit
struct UIScreenType {
static let isiPhoneSE = UIDevice.current.userInterfaceIdiom == .phone &&
UIScreen.main.nativeBounds.height == 1136
static let isiPhone6s = UIDevice.current.userInterfaceIdiom == .phone &&
UIScreen.main.nativeBounds.height == 1334
static let isiPhone6sPlus = UIDevice.current.userInterfaceIdiom == .phone &&
UIScreen.main.nativeBounds.height == 2208
static let isiPhone12Mini = UIDevice.current.userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height == 2340
static func setUpTopStackMultiplier() -> CGFloat {
if UIScreenType.isiPhoneSE || UIScreenType.isiPhone6s || UIScreenType.isiPhone6sPlus || UIScreenType.isiPhone12Mini {
return 0.15
} else {
return 0.12
}
}
static func setUpTopSpacing() -> CGFloat {
if UIScreenType.isiPhoneSE || UIScreenType.isiPhone6s || UIScreenType.isiPhone6sPlus {
return 70
} else {
return 120
}
}
static func setUpTitleSpacing() -> CGFloat {
if UIScreenType.isiPhoneSE || UIScreenType.isiPhone6s || UIScreenType.isiPhone12Mini {
return 20
} else {
return 40
}
}
static func setUpPadding() -> CGFloat {
if UIScreenType.isiPhoneSE {
return 30
} else if UIScreenType.isiPhone6s || UIScreenType.isiPhone12Mini {
return 50
} else {
return 60
}
}
static func setUpButtonPadding() -> CGFloat {
if UIScreenType.isiPhoneSE {
return 20
} else if UIScreenType.isiPhone6s || UIScreenType.isiPhone12Mini {
return 40
} else {
return 60
}
}
}
| 29.878788 | 125 | 0.584178 |
b9691b650023d90bd0a081a8ecfe1a915d2f0098 | 195 | //
// ChannelDB+CoreDataClass.swift
//
//
// Created by Марат Джаныбаев on 27.10.2020.
//
//
import Foundation
import CoreData
@objc(ChannelDB)
public class ChannelDB: NSManagedObject {
}
| 12.1875 | 45 | 0.707692 |
4812c0e7abd1da0175f847c51d54ec014ab9aa4f | 415 | import TMDBSwift
import XCTest
final class TMDBMoviesTest: XCTestCase {
private let tmdb = TMDB(apiKey: "my_awesome_api_key")
func testTMDBMovies_images_toJSONToModel() {
let images = createMovieImagesMock()
XCTAssertEqual(images.identifier, 550)
}
func testTMDBMovies_imagesPath_buildCorrect() {
let path = Movies.images(movieId: 56).path
XCTAssertEqual(path, "movie/56/images")
}
}
| 21.842105 | 55 | 0.746988 |
e80f079f89fa76963e7dca3bd2ed50b710ed7cee | 247 | //
// FoodItemTableViewCell.swift
// MetabolicCompassNutritionManager
//
// Created by Edwin L. Whitman on 7/21/16.
// Copyright © 2016 Edwin L. Whitman. All rights reserved.
//
import UIKit
class FoodItemTableViewCell: UITableViewCell {
}
| 17.642857 | 59 | 0.736842 |
5dbf2e90f502c87ba64be754e7d2d83696fb25b1 | 656 | //
// String.swift
// SurfPlaybook
//
// Created by Александр Чаусов on 15.04.2021.
// Copyright © 2021 Surf. All rights reserved.
//
extension String {
/// Возвращает строку, либо nil, если она пуста
func normalized() -> String? {
return self.isEmpty ? nil : self
}
/// Возвращает `true`, если в строке содержится переданная подстрока
/// При этом не учитывается регистр букв
func containsCaseInsensitive(string: String) -> Bool {
let searchRange = self.startIndex..<self.endIndex
let range = self.range(of: string, options: .caseInsensitive, range: searchRange)
return range != nil
}
}
| 26.24 | 89 | 0.655488 |
1ea4b510d947199c048f265447e4e02bf036f30e | 807 | //
// DetailViewController.swift
// WXCP_Tinder
//
// Created by Will Xu on 10/25/18.
// Copyright © 2018 Will Xu . All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var picView: UIImageView!
var image: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
self.picView.image = self.image
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 24.454545 | 106 | 0.662949 |
ff19c78ea25976fc6d31a2b84356ae6cae44bb33 | 2,468 | //
// 20. Set Matrix Zeroes.swift
// leetCode
//
// Created by czw on 7/20/20.
// Copyright © 2020 czw. All rights reserved.
//
import Foundation
/*
给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
示例 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
进阶:
一个直接的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。
一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
你能想出一个常数空间的解决方案吗?
分析:
1. 所有 row 中有 0 的索引
2. 找到 col 中有 0 的索引
*/
class SetMatrixZeroes {
func setZeroes(_ matrix: inout [[Int]]) {
var rowSet = Set<Int>()
var colSet = Set<Int>()
for (i,row) in matrix.enumerated() {
for (j, v) in row.enumerated() {
if v == 0 {
rowSet.insert(i)
colSet.insert(j)
}
}
}
for (i,row) in matrix.enumerated() {
if rowSet.contains(i) {
for (j, _) in row.enumerated() {
matrix[i][j] = 0
}
continue
}
for (j, _) in row.enumerated() {
if colSet.contains(j) {
matrix[i][j] = 0
}
}
}
}
func setZeroes_(_ matrix: inout [[Int]]) {
var zeroRow = false
var zeroColumn = false
for i in 0 ..< matrix.count {
for j in 0 ..< matrix[i].count {
if matrix[i][j] == 0 {
if i == 0 { zeroRow = true }
if j == 0 { zeroColumn = true }
matrix[0][j] = 0
matrix[i][0] = 0
}
}
}
for j in 1..<matrix[0].count {
if matrix[0][j] == 0 {
for i in 0 ..< matrix.count {
matrix[i][j] = 0
}
}
}
for i in 1..<matrix.count {
if matrix[i][0] == 0 {
for j in 0 ..< matrix[i].count {
matrix[i][j] = 0
}
}
}
if zeroRow {
for j in 0..<matrix[0].count {
matrix[0][j] = 0
}
}
if zeroColumn {
for i in 0..<matrix.count {
matrix[i][0] = 0
}
}
}
}
extension SetMatrixZeroes: Algorithm {
func doTest() {
var m = [
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
performLogCostTime(self.name + " method1") {
setZeroes(&m)
print(m)
}
m = [
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
performLogCostTime(self.name + " method2") {
setZeroes(&m)
print(m)
}
}
}
| 17.628571 | 53 | 0.447731 |
e6b6840d4272e77872c72fbaf7b858838e7fe0c1 | 5,242 | //
// FaceVerification.swift
// FaceTec
//
// Created by Alex Serdukov on 24.12.2020.
// Copyright © 2020 Facebook. All rights reserved.
//
import Foundation
class FaceVerification {
// singletone instance
static let shared = FaceVerification()
private var serverURL: String?
private var jwtAccessToken: String?
private var lastRequest: URLSessionTask?
private let succeedProperty = "success"
private let errorMessageProperty = "error"
private let sessionTokenProperty = "sessionToken"
private init() {}
func register(_ serverURL: String, _ jwtAccessToken: String) -> Void {
self.serverURL = serverURL
self.jwtAccessToken = jwtAccessToken
}
func getSessionToken(sessionTokenCallback: @escaping (String?, Error?) -> Void) -> Void {
request("/verify/face/session", "GET", [:]) { response, error in
if error != nil {
sessionTokenCallback(nil, error)
return
}
guard let sessionToken = response?[self.sessionTokenProperty] as? String else {
sessionTokenCallback(nil, FaceVerificationError.emptyResponse)
return
}
sessionTokenCallback(sessionToken, nil)
}
}
func enroll(
_ enrollmentIdentifier: String,
_ payload: [String : Any],
enrollmentResultCallback: @escaping ([String: AnyObject]?, Error?) -> Void
) -> Void {
enroll(enrollmentIdentifier, payload, withDelegate: nil, callback: enrollmentResultCallback)
}
func enroll(
_ enrollmentIdentifier: String,
_ payload: [String : Any],
withDelegate: URLSessionDelegate? = nil,
callback enrollmentResultCallback: @escaping ([String: AnyObject]?, Error?) -> Void
) -> Void {
let enrollmentUri = "/verify/face/" + enrollmentIdentifier.urlEncoded()
request(enrollmentUri, "PUT", payload, withDelegate) { response, error in
enrollmentResultCallback(response, error)
}
}
func cancelInFlightRequests() {
if lastRequest != nil {
lastRequest!.cancel()
lastRequest = nil
}
}
private func request(
_ url: String,
_ method: String,
_ parameters: [String : Any] = [:],
_ resultCallback: @escaping ([String: AnyObject]?, Error?) -> Void
) -> Void {
request(url, method, parameters, nil, resultCallback)
}
private func request(
_ url: String,
_ method: String,
_ parameters: [String : Any] = [:],
_ withDelegate: URLSessionDelegate? = nil,
_ resultCallback: @escaping ([String: AnyObject]?, Error?) -> Void
) {
let config = URLSessionConfiguration.default
let request = createRequest(url, method, parameters)
let session = withDelegate == nil ? URLSession(configuration: config)
: URLSession(configuration: config, delegate: withDelegate, delegateQueue: OperationQueue.main)
lastRequest = session.dataTask(with: request as URLRequest) { data, response, httpError in
self.lastRequest = nil
if httpError != nil {
resultCallback(nil, httpError)
return
}
guard let json = self.parseResponse(data) else {
resultCallback(nil, FaceVerificationError.unexpectedResponse)
return
}
if (json[self.succeedProperty] as! Bool == false) {
let errorMessage = json[self.errorMessageProperty] as? String
let error: FaceVerificationError = errorMessage == nil ? .unexpectedResponse : .failedResponse(errorMessage!)
resultCallback(json, error)
return
}
resultCallback(json, nil)
}
lastRequest!.resume()
}
private func createRequest(_ url: String, _ method: String, _ parameters: [String : Any] = [:]) -> URLRequest {
let request = NSMutableURLRequest(url: NSURL(string: serverURL! + url)! as URL)
request.httpMethod = method.uppercased()
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer " + jwtAccessToken!, forHTTPHeaderField: "Authorization")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions(rawValue: 0))
return request as URLRequest
}
private func parseResponse(_ data: Data?) -> [String: AnyObject]? {
guard let data = data else {
return nil
}
guard let json = try? JSONSerialization.jsonObject(
with: data,
options: JSONSerialization.ReadingOptions.allowFragments
) as? [String: AnyObject] else {
return nil
}
if !(json[succeedProperty] is Bool) {
return nil
}
return json
}
}
| 33.819355 | 138 | 0.583747 |
1c173ae9ed45171d0f25a445f62403d98cd39efd | 5,605 | //
// ContentView.swift
// Time-Mk-Menu-bar
//
// Created by Matej Plavevski on 8/25/20.
// Copyright © 2020 Matej Plavevski. All rights reserved.
//
import SwiftUI
import AppKit
import SwiftyXMLParser
import SwiftSoup
import URLImage
struct ContentView: View {
@State private var results = [NewsPiece]()
@State private var selectedFeed = 0
@State private var showingAlert = false
@State private var errorMessage = ""
var NewsFeedTitles = Array(rss_feeds.orderedKeys)
//var selectedTitle = rss_feeds[self.NewsFeedTitles[self.selectedFeed]]
var body: some View {
VStack {
VStack {
Text("Тајм.Мк - Топ вести").font(.headline).padding(.top,10)
HStack{
Picker(selection: $selectedFeed.onChange(updateFeedFromPickerSelection), label: Text("Категорија:").font(.system(size: 12))) {
ForEach(0 ..< NewsFeedTitles.count) {
Text(self.NewsFeedTitles[$0]).tag($0)
}
}
Button(action: {self.loadData(feed: rss_feeds[self.NewsFeedTitles[self.selectedFeed]]!)}){
Text("Освежи вести")
.font(.caption)
.fontWeight(.semibold)
}
Button(action: {
NSApplication.shared.terminate(self)
})
{
//Image(systemName: "power")
Image("Power").resizable().scaledToFit()
}
}.padding(.trailing, 10).padding(.leading, 10)
}
// use geometry reader to fix list content width
GeometryReader { gp in
List(self.results, id: \.title) { item in
VStack(alignment: .leading) {
//URLImage(URL(string:item.image)!)
Text(item.title)
.font(.headline).padding(.vertical, 5)
Text(item.description).padding(.top, 5)
HStack{
Button(action: {
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([.string], owner: nil)
pasteboard.setString(item.article_url.absoluteString, forType: .string)
}){
Text("Копирај")
}
Button(action: {
NSWorkspace.shared.open(item.article_url)
}){
Text("Отвори")
}
}
}.frame(width: gp.size.width) // << here !!
}.onAppear(perform: {
self.loadData(feed: rss_feeds[self.NewsFeedTitles[self.selectedFeed]]!);
}).alert(isPresented: self.$showingAlert){
Alert(title: Text("Се случи грешка!"), message: Text(self.errorMessage), dismissButton: .default(Text("Во ред")))
}
}
}
}
func updateFeedFromPickerSelection(_ tag: Int) {
// https://stackoverflow.com/questions/57518852/swiftui-picker-onchange-or-equivalent
self.loadData(feed: rss_feeds[self.NewsFeedTitles[tag]]!)
print("Color tag: \(tag)")
}
func loadData(feed: String) {
var temp = [NewsPiece]()
guard let url = URL(string: feed) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
let xml = XML.parse(data)
let accessor = xml["rss"]["channel"]["item"]
for news_piece in accessor {
let title = news_piece["title"].text!
let description = news_piece["description"].text!
do {
let doc: Document = try SwiftSoup.parse(description)
//let image = try doc.select("img").first()!.attr("src")
let url = news_piece["link"].text!
print(url)
let news_content = try doc.select("td")[1].text()
print(news_content)
temp.append(
NewsPiece(
title: title,
description: news_content,
//image: image,
article_url: URL(string: url) ?? URL(string: "https://google.com")!
)
)
} catch {
print("Error scraping...")
}
}
DispatchQueue.main.async {
// update our UI
self.results = temp
}
return
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
self.errorMessage = error?.localizedDescription ?? "Непозната грешка"
self.showingAlert = true
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 38.390411 | 146 | 0.458162 |
228a49e7283465699200bbcafce89f386302e28e | 2,660 | //
// Network.swift
// Grailed
//
// Created by Andrew Copp on 9/9/17.
// Copyright © 2017 Andrew Copp. All rights reserved.
//
import Foundation
import StoreType
public class HTTP {
let host: String
let urlSession: URLSession
public init(host: String) {
self.host = host
let configuration: URLSessionConfiguration = URLSessionConfiguration.default
self.urlSession = URLSession(configuration: configuration)
}
}
extension HTTP: AsynchronousStoreType {
public func read(requests: ReadRequestsType, completion: @escaping (ReadResponsesType) -> ()) {
if requests.requests().count != 1 {
// TODO - Batching
return
}
requests.requests().forEach() { request in
var url: URL = URL(string: self.host)!
switch requests.model() {
case "articles":
url = url.appendingPathComponent("articles").appendingPathComponent("ios_index")
case "searches":
url = url.appendingPathComponent("merchandise").appendingPathComponent("marquee")
default:
url = url.appendingPathComponent(requests.model())
}
var urlRequest: URLRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
self.urlSession.dataTask(with: urlRequest) { optionalData, optionalResponse, optionalError in
if let error: Error = optionalError {
print(error)
}
guard let data: Data = optionalData else {
return
}
let optionalJSON: JSONDictionary?
do {
optionalJSON = try JSONSerialization.jsonObject(with: data, options: []) as? JSONDictionary
} catch {
print(error)
return
}
guard let json: JSONArray = optionalJSON?["data"] as? JSONArray else {
return
}
let responses: [ReadResponseType] = [ReadResponse(objects: json)]
let response: ReadResponsesType = ReadResponses(responses: responses)
completion(response)
}.resume()
}
}
public func write(requests: WriteRequestsType, completion: @escaping (WriteResponsesType) -> ()) {
}
}
| 29.88764 | 111 | 0.518045 |
03947bb3a13660027189cc0bddc651922a6e5ece | 1,872 | //
// SingleLineTableViewCell.swift
// Berkie
//
// Created by Gina De La Rosa on 9/10/18.
// Copyright © 2018 Gina De La Rosa. All rights reserved.
//
import UIKit
import Charts
class SingleLineTableViewCell: UITableViewCell {
@IBOutlet weak var singleLineView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func createChart() {
//Data point setup
var dataEntries: [ChartDataEntry] = []
for i in 0..<months.count {
let dataEntry = ChartDataEntry.init(x: Double(i), y: moneySavedOverMonths[i])
dataEntries.append(dataEntry)
}
//Configure settings for the line
let chartDataSet = LineChartDataSet.init(values: dataEntries, label: "Budget Goals")
chartDataSet.colors = [UIColor(red: 137/255, green: 4/255, blue: 61/255, alpha: 1)]
chartDataSet.circleRadius = 2.0
chartDataSet.circleColors = [UIColor.gray]
let chartData = LineChartData(dataSet: chartDataSet)
//Axis setup
let singleLineGraph = LineChartView()
singleLineGraph.frame = CGRect(x: 0, y: 0, width: singleLineView.bounds.width, height: singleLineView.bounds.height)
singleLineGraph.xAxis.valueFormatter = IndexAxisValueFormatter(values:months)
singleLineGraph.xAxis.labelPosition = .bottom
singleLineGraph.chartDescription?.text = ""
singleLineGraph.rightAxis.enabled = false
singleLineGraph.xAxis.drawGridLinesEnabled = false
singleLineGraph.leftAxis.drawGridLinesEnabled = false
singleLineGraph.leftAxis.drawLabelsEnabled = true
singleLineGraph.data = chartData
singleLineGraph.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)
singleLineView.addSubview(singleLineGraph)
}
}
| 34.666667 | 124 | 0.667735 |
c13f0c1ac3ff66722df709ffb0cca98816a3247e | 21,577 | /*╔══════════════════════════════════════════════════════════════════════════════════════════════════╗
║ ThreeLineElementTests.swift ║
║ ║
║ Created by Gavin Eadie on May05/19 Copyright 2019-20 Ramsay Consulting. All rights reserved. ║
╚══════════════════════════════════════════════════════════════════════════════════════════════════╝*/
import XCTest
@testable import SatelliteKit
#if canImport(XMLCoder)
import XMLCoder
#endif
class ThreeLineElementTests: XCTestCase {
func testNullLine0() {
do {
let tle = try TLE("",
"1 00000 57001 98001.00000000 .00000000 00000-0 00000-0 0 0000",
"2 00000 0.0000 0.0000 0000000 0.0000 0.0000 15.00000000 00000")
print(Satellite(withTLE: tle).debugDescription())
XCTAssertEqual(tle.t₀, 17533.000) // the TLE t=0 time (days from 1950)
XCTAssertEqual(tle.e₀, 0.0) // TLE .. eccentricity
XCTAssertEqual(tle.M₀, 0.0) // Mean anomaly (rad).
XCTAssertEqual(tle.n₀, 0.0653602440158348,
accuracy: 1e-12) // Mean motion (rads/min) << [un'Kozai'd]
print("mean altitude (Kms): \((tle.a₀ - 1.0) * EarthConstants.Rₑ)")
XCTAssertEqual(tle.i₀, 0.0) // TLE .. inclination (rad).
XCTAssertEqual(tle.ω₀, 0.0) // Argument of perigee (rad).
XCTAssertEqual(tle.Ω₀, 0.0) // Right Ascension of the Ascending node (rad).
} catch {
print(error)
}
}
func testIndexedLine0() {
do {
let tle = try TLE("0 ZERO OBJECT",
"1 00000 57001 98001.00000000 .00000000 00000-0 00000-0 0 0000",
"2 00000 0.0000 0.0000 0000000 0.0000 0.0000 15.00000000 00000")
print(Satellite(withTLE: tle).debugDescription())
XCTAssertEqual(tle.t₀, 17533.000) // the TLE t=0 time (days from 1950)
XCTAssertEqual(tle.e₀, 0.0) // TLE .. eccentricity
XCTAssertEqual(tle.M₀, 0.0) // Mean anomaly (rad).
XCTAssertEqual(tle.n₀, 0.0653602440158348,
accuracy: 1e-12) // Mean motion (rads/min) << [un'Kozai'd]
XCTAssertEqual(tle.i₀, 0.0) // TLE .. inclination (rad).
XCTAssertEqual(tle.ω₀, 0.0) // Argument of perigee (rad).
XCTAssertEqual(tle.Ω₀, 0.0) // Right Ascension of the Ascending node (rad).
} catch {
print(error)
}
}
func testNoIndexTLE() {
do {
let tle = try TLE("ZERO OBJECT",
"1 00000 57001 98001.00000000 .00000000 00000-0 00000-0 0 0000",
"2 00000 0.0000 0.0000 0000000 0.0000 0.0000 15.00000000 00000")
print(Satellite(withTLE: tle).debugDescription())
XCTAssertEqual(tle.t₀, 17533.000) // the TLE t=0 time (days from 1950)
XCTAssertEqual(tle.e₀, 0.0) // TLE .. eccentricity
XCTAssertEqual(tle.M₀, 0.0) // Mean anomaly (rad).
XCTAssertEqual(tle.n₀, 0.0653602440158348,
accuracy: 1e-12) // Mean motion (rads/min) << [un'Kozai'd]
XCTAssertEqual(tle.i₀, 0.0) // TLE .. inclination (rad).
XCTAssertEqual(tle.ω₀, 0.0) // Argument of perigee (rad).
XCTAssertEqual(tle.Ω₀, 0.0) // Right Ascension of the Ascending node (rad).
} catch {
print(error)
}
}
func testSuccessFormatTLE() {
XCTAssertTrue(formatOK("1 25544U 98067A 17108.89682041 .00002831 00000-0 50020-4 0 9990",
"2 25544 51.6438 333.8309 0007185 71.6711 62.5473 15.54124690 52531"))
}
/*┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
│ line 1 has no leading "1" │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘*/
func testFailureFormatTLE1() {
XCTAssertFalse(formatOK("X 25544U 98067A 17108.89682041 .00002831 00000-0 50020-4 0 9990",
"2 25544 51.6438 333.8309 0007185 71.6711 62.5473 15.54124690 52531"))
}
/*┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
│ line 1 has no leading "1" (blank) │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘*/
func testFailureFormatTLE2() {
XCTAssertFalse(formatOK(" 25544U 98067A 17108.89682041 .00002831 00000-0 50020-4 0 9990",
"2 25544 51.6438 333.8309 0007185 71.6711 62.5473 15.54124690 52531"))
}
/*┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
│ line 1 has bad checksum │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘*/
func testFailureFormatTLE3() {
XCTAssertFalse(formatOK("1 25544U 98067A 17108.89682041 .00002831 00000-0 50020-4 0 9991",
"2 25544 51.6438 333.8309 0007185 71.6711 62.5473 15.54124690 52531"))
}
/*┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
│ line 1 has bad length │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘*/
func testFailureFormatTLE4() {
XCTAssertFalse(formatOK("1 25544U 98067A 17108.89682041 .00002831 00000-0 50020-4 0 9991",
"2 25544 51.6438 333.8309 0007185 71.6711 62.5473 15.54124690 52531"))
}
/*┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
│ line 1 has non-zero ephemeris type │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘*/
func testFailureNonZeroEphemType() {
XCTAssertTrue(formatOK("1 44433U 19040B 19196.49919926 .00000000 00000-0 00000-0 2 5669",
"2 44433 052.6278 127.6338 9908875 004.4926 008.9324 00.01340565 01"))
do {
let tle = try TLE("Spektr-RG Booster",
"1 44433U 19040B 19196.49919926 .00000000 00000-0 00000-0 2 5669",
"2 44433 052.6278 127.6338 9908875 004.4926 008.9324 00.01340565 01")
print(Satellite(withTLE: tle).debugDescription())
} catch {
print(error)
}
}
func testTleAccess() {
let sat = Satellite("ISS (ZARYA)",
"1 25544U 98067A 17108.89682041 .00002831 00000-0 50020-4 0 9990",
"2 25544 51.6438 333.8309 0007185 71.6711 62.5473 15.54124690 52531")
print("Mean motion:", sat.tle.n₀)
}
func testJsonTLE() {
let jsonData = """
{"OBJECT_NAME":"XINGYUN-2 01",
"OBJECT_ID":"2020-028A",
"EPOCH":"2020-06-03T21:51:26.358336",
"MEAN_MOTION":15.00667713,
"ECCENTRICITY":0.0011896,
"INCLINATION":97.5563,
"RA_OF_ASC_NODE":186.395,
"ARG_OF_PERICENTER":178.0873,
"MEAN_ANOMALY":235.0112,
"EPHEMERIS_TYPE":0,
"CLASSIFICATION_TYPE":"U",
"NORAD_CAT_ID":45602,
"ELEMENT_SET_NO":999,
"REV_AT_EPOCH":343,
"BSTAR":7.4303e-5,
"MEAN_MOTION_DOT":8.83e-6,
"MEAN_MOTION_DDOT":0}
""".data(using: .utf8)!
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601Micros)
do {
let tle = try jsonDecoder.decode(TLE.self, from: jsonData)
print(Satellite(withTLE: tle).debugDescription())
} catch {
print(error)
}
}
func testJsonTLEArray() {
let jsonData = """
[{
"OBJECT_NAME": "ATLAS CENTAUR 2",
"OBJECT_ID": "1963-047A",
"EPOCH": "2020-06-05T19:21:58.044384",
"MEAN_MOTION": 14.0260002,
"ECCENTRICITY": 0.0585625,
"INCLINATION": 30.3559,
"RA_OF_ASC_NODE": 314.9437,
"ARG_OF_PERICENTER": 85.6228,
"MEAN_ANOMALY": 281.1015,
"EPHEMERIS_TYPE": 0,
"CLASSIFICATION_TYPE": "U",
"NORAD_CAT_ID": 694,
"ELEMENT_SET_NO": 999,
"REV_AT_EPOCH": 83546,
"BSTAR": 2.8454e-5,
"MEAN_MOTION_DOT": 3.01e-6,
"MEAN_MOTION_DDOT": 0
},{
"OBJECT_NAME": "THOR AGENA D R/B",
"OBJECT_ID": "1964-002A",
"EPOCH": "2020-06-05T17:39:55.010304",
"MEAN_MOTION": 14.32395649,
"ECCENTRICITY": 0.0032737,
"INCLINATION": 99.0129,
"RA_OF_ASC_NODE": 48.8284,
"ARG_OF_PERICENTER": 266.0175,
"MEAN_ANOMALY": 93.7265,
"EPHEMERIS_TYPE": 0,
"CLASSIFICATION_TYPE": "U",
"NORAD_CAT_ID": 733,
"ELEMENT_SET_NO": 999,
"REV_AT_EPOCH": 93714,
"BSTAR": 2.6247e-5,
"MEAN_MOTION_DOT": 2.3e-7,
"MEAN_MOTION_DDOT": 0
},{
"OBJECT_NAME": "SL-3 R/B",
"OBJECT_ID": "1964-053B",
"EPOCH": "2020-06-05T20:39:17.038368",
"MEAN_MOTION": 14.59393422,
"ECCENTRICITY": 0.0055713,
"INCLINATION": 65.0789,
"RA_OF_ASC_NODE": 2.8558,
"ARG_OF_PERICENTER": 32.0461,
"MEAN_ANOMALY": 328.4005,
"EPHEMERIS_TYPE": 0,
"CLASSIFICATION_TYPE": "U",
"NORAD_CAT_ID": 877,
"ELEMENT_SET_NO": 999,
"REV_AT_EPOCH": 95980,
"BSTAR": 7.6135e-6,
"MEAN_MOTION_DOT": -8.4e-7,
"MEAN_MOTION_DDOT": 0
}]
""".data(using: .utf8)!
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601Micros)
do {
let tleArray = try jsonDecoder.decode([TLE].self, from: jsonData)
print(Satellite(withTLE: tleArray[0]).debugDescription())
print(Satellite(withTLE: tleArray[1]).debugDescription())
print(Satellite(withTLE: tleArray[2]).debugDescription())
} catch {
print(error)
}
}
#if canImport(XMLCoder)
func testXmlTLEArray() {
let xmlData = """
<ndm xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://sanaregistry.org/r/ndmxml/ndmxml-1.0-master.xsd">
<omm>
<header>
<CREATION_DATE/>
<ORIGINATOR/>
</header>
<body>
<segment>
<metadata>
<OBJECT_NAME>ATLAS CENTAUR 2</OBJECT_NAME>
<OBJECT_ID>1963-047A</OBJECT_ID>
<CENTER_NAME>EARTH</CENTER_NAME>
<REF_FRAME>TEME</REF_FRAME>
<TIME_SYSTEM>UTC</TIME_SYSTEM>
<MEAN_ELEMENT_THEORY>SGP4</MEAN_ELEMENT_THEORY>
</metadata>
<data>
<meanElements>
<EPOCH>2020-06-06T10:44:23.559360</EPOCH>
<MEAN_MOTION>14.02600247</MEAN_MOTION>
<ECCENTRICITY>.0585615</ECCENTRICITY>
<INCLINATION>30.3558</INCLINATION>
<RA_OF_ASC_NODE>311.4167</RA_OF_ASC_NODE>
<ARG_OF_PERICENTER>91.1851</ARG_OF_PERICENTER>
<MEAN_ANOMALY>275.5862</MEAN_ANOMALY>
</meanElements>
<tleParameters>
<EPHEMERIS_TYPE>0</EPHEMERIS_TYPE>
<CLASSIFICATION_TYPE>U</CLASSIFICATION_TYPE>
<NORAD_CAT_ID>694</NORAD_CAT_ID>
<ELEMENT_SET_NO>999</ELEMENT_SET_NO>
<REV_AT_EPOCH>83555</REV_AT_EPOCH>
<BSTAR>.28591E-4</BSTAR>
<MEAN_MOTION_DOT>3.03E-6</MEAN_MOTION_DOT>
<MEAN_MOTION_DDOT>0</MEAN_MOTION_DDOT>
</tleParameters>
</data>
</segment>
</body>
</omm>
<omm>
<header>
<CREATION_DATE/>
<ORIGINATOR/>
</header>
<body>
<segment>
<metadata>
<OBJECT_NAME>THOR AGENA D R/B</OBJECT_NAME>
<OBJECT_ID>1964-002A</OBJECT_ID>
<CENTER_NAME>EARTH</CENTER_NAME>
<REF_FRAME>TEME</REF_FRAME>
<TIME_SYSTEM>UTC</TIME_SYSTEM>
<MEAN_ELEMENT_THEORY>SGP4</MEAN_ELEMENT_THEORY>
</metadata>
<data>
<meanElements>
<EPOCH>2020-06-06T07:04:37.126560</EPOCH>
<MEAN_MOTION>14.32395701</MEAN_MOTION>
<ECCENTRICITY>.0032725</ECCENTRICITY>
<INCLINATION>99.0129</INCLINATION>
<RA_OF_ASC_NODE>49.4090</RA_OF_ASC_NODE>
<ARG_OF_PERICENTER>264.3266</ARG_OF_PERICENTER>
<MEAN_ANOMALY>95.4185</MEAN_ANOMALY>
</meanElements>
<tleParameters>
<EPHEMERIS_TYPE>0</EPHEMERIS_TYPE>
<CLASSIFICATION_TYPE>U</CLASSIFICATION_TYPE>
<NORAD_CAT_ID>733</NORAD_CAT_ID>
<ELEMENT_SET_NO>999</ELEMENT_SET_NO>
<REV_AT_EPOCH>93722</REV_AT_EPOCH>
<BSTAR>.25433E-4</BSTAR>
<MEAN_MOTION_DOT>2.1E-7</MEAN_MOTION_DOT>
<MEAN_MOTION_DDOT>0</MEAN_MOTION_DDOT>
</tleParameters>
</data>
</segment>
</body>
</omm>
<omm>
<header>
<CREATION_DATE/>
<ORIGINATOR/>
</header>
<body>
<segment>
<metadata>
<OBJECT_NAME>SL-3 R/B</OBJECT_NAME>
<OBJECT_ID>1964-053B</OBJECT_ID>
<CENTER_NAME>EARTH</CENTER_NAME>
<REF_FRAME>TEME</REF_FRAME>
<TIME_SYSTEM>UTC</TIME_SYSTEM>
<MEAN_ELEMENT_THEORY>SGP4</MEAN_ELEMENT_THEORY>
</metadata>
<data>
<meanElements>
<EPOCH>2020-06-05T22:17:57.747840</EPOCH>
<MEAN_MOTION>14.59393420</MEAN_MOTION>
<ECCENTRICITY>.0055722</ECCENTRICITY>
<INCLINATION>65.0789</INCLINATION>
<RA_OF_ASC_NODE>2.6555</RA_OF_ASC_NODE>
<ARG_OF_PERICENTER>32.0150</ARG_OF_PERICENTER>
<MEAN_ANOMALY>328.4314</MEAN_ANOMALY>
</meanElements>
<tleParameters>
<EPHEMERIS_TYPE>0</EPHEMERIS_TYPE>
<CLASSIFICATION_TYPE>U</CLASSIFICATION_TYPE>
<NORAD_CAT_ID>877</NORAD_CAT_ID>
<ELEMENT_SET_NO>999</ELEMENT_SET_NO>
<REV_AT_EPOCH>95981</REV_AT_EPOCH>
<BSTAR>.75354E-5</BSTAR>
<MEAN_MOTION_DOT>-8.4E-7</MEAN_MOTION_DOT>
<MEAN_MOTION_DDOT>0</MEAN_MOTION_DDOT>
</tleParameters>
</data>
</segment>
</body>
</omm>
</ndm>
""".data(using: .utf8)!
let result = NavigationDataMessage(from: xmlData)
let tle = TLE(commonName: result.omms[0].body.segment.metadata.commonName,
noradIndex: result.omms[0].body.segment.data.tleParameters.noradIndex,
launchName: result.omms[0].body.segment.metadata.launchName,
t₀: result.omms[0].body.segment.data.meanElements.t₀,
e₀: result.omms[0].body.segment.data.meanElements.e₀,
i₀: result.omms[0].body.segment.data.meanElements.i₀,
ω₀: result.omms[0].body.segment.data.meanElements.ω₀,
Ω₀: result.omms[0].body.segment.data.meanElements.Ω₀,
M₀: result.omms[0].body.segment.data.meanElements.M₀,
n₀: result.omms[0].body.segment.data.meanElements.n₀,
ephemType: result.omms[0].body.segment.data.tleParameters.ephemType,
tleClass: result.omms[0].body.segment.data.tleParameters.tleClass,
tleNumber: result.omms[0].body.segment.data.tleParameters.tleNumber,
revNumber: result.omms[0].body.segment.data.tleParameters.revNumber,
dragCoeff: result.omms[0].body.segment.data.tleParameters.dragCoeff)
print(Satellite(withTLE: tle.debugDescription()))
}
#endif
func testLongFile() {
do {
let contents = try String(contentsOfFile: "/Users/gavin/Development/sat_code/all_tle.txt")
_ = preProcessTLEs(contents)
} catch {
print(error)
}
}
func testBase34() {
XCTAssert(base10ID( "") == 0)
XCTAssert(alpha5ID( "") == 0)
XCTAssert(alpha5ID( "5") == 5)
XCTAssert(alpha5ID("10000") == 10000, "got \(alpha5ID("10000"))")
// numerical checks
XCTAssert(alpha5ID("A0000") == 100000, "got \(alpha5ID("A0000"))")
XCTAssert(alpha5ID("H0000") == 170000, "got \(alpha5ID("H0000"))")
XCTAssert(alpha5ID("J0000") == 180000, "got \(alpha5ID("J0000"))")
XCTAssert(alpha5ID("N0000") == 220000, "got \(alpha5ID("N0000"))")
XCTAssert(alpha5ID("P0000") == 230000, "got \(alpha5ID("P0000"))")
XCTAssert(alpha5ID("Z0000") == 330000, "got \(alpha5ID("Z0000"))")
XCTAssert(alpha5ID("Z9999") == 339999, "got \(alpha5ID("Z9999"))")
XCTAssert(alpha5ID("J2931") == 182931, "got \(alpha5ID("J2931"))")
XCTAssert(alpha5ID("W1928") == 301928, "got \(alpha5ID("W1928"))")
XCTAssert(alpha5ID("E8493") == 148493, "got \(alpha5ID("E8493"))")
XCTAssert(alpha5ID("P4018") == 234018, "got \(alpha5ID("P4018"))")
XCTAssert(alpha5ID("I0000") == 0, "got \(alpha5ID("I0000"))")
XCTAssert(alpha5ID("0I000") == 0, "got \(alpha5ID("0I000"))")
// lowercase
XCTAssert(alpha5ID("a5678") == 105678, "got \(alpha5ID("a5678"))")
// failure modes
XCTAssert(alpha5ID("!0000") == 0, "got \(alpha5ID("!9999"))")
XCTAssert(alpha5ID("~0000") == 0, "got \(alpha5ID("~9999"))")
XCTAssert(alpha5ID("AAAAA") == 0, "got \(alpha5ID("AAAAA"))")
}
func testBase10() {
XCTAssert(base10ID("") == 0)
XCTAssert(base10ID("5") == 5)
XCTAssert(base10ID("10000") == 10000, "got \(base10ID("10000"))")
XCTAssert(base10ID("99999") == 99999, "got \(base10ID("99999"))")
}
// func testPerformanceExample() { // May06/19 = iOS sim average: 2.267
//
// self.measure {
// testLongFile()
// }
// }
}
| 44.034694 | 111 | 0.443852 |
91032b5e24c54443105b2f0343f8db69738ca1f7 | 2,194 | final class TupleDeclTests: PrettyPrintTestCase {
func testBasicTuples() {
let input =
"""
let a = (1, 2, 3)
let a: (Int, Int, Int) = (1, 2, 3)
let a = (1, 2, 3, 4, 5, 6, 70, 80, 90)
let a = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
let a = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
"""
let expected =
"""
let a = (1, 2, 3)
let a: (Int, Int, Int) = (1, 2, 3)
let a = (
1, 2, 3, 4, 5, 6, 70, 80, 90
)
let a = (
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
)
let a = (
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12
)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 37)
}
func testLabeledTuples() {
let input =
"""
let a = (A: var1, B: var2)
var b: (A: Int, B: Double)
"""
let expected =
"""
let a = (A: var1, B: var2)
var b: (A: Int, B: Double)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 30)
}
func testDiscretionaryNewlineAfterColon() {
let input =
"""
let a = (
reallyLongKeySoTheValueWillWrap:
value,
b: c
)
let a = (
shortKey:
value,
b:
c,
label: Deeply.Nested.InnerMember,
label2:
Deeply.Nested.InnerMember
)
"""
let expected =
"""
let a = (
reallyLongKeySoTheValueWillWrap:
value,
b: c
)
let a = (
shortKey:
value,
b:
c,
label: Deeply.Nested
.InnerMember,
label2:
Deeply.Nested
.InnerMember
)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 25)
}
func testGroupsTrailingComma() {
let input =
"""
let t = (
condition ? firstOption : secondOption,
bar()
)
"""
let expected =
"""
let t = (
condition
? firstOption
: secondOption,
bar()
)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 32)
}
}
| 19.078261 | 76 | 0.447584 |
d640db7d29f61fedb1d3b4203f5ef068ddec33ca | 1,745 | import Foundation
extension String {
func partitionSlices(by length: Int) -> [Substring] {
var startIndex = self.startIndex
var results = [Substring]()
while startIndex < self.endIndex {
let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
results.append(self[startIndex..<endIndex])
startIndex = endIndex
}
return results
}
func partition(by length: Int) -> [String] {
return partitionSlices(by: length).map { String($0) }
}
func split(separator: CharacterSet) -> Array<Substring> {
var index = startIndex
var substrings = Array<Substring>()
var rangeStart = startIndex
var rangeEnd = startIndex
while index != endIndex {
if separator.contains(self[index].unicodeScalars.first!) {
substrings.append(self[rangeStart...rangeEnd])
while index != endIndex && separator.contains(self[index].unicodeScalars.first!) {
index = self.index(after: index)
rangeStart = index
rangeEnd = index
}
} else {
rangeEnd = index
index = self.index(after: index)
}
}
substrings.append(self[rangeStart...])
return substrings
}
var nsRange: NSRange { return NSMakeRange(0, count) }
func substring(with nsRange: NSRange) -> SubSequence {
let range = index(startIndex, offsetBy: nsRange.location)..<index(startIndex, offsetBy: nsRange.location + nsRange.length)
return self[range]
}
}
| 32.314815 | 130 | 0.565616 |
1c090840a251a826faf9db5296484813d8574306 | 2,047 | //
// Discovery.swift
// Elfo
//
// Created by Douwe Bos on 12/12/20.
//
import Foundation
import CocoaAsyncSocket
protocol ElfoDiscoveryDelegate: class {
func didDiscover(service: NetService)
}
class ElfoDiscovery: NSObject {
let config: Elfo.Configuration
weak var delegate: ElfoDiscoveryDelegate? = nil
private var service: NetServiceBrowser? = nil
private var services: [NetService] = []
init(config: Elfo.Configuration) {
self.config = config
super.init()
}
func start() {
services = []
service = NetServiceBrowser()
service?.delegate = self
service?.searchForServices(ofType: self.config.netserviceType,
inDomain: self.config.netserviceDomain
)
}
func restart() {
service?.stop()
service = nil
start()
}
}
extension ElfoDiscovery: NetServiceBrowserDelegate {
func netServiceBrowserWillSearch(_ browser: NetServiceBrowser) {
}
func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser) {
}
func netServiceBrowser(_ browser: NetServiceBrowser, didFindDomain domainString: String, moreComing: Bool) {
}
func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
services.append(service)
service.delegate = self
service.resolve(withTimeout: 30.0)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) {
if let index = services.firstIndex(of: service) {
services.remove(at: index)
}
}
func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {
restart()
}
}
extension ElfoDiscovery: NetServiceDelegate {
func netServiceDidResolveAddress(_ sender: NetService) {
delegate?.didDiscover(service: sender)
}
}
| 24.369048 | 112 | 0.63361 |
1ac09add6731fe3cc9003636f314bcdc101c6235 | 180 | //
// LaunchViewContoller.swift
// Asteroids
//
// Copyright © 2016 Kamil Grzegorzewicz. All rights reserved.
//
import UIKit
class LaunchViewContoller: UIViewController {
}
| 13.846154 | 62 | 0.733333 |
5b1c0ea06d78c23d66062bad51f9b5581eb47e75 | 2,132 | //
// PlayingCard.swift
// PlayingCard
//
// Created by 洋蔥胖 on 2019/5/1.
// Copyright © 2019 ChrisYoung. All rights reserved.
//
import Foundation
struct PlayingCard: CustomStringConvertible {
var description: String {
return "\(rank)\(suit)"
}
var suit: Suit
var rank: Rank
enum Suit: String , CustomStringConvertible{
case spades = "♠️"
case hearts = "♥️"
case clubs = "♣️"
case diamonds = "♦️"
static var all: [Suit] = [.spades, .hearts, .clubs, .diamonds]
var description: String {
switch self {
case .spades:
return "♠️"
case .hearts:
return "❤️"
case .clubs:
return "♣️"
case .diamonds:
return "♦️"
}
}
}
enum Rank : CustomStringConvertible{
case ace
case face(String)
case numeric(Int)
var order: Int {
switch self {
case .ace :
return 1
case .numeric(let pips) :
return pips
case .face(let kind) where kind == "J": return 11
case .face(let kind) where kind == "Q": return 12
case .face(let kind) where kind == "K": return 13
default:
return 0
}
}
static var all: [Rank] {
var allRanks = [Rank.ace]
for pips in 2...10 {
allRanks.append(Rank.numeric(pips))
}
allRanks += [Rank.face("J"), .face("Q"), .face("K")]
return allRanks
}
var description: String {
switch self {
case .ace:
return "A"
case .numeric(let pips):
return String(pips)
case .face(let kind):
return kind
}
}
}
}
| 23.428571 | 70 | 0.409944 |
030e1dc3a4328d73577e83984220b353f455ce85 | 4,417 | //
// CleanUnusedImports.swift
// SMCheckProject
//
// Created by daiming on 2017/3/1.
// Copyright © 2017年 Starming. All rights reserved.
//
import Cocoa
import RxSwift
//获取递归后所有的import
class CleanUnusedImports: NSObject {
func find(files:Dictionary<String, File>) -> Observable<Any> {
return Observable.create({ (observer) -> Disposable in
var allFiles = [String:File]() //需要查找的头文件
var newFiles = [String:File]() //递归全的文件
var allObjects = [String:Object]()
var allUsedObjects = [String:Object]()
for (_, aFile) in files {
allFiles[aFile.name] = aFile
}
for (_, aFile) in allFiles {
//单文件处理
aFile.recursionImports = self.fetchImports(file: aFile, allFiles: allFiles, allRecursionImports:[Import]())
//记录所有import的的类
for aImport in aFile.recursionImports {
for (name, aObj) in aImport.file.objects {
//全部类
aFile.importObjects[name] = aObj
allObjects[name] = aObj
}
}
newFiles[aFile.name] = aFile
//处理无用的import
//记录所有用过的类
for aMethod in aFile.methods {
let _ = ParsingMethodContent.parsing(method: aMethod, file: aFile).subscribe(onNext:{ (result) in
if result is Object {
let aObj = result as! Object
allUsedObjects[aObj.name] = aObj
}
})
}
//记录类的父类,作为已用类
for (_, value) in allObjects {
if value.superName.characters.count > 0 {
guard let obj = allObjects[value.superName] else {
continue
}
allUsedObjects[value.superName] = obj
}
}
}
// print("\(allObjects.keys)")
// print("-----------------------")
// print("\(allUsedObjects.keys)")
//遍历对比出无用的类
var allUnUsedObjects = [String:Object]()
for (key, value) in allObjects {
guard let _ = allUsedObjects[key] else {
allUnUsedObjects[key] = value
continue
}
}
observer.on(.next(allUnUsedObjects))
observer.on(.next(newFiles))
observer.on(.completed)
return Disposables.create {
//
}
})
}
//递归获取所有import
func fetchImports(file: File, allFiles:[String:File], allRecursionImports:[Import]) -> [Import] {
var allRecursionImports = allRecursionImports
for aImport in file.imports {
guard let importFile = allFiles[aImport.fileName] else {
continue
}
if !checkIfContain(aImport: aImport, inImports: allRecursionImports) {
allRecursionImports.append(addFileObjectTo(aImport: aImport, allFiles: allFiles))
} else {
continue
}
let reRecursionImports = fetchImports(file: importFile, allFiles: allFiles, allRecursionImports: allRecursionImports)
for aImport in reRecursionImports {
if !checkIfContain(aImport: aImport, inImports: allRecursionImports) {
allRecursionImports.append(addFileObjectTo(aImport: aImport, allFiles: allFiles))
}
}
}
return allRecursionImports
}
func addFileObjectTo(aImport:Import, allFiles: [String:File]) -> Import {
var mImport = aImport
guard let aFile = allFiles[aImport.fileName] else {
return aImport
}
mImport.file = aFile
return mImport
}
func checkIfContain(aImport:Import, inImports:[Import]) -> Bool{
let tf = inImports.contains { element in
if aImport.fileName == element.fileName {
return true
} else {
return false
}
}
return tf
}
}
| 35.055556 | 129 | 0.493321 |
21cfeebd788ae14ab959a025147fe7c61fce302a | 59,179 | //
// SetTests.swift
// Outlaw
//
// Created by Brian Mullen on 11/9/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import XCTest
@testable import Outlaw
class SetTests: OutlawTestCase, DateTesting {
static var allTests = [("testValue", testValue),
("testNestedValue", testNestedValue),
("testKeyNotFound", testKeyNotFound),
("testTypeMismatch", testTypeMismatch),
("testOptional", testOptional),
("testOptionalNestedValue", testOptionalNestedValue),
("testOptionalKeyNotFound", testOptionalKeyNotFound),
("testOptionalTypeMismatch", testOptionalTypeMismatch),
("testTransformValue", testTransformValue),
("testOptionalTransformValue", testOptionalTransformValue),
("testTransformOptionalValue", testTransformOptionalValue),
("testOptionalTransformOptionalValue", testOptionalTransformOptionalValue),
("testTransformValueOfOptionals", testTransformValueOfOptionals),
("testOptionalTransformValueOfOptionals", testOptionalTransformValueOfOptionals),
("testTransformOptionalValueOfOptionals", testTransformOptionalValueOfOptionals),
("testOptionalTransformOptionalValueOfOptionals", testOptionalTransformOptionalValueOfOptionals)]
func testValue() {
let bool: Set<Bool> = try! data.value(for: "bool")
XCTAssertEqual(bool.count, 2)
XCTAssertEqual(bool.first, false)
let string: Set<String> = try! data.value(for: "string")
XCTAssertEqual(string.count, 1)
XCTAssertEqual(string.first, "Hello, Outlaw!")
let character: Set<Character> = try! data.value(for: "character")
XCTAssertEqual(character.count, 1)
XCTAssertEqual(character.first, "O")
let float: Set<Float> = try! data.value(for: "float")
XCTAssertEqual(float.count, 1)
XCTAssertEqual(float.first, 3.14)
let double: Set<Double> = try! data.value(for: "double")
XCTAssertEqual(double.count, 1)
XCTAssertEqual(double.first, 3.14159265359)
let int: Set<Int> = try! data.value(for: "int")
XCTAssertEqual(int.count, 1)
XCTAssertEqual(int.first, -3)
let int8: Set<Int8> = try! data.value(for: "int8")
XCTAssertEqual(int8.count, 1)
XCTAssertEqual(int8.first, -8)
let int16: Set<Int16> = try! data.value(for: "int16")
XCTAssertEqual(int16.count, 1)
XCTAssertEqual(int16.first, -16)
let int32: Set<Int32> = try! data.value(for: "int32")
XCTAssertEqual(int32.count, 1)
XCTAssertEqual(int32.first, -32)
let int64: Set<Int64> = try! data.value(for: "int64")
XCTAssertEqual(int64.count, 1)
XCTAssertEqual(int64.first, -64)
let uint: Set<UInt> = try! data.value(for: "uint")
XCTAssertEqual(uint.count, 1)
XCTAssertEqual(uint.first, 3)
let uint8: Set<UInt8> = try! data.value(for: "uint8")
XCTAssertEqual(uint8.count, 1)
XCTAssertEqual(uint8.first, 8)
let uint16: Set<UInt16> = try! data.value(for: "uint16")
XCTAssertEqual(uint16.count, 1)
XCTAssertEqual(uint16.first, 16)
let uint32: Set<UInt32> = try! data.value(for: "uint32")
XCTAssertEqual(uint32.count, 1)
XCTAssertEqual(uint32.first, 32)
let uint64: Set<UInt64> = try! data.value(for: "uint64")
XCTAssertEqual(uint64.count, 1)
XCTAssertEqual(uint64.first, 64)
let url: Set<URL> = try! data.value(for: "url")
XCTAssertEqual(url.count, 1)
XCTAssertEqual(url.first?.absoluteString, "https://developer.apple.com/")
let date: Set<Date> = try! data.value(for: "date")
XCTAssertEqual(date.count, 1)
XCTAssertEqual(formatDate(date.first!), formatDate(dateForAssert()))
}
func testNestedValue() {
let bool: Set<Bool> = try! data.value(for: "object.bool")
XCTAssertEqual(bool.count, 2)
XCTAssertEqual(bool.first, false)
let string: Set<String> = try! data.value(for: "object.string")
XCTAssertEqual(string.count, 1)
XCTAssertEqual(string.first, "Hello, Outlaw!")
let character: Set<Character> = try! data.value(for: "object.character")
XCTAssertEqual(character.count, 1)
XCTAssertEqual(character.first, "O")
let float: Set<Float> = try! data.value(for: "object.float")
XCTAssertEqual(float.count, 1)
XCTAssertEqual(float.first, 3.14)
let double: Set<Double> = try! data.value(for: "object.double")
XCTAssertEqual(double.count, 1)
XCTAssertEqual(double.first, 3.14159265359)
let int: Set<Int> = try! data.value(for: "object.int")
XCTAssertEqual(int.count, 1)
XCTAssertEqual(int.first, -3)
let int8: Set<Int8> = try! data.value(for: "object.int8")
XCTAssertEqual(int8.count, 1)
XCTAssertEqual(int8.first, -8)
let int16: Set<Int16> = try! data.value(for: "object.int16")
XCTAssertEqual(int16.count, 1)
XCTAssertEqual(int16.first, -16)
let int32: Set<Int32> = try! data.value(for: "object.int32")
XCTAssertEqual(int32.count, 1)
XCTAssertEqual(int32.first, -32)
let int64: Set<Int64> = try! data.value(for: "object.int64")
XCTAssertEqual(int64.count, 1)
XCTAssertEqual(int64.first, -64)
let uint: Set<UInt> = try! data.value(for: "object.uint")
XCTAssertEqual(uint.count, 1)
XCTAssertEqual(uint.first, 3)
let uint8: Set<UInt8> = try! data.value(for: "object.uint8")
XCTAssertEqual(uint8.count, 1)
XCTAssertEqual(uint8.first, 8)
let uint16: Set<UInt16> = try! data.value(for: "object.uint16")
XCTAssertEqual(uint16.count, 1)
XCTAssertEqual(uint16.first, 16)
let uint32: Set<UInt32> = try! data.value(for: "object.uint32")
XCTAssertEqual(uint32.count, 1)
XCTAssertEqual(uint32.first, 32)
let uint64: Set<UInt64> = try! data.value(for: "object.uint64")
XCTAssertEqual(uint64.count, 1)
XCTAssertEqual(uint64.first, 64)
let url: Set<URL> = try! data.value(for: "object.url")
XCTAssertEqual(url.count, 1)
XCTAssertEqual(url.first?.absoluteString, "https://developer.apple.com/")
let date: Set<Date> = try! data.value(for: "object.date")
XCTAssertEqual(date.count, 1)
XCTAssertEqual(formatDate(date.first!), formatDate(dateForAssert()))
}
func testKeyNotFound() {
var value: Set<Int> = []
let ex = self.expectation(description: "Key not found")
do {
value = try data.value(for: "keyNotFound")
}
catch {
if case OutlawError.keyNotFound = error {
ex.fulfill()
}
}
self.waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(value.count, 0)
}
func testTypeMismatch() {
var value: Set<Int> = []
let ex = self.expectation(description: "Type mismatch")
do {
value = try data.value(for: "object")
}
catch {
if case OutlawError.typeMismatchWithKey = error {
ex.fulfill()
}
}
self.waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(value.count, 0)
}
// MARK: -
// MARK: Optionals
func testOptional() {
let bool: Set<Bool>? = data.value(for: "bool")
XCTAssertEqual(bool?.count, 2)
XCTAssertEqual(bool?.first, false)
let string: Set<String>? = data.value(for: "string")
XCTAssertEqual(string?.count, 1)
XCTAssertEqual(string?.first, "Hello, Outlaw!")
let character: Set<Character>? = data.value(for: "character")
XCTAssertEqual(character?.count, 1)
XCTAssertEqual(character?.first, "O")
let float: Set<Float>? = data.value(for: "float")
XCTAssertEqual(float?.count, 1)
XCTAssertEqual(float?.first, 3.14)
let double: Set<Double>? = data.value(for: "double")
XCTAssertEqual(double?.count, 1)
XCTAssertEqual(double?.first, 3.14159265359)
let int: Set<Int>? = data.value(for: "int")
XCTAssertEqual(int?.count, 1)
XCTAssertEqual(int?.first, -3)
let int8: Set<Int8>? = data.value(for: "int8")
XCTAssertEqual(int8?.count, 1)
XCTAssertEqual(int8?.first, -8)
let int16: Set<Int16>? = data.value(for: "int16")
XCTAssertEqual(int16?.count, 1)
XCTAssertEqual(int16?.first, -16)
let int32: Set<Int32>? = data.value(for: "int32")
XCTAssertEqual(int32?.count, 1)
XCTAssertEqual(int32?.first, -32)
let int64: Set<Int64>? = data.value(for: "int64")
XCTAssertEqual(int64?.count, 1)
XCTAssertEqual(int64?.first, -64)
let uint: Set<UInt>? = data.value(for: "uint")
XCTAssertEqual(uint?.count, 1)
XCTAssertEqual(uint?.first, 3)
let uint8: Set<UInt8>? = data.value(for: "uint8")
XCTAssertEqual(uint8?.count, 1)
XCTAssertEqual(uint8?.first, 8)
let uint16: Set<UInt16>? = data.value(for: "uint16")
XCTAssertEqual(uint16?.count, 1)
XCTAssertEqual(uint16?.first, 16)
let uint32: Set<UInt32>? = data.value(for: "uint32")
XCTAssertEqual(uint32?.count, 1)
XCTAssertEqual(uint32?.first, 32)
let uint64: Set<UInt64>? = data.value(for: "uint64")
XCTAssertEqual(uint64?.count, 1)
XCTAssertEqual(uint64?.first, 64)
let url: Set<URL>? = data.value(for: "url")
XCTAssertEqual(url?.count, 1)
XCTAssertEqual(url?.first?.absoluteString, "https://developer.apple.com/")
let date: Set<Date>? = data.value(for: "date")
XCTAssertEqual(date?.count, 1)
XCTAssertEqual(formatDate(date!.first!), formatDate(dateForAssert()))
}
func testOptionalNestedValue() {
let bool: Set<Bool>? = data.value(for: "object.bool")
XCTAssertEqual(bool?.count, 2)
XCTAssertEqual(bool?.first, false)
let string: Set<String>? = data.value(for: "object.string")
XCTAssertEqual(string?.count, 1)
XCTAssertEqual(string?.first, "Hello, Outlaw!")
let character: Set<Character>? = data.value(for: "object.character")
XCTAssertEqual(character?.count, 1)
XCTAssertEqual(character?.first, "O")
let float: Set<Float>? = data.value(for: "object.float")
XCTAssertEqual(float?.count, 1)
XCTAssertEqual(float?.first, 3.14)
let double: Set<Double>? = data.value(for: "object.double")
XCTAssertEqual(double?.count, 1)
XCTAssertEqual(double?.first, 3.14159265359)
let int: Set<Int>? = data.value(for: "object.int")
XCTAssertEqual(int?.count, 1)
XCTAssertEqual(int?.first, -3)
let int8: Set<Int8>? = data.value(for: "object.int8")
XCTAssertEqual(int8?.count, 1)
XCTAssertEqual(int8?.first, -8)
let int16: Set<Int16>? = data.value(for: "object.int16")
XCTAssertEqual(int16?.count, 1)
XCTAssertEqual(int16?.first, -16)
let int32: Set<Int32>? = data.value(for: "object.int32")
XCTAssertEqual(int32?.count, 1)
XCTAssertEqual(int32?.first, -32)
let int64: Set<Int64>? = data.value(for: "object.int64")
XCTAssertEqual(int64?.count, 1)
XCTAssertEqual(int64?.first, -64)
let uint: Set<UInt>? = data.value(for: "object.uint")
XCTAssertEqual(uint?.count, 1)
XCTAssertEqual(uint?.first, 3)
let uint8: Set<UInt8>? = data.value(for: "object.uint8")
XCTAssertEqual(uint8?.count, 1)
XCTAssertEqual(uint8?.first, 8)
let uint16: Set<UInt16>? = data.value(for: "object.uint16")
XCTAssertEqual(uint16?.count, 1)
XCTAssertEqual(uint16?.first, 16)
let uint32: Set<UInt32>? = data.value(for: "object.uint32")
XCTAssertEqual(uint32?.count, 1)
XCTAssertEqual(uint32?.first, 32)
let uint64: Set<UInt64>? = data.value(for: "object.uint64")
XCTAssertEqual(uint64?.count, 1)
XCTAssertEqual(uint64?.first, 64)
let url: Set<URL>? = data.value(for: "object.url")
XCTAssertEqual(url?.count, 1)
XCTAssertEqual(url?.first?.absoluteString, "https://developer.apple.com/")
let date: Set<Date>? = data.value(for: "object.date")
XCTAssertEqual(date?.count, 1)
XCTAssertEqual(formatDate(date!.first!), formatDate(dateForAssert()))
}
func testOptionalKeyNotFound() {
let value: Set<Int>? = data.value(for: "keyNotFound")
XCTAssertNil(value)
}
func testOptionalTypeMismatch() {
let value: Set<Int>? = data.value(for: "object")
XCTAssertNil(value)
}
// MARK: -
// MARK: Transforms
func testTransformValue() {
let bool: Set<Bool> = try! data.value(for: "boolTransform", with: { (rawValue: String) -> Bool in
return rawValue == "TRUE"
})
XCTAssertEqual(bool.count, 1)
XCTAssertEqual(bool.first, true)
let string: Set<String> = try! data.value(for: "stringTransform", with: { (rawValue: Bool) -> String in
return rawValue ? "TRUE" : "FALSE"
})
XCTAssertEqual(string.count, 1)
XCTAssertEqual(string.first, "TRUE")
let character: Set<Character> = try! data.value(for: "characterTransform", with: { (rawValue: Bool) -> Character in
return rawValue ? "1" : "0"
})
XCTAssertEqual(character.count, 1)
XCTAssertEqual(character.first, "1")
let float: Set<Float> = try! data.value(for: "floatTransform", with: { (rawValue: String) -> Float in
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(float.count, 1)
XCTAssertEqual(float.first, 3.14)
let double: Set<Double> = try! data.value(for: "doubleTransform", with: { (rawValue: String) -> Double in
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(double.count, 1)
XCTAssertEqual(double.first, 3.14)
let int: Set<Int> = try! data.value(for: "intTransform", with: { (rawValue: String) -> Int in
guard let value = Int(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "intTransform", expected: Int.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int.count, 1)
XCTAssertEqual(int.first, 12345)
let int8: Set<Int8> = try! data.value(for: "int8Transform", with: { (rawValue: String) -> Int8 in
guard let value = Int8(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "intTransform", expected: Int8.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int8.count, 1)
XCTAssertEqual(int8.first, 123)
let int16: Set<Int16> = try! data.value(for: "int16Transform", with: { (rawValue: String) -> Int16 in
guard let value = Int16(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "int16Transform", expected: Int16.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int16.count, 1)
XCTAssertEqual(int16.first, 12345)
let int32: Set<Int32> = try! data.value(for: "int32Transform", with: { (rawValue: String) -> Int32 in
guard let value = Int32(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "int32Transform", expected: Int32.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int32.count, 1)
XCTAssertEqual(int32.first, 12345)
let int64: Set<Int64> = try! data.value(for: "int64Transform", with: { (rawValue: String) -> Int64 in
guard let value = Int64(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "int64Transform", expected: Int64.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int64.count, 1)
XCTAssertEqual(int64.first, 12345)
let uint: Set<UInt> = try! data.value(for: "uintTransform", with: { (rawValue: String) -> UInt in
guard let value = UInt(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uintTransform", expected: UInt.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint.count, 1)
XCTAssertEqual(uint.first, 12345)
let uint8: Set<UInt8> = try! data.value(for: "uint8Transform", with: { (rawValue: String) -> UInt8 in
guard let value = UInt8(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uintTransform", expected: UInt8.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint8.count, 1)
XCTAssertEqual(uint8.first, 123)
let uint16: Set<UInt16> = try! data.value(for: "uint16Transform", with: { (rawValue: String) -> UInt16 in
guard let value = UInt16(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uint16Transform", expected: UInt16.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint16.count, 1)
XCTAssertEqual(uint16.first, 12345)
let uint32: Set<UInt32> = try! data.value(for: "uint32Transform", with: { (rawValue: String) -> UInt32 in
guard let value = UInt32(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uint32Transform", expected: UInt32.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint32.count, 1)
XCTAssertEqual(uint32.first, 12345)
let uint64: Set<UInt64> = try! data.value(for: "uint64Transform", with: { (rawValue: String) -> UInt64 in
guard let value = UInt64(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uint64Transform", expected: UInt64.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint64.count, 1)
XCTAssertEqual(uint64.first, 12345)
let url: Set<URL> = try! data.value(for: "urlTransform", with: { (rawValue: String) -> URL in
let urlValue = rawValue == "HOMEPAGE" ? "http://molbie.co" : rawValue
guard let value = URL(string: urlValue) else {
throw OutlawError.typeMismatchWithKey(key: "urlTransform", expected: URL.self, actual: rawValue)
}
return value
})
XCTAssertEqual(url.count, 1)
XCTAssertEqual(url.first?.absoluteString, "http://molbie.co")
let formatter = shortDateformatter()
let date: Set<Date> = try! data.value(for: "dateTransform", with: { (rawValue: String) -> Date in
return formatter.date(from: rawValue)!
})
XCTAssertEqual(date.count, 1)
XCTAssertEqual(formatShortDate(date.first!), formatShortDate(shortDateForAssert()))
}
func testOptionalTransformValue() {
let bool: Set<Bool> = try! data.value(for: "boolTransform", with: { (rawValue: String?) -> Bool in
return rawValue == "TRUE"
})
XCTAssertEqual(bool.count, 1)
XCTAssertEqual(bool.first, true)
let string: Set<String> = try! data.value(for: "stringTransform", with: { (rawValue: Bool?) -> String in
guard let rawValue = rawValue else { return "FALSE" }
return rawValue ? "TRUE" : "FALSE"
})
XCTAssertEqual(string.count, 1)
XCTAssertEqual(string.first, "TRUE")
let character: Set<Character> = try! data.value(for: "characterTransform", with: { (rawValue: Bool?) -> Character in
guard let rawValue = rawValue else { return "0" }
return rawValue ? "1" : "0"
})
XCTAssertEqual(character.count, 1)
XCTAssertEqual(character.first, "1")
let float: Set<Float> = try! data.value(for: "floatTransform", with: { (rawValue: String?) -> Float in
guard let rawValue = rawValue else { return 0 }
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(float.count, 1)
XCTAssertEqual(float.first, 3.14)
let double: Set<Double> = try! data.value(for: "doubleTransform", with: { (rawValue: String?) -> Double in
guard let rawValue = rawValue else { return 0 }
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(double.count, 1)
XCTAssertEqual(double.first, 3.14)
let int: Set<Int> = try! data.value(for: "intTransform", with: { (rawValue: String?) -> Int in
guard let value = Int(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "intTransform", expected: Int.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(int.count, 1)
XCTAssertEqual(int.first, 12345)
let int8: Set<Int8> = try! data.value(for: "int8Transform", with: { (rawValue: String?) -> Int8 in
guard let value = Int8(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "int8Transform", expected: Int8.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(int8.count, 1)
XCTAssertEqual(int8.first, 123)
let int16: Set<Int16> = try! data.value(for: "int16Transform", with: { (rawValue: String?) -> Int16 in
guard let value = Int16(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "int16Transform", expected: Int16.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(int16.count, 1)
XCTAssertEqual(int16.first, 12345)
let int32: Set<Int32> = try! data.value(for: "int32Transform", with: { (rawValue: String?) -> Int32 in
guard let value = Int32(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "int32Transform", expected: Int32.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(int32.count, 1)
XCTAssertEqual(int32.first, 12345)
let int64: Set<Int64> = try! data.value(for: "intTransform", with: { (rawValue: String?) -> Int64 in
guard let value = Int64(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "intTransform", expected: Int64.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(int64.count, 1)
XCTAssertEqual(int64.first, 12345)
let uint: Set<UInt> = try! data.value(for: "uintTransform", with: { (rawValue: String?) -> UInt in
guard let value = UInt(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "uintTransform", expected: UInt.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(uint.count, 1)
XCTAssertEqual(uint.first, 12345)
let uint8: Set<UInt8> = try! data.value(for: "uint8Transform", with: { (rawValue: String?) -> UInt8 in
guard let value = UInt8(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "uint8Transform", expected: UInt8.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(uint8.count, 1)
XCTAssertEqual(uint8.first, 123)
let uint16: Set<UInt16> = try! data.value(for: "uint16Transform", with: { (rawValue: String?) -> UInt16 in
guard let value = UInt16(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "uint16Transform", expected: UInt16.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(uint16.count, 1)
XCTAssertEqual(uint16.first, 12345)
let uint32: Set<UInt32> = try! data.value(for: "uint32Transform", with: { (rawValue: String?) -> UInt32 in
guard let value = UInt32(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "uint32Transform", expected: UInt32.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(uint32.count, 1)
XCTAssertEqual(uint32.first, 12345)
let uint64: Set<UInt64> = try! data.value(for: "uintTransform", with: { (rawValue: String?) -> UInt64 in
guard let value = UInt64(rawValue ?? "0") else {
throw OutlawError.typeMismatchWithKey(key: "uintTransform", expected: UInt64.self, actual: rawValue ?? "nil")
}
return value
})
XCTAssertEqual(uint64.count, 1)
XCTAssertEqual(uint64.first, 12345)
let url: Set<URL> = try! data.value(for: "urlTransform", with: { (rawValue: String?) -> URL in
let urlValue = rawValue == "HOMEPAGE" ? "http://molbie.co" : (rawValue ?? "")
guard let value = URL(string: urlValue) else {
throw OutlawError.typeMismatchWithKey(key: "urlTransform", expected: URL.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(url.count, 1)
XCTAssertEqual(url.first?.absoluteString, "http://molbie.co")
let formatter = shortDateformatter()
let date: Set<Date> = try! data.value(for: "dateTransform", with: { (rawValue: String?) -> Date in
guard let dateValue = rawValue else {
throw OutlawError.typeMismatchWithKey(key: "transform", expected: Date.self, actual: rawValue ?? "")
}
return formatter.date(from: dateValue)!
})
XCTAssertEqual(date.count, 1)
XCTAssertEqual(formatShortDate(date.first!), formatShortDate(shortDateForAssert()))
}
func testTransformOptionalValue() {
let bool: Set<Bool>? = data.value(for: "boolTransform", with: { (rawValue: String) -> Bool in
return rawValue == "TRUE"
})
XCTAssertEqual(bool?.count, 1)
XCTAssertEqual(bool?.first, true)
let string: Set<String>? = data.value(for: "stringTransform", with: { (rawValue: Bool) -> String in
return rawValue ? "TRUE" : "FALSE"
})
XCTAssertEqual(string?.count, 1)
XCTAssertEqual(string?.first, "TRUE")
let character: Set<Character>? = data.value(for: "characterTransform", with: { (rawValue: Bool) -> Character in
return rawValue ? "1" : "0"
})
XCTAssertEqual(character?.count, 1)
XCTAssertEqual(character?.first, "1")
let float: Set<Float>? = data.value(for: "floatTransform", with: { (rawValue: String) -> Float in
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(float?.count, 1)
XCTAssertEqual(float?.first, 3.14)
let double: Set<Double>? = data.value(for: "doubleTransform", with: { (rawValue: String) -> Double in
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(double?.count, 1)
XCTAssertEqual(double?.first, 3.14)
let int: Set<Int>? = data.value(for: "intTransform", with: { (rawValue: String) -> Int in
guard let value = Int(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "intTransform", expected: Int.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int?.count, 1)
XCTAssertEqual(int?.first, 12345)
let int8: Set<Int8>? = data.value(for: "int8Transform", with: { (rawValue: String) -> Int8 in
guard let value = Int8(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "int8Transform", expected: Int8.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int8?.count, 1)
XCTAssertEqual(int8?.first, 123)
let int16: Set<Int16>? = data.value(for: "int16Transform", with: { (rawValue: String) -> Int16 in
guard let value = Int16(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "int16Transform", expected: Int16.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int16?.count, 1)
XCTAssertEqual(int16?.first, 12345)
let int32: Set<Int32>? = data.value(for: "int32Transform", with: { (rawValue: String) -> Int32 in
guard let value = Int32(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "int32Transform", expected: Int32.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int32?.count, 1)
XCTAssertEqual(int32?.first, 12345)
let int64: Set<Int64>? = data.value(for: "int64Transform", with: { (rawValue: String) -> Int64 in
guard let value = Int64(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "int64Transform", expected: Int64.self, actual: rawValue)
}
return value
})
XCTAssertEqual(int64?.count, 1)
XCTAssertEqual(int64?.first, 12345)
let uint: Set<UInt>? = data.value(for: "uintTransform", with: { (rawValue: String) -> UInt in
guard let value = UInt(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uintTransform", expected: UInt.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint?.count, 1)
XCTAssertEqual(uint?.first, 12345)
let uint8: Set<UInt8>? = data.value(for: "uint8Transform", with: { (rawValue: String) -> UInt8 in
guard let value = UInt8(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uint8Transform", expected: UInt8.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint8?.count, 1)
XCTAssertEqual(uint8?.first, 123)
let uint16: Set<UInt16>? = data.value(for: "uint16Transform", with: { (rawValue: String) -> UInt16 in
guard let value = UInt16(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uint16Transform", expected: UInt16.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint16?.count, 1)
XCTAssertEqual(uint16?.first, 12345)
let uint32: Set<UInt32>? = data.value(for: "uint32Transform", with: { (rawValue: String) -> UInt32 in
guard let value = UInt32(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uint32Transform", expected: UInt32.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint32?.count, 1)
XCTAssertEqual(uint32?.first, 12345)
let uint64: Set<UInt64>? = data.value(for: "uint64Transform", with: { (rawValue: String) -> UInt64 in
guard let value = UInt64(rawValue) else {
throw OutlawError.typeMismatchWithKey(key: "uint64Transform", expected: UInt64.self, actual: rawValue)
}
return value
})
XCTAssertEqual(uint64?.count, 1)
XCTAssertEqual(uint64?.first, 12345)
let url: Set<URL>? = data.value(for: "urlTransform", with: { (rawValue: String) -> URL in
let urlValue = rawValue == "HOMEPAGE" ? "http://molbie.co" : rawValue
guard let value = URL(string: urlValue) else {
throw OutlawError.typeMismatchWithKey(key: "urlTransform", expected: URL.self, actual: rawValue)
}
return value
})
XCTAssertEqual(url?.count, 1)
XCTAssertEqual(url?.first?.absoluteString, "http://molbie.co")
let formatter = shortDateformatter()
let date: Set<Date>? = data.value(for: "dateTransform", with: { (rawValue: String) -> Date in
return formatter.date(from: rawValue)!
})
XCTAssertEqual(date?.count, 1)
XCTAssertEqual(formatShortDate(date!.first!), formatShortDate(shortDateForAssert()))
}
func testOptionalTransformOptionalValue() {
let bool: Set<Bool>? = data.value(for: "boolTransform", with: { (rawValue: String?) -> Bool in
return rawValue == "TRUE"
})
XCTAssertEqual(bool?.count, 1)
XCTAssertEqual(bool?.first, true)
let string: Set<String>? = data.value(for: "stringTransform", with: { (rawValue: Bool?) -> String in
let value = rawValue ?? false
return value ? "TRUE" : "FALSE"
})
XCTAssertEqual(string?.count, 1)
XCTAssertEqual(string?.first, "TRUE")
let character: Set<Character>? = data.value(for: "characterTransform", with: { (rawValue: Bool?) -> Character in
let value = rawValue ?? false
return value ? "1" : "0"
})
XCTAssertEqual(character?.count, 1)
XCTAssertEqual(character?.first, "1")
let float: Set<Float>? = data.value(for: "floatTransform", with: { (rawValue: String?) -> Float in
let value = rawValue ?? ""
return value == "PI" ? 3.14 : 0
})
XCTAssertEqual(float?.count, 1)
XCTAssertEqual(float?.first, 3.14)
let double: Set<Double>? = data.value(for: "doubleTransform", with: { (rawValue: String?) -> Double in
let value = rawValue ?? ""
return value == "PI" ? 3.14 : 0
})
XCTAssertEqual(double?.count, 1)
XCTAssertEqual(double?.first, 3.14)
let int: Set<Int>? = data.value(for: "intTransform", with: { (rawValue: String?) -> Int in
guard let value = Int(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "intTransform", expected: Int.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(int?.count, 1)
XCTAssertEqual(int?.first, 12345)
let int8: Set<Int8>? = data.value(for: "int8Transform", with: { (rawValue: String?) -> Int8 in
guard let value = Int8(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "int8Transform", expected: Int8.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(int8?.count, 1)
XCTAssertEqual(int8?.first, 123)
let int16: Set<Int16>? = data.value(for: "int16Transform", with: { (rawValue: String?) -> Int16 in
guard let value = Int16(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "int16Transform", expected: Int16.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(int16?.count, 1)
XCTAssertEqual(int16?.first, 12345)
let int32: Set<Int32>? = data.value(for: "int32Transform", with: { (rawValue: String?) -> Int32 in
guard let value = Int32(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "int32Transform", expected: Int32.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(int32?.count, 1)
XCTAssertEqual(int32?.first, 12345)
let int64: Set<Int64>? = data.value(for: "int64Transform", with: { (rawValue: String?) -> Int64 in
guard let value = Int64(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "int64Transform", expected: Int64.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(int64?.count, 1)
XCTAssertEqual(int64?.first, 12345)
let uint: Set<UInt>? = data.value(for: "uintTransform", with: { (rawValue: String?) -> UInt in
guard let value = UInt(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "uintTransform", expected: UInt.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(uint?.count, 1)
XCTAssertEqual(uint?.first, 12345)
let uint8: Set<UInt8>? = data.value(for: "uint8Transform", with: { (rawValue: String?) -> UInt8 in
guard let value = UInt8(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "uint8Transform", expected: UInt8.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(uint8?.count, 1)
XCTAssertEqual(uint8?.first, 123)
let uint16: Set<UInt16>? = data.value(for: "uint16Transform", with: { (rawValue: String?) -> UInt16 in
guard let value = UInt16(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "uint16Transform", expected: UInt16.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(uint16?.count, 1)
XCTAssertEqual(uint16?.first, 12345)
let uint32: Set<UInt32>? = data.value(for: "uint32Transform", with: { (rawValue: String?) -> UInt32 in
guard let value = UInt32(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "uint32Transform", expected: UInt32.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(uint32?.count, 1)
XCTAssertEqual(uint32?.first, 12345)
let uint64: Set<UInt64>? = data.value(for: "uint64Transform", with: { (rawValue: String?) -> UInt64 in
guard let value = UInt64(rawValue ?? "") else {
throw OutlawError.typeMismatchWithKey(key: "uint64Transform", expected: UInt64.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(uint64?.count, 1)
XCTAssertEqual(uint64?.first, 12345)
let url: Set<URL>? = data.value(for: "urlTransform", with: { (rawValue: String?) -> URL in
let urlValue = rawValue == "HOMEPAGE" ? "http://molbie.co" : (rawValue ?? "")
guard let value = URL(string: urlValue) else {
throw OutlawError.typeMismatchWithKey(key: "urlTransform", expected: URL.self, actual: rawValue ?? "")
}
return value
})
XCTAssertEqual(url?.count, 1)
XCTAssertEqual(url?.first?.absoluteString, "http://molbie.co")
let formatter = shortDateformatter()
let date: Set<Date>? = data.value(for: "dateTransform", with: { (rawValue: String?) -> Date in
let value = rawValue ?? "11/18/2016"
return formatter.date(from: value)!
})
XCTAssertEqual(date?.count, 1)
XCTAssertEqual(formatShortDate(date!.first!), formatShortDate(shortDateForAssert()))
}
// MARK: -
// MARK: Transforms of Optionals
func testTransformValueOfOptionals() {
let bool: Set<Bool> = try! data.value(for: "boolTransform", with: { (rawValue: String) -> Bool? in
return rawValue == "TRUE"
})
XCTAssertEqual(bool.count, 1)
XCTAssertEqual(bool.first, true)
let string: Set<String> = try! data.value(for: "stringTransform", with: { (rawValue: Bool) -> String? in
return rawValue ? "TRUE" : "FALSE"
})
XCTAssertEqual(string.count, 1)
XCTAssertEqual(string.first, "TRUE")
let character: Set<Character> = try! data.value(for: "characterTransform", with: { (rawValue: Bool) -> Character? in
return rawValue ? "1" : "0"
})
XCTAssertEqual(character.count, 1)
XCTAssertEqual(character.first, "1")
let float: Set<Float> = try! data.value(for: "floatTransform", with: { (rawValue: String) -> Float? in
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(float.count, 1)
XCTAssertEqual(float.first, 3.14)
let double: Set<Double> = try! data.value(for: "doubleTransform", with: { (rawValue: String) -> Double? in
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(double.count, 1)
XCTAssertEqual(double.first, 3.14)
let int: Set<Int> = try! data.value(for: "intTransform", with: { (rawValue: String) -> Int? in
return Int(rawValue)
})
XCTAssertEqual(int.count, 1)
XCTAssertEqual(int.first, 12345)
let int8: Set<Int8> = try! data.value(for: "int8Transform", with: { (rawValue: String) -> Int8? in
return Int8(rawValue)
})
XCTAssertEqual(int8.count, 1)
XCTAssertEqual(int8.first, 123)
let int16: Set<Int16> = try! data.value(for: "int16Transform", with: { (rawValue: String) -> Int16? in
return Int16(rawValue)
})
XCTAssertEqual(int16.count, 1)
XCTAssertEqual(int16.first, 12345)
let int32: Set<Int32> = try! data.value(for: "int32Transform", with: { (rawValue: String) -> Int32? in
return Int32(rawValue)
})
XCTAssertEqual(int32.count, 1)
XCTAssertEqual(int32.first, 12345)
let int64: Set<Int64> = try! data.value(for: "int64Transform", with: { (rawValue: String) -> Int64? in
return Int64(rawValue)
})
XCTAssertEqual(int64.count, 1)
XCTAssertEqual(int64.first, 12345)
let uint: Set<UInt> = try! data.value(for: "uintTransform", with: { (rawValue: String) -> UInt? in
return UInt(rawValue)
})
XCTAssertEqual(uint.count, 1)
XCTAssertEqual(uint.first, 12345)
let uint8: Set<UInt8> = try! data.value(for: "uint8Transform", with: { (rawValue: String) -> UInt8? in
return UInt8(rawValue)
})
XCTAssertEqual(uint8.count, 1)
XCTAssertEqual(uint8.first, 123)
let uint16: Set<UInt16> = try! data.value(for: "uint16Transform", with: { (rawValue: String) -> UInt16? in
return UInt16(rawValue)
})
XCTAssertEqual(uint16.count, 1)
XCTAssertEqual(uint16.first, 12345)
let uint32: Set<UInt32> = try! data.value(for: "uint32Transform", with: { (rawValue: String) -> UInt32? in
return UInt32(rawValue)
})
XCTAssertEqual(uint32.count, 1)
XCTAssertEqual(uint32.first, 12345)
let uint64: Set<UInt64> = try! data.value(for: "uint64Transform", with: { (rawValue: String) -> UInt64? in
return UInt64(rawValue)
})
XCTAssertEqual(uint64.count, 1)
XCTAssertEqual(uint64.first, 12345)
let url: Set<URL> = try! data.value(for: "urlTransform", with: { (rawValue: String) -> URL? in
let urlValue = rawValue == "HOMEPAGE" ? "http://molbie.co" : rawValue
return URL(string: urlValue)
})
XCTAssertEqual(url.count, 1)
XCTAssertEqual(url.first?.absoluteString, "http://molbie.co")
let formatter = shortDateformatter()
let date: Set<Date> = try! data.value(for: "dateTransform", with: { (rawValue: String) -> Date? in
return formatter.date(from: rawValue)!
})
XCTAssertEqual(date.count, 1)
XCTAssertEqual(formatShortDate(date.first!), formatShortDate(shortDateForAssert()))
}
func testOptionalTransformValueOfOptionals() {
let bool: Set<Bool> = try! data.value(for: "boolTransform", with: { (rawValue: String?) -> Bool? in
return rawValue == "TRUE"
})
XCTAssertEqual(bool.count, 1)
XCTAssertEqual(bool.first, true)
let string: Set<String> = try! data.value(for: "stringTransform", with: { (rawValue: Bool?) -> String? in
guard let rawValue = rawValue else { return "FALSE" }
return rawValue ? "TRUE" : "FALSE"
})
XCTAssertEqual(string.count, 1)
XCTAssertEqual(string.first, "TRUE")
let character: Set<Character> = try! data.value(for: "characterTransform", with: { (rawValue: Bool?) -> Character? in
guard let rawValue = rawValue else { return "0" }
return rawValue ? "1" : "0"
})
XCTAssertEqual(character.count, 1)
XCTAssertEqual(character.first, "1")
let float: Set<Float> = try! data.value(for: "floatTransform", with: { (rawValue: String?) -> Float? in
guard let rawValue = rawValue else { return 0 }
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(float.count, 1)
XCTAssertEqual(float.first, 3.14)
let double: Set<Double> = try! data.value(for: "doubleTransform", with: { (rawValue: String?) -> Double? in
guard let rawValue = rawValue else { return 0 }
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(double.count, 1)
XCTAssertEqual(double.first, 3.14)
let int: Set<Int> = try! data.value(for: "intTransform", with: { (rawValue: String?) -> Int? in
return Int(rawValue ?? "0")
})
XCTAssertEqual(int.count, 1)
XCTAssertEqual(int.first, 12345)
let int8: Set<Int8> = try! data.value(for: "int8Transform", with: { (rawValue: String?) -> Int8? in
return Int8(rawValue ?? "0")
})
XCTAssertEqual(int8.count, 1)
XCTAssertEqual(int8.first, 123)
let int16: Set<Int16> = try! data.value(for: "int16Transform", with: { (rawValue: String?) -> Int16? in
return Int16(rawValue ?? "0")
})
XCTAssertEqual(int16.count, 1)
XCTAssertEqual(int16.first, 12345)
let int32: Set<Int32> = try! data.value(for: "int32Transform", with: { (rawValue: String?) -> Int32? in
return Int32(rawValue ?? "0")
})
XCTAssertEqual(int32.count, 1)
XCTAssertEqual(int32.first, 12345)
let int64: Set<Int64> = try! data.value(for: "intTransform", with: { (rawValue: String?) -> Int64? in
return Int64(rawValue ?? "0")
})
XCTAssertEqual(int64.count, 1)
XCTAssertEqual(int64.first, 12345)
let uint: Set<UInt> = try! data.value(for: "uintTransform", with: { (rawValue: String?) -> UInt? in
return UInt(rawValue ?? "0")
})
XCTAssertEqual(uint.count, 1)
XCTAssertEqual(uint.first, 12345)
let uint8: Set<UInt8> = try! data.value(for: "uint8Transform", with: { (rawValue: String?) -> UInt8? in
return UInt8(rawValue ?? "0")
})
XCTAssertEqual(uint8.count, 1)
XCTAssertEqual(uint8.first, 123)
let uint16: Set<UInt16> = try! data.value(for: "uint16Transform", with: { (rawValue: String?) -> UInt16? in
return UInt16(rawValue ?? "0")
})
XCTAssertEqual(uint16.count, 1)
XCTAssertEqual(uint16.first, 12345)
let uint32: Set<UInt32> = try! data.value(for: "uint32Transform", with: { (rawValue: String?) -> UInt32? in
return UInt32(rawValue ?? "0")
})
XCTAssertEqual(uint32.count, 1)
XCTAssertEqual(uint32.first, 12345)
let uint64: Set<UInt64> = try! data.value(for: "uintTransform", with: { (rawValue: String?) -> UInt64? in
return UInt64(rawValue ?? "0")
})
XCTAssertEqual(uint64.count, 1)
XCTAssertEqual(uint64.first, 12345)
let url: Set<URL> = try! data.value(for: "urlTransform", with: { (rawValue: String?) -> URL? in
let urlValue = rawValue == "HOMEPAGE" ? "http://molbie.co" : (rawValue ?? "")
return URL(string: urlValue)
})
XCTAssertEqual(url.count, 1)
XCTAssertEqual(url.first?.absoluteString, "http://molbie.co")
let formatter = shortDateformatter()
let date: Set<Date> = try! data.value(for: "dateTransform", with: { (rawValue: String?) -> Date? in
guard let dateValue = rawValue else { return nil }
return formatter.date(from: dateValue)!
})
XCTAssertEqual(date.count, 1)
XCTAssertEqual(formatShortDate(date.first!), formatShortDate(shortDateForAssert()))
}
func testTransformOptionalValueOfOptionals() {
let bool: Set<Bool>? = data.value(for: "boolTransform", with: { (rawValue: String) -> Bool? in
return rawValue == "TRUE"
})
XCTAssertEqual(bool?.count, 1)
XCTAssertEqual(bool?.first, true)
let string: Set<String>? = data.value(for: "stringTransform", with: { (rawValue: Bool) -> String? in
return rawValue ? "TRUE" : "FALSE"
})
XCTAssertEqual(string?.count, 1)
XCTAssertEqual(string?.first, "TRUE")
let character: Set<Character>? = data.value(for: "characterTransform", with: { (rawValue: Bool) -> Character? in
return rawValue ? "1" : "0"
})
XCTAssertEqual(character?.count, 1)
XCTAssertEqual(character?.first, "1")
let float: Set<Float>? = data.value(for: "floatTransform", with: { (rawValue: String) -> Float? in
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(float?.count, 1)
XCTAssertEqual(float?.first, 3.14)
let double: Set<Double>? = data.value(for: "doubleTransform", with: { (rawValue: String) -> Double? in
return rawValue == "PI" ? 3.14 : 0
})
XCTAssertEqual(double?.count, 1)
XCTAssertEqual(double?.first, 3.14)
let int: Set<Int>? = data.value(for: "intTransform", with: { (rawValue: String) -> Int? in
return Int(rawValue)
})
XCTAssertEqual(int?.count, 1)
XCTAssertEqual(int?.first, 12345)
let int8: Set<Int8>? = data.value(for: "int8Transform", with: { (rawValue: String) -> Int8? in
return Int8(rawValue)
})
XCTAssertEqual(int8?.count, 1)
XCTAssertEqual(int8?.first, 123)
let int16: Set<Int16>? = data.value(for: "int16Transform", with: { (rawValue: String) -> Int16? in
return Int16(rawValue)
})
XCTAssertEqual(int16?.count, 1)
XCTAssertEqual(int16?.first, 12345)
let int32: Set<Int32>? = data.value(for: "int32Transform", with: { (rawValue: String) -> Int32? in
return Int32(rawValue)
})
XCTAssertEqual(int32?.count, 1)
XCTAssertEqual(int32?.first, 12345)
let int64: Set<Int64>? = data.value(for: "int64Transform", with: { (rawValue: String) -> Int64? in
return Int64(rawValue)
})
XCTAssertEqual(int64?.count, 1)
XCTAssertEqual(int64?.first, 12345)
let uint: Set<UInt>? = data.value(for: "uintTransform", with: { (rawValue: String) -> UInt? in
return UInt(rawValue)
})
XCTAssertEqual(uint?.count, 1)
XCTAssertEqual(uint?.first, 12345)
let uint8: Set<UInt8>? = data.value(for: "uint8Transform", with: { (rawValue: String) -> UInt8? in
return UInt8(rawValue)
})
XCTAssertEqual(uint8?.count, 1)
XCTAssertEqual(uint8?.first, 123)
let uint16: Set<UInt16>? = data.value(for: "uint16Transform", with: { (rawValue: String) -> UInt16? in
return UInt16(rawValue)
})
XCTAssertEqual(uint16?.count, 1)
XCTAssertEqual(uint16?.first, 12345)
let uint32: Set<UInt32>? = data.value(for: "uint32Transform", with: { (rawValue: String) -> UInt32? in
return UInt32(rawValue)
})
XCTAssertEqual(uint32?.count, 1)
XCTAssertEqual(uint32?.first, 12345)
let uint64: Set<UInt64>? = data.value(for: "uint64Transform", with: { (rawValue: String) -> UInt64? in
return UInt64(rawValue)
})
XCTAssertEqual(uint64?.count, 1)
XCTAssertEqual(uint64?.first, 12345)
let url: Set<URL>? = data.value(for: "urlTransform", with: { (rawValue: String) -> URL? in
let urlValue = rawValue == "HOMEPAGE" ? "http://molbie.co" : rawValue
return URL(string: urlValue)
})
XCTAssertEqual(url?.count, 1)
XCTAssertEqual(url?.first?.absoluteString, "http://molbie.co")
let formatter = shortDateformatter()
let date: Set<Date>? = data.value(for: "dateTransform", with: { (rawValue: String) -> Date? in
return formatter.date(from: rawValue)!
})
XCTAssertEqual(date?.count, 1)
XCTAssertEqual(formatShortDate(date!.first!), formatShortDate(shortDateForAssert()))
}
func testOptionalTransformOptionalValueOfOptionals() {
let bool: Set<Bool>? = data.value(for: "boolTransform", with: { (rawValue: String?) -> Bool? in
return rawValue == "TRUE"
})
XCTAssertEqual(bool?.count, 1)
XCTAssertEqual(bool?.first, true)
let string: Set<String>? = data.value(for: "stringTransform", with: { (rawValue: Bool?) -> String? in
let value = rawValue ?? false
return value ? "TRUE" : "FALSE"
})
XCTAssertEqual(string?.count, 1)
XCTAssertEqual(string?.first, "TRUE")
let character: Set<Character>? = data.value(for: "characterTransform", with: { (rawValue: Bool?) -> Character? in
let value = rawValue ?? false
return value ? "1" : "0"
})
XCTAssertEqual(character?.count, 1)
XCTAssertEqual(character?.first, "1")
let float: Set<Float>? = data.value(for: "floatTransform", with: { (rawValue: String?) -> Float? in
let value = rawValue ?? ""
return value == "PI" ? 3.14 : 0
})
XCTAssertEqual(float?.count, 1)
XCTAssertEqual(float?.first, 3.14)
let double: Set<Double>? = data.value(for: "doubleTransform", with: { (rawValue: String?) -> Double? in
let value = rawValue ?? ""
return value == "PI" ? 3.14 : 0
})
XCTAssertEqual(double?.count, 1)
XCTAssertEqual(double?.first, 3.14)
let int: Set<Int>? = data.value(for: "intTransform", with: { (rawValue: String?) -> Int? in
return Int(rawValue ?? "")
})
XCTAssertEqual(int?.count, 1)
XCTAssertEqual(int?.first, 12345)
let int8: Set<Int8>? = data.value(for: "int8Transform", with: { (rawValue: String?) -> Int8? in
return Int8(rawValue ?? "")
})
XCTAssertEqual(int8?.count, 1)
XCTAssertEqual(int8?.first, 123)
let int16: Set<Int16>? = data.value(for: "int16Transform", with: { (rawValue: String?) -> Int16? in
return Int16(rawValue ?? "")
})
XCTAssertEqual(int16?.count, 1)
XCTAssertEqual(int16?.first, 12345)
let int32: Set<Int32>? = data.value(for: "int32Transform", with: { (rawValue: String?) -> Int32? in
return Int32(rawValue ?? "")
})
XCTAssertEqual(int32?.count, 1)
XCTAssertEqual(int32?.first, 12345)
let int64: Set<Int64>? = data.value(for: "int64Transform", with: { (rawValue: String?) -> Int64? in
return Int64(rawValue ?? "")
})
XCTAssertEqual(int64?.count, 1)
XCTAssertEqual(int64?.first, 12345)
let uint: Set<UInt>? = data.value(for: "uintTransform", with: { (rawValue: String?) -> UInt? in
return UInt(rawValue ?? "")
})
XCTAssertEqual(uint?.count, 1)
XCTAssertEqual(uint?.first, 12345)
let uint8: Set<UInt8>? = data.value(for: "uint8Transform", with: { (rawValue: String?) -> UInt8? in
return UInt8(rawValue ?? "")
})
XCTAssertEqual(uint8?.count, 1)
XCTAssertEqual(uint8?.first, 123)
let uint16: Set<UInt16>? = data.value(for: "uint16Transform", with: { (rawValue: String?) -> UInt16? in
return UInt16(rawValue ?? "")
})
XCTAssertEqual(uint16?.count, 1)
XCTAssertEqual(uint16?.first, 12345)
let uint32: Set<UInt32>? = data.value(for: "uint32Transform", with: { (rawValue: String?) -> UInt32? in
return UInt32(rawValue ?? "")
})
XCTAssertEqual(uint32?.count, 1)
XCTAssertEqual(uint32?.first, 12345)
let uint64: Set<UInt64>? = data.value(for: "uint64Transform", with: { (rawValue: String?) -> UInt64? in
return UInt64(rawValue ?? "")
})
XCTAssertEqual(uint64?.count, 1)
XCTAssertEqual(uint64?.first, 12345)
let url: Set<URL>? = data.value(for: "urlTransform", with: { (rawValue: String?) -> URL? in
let urlValue = rawValue == "HOMEPAGE" ? "http://molbie.co" : (rawValue ?? "")
return URL(string: urlValue)
})
XCTAssertEqual(url?.count, 1)
XCTAssertEqual(url?.first?.absoluteString, "http://molbie.co")
let formatter = shortDateformatter()
let date: Set<Date>? = data.value(for: "dateTransform", with: { (rawValue: String?) -> Date? in
let value = rawValue ?? "11/18/2016"
return formatter.date(from: value)!
})
XCTAssertEqual(date?.count, 1)
XCTAssertEqual(formatShortDate(date!.first!), formatShortDate(shortDateForAssert()))
}
}
| 43.19635 | 127 | 0.574393 |
ffe94ea3d183f6b40fea6fe75c97e00533a9e07f | 4,813 | //
// LMSTests.swift
// NNKit
//
// Copyright 2017 DLVM Team.
//
// 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 NNKit
class LMSTests : XCTestCase {
func testArith() {
let x = ^10
XCTAssertEqual((x + 10).!, 20)
}
func testFuncApp() {
let giveOne = lambda { ^1 }
XCTAssertEqual(giveOne[].!, 1)
let f = giveOne.!
XCTAssertEqual(f(), 1)
}
func testTuple() {
let perceptron = lambda { (w: Rep<Float>, x: Rep<Float>, b: Rep<Float>) in
w * x + b
}
let result = perceptron[^0.8, ^1.0, ^0.4].!
XCTAssertEqual(result, 1.2)
}
func testIndirectRecursion() {
func fac(_ n: Rep<Int>) -> Rep<Int> {
return .if(n == 0, then: ^1, else: n * lambda(fac)[n-1])
}
let result = fac(^5).!
XCTAssertEqual(result, 120)
}
func testResultCaching() {
let sumTimes10: Rep<(Int, Int) -> (Int) -> Int> =
lambda { x, y in lambda { z in (x + y + z) * ^10 } }
XCTAssertFalse(sumTimes10.shouldInvalidateCache)
let expr = sumTimes10 as! LambdaExpression<(Int, Int), (Int) -> Int>
XCTAssertTrue(expr.closure.body.shouldInvalidateCache)
let innerLambda = sumTimes10[^3, ^4]
XCTAssertFalse(innerLambda.shouldInvalidateCache)
let prod = innerLambda[^5]
XCTAssertEqual(prod.!, 120)
XCTAssertEqual(prod.!, 120)
let prod2 = sumTimes10[^1, ^2][prod]
XCTAssertEqual(prod2.!, 1230)
XCTAssertEqual(prod2.!, 1230)
XCTAssertEqual(prod.!, 120)
XCTAssertEqual(prod2.!, 1230)
}
func testCond() {
func fib(_ n: Rep<Int>) -> Rep<Int> {
let next = lambda { n in fib(n - 1) + fib(n - 2) }
return cond(n == 0, ^0,
n == 1, ^1,
n > 1, next[n],
else: next[n])
}
let f5 = fib(^5)
XCTAssertEqual(f5.!, 5)
XCTAssertEqual(f5.!, 5)
let f12 = lambda(fib)[f5 + 7]
XCTAssertEqual(f12.!, 144)
XCTAssertEqual(f12.!, 144)
}
func testHOF() {
/// Collections
let array = ^[1.0, 2.0, 3.0, 4.0]
let sum = array.reduce(0, +)
XCTAssertEqual(sum.!, 10)
let product = array.reduce(1, *)
XCTAssertEqual(product.!, 24)
let incrBySum = array.map { $0 + sum }
XCTAssertEqual(incrBySum.!, [11, 12, 13, 14])
let odds = array.filter { $0 % 2 != 0 }
XCTAssertEqual(odds.!, [1, 3])
let zipped = zip(array, incrBySum)
XCTAssert((zipped.!).elementsEqual(
[(1, 11), (2, 12), (3, 13), (4, 14)], by: ==))
let zippedWith = zip(array, incrBySum, with: -)
XCTAssert((zippedWith.!).elementsEqual(
[-10, -10, -10, -10], by: ==))
/// Currying
let ten = ^10
let add: Rep<(Int, Int) -> Int> = lambda(+)
let curry = lambda { (f: Rep<(Int, Int) -> Int>) in
lambda { x in
lambda { y in
f[x, y]
}
}
}
let curryAdd = curry[add]
let addTen = curryAdd[ten]
let twentyFive = addTen[^15]
XCTAssertEqual(twentyFive.!, 25)
/// Y combinator
let fac: Rep<(Int) -> Int> = fix { f in
lambda { (n: Rep<Int>) in
.if(n == 0, then: ^1, else: n * f[n - 1])
}
}
let fib: Rep<(Int) -> Int> = fix { f in
lambda { (n: Rep<Int>) in
.if(n == 0,
then: ^0,
else: .if(n == 1,
then: ^1,
else: f[n-1] + f[n-2]))
}
}
XCTAssertEqual(fac[^5].!, 120)
XCTAssertEqual(fib[^5].!, 5)
}
static var allTests : [(String, (LMSTests) -> () throws -> Void)] {
return [
("testArith", testArith),
("testFuncApp", testFuncApp),
("testTuple", testTuple),
("testIndirectRecursion", testIndirectRecursion),
("testResultCaching", testResultCaching),
("testCond", testCond),
("testHOF", testHOF)
]
}
}
| 32.086667 | 82 | 0.503636 |
5df394b2146b5f98ee899f8f19e2c2d8903b05a2 | 1,464 | //
// Result.swift
// Library
//
// Created by Cosmin Stirbu on 2/28/17.
// MIT License
//
// Copyright (c) 2017 Fortech
//
// 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
@testable import Library
public func ==<T>(lhs: Result<T>, rhs: Result<T>) -> Bool {
// Shouldn't be used for PRODUCTION enum comparison. Good enough for unit tests.
return String(describing: lhs) == String(describing: rhs)
}
| 41.828571 | 82 | 0.739071 |
03470643aafcc98a4605da49ac960693a6c65821 | 136 | //
// Define.swift
// toBook
//
// Created by Mac on 16/12/16.
// Copyright © 2016年 Mac. All rights reserved.
//
import Foundation
| 13.6 | 47 | 0.639706 |
f578125170797a2546372256c113512521edea7a | 1,009 | //
// FaceView.swift
// SampleApp
//
// Created by Cesar Vargas on 24.03.20.
// Copyright © 2020 Cesar Vargas. All rights reserved.
//
import Foundation
import Warhol
import UIKit
final class FaceView: UIView, CameraFrontView {
var viewModel: FaceViewModel?
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext(),
let viewModel = viewModel else {
return
}
context.saveGState()
defer {
context.restoreGState()
}
context.addRect(viewModel.boundingBox)
UIColor.red.setStroke()
context.strokePath()
UIColor.white.setStroke()
Array(viewModel.landmarks.values).forEach {self.draw(landmark: $0, closePath: true, in: context) }
}
private func draw(landmark: FaceLandmarkPerimeter, closePath: Bool, in context: CGContext) {
guard !landmark.isEmpty else {
return
}
context.addLines(between: landmark)
if closePath {
context.closePath()
}
context.strokePath()
}
}
| 19.784314 | 102 | 0.674926 |
0184b381b9c3821b4157bb3ba748878ddc281708 | 1,186 | //
// ViewController.swift
// Tipca
//
// Created by Laura Salazar on 9/15/18.
// Copyright © 2018 Laura Salazar. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
@IBAction func calculateTip(_ sender: Any) {
let tipPercentages = [0.10, 0.15, 0.18, 0.25]
let bill = Double(billField.text!) ?? 0
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = String(format: "$%.2f",tip)
totalLabel.text = String(format: "$%.2f", total)
}
}
| 25.782609 | 80 | 0.630691 |
fcdbdf9fd1c5ea0b812c4de8f5237a46b0644d64 | 384 | //
// PXFlowBehaviourDefault.swift
// MercadoPagoSDK
//
// Created by AUGUSTO COLLERONE ALFONSO on 11/02/2020.
//
import Foundation
/**
Default PX implementation of Flow Behaviour for public distribution. (No-trackings)
*/
final class PXFlowBehaviourDefault: NSObject, PXFlowBehaviourProtocol {
func trackConversion() {}
func trackConversion(result: PXResultKey) {}
}
| 21.333333 | 84 | 0.747396 |
b948073620ebbefdc22dc734f2f9d330eba063ff | 236 | //
// PhotoClientError.swift
// PhotoClientModels
//
// Created by Đinh Văn Nhật on 2021/10/09.
//
import Foundation
public enum PhotoClientError: Error {
case parsing(descritpion: String)
case setup(descritpion: String)
}
| 16.857143 | 43 | 0.716102 |
792623e43b4bf19db6529316608b1cb5dc04dca8 | 1,449 | //
// DailyTaskTableViewCell.swift
// Maily
//
// Created by Danb on 2017. 4. 3..
// Copyright © 2017년 Febrix. All rights reserved.
//
import UIKit
class DailyTaskTableViewCell: UITableViewCell {
@IBOutlet weak var dailyCell: UIView!
@IBOutlet weak var dailyTaskLabel: UILabel!
@IBOutlet weak var dailyTaskIcon: UIImageView!
@IBOutlet weak var dailyTaskColorBar: UIView!
@IBOutlet weak var dailyTaskGoal: UILabel!
@IBOutlet weak var dailyTaskDate: UILabel!
@IBOutlet weak var dailyTaskGoalPriority: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.2
self.layer.shadowOffset = CGSize(width: 0, height: 3)
self.layer.shadowRadius = 5
}
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
}
override func layoutSubviews() {
dailyCell.clipsToBounds = true
// dailyCell.layer.shadowColor = UIColor.blue.cgColor
// dailyCell.layer.shadowOffset = CGSize(width: 3, height: 3)
// dailyCell.layer.shadowOpacity = 0.3
dailyCell.layer.cornerRadius = 3
}
}
| 26.833333 | 68 | 0.659765 |
2f3cb854f4459eec61dfb0db8fafbdaa4523d85e | 2,907 | // JWTHelper.swift
//
// Copyright (c) 2015 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import JWTDecode
func jwt(withBody body: [String: Any]) -> JWT {
var jwt: String = ""
do {
let data = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions())
let base64 = data.base64EncodedString(options: NSData.Base64EncodingOptions())
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.\(base64).SIGNATURE"
} catch _ {
NSException(name: NSExceptionName.invalidArgumentException, reason: "Failed to build jwt", userInfo: nil).raise()
}
return try! decode(jwt: jwt)
}
func jwtThatExpiresAt(date: Date) -> JWT {
return jwt(withBody: ["exp": date.timeIntervalSince1970 as AnyObject])
}
func expiredJWT() -> JWT {
let seconds = Int(arc4random_uniform(60) + 1) * -1
let date = (Calendar.current as NSCalendar).date(byAdding: .second, value: seconds, to: Date(), options: NSCalendar.Options())
return jwtThatExpiresAt(date: date!)
}
func nonExpiredJWT() -> JWT {
let hours = Int(arc4random_uniform(200) + 1)
let date = (Calendar.current as NSCalendar).date(byAdding: .hour, value: hours, to: Date(), options: NSCalendar.Options())
return jwtThatExpiresAt(date: date!)
}
class JWTHelper: NSObject {
class func newJWT(withBody body: [String: AnyObject]) -> JWT {
return jwt(withBody: body)
}
class func newJWTThatExpiresAt(date: Date) -> JWT {
return jwtThatExpiresAt(date: date)
}
class func newExpiredJWT() -> JWT {
return expiredJWT()
}
class func newNonExpiredJWT() -> JWT {
return nonExpiredJWT()
}
}
| 38.76 | 130 | 0.699346 |
2283e89040d8c038ed9362a343a24baf4db99077 | 1,106 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
/// A function source node.
class MethodNode: TypeMemberNode {
var implementation: String?
override class func keyword() -> String { return "func" }
override func source() -> String {
var result = ""
result += Text.docs(for: name, bundle: bundle, sections: [.abstract, .discussion])
let kindString = (kind == .instance || kind == .interface) ? "" : kind.rawValue
let levelString = level == .default ? "" : level.rawValue
result += "\(levelString) \(kindString) func \(name.lowercased())() { /* code */ }\n\n"
if kind == .interface {
implementation = result
result = "func \(name.lowercased())()\n\n"
}
return result
}
}
| 30.722222 | 95 | 0.619349 |
487de43ab5511d767d26e21263697d73c632f558 | 16,859 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
import XCTest
@testable import SwiftDocC
import Markdown
class RedirectedTests: XCTestCase {
func testEmpty() throws {
let source = "@Redirected"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let redirected = Redirect(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNil(redirected)
XCTAssertEqual(1, problems.count)
XCTAssertFalse(problems.containsErrors)
XCTAssertEqual("org.swift.docc.HasArgument.from", problems.first?.diagnostic.identifier)
}
func testValid() throws {
let oldPath = "/old/path/to/this/page"
let source = "@Redirected(from: \(oldPath))"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let redirected = Redirect(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(redirected)
XCTAssertTrue(problems.isEmpty)
XCTAssertEqual(redirected?.oldPath.path, oldPath)
}
func testInvalidURL() throws {
let someCharactersThatAreNotAllowedInPaths = "⊂⧺∀ℝ∀⊂⊤∃∫"
for character in someCharactersThatAreNotAllowedInPaths {
XCTAssertFalse(CharacterSet.urlPathAllowed.contains(character.unicodeScalars.first!), "Verify that \(character) is invalid")
let pathWithInvalidCharacter = "/path/with/invalid\(character)for/paths"
let source = "@Redirected(from: \(pathWithInvalidCharacter))"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let redirected = Redirect(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNil(redirected?.oldPath.absoluteString, "\(character)")
XCTAssertFalse(problems.containsErrors)
XCTAssertEqual(1, problems.count)
XCTAssertEqual(problems.first?.diagnostic.identifier, "org.swift.docc.HasArgument.from.ConversionFailed")
XCTAssertEqual(
problems.first?.diagnostic.localizedSummary,
"Can't convert '\(pathWithInvalidCharacter)' to type URL"
)
}
}
func testExtraArguments() throws {
let oldPath = "/old/path/to/this/page"
let source = "@Redirected(from: \(oldPath), argument: value)"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let redirected = Redirect(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(redirected, "Even if there are warnings we can create a Redirected value")
XCTAssertFalse(problems.containsErrors)
XCTAssertEqual(1, problems.count)
XCTAssertEqual("org.swift.docc.UnknownArgument", problems.first?.diagnostic.identifier)
}
func testExtraDirective() throws {
let oldPath = "/old/path/to/this/page"
let source = """
@Redirected(from: \(oldPath)) {
@Image
}
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let redirected = Redirect(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(redirected, "Even if there are warnings we can create a Redirected value")
XCTAssertEqual(2, problems.count)
XCTAssertFalse(problems.containsErrors)
XCTAssertEqual("org.swift.docc.HasOnlyKnownDirectives", problems.first?.diagnostic.identifier)
XCTAssertEqual("org.swift.docc.Redirect.UnexpectedContent", problems.last?.diagnostic.identifier)
}
func testExtraContent() throws {
let oldPath = "/old/path/to/this/page"
let source = """
@Redirected(from: \(oldPath)) {
Some text
}
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let redirected = Redirect(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(redirected, "Even if there are warnings we can create a Redirected value")
XCTAssertFalse(problems.containsErrors)
XCTAssertEqual(1, problems.count)
XCTAssertEqual("org.swift.docc.Redirect.UnexpectedContent", problems.first?.diagnostic.identifier)
}
// MARK: - Redirect support
func testTechnologySupportsRedirect() throws {
let source = """
@Tutorials(name: "Technology X") {
@Intro(title: "Technology X") {
You'll learn all about Technology X.
}
@Redirected(from: /old/path/to/this/page)
@Redirected(from: /another/old/path/to/this/page)
}
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let technology = Technology(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(technology, "A Technology value can be created with a Redirected child.")
XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.localizedSummary })")
var analyzer = SemanticAnalyzer(source: nil, context: context, bundle: bundle)
_ = analyzer.visit(document)
XCTAssert(analyzer.problems.isEmpty, "Expected no problems. Got \(analyzer.problems.localizedDescription)")
}
func testVolumeAndChapterSupportsRedirect() throws {
let source = """
@Volume(name: "Name of this volume") {
@Image(source: image.png, alt: image)
@Redirected(from: /old/path/to/this/page)
@Redirected(from: /another/old/path/to/this/page)
@Chapter(name: "Chapter 1") {
In this chapter, you'll follow Tutorial 1. Feel free to add more `Reference`s below.
@Redirected(from: /old/path/to/this/page)
@Redirected(from: /another/old/path/to/this/page)
@Image(source: image.png, alt: image)
@TutorialReference(tutorial: "doc://com.test.bundle/Tutorial")
}
}
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let volume = Volume(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(volume, "A Volume value can be created with a Redirected child.")
XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.localizedSummary })")
}
func testTutorialAndSectionsSupportsRedirect() throws {
let source = """
@Tutorial(time: 20, projectFiles: project.zip) {
@Intro(title: "Basic Augmented Reality App") {
@Video(source: video.mov)
}
@Redirected(from: /old/path/to/this/page)
@Redirected(from: /another/old/path/to/this/page)
@Section(title: "Create a New AR Project") {
@ContentAndMedia {
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Phasellus faucibus scelerisque eleifend donec pretium.
Ultrices dui sapien eget mi proin sed libero enim. Quis auctor elit sed vulputate mi sit amet.
@Image(source: arkit.png, alt: "Description of this image")
}
@Redirected(from: /old/path/to/this/page)
@Redirected(from: /another/old/path/to/this/page)
@Steps {
Let's get started building the Augmented Reality app.
@Step {
Lorem ipsum dolor sit amet, consectetur.
@Image(source: Sierra.jpg, alt: "Description of this image")
}
}
}
@Assessments {
@MultipleChoice {
Lorem ipsum dolor sit amet?
@Choice(isCorrect: true) {
`anchor.hitTest(view)`
@Justification {
This is correct because it is.
}
}
@Choice(isCorrect: false) {
`anchor.hitTest(view)`
@Justification {
This is false because it is.
}
}
}
}
}
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let tutorial = Tutorial(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(tutorial, "A Tutorial value can be created with a Redirected child.")
XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.localizedSummary })")
var analyzer = SemanticAnalyzer(source: nil, context: context, bundle: bundle)
_ = analyzer.visit(document)
XCTAssert(analyzer.problems.isEmpty, "Expected no problems. Got \(analyzer.problems.localizedDescription)")
}
func testTutorialArticleSupportsRedirect() throws {
let source = """
@Article(time: 20) {
@Intro(title: "Making an Augmented Reality App") {
This is an abstract for the intro.
}
@Redirected(from: /old/path/to/this/page)
@Redirected(from: /another/old/path/to/this/page)
## Section Name
![full width image](referenced-article-image.png)
}
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let article = TutorialArticle(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(article, "A TutorialArticle value can be created with a Redirected child.")
XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.localizedSummary })")
var analyzer = SemanticAnalyzer(source: nil, context: context, bundle: bundle)
_ = analyzer.visit(document)
XCTAssert(analyzer.problems.isEmpty, "Expected no problems. Got \(analyzer.problems.localizedDescription)")
}
func testResourcesSupportsRedirect() throws {
let source = """
@Resources(technology: doc:/TestOverview) {
Find the tools and a comprehensive set of resources for creating AR experiences on iOS.
@Redirected(from: /old/path/to/this/page)
@Redirected(from: /another/old/path/to/this/page)
@Documentation(destination: "https://www.example.com/documentation/technology") {
Browse and search detailed API documentation.
- <doc://org.swift.docc.example/tutorials/Test-Bundle/TestTutorial>
- <doc://org.swift.docc.example/tutorials/Test-Bundle/TestTutorial2>
}
@SampleCode(destination: "https://www.example.com/documentation/technology") {
Browse and search detailed sample code.
- <doc://org.swift.docc.example/tutorials/Test-Bundle/TestTutorial>
- <doc://org.swift.docc.example/tutorials/Test-Bundle/TestTutorial2>
}
@Downloads(destination: "https://www.example.com/download") {
Download Xcode 10, which includes the latest tools and SDKs.
}
@Videos(destination: "https://www.example.com/videos") {
See AR presentation from WWDC and other events.
}
@Forums(destination: "https://www.example.com/forums") {
Discuss AR with Apple engineers and other developers.
}
}
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let article = Resources(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(article, "A Resources value can be created with a Redirected child.")
XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.localizedSummary })")
}
func testArticleSupportsRedirect() throws {
let source = """
# Plain article
The abstract of this article
@Redirected(from: /old/path/to/this/page)
@Redirected(from: /another/old/path/to/this/page)
## Section Name
![full width image](referenced-article-image.png)
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let article = Article(from: document, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(article, "An Article value can be created with a Redirected child.")
XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.localizedSummary })")
var analyzer = SemanticAnalyzer(source: nil, context: context, bundle: bundle)
_ = analyzer.visit(document)
XCTAssert(analyzer.problems.isEmpty, "Expected no problems. Got \(analyzer.problems.localizedDescription)")
}
func testIncorrectArgumentLabel() throws {
let source = "@Redirected(fromURL: /old/path)"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let redirected = Redirect(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNil(redirected)
XCTAssertEqual(2, problems.count)
XCTAssertFalse(problems.containsErrors)
let expectedIds = [
"org.swift.docc.UnknownArgument",
"org.swift.docc.HasArgument.from",
]
let problemIds = problems.map(\.diagnostic.identifier)
for id in expectedIds {
XCTAssertTrue(problemIds.contains(id))
}
}
}
| 46.571823 | 138 | 0.620203 |
14550f47b1e04fecd594a7b731960d4fc96f1790 | 1,337 | //
// YWChooseStrategyViewController.swift
// YWLiwuShuo
//
// Created by Mac on 2017/5/18.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class YWChooseStrategyViewController: YWBaseStrategyViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setupUIFrame()
}
func setupUI() {
headerView.addSubview(topic)
headerView.addSubview(banner)
tableView.tableHeaderView = headerView
}
func setupUIFrame() {
banner.frame = CGRectMake(0, 0, self.tableView.bounds.width, 170)
topic.frame = CGRectMake(0, banner.bounds.size.height, banner.bounds.size.width, 120)
headerView.frame = CGRectMake(0, 0, self.tableView.bounds.width, banner.bounds.height + topic.bounds.height + 10)
//重新设置高度并赋值
tableView.tableHeaderView = headerView
}
//MARK: -懒加载
private lazy var headerView: UIView = UIView()
private lazy var banner: BannerCollectionView = BannerCollectionView(frame: CGRectZero, collectionViewLayout: BannerFlowLayout())
private lazy var topic: TopicCollectionView = TopicCollectionView(frame: CGRectZero, collectionViewLayout: TopicFlowLayout())
}
| 27.285714 | 133 | 0.68362 |
61be95a6eac03359bbe5a88bce7e0a9d465cae84 | 1,155 | //
// BotViewController.swift
// LucasBot
//
// Created by Mirko Justiniano on 1/16/17.
// Copyright © 2017 LB. All rights reserved.
//
import Foundation
import UIKit
class MemoriaVC: UIViewController {
var nav:NavController?
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if (self.navigationController != nil && (self.navigationController?.isKind(of: NavController.classForCoder()))!) {
self.nav = self.navigationController as? NavController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| 25.666667 | 122 | 0.651082 |
4b7e513664ee943e03a694164e9a5207a5d0c5a5 | 4,057 | /**
https://www.hackerrank.com/challenges/ctci-is-binary-search-tree
For the purposes of this challenge, we define a binary search tree to be a binary tree with the following ordering properties:
The data value of every node in a node's left subtree is less than the data value of that node.
The data value of every node in a node's right subtree is greater than the data value of that node.
Given the root node of a binary tree, can you determine if it's also a binary search tree?
Note: A binary tree is not a binary search if there are duplicate values.
*/
import Foundation
class BinarySearchTree: CustomStringConvertible {
var nodeValue: Int
var leftTree: BinarySearchTree?
var rightTree: BinarySearchTree?
public var description: String {
let leftTree = self.leftTree == nil ? "nil" : "\(self.leftTree!)"
let rightTree = self.rightTree == nil ? "nil" : "\(self.rightTree!)"
return "\(self.nodeValue): [\(leftTree), \(rightTree)]"
}
// initializers
init(_ nodeValue:Int) {
self.nodeValue = nodeValue
}
init(_ nodeValue:Int, leftTree:BinarySearchTree?, rightTree:BinarySearchTree) {
self.nodeValue = nodeValue
self.leftTree = leftTree
self.rightTree = rightTree
}
public func getLeftChildNodeValue() -> Int? {
return self.leftTree?.nodeValue
}
public func getRightChildNodeValue() -> Int? {
return self.rightTree?.nodeValue
}
// Is it a BST?
public func isBst() -> Bool {
// Check that current node is leftNodeValue < currentNodeValue < rightNodeValue
//print("checking: \(self.nodeValue)")
// Left Node first
if let leftNodeValue = getLeftChildNodeValue() {
if leftNodeValue >= self.nodeValue {
// problem, so we can already return false
return false
}
}
// Right node next
if let rightNodeValue = getRightChildNodeValue() {
if rightNodeValue <= self.nodeValue {
// problem, so we can already return false
return false
}
}
// else, either the nodes followed the right order OR were nil (which we accept)
// Recurse into left first, then right, but only if not nil
let leftTreeIsBst:Bool
if self.leftTree == nil {
// is empty, so we call that "true"
leftTreeIsBst = true
} else {
// not empty, so we recurse
leftTreeIsBst = leftTree!.isBst()
}
let rightTreeIsBst:Bool
if self.rightTree == nil {
// is empty, so we call that "true"
rightTreeIsBst = true
} else {
// not empty, so we recurse
rightTreeIsBst = rightTree!.isBst()
}
return leftTreeIsBst && rightTreeIsBst
}
}
/**
Represent the following tree, which is a BST:
5
3 7
2 4 6 8
*/
let e1_node2 = BinarySearchTree(2)
let e1_node4 = BinarySearchTree(4)
let e1_node3 = BinarySearchTree(3,leftTree:e1_node2,rightTree:e1_node4)
let e1_node6 = BinarySearchTree(6)
let e1_node8 = BinarySearchTree(8)
let e1_node7 = BinarySearchTree(7,leftTree:e1_node6,rightTree:e1_node8)
let e1_node5_root = BinarySearchTree(5,leftTree:e1_node3,rightTree:e1_node7)
print("e1: \(e1_node5_root)")
print("e1 isBst: \(e1_node5_root.isBst())")
print()
/**
Represent the following tree, which is NOT a BST:
5
4 7
2 4 6 8
*/
let e2_node2 = BinarySearchTree(2)
let e2_node4 = BinarySearchTree(4)
let e2_node4b = BinarySearchTree(4,leftTree:e2_node2,rightTree:e2_node4)
let e2_node6 = BinarySearchTree(6)
let e2_node8 = BinarySearchTree(8)
let e2_node7 = BinarySearchTree(7,leftTree:e2_node6,rightTree:e2_node8)
let e2_node5_root = BinarySearchTree(5,leftTree:e2_node4b,rightTree:e2_node7)
print("e2: \(e2_node5_root)")
print("e2 isBst: \(e2_node5_root.isBst())")
| 30.051852 | 127 | 0.634952 |
d9b30d40a306873a51faf30874c1ab01d96fdda6 | 4,123 | import Foundation
import CryptoSwift
public extension URLRequest {
private static let kHMACShaTypeString = "AWS4-HMAC-SHA256"
private static let kAWS4Request = "aws4_request"
private static let kAllowedCharacters = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~")
private static let iso8601Formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyyMMdd'T'HHmmssXXXXX"
return formatter
}()
private var currentIso8601Date: (full: String, short: String) {
let date = URLRequest.iso8601Formatter.string(from: Date())
let shortDate = date[...String.Index(encodedOffset: 7)]
return (full: date, short: String(shortDate))
}
public mutating func sign(accessKeyId: String, secretAccessKey: String) throws {
guard let url = url, let host = url.host, let method = httpMethod else { throw SignError.generalError(reason: "URLRequest doesn't have a proper URL") }
let hostComponents = host.components(separatedBy: ".")
guard hostComponents.count > 3 else { throw SignError.generalError(reason: "Incorrect host format. The host should contain service name and region, e.g sns.us-east-1.amazonaws.com") }
let serviceName = hostComponents[0]
let awsRegion = host.starts(with: "iam") ? "us-east-1" : hostComponents[1]
var body = ""
if let bodyData = httpBody, let bodyString = String(data: bodyData, encoding: .utf8) {
body = bodyString
}
let date = currentIso8601Date
addValue(host, forHTTPHeaderField: "Host")
addValue(date.full, forHTTPHeaderField: "X-Amz-Date")
let headers = allHTTPHeaderFields ?? [:]
let signedHeaders = headers.map{ $0.key.lowercased() }.sorted().joined(separator: ";")
var urlComponents = URLComponents(string: url.absoluteString)
urlComponents?.queryItems = URLComponents(string: url.absoluteString)?.queryItems?.sorted { $0.name < $1.name }.map {
let percentEncodedName = $0.name.addingPercentEncoding(withAllowedCharacters: URLRequest.kAllowedCharacters) ?? $0.name
let percentEncodedValue = $0.value?.addingPercentEncoding(withAllowedCharacters: URLRequest.kAllowedCharacters) ?? $0.value
return URLQueryItem(name: percentEncodedName, value: percentEncodedValue)
}
let queryString = urlComponents?.query ?? ""
let canonicalRequestHash = [method, url.path == "" ? "/" : url.path, queryString,
headers.map{ $0.key.lowercased() + ":" + $0.value }.sorted().joined(separator: "\n"),
"", signedHeaders, body.sha256()].joined(separator: "\n").sha256()
let credentials = [date.short, awsRegion, serviceName, URLRequest.kAWS4Request].joined(separator: "/")
let stringToSign = [URLRequest.kHMACShaTypeString, date.full, credentials, canonicalRequestHash].joined(separator: "\n")
let signature = try [date.short, awsRegion, serviceName, URLRequest.kAWS4Request, stringToSign].reduce([UInt8]("AWS4\(secretAccessKey)".utf8), {
try HMAC(key: $0, variant: .sha256).authenticate([UInt8]($1.utf8))
}).toHexString()
let authorization = URLRequest.kHMACShaTypeString + " Credential=" + accessKeyId + "/" + credentials + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature
addValue(authorization, forHTTPHeaderField: "Authorization")
}
}
public enum SignError: Error {
case generalError(reason: String?)
}
extension SignError: LocalizedError {
public var errorDescription: String? {
switch self {
case .generalError(let reason):
return "Signing failed! " + (reason ?? "No failure reason available")
}
}
public var localizedDescription: String {
return errorDescription!
}
}
| 49.083333 | 191 | 0.672811 |
0a202450910f02856a248761d61157cd0a3f4578 | 3,499 | //
// ContactsSceneController.swift
// SFSDKStarter
//
// Created by Kevin Poorman on 10/16/19.
// Copyright © 2019 Salesforce. All rights reserved.
//
import Foundation
import UIKit
import SalesforceSDKCore
class ContactsSceneController: UITableViewController {
// MARK: - Properties
var accountId: String?
var name: String?
var contactRows = [Dictionary<String, Any>]()
// MARK: - View lifecycle
override func loadView() {
super.loadView()
updateViews()
fetchContactsFromAPI()
}
//MARK: - Helper Methods
private func updateViews() {
if let name = name {
self.title = name + "'s Contacts"
} else {
self.title = "Contacts"
}
}
private func fetchContactsFromAPI() {
guard let accountId = accountId else {
Service.showAlert(on: self, style: .alert, title: Service.errorTitle, message: Service.errorMsg)
return
}
let request = RestClient.shared.request(forQuery: "SELECT Id, Name FROM Contact WHERE accountid = '\(accountId)'")
RestClient.shared.send(request: request, onFailure: { (error, urlResponse) in
SalesforceLogger.d(type(of:self), message:"Error invoking: \(request)")
Service.showAlert(on: self, style: .alert, title: Service.errorTitle, message: error?.localizedDescription)
}) { [weak self] (response, urlResponse) in
guard let strongSelf = self,
let jsonResponse = response as? Dictionary<String,Any>,
let result = jsonResponse ["records"] as? [Dictionary<String,Any>] else {
return
}
SalesforceLogger.d(type(of:strongSelf),message:"Invoked: \(request)")
DispatchQueue.main.async {
strongSelf.contactRows = result
strongSelf.tableView.reloadData()
}
}
}
}
extension ContactsSceneController {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return self.contactRows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "ContactCell"
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier:cellIdentifier) ?? UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
let contact = contactRows[indexPath.row]
cell.textLabel?.text = contact["Name"] as? String
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.textLabel?.textColor = .white
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toContactDetailSegue" {
guard let destination = segue.destination as? ContactDetailsSceneController, let indexPath = self.tableView.indexPathForSelectedRow else {
return
}
if let name = self.contactRows[indexPath.row]["Name"] as? String {
destination.name = name
}
if let contactId = self.contactRows[indexPath.row]["Id"] as? String {
destination.contactId = contactId
}
}
}
}
| 34.303922 | 166 | 0.61589 |
e618ea25bb698382f6bc7594578f8e5135eb9663 | 5,444 | //
// AppDelegate.swift
// Cliptube
//
// Created by Daniel Vollmer on 03.10.20.
//
import AppKit
import XCDYouTubeKit
import Combine
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
@IBOutlet var watchClipboardMenuItem : NSMenuItem!
let dc: DocumentController
var pbWatcher: AnyCancellable? // our pasteboard watcher
var historySizeKVOToken: NSKeyValueObservation?
override init() {
UserDefaults.standard.registerMyDefaults()
dc = DocumentController()
}
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool { return false; }
func applicationDidFinishLaunching(_ aNotification: Notification) {
updateWatcher(shouldWatch: UserDefaults.standard.shouldWatchClipboard)
historySizeKVOToken = UserDefaults.standard.observe(\.historySize, options: [.old, .new]) { [weak self] (defaults, change) in
guard let self = self,
let oldValue = change.oldValue,
let newValue = change.newValue
else { return }
if oldValue == newValue { return }
let oldHistoryCount = self.dc.history.count
self.dc.history.maxSize = newValue
if newValue < oldHistoryCount {
// update stored history (because setting the new maxSize has truncated it)
UserDefaults.standard.history = self.dc.history.items
}
}
}
func applicationWillTerminate(_ aNotification: Notification) {
pbWatcher = nil
historySizeKVOToken?.invalidate()
UserDefaults.standard.history = dc.history.items
}
/// Enables or disables clipboard watching depending on the argument, and sets the menu item appropriately.
func updateWatcher(shouldWatch: Bool) {
if shouldWatch {
watchClipboardMenuItem.state = .on
if pbWatcher == nil {
pbWatcher = PasteboardPublisher().sink { maybeURLs in
self.dc.openAllVideos(maybeURLs: maybeURLs, display: true)
}
}
} else {
watchClipboardMenuItem.state = .off
pbWatcher = nil
}
}
@IBAction func toggleWatchClipBoard(sender: NSMenuItem) {
let shouldWatchClipboard = sender.state == .off // we invert the current state to obtain the desired state
UserDefaults.standard.shouldWatchClipboard = shouldWatchClipboard
updateWatcher(shouldWatch: shouldWatchClipboard)
}
func menuNeedsUpdate(_ menu: NSMenu) {
if menu.title == "History" {
menu.removeAllItems()
let historyItems = dc.history.items
for (id, title) in historyItems {
let item = NSMenuItem(title: title, action: #selector(DocumentController.openHistoryItem), keyEquivalent: "")
item.representedObject = id
menu.addItem(item)
}
if historyItems.count > 0 {
menu.addItem(NSMenuItem.separator())
}
menu.addItem(NSMenuItem(title: "Clear History", action: #selector(DocumentController.clearHistory), keyEquivalent: ""))
}
}
@IBAction func showHelp(_ sender: Any?) {
NSWorkspace.shared.open(URL(string: "https://www.github.com/q-p/Cliptube")!)
}
}
extension UserDefaults {
/// The key associated with the Watch Clipboard.
static let WatchClipboardKey = "watchClipboard"
/// Synthesized variable for shouldWatchClipboard, backed by the UserDefaults instance.
var shouldWatchClipboard: Bool {
get { return self.bool(forKey: UserDefaults.WatchClipboardKey) }
set { self.set(newValue, forKey: UserDefaults.WatchClipboardKey) }
}
/// The key associated with the Volume.
static let VolumeKey = "volume"
/// Synthesized variable for Volume, backed by the UserDefaults instance.
var volume: Float {
get { return self.float(forKey: UserDefaults.VolumeKey) }
set { self.set(newValue, forKey: UserDefaults.VolumeKey) }
}
/// The key associated with the HistorySize.
static let HistorySizeKey = "historySize"
/// Synthesized variable for HistorySize, backed by the UserDefaults instance.
@objc dynamic var historySize: Int {
get { return self.integer(forKey: UserDefaults.HistorySizeKey) }
set { self.set(newValue, forKey: UserDefaults.HistorySizeKey) }
}
static let HistoryKey = "history"
static let HistoryIDKey = "id"
static let HistoryTitleKey = "title"
/// Synthesized variable for History, backed by the UserDefaults instance.
var history: [(String, String)] {
get {
guard let array = self.array(forKey: UserDefaults.HistoryKey) else { return [] }
let available = min(array.count, self.historySize)
var result: [(String, String)] = []
result.reserveCapacity(available)
for itemAny in array.prefix(available) {
guard let dict = itemAny as? Dictionary<String, String>,
let id = dict[UserDefaults.HistoryIDKey],
let title = dict[UserDefaults.HistoryTitleKey]
else { continue }
result.append((id, title))
}
return result
}
set {
let available = min(newValue.count, self.historySize)
self.set(newValue.prefix(available).map { [UserDefaults.HistoryIDKey: $0, UserDefaults.HistoryTitleKey: $1] },
forKey: UserDefaults.HistoryKey)
}
}
/// Registers the defaults for Cliptube.
func registerMyDefaults() {
self.register(defaults: [
UserDefaults.WatchClipboardKey: true,
UserDefaults.HistorySizeKey: 20,
UserDefaults.HistoryKey: [],
UserDefaults.VolumeKey: 0.5,
// "NSQuitAlwaysKeepsWindows": true,
])
}
}
| 33.398773 | 129 | 0.69673 |
bb3e05fadd6fce7677b97b360fd2a9f695c458dd | 2,357 | import UIKit
/// The transition used when layout attributes change for a view during an
/// update cycle.
///
/// **'Inherited' transitions:** the 'inherited' transition is determined by searching up the tree (not literally, but
/// this is the resulting behavior). The nearest ancestor that defines an animation will be used, following this
/// logic:
/// - Ancestors with a layout transition of `none` will result in no inherited animation for their descendents.
/// - Ancestors in the tree with a layout transition of `inherited` will be skipped, and the search will continue
/// up the tree.
/// - Any ancestors in the tree with a layout transition of `inheritedWithFallback` will be used *if* they do not
/// themselves inherit a layout transition from one of their ancestors.
/// - Ancestors with a layout transition of `specific` will always be used for their descendents inherited
/// animation.
/// - If no ancestor is found that specifies a layout transition, but the containing `BlueprintView` has the `element`
/// property assigned from within a `UIKit` animation block, that animation will be used as the inherited animation.
public enum LayoutTransition {
/// The view will never animate layout changes.
case none
/// Layout changes will always animate with the given attributes.
case specific(AnimationAttributes = .default)
/// The view will only animate layout changes if an inherited transition exists.
case inherited
/// The view will animate along with an inherited transition (if present) or the specified fallback attributes.
case inheritedWithFallback(AnimationAttributes = .default)
}
extension LayoutTransition {
func perform(_ animations: @escaping () -> Void) {
switch self {
case .inherited:
animations()
case .none:
UIView.performWithoutAnimation(animations)
case .inheritedWithFallback(let fallback):
if UIView.isInAnimationBlock {
animations()
} else {
fallback.perform(
animations: animations,
completion: {}
)
}
case .specific(let attributes):
attributes.perform(
animations: animations,
completion: {}
)
}
}
}
| 37.412698 | 118 | 0.668222 |
e26ed710c5796cf051c63f8b6719c7a17e5a4d7c | 1,115 | //
// AOperationDelegate.swift
// AOperation
//
// Created by Seyed Samad Gholamzadeh on 11/25/20.
//
import Foundation
/**
Methods for react to the changes of operation's lifecycle.
Use the methods of this protocol to react to the following states:
* Operation starts to executtion
* Operation finishes its execution
*/
public protocol AOperationDelegate: class {
/// Tells the delegate the operation starts to execution
/// - Parameter operation: The operation informing the delegate of this impending event.
func operationDidStart(_ operation: AOperation)
/// Tells the delegate the operation finishes its execution
/// - Parameters:
/// - operation: The operation informing the delegate of this impending event.
/// - errors: The errors published by operation. The array would be empty if operation finishes successfully.
func operationDidFinish(_ operation: AOperation, with errors: [AOperationError])
}
public extension AOperationDelegate {
func operationDidStart(_ operation: AOperation) {}
func operationDidFinish(_ operation: AOperation, with errors: [AOperationError]) {}
}
| 29.342105 | 112 | 0.763229 |
ebf0e308543e521a6c87121c6964f04e2b6aa663 | 2,781 | //
// Barcode+cgImage.swift
// RoverExperiences
//
// Created by Andrew Clunis on 2018-08-24.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import UIKit
import os
extension Barcode {
/**
* Render the Barcode to a CGImage.
*
* Note that what length and sort of text is valid depends on the Barcode format.
*
* Note: you are responsible for freeing the returned CGImage when you are finished with it.
*/
var cgImage: CGImage? {
let filterName: String
switch format {
case .aztecCode:
filterName = "CIAztecCodeGenerator"
case .code128:
filterName = "CICode128BarcodeGenerator"
case .pdf417:
filterName = "CIPDF417BarcodeGenerator"
case .qrCode:
filterName = "CIQRCodeGenerator"
}
let data = text.data(using: String.Encoding.ascii)!
var params: [String: Any] = {
switch format {
case .pdf417:
return [
"inputCorrectionLevel": 2,
"inputPreferredAspectRatio": 4
// inputQuietSpace appears to be 2-ish, but is not configurable.
]
case .qrCode:
return [
// // we want a quiet space of 1, however it's not configurable. Thankfully, 1 is the default.
// "inputQuietSpace": 1.0,
"inputCorrectionLevel": "M"
]
case .code128:
return [
"inputQuietSpace": 1
]
case .aztecCode:
return [
"inputCompactStyle": true,
// inputQuietSpace appears to be 2-ish, but is not configurable.
// must be set to 0 or nil, but there is a bug in iOS that prevents us setting it explicitly.
// However, it is the default.
// "inputLayers": nil,
"inputCorrectionLevel": 33
]
}
}()
params["inputMessage"] = data
#if swift(>=4.2)
let filter = CIFilter(name: filterName, parameters: params)!
#else
let filter = CIFilter(name: filterName, withInputParameters: params)!
#endif
guard let outputImage = filter.outputImage else {
os_log("Unable to render barcode - see logs emitted directly by CIFilter for details", log: .general, type: .error)
return nil
}
let context = CIContext.init(options: nil)
let renderedBarcode = context.createCGImage(outputImage, from: outputImage.extent)!
return renderedBarcode
}
}
| 32.717647 | 127 | 0.532183 |
e25f5f76adb8c87f8a0d6dd4bab3a12cc230b9ff | 4,133 | //
// RankingRepository.swift
// NicoApp
//
// Created by 林達也 on 2016/03/06.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import Foundation
import NicoAPI
import NicoEntity
import RxAPISchema
import RxSwift
import QueryKit
import RealmSwift
import Timepiece
import NicoRepository
private func ==(lhs: RankingRepositoryImpl.TokenKey, rhs: RankingRepositoryImpl.TokenKey) -> Bool {
return lhs.category == rhs.category
&& lhs.period == rhs.period
&& lhs.target == rhs.target
}
public final class RankingRepositoryImpl: RankingRepository {
private struct TokenKey: Hashable {
var category: GetRanking.Category
var period: GetRanking.Category
var target: GetRanking.Target
private var hashValue: Int {
return "\(category)-\(period)-\(target)".hashValue
}
}
private let client: Client
private var tokens: [TokenKey: NotificationToken] = [:]
public init(client: Client) {
self.client = client
}
public func categories() -> [GetRanking.Category] {
return [
.All, .Music, .Ent, .Anime, .Game, .Animal, .Science, .Other
]
}
public func list(category: GetRanking.Category, period: GetRanking.Period, target: GetRanking.Target) -> Observable<[Video]> {
func cache() -> Observable<[Video]?> {
return Observable.create { subscribe in
do {
let realm = try Realm()
let ref = realm.objects(RefRanking)
.filter(RefRanking.category == category.rawValue
&& RefRanking.period == period.rawValue
&& RefRanking.target == target.rawValue
&& RefRanking.createAt > NSDate() - 30.minutes
).first
subscribe.onNext(ref.map {
$0.items.map { $0 }
})
subscribe.onCompleted()
} catch {
subscribe.onError(error)
}
return NopDisposable.instance
}.subscribeOn(mainScheduler)
}
func get() -> Observable<[Video]> {
return client
.start {
self.client.request(GetRanking(target: target, period: period, category: category))
}
.flatMap { ids in
self.client.request(GetThumbInfo<VideoImpl>(videos: ids))
}
.observeOn(backgroundScheduler)
.map { videos -> String in
let ref = RefRanking()
ref._category = category.rawValue
ref._period = period.rawValue
ref._target = target.rawValue
let realm = try Realm()
try realm.write {
realm.delete(
realm.objects(RefRanking)
.filter(RefRanking.category == category.rawValue
&& RefRanking.period == period.rawValue
&& RefRanking.target == target.rawValue
)
)
let items: [VideoImpl] = videos.map {
let video = $0 as! VideoImpl
realm.add(video, update: true)
return video
}
ref.items.appendContentsOf(items)
realm.add(ref)
}
return ref.id
}
.observeOn(mainScheduler)
.map { id in
let realm = try Realm()
realm.refresh()
let ref = realm.objectForPrimaryKey(RefRanking.self, key: id)!
return ref.items.map { $0 }
}
}
return cache() ?? get()
}
}
| 34.157025 | 130 | 0.479071 |
ff9341f3bda77b5e5872754d107547fadfa766f5 | 2,020 | #if os(iOS)
import Foundation
import SwiftUI
@available(iOS 13.0, *)
open class HostingController<State, Store: ViewControllerStore<State>, Content: StateView>: UIHostingController<Content>, StatefulView where Content.StateType == State {
private let viewStore: Store
private let delegate: Content.Delegate
public private(set) var renderPolicy: RenderPolicy
public required init(viewStore: Store) {
self.viewStore = viewStore
self.renderPolicy = .notPossible(.viewNotReady)
precondition(viewStore is Content.Delegate, "ViewStore does not conform to Delegate type: \(type(of: Content.Delegate.self))")
delegate = viewStore as! Content.Delegate
super.init(rootView: Content(state: viewStore.state, delegate: viewStore as? Content.Delegate))
// SwiftUI does not need time to "load a view" like a UIViewController since the view is declarative.
// The rendering can happen right away.
self.renderPolicy = .possible
try! self.viewStore += self
self.viewStore.viewControllerDidLoad()
}
public required init?(coder: NSCoder) {
fatalError("HostingController does not support init?(coder:)")
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewStore.viewControllerWillAppear()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
viewStore.viewControllerDidAppear()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
viewStore.viewControllerWillDisappear()
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
viewStore.viewControllerDidDisappear()
}
public func render(state: State, from distinctState: State.State?) {
rootView = Content(state: state, delegate: delegate)
}
}
#endif
| 34.237288 | 169 | 0.685644 |
eb2c978ece0788cb82e1a4aa2b365fc41f5198e2 | 613 | //
// ID3TagConfiguration.swift
//
// Created by Fabrizio Duroni on 20/02/2018.
// 2018 Fabrizio Duroni.
//
import Foundation
class ID3TagConfiguration {
private let headers: [ID3Version : [UInt8]] = [
.version2 : [UInt8]("ID3".utf8) + [0x02, 0x00, 0x00],
.version3 : [UInt8]("ID3".utf8) + [0x03, 0x00, 0x00],
.version4 : [UInt8]("ID3".utf8) + [0x04, 0x00, 0x00]
]
private let tagHeaderSizeInBytes = 10
func headerSize() -> Int {
return tagHeaderSizeInBytes
}
func headerFor(version: ID3Version) -> [UInt8] {
return headers[version]!
}
}
| 23.576923 | 61 | 0.608483 |
fcfce314d2bbd94f05995ec6f2650e1153a9ad25 | 3,777 | //
// ParseLiveQueryDelegate.swift
// ParseSwift
//
// Created by Corey Baker on 1/4/21.
// Copyright © 2021 Parse Community. All rights reserved.
//
#if !os(Linux) && !os(Android)
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
// swiftlint:disable line_length
/// Receive/respond to notifications from the ParseLiveQuery Server.
public protocol ParseLiveQueryDelegate: AnyObject {
/**
Respond to authentication requests from a ParseLiveQuery Server. If you become a delegate
and implement this method you will need to with
`completionHandler(.performDefaultHandling, nil)` to accept all connections approved
by the OS. Becoming a delegate allows you to make authentication decisions for all connections in
the `ParseLiveQuery` session, meaning there can only be one delegate for the whole session. The newest
instance to become the delegate will be the only one to receive authentication challenges.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call. Its parameters are:
- disposition - One of several constants that describes how the challenge should be handled.
- credential - The credential that should be used for authentication if disposition is
URLSessionAuthChallengeUseCredential; otherwise, `nil`.
See Apple's [documentation](https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/1411595-urlsession) for more for details.
*/
func received(_ challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition,
URLCredential?) -> Void)
/**
Receive errors from the ParseLiveQuery task/connection.
- parameter error: An error from the session task.
- note: The type of error received can vary from `ParseError`, `URLError`, `POSIXError`, etc.
*/
func received(_ error: Error)
/**
Receive unsupported data from the ParseLiveQuery task/connection.
- parameter error: An error from the session task.
*/
func receivedUnsupported(_ data: Data?, socketMessage: URLSessionWebSocketTask.Message?)
#if !os(watchOS)
/**
Receive metrics about the ParseLiveQuery task/connection.
- parameter metrics: An object that encapsualtes the performance metrics collected by the URL
Loading System during the execution of a session task.
See Apple's [documentation](https://developer.apple.com/documentation/foundation/urlsessiontasktransactionmetrics) for more for details.
*/
func received(_ metrics: URLSessionTaskTransactionMetrics)
#endif
/**
Receive notifications when the ParseLiveQuery closes a task/connection.
- parameter code: The close code provided by the server.
- parameter reason: The close reason provided by the server.
If the close frame didn’t include a reason, this value is nil.
*/
func closedSocket(_ code: URLSessionWebSocketTask.CloseCode?, reason: Data?)
}
public extension ParseLiveQueryDelegate {
func received(_ challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition,
URLCredential?) -> Void) {
completionHandler(.performDefaultHandling, nil)
}
func received(_ error: Error) { }
func receivedUnsupported(_ data: Data?, socketMessage: URLSessionWebSocketTask.Message?) { }
func received(_ metrics: URLSessionTaskTransactionMetrics) { }
func closedSocket(_ code: URLSessionWebSocketTask.CloseCode?, reason: Data?) { }
}
#endif
| 46.060976 | 150 | 0.72412 |
0904e85a6abf84e622f7af1b17aacf50614ba2b6 | 4,236 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Corner segments for the game board's border UI.
*/
import SceneKit
extension GameBoard {
enum Corner: CaseIterable {
case topLeft
case topRight
case bottomLeft
case bottomRight
var u: Float {
switch self {
case .topLeft: return -1
case .topRight: return 1
case .bottomLeft: return -1
case .bottomRight: return 1
}
}
var v: Float {
switch self {
case .topLeft: return -1
case .topRight: return -1
case .bottomLeft: return 1
case .bottomRight: return 1
}
}
}
enum Alignment: CaseIterable {
case horizontal
case vertical
func xOffset(for size: CGSize) -> Float {
switch self {
case .horizontal: return Float(size.width / 2 - BorderSegment.thickness) / 2
case .vertical: return Float(size.width / 2)
}
}
func yOffset(for size: CGSize) -> Float {
switch self {
case .horizontal: return Float(size.height / 2 - BorderSegment.thickness / 2)
case .vertical: return Float(size.height / 2) / 2
}
}
}
class BorderSegment: SCNNode {
// MARK: - Configuration & Initialization
/// Thickness of the border lines.
static let thickness: CGFloat = 0.012
/// The scale of segment's length when in the open state
static let openScale: Float = 0.4
let corner: Corner
let alignment: Alignment
let plane: SCNPlane
init(corner: Corner, alignment: Alignment, borderSize: CGSize) {
self.corner = corner
self.alignment = alignment
plane = SCNPlane(width: BorderSegment.thickness, height: BorderSegment.thickness)
self.borderSize = borderSize
super.init()
let material = plane.firstMaterial!
material.diffuse.contents = GameBoard.borderColor
material.emission.contents = GameBoard.borderColor
material.isDoubleSided = true
material.ambient.contents = UIColor.black
material.lightingModel = .constant
geometry = plane
opacity = 0.8
}
var borderSize: CGSize {
didSet {
switch alignment {
case .horizontal: plane.width = borderSize.width / 2
case .vertical: plane.height = borderSize.height / 2
}
simdScale = float3(1)
simdPosition = float3(corner.u * alignment.xOffset(for: borderSize),
corner.v * alignment.yOffset(for: borderSize),
0)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
// MARK: - Animating Open/Closed
func open() {
var offset = float2()
if alignment == .horizontal {
simdScale = float3(BorderSegment.openScale, 1, 1)
offset.x = (1 - BorderSegment.openScale) * Float(borderSize.width) / 4
} else {
simdScale = float3(1, BorderSegment.openScale, 1)
offset.y = (1 - BorderSegment.openScale) * Float(borderSize.height) / 4
}
simdPosition = float3(corner.u * alignment.xOffset(for: borderSize) + corner.u * offset.x,
corner.v * alignment.yOffset(for: borderSize) + corner.v * offset.y,
0)
}
func close() {
simdScale = float3(1)
simdPosition = float3(corner.u * alignment.xOffset(for: borderSize),
corner.v * alignment.yOffset(for: borderSize),
0)
}
}
}
| 32.837209 | 102 | 0.506138 |
e9be1f425f7396f449974c97d231e73e9be7256d | 3,454 |
import UIKit
public final class BreatheView: UIView {
public static let nodeColor: UIColor = UIColor(red: 100/255, green: 190/255, blue: 230/255, alpha: 1)
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override public func layoutSubviews() {
super.layoutSubviews()
replicatorLayer.position = center
}
public var isAnimating: Bool {
return _isAnimating
}
public var nodesCount: Int = 9 {
didSet {
stopAnimations()
updateReplicatorLayers()
}
}
public func startAnimations() {
_isAnimating = true
applyReplicatorLayerAnimations(true)
}
public func stopAnimations() {
_isAnimating = false
applyReplicatorLayerAnimations(false)
}
private var _isAnimating: Bool = false
private lazy var replicatorLayer = makeReplicatorLayer(withInstanceCount: nodesCount)
private lazy var radius: CGFloat = {
return min(bounds.width, bounds.height)/2
}()
private lazy var node: CALayer = {
let circle = CALayer()
circle.compositingFilter = "screenBlendMode"
circle.frame = CGRect(origin: CGPoint(x: 0, y: -radius/2), size: CGSize(width: radius, height: radius))
circle.backgroundColor = BreatheView.nodeColor.withAlphaComponent(0.75).cgColor
circle.cornerRadius = radius/2
return circle
}()
private var nodeAngleTransformValue: CATransform3D {
let angle = -CGFloat.pi * 2.0 / CGFloat(nodesCount)
return CATransform3DMakeRotation(angle, 0, 0, -1)
}
private func commonInit() {
backgroundColor = UIColor.clear
layer.backgroundColor = UIColor.clear.cgColor
layer.addSublayer(replicatorLayer)
}
private func makeReplicatorLayer(withInstanceCount instanceCount: Int) -> CAReplicatorLayer {
let replicatorLayer = CAReplicatorLayer()
replicatorLayer.addSublayer(node)
replicatorLayer.instanceCount = instanceCount
replicatorLayer.instanceBlueOffset = (-0.33 / Float(nodesCount))
replicatorLayer.instanceTransform = nodeAngleTransformValue
return replicatorLayer
}
private func updateReplicatorLayers() {
replicatorLayer.instanceCount = nodesCount
replicatorLayer.instanceTransform = nodeAngleTransformValue
}
private func applyReplicatorLayerAnimations(_ apply: Bool) {
if apply {
let center = CGPoint(x: layer.bounds.width/2 - radius, y: layer.bounds.height/2 - radius)
node.add(CABasicAnimation.Custom.MoveAndReverse.animation(from: node.position, to: center),
forKey: CABasicAnimation.Custom.MoveAndReverse.key)
node.add(CABasicAnimation.Custom.ScaleDownAndReverse.animation,
forKey: CABasicAnimation.Custom.ScaleDownAndReverse.key)
replicatorLayer.add(CABasicAnimation.Custom.RotateAndReverse.animation,
forKey: CABasicAnimation.Custom.RotateAndReverse.key)
} else {
node.removeAllAnimations()
replicatorLayer.removeAllAnimations()
}
}
}
| 32.895238 | 111 | 0.639838 |
ebf8d2ecf75b49f4e18f430a1ee475ac640e29e9 | 2,433 | //
// EnterPasscodeState.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
public let PasscodeLockIncorrectPasscodeNotification = "passcode.lock.incorrect.passcode.notification"
struct EnterPasscodeState: PasscodeLockStateType {
let title: String
let description: String
let isCancellableAction: Bool
var isTouchIDAllowed = true
static let incorrectPasscodeAttemptsKey = "incorrectPasscodeAttempts"
static var incorrectPasscodeAttempts: Int {
get {
return UserDefaults.standard.integer(forKey: incorrectPasscodeAttemptsKey)
}
set {
UserDefaults.standard.set(newValue, forKey: incorrectPasscodeAttemptsKey)
}
}
private var isNotificationSent = false
init(allowCancellation: Bool = false) {
isCancellableAction = allowCancellation
title = localizedStringFor("PasscodeLockEnterTitle", comment: "Enter passcode title")
description = localizedStringFor("PasscodeLockEnterDescription", comment: "Enter passcode description")
}
mutating func acceptPasscode(_ passcode: [String], fromLock lock: PasscodeLockType) {
guard let currentPasscode = lock.repository.passcode else {
return
}
var incorrectPasscodeAttempts = EnterPasscodeState.incorrectPasscodeAttempts
if passcode == currentPasscode {
lock.delegate?.passcodeLockDidSucceed(lock)
incorrectPasscodeAttempts = 0
} else {
incorrectPasscodeAttempts += 1
if incorrectPasscodeAttempts >= lock.configuration.maximumInccorectPasscodeAttempts {
postNotification()
incorrectPasscodeAttempts = 0
}
lock.delegate?.passcodeLockDidFail(lock)
}
EnterPasscodeState.incorrectPasscodeAttempts = incorrectPasscodeAttempts
}
fileprivate mutating func postNotification() {
guard !isNotificationSent else { return }
let center = NotificationCenter.default
center.post(name: Notification.Name(rawValue: PasscodeLockIncorrectPasscodeNotification), object: nil)
isNotificationSent = true
}
}
| 31.597403 | 111 | 0.652281 |
e6a1802984b272de1c869bbd6f95fce2a0ca87a4 | 4,586 | //
// AppDelegate.swift
// WatsonWasteSorter
//
// Created by XiaoguangMo on 1/31/18.
// Copyright © 2018 IBM Inc. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "WatsonWasteSorter")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 49.311828 | 285 | 0.690798 |
d717b88da11d62d830fb5406daf7c3b2fdfe6d62 | 4,719 | //
// ServiceInspectionFormFilledCellHeader.swift
// Pods-StantUiIosLibraryDemo
//
// Created by Renato Vieira on 6/4/20.
//
import UIKit
public class ServiceInspectionFormFilledCellHeader: UIView {
public var statusBadge: CellBadge?
public var circleView: UIView?
public var dateView: UIView?
public var beginAtLabel: UILabel?
public var separatorView: UIView?
public var endAtLabel: UILabel?
public func configure(status: ServiceInspectionFormFilledCellTypeEnum,
beginAt: String,
endAt: String,
color: UIColor) {
self.configureStatusBadge(status: status,
color: color)
self.configureCircle()
self.configureDateView(beginAt: beginAt,
endAt: endAt)
}
fileprivate func configureStatusBadge(status: ServiceInspectionFormFilledCellTypeEnum, color: UIColor) {
statusBadge = CellBadge()
guard let statusBadge = statusBadge else { return }
self.addSubview(statusBadge)
statusBadge.anchor(top: self.topAnchor,
leading: self.leadingAnchor)
statusBadge.configureBadge(color: color,
title: status.stringValue().uppercased(),
size: CGSize(width: 112, height: 28))
}
fileprivate func configureCircle() {
circleView = UIView()
guard let circleView = circleView else { return }
circleView.backgroundColor = .blueLightStant
circleView.layer.cornerRadius = 4
self.addSubview(circleView)
circleView.anchor(top: self.topAnchor,
leading: statusBadge?.titleLabel?.trailingAnchor,
padding: UIEdgeInsets(top: 11,
left: 8,
bottom: 0,
right: 0),
size: CGSize(width: 8,
height: 8))
}
fileprivate func configureDateView(beginAt: String, endAt: String) {
dateView = UIView()
guard let dateView = dateView else { return }
dateView.backgroundColor = .lightGrayStant
dateView.layer.cornerRadius = 3
self.addSubview(dateView)
dateView.anchor(top: self.topAnchor,
trailing: self.trailingAnchor,
padding: UIEdgeInsets(top: 4, left: 0, bottom: 0, right: 14),
size: CGSize(width: 152, height: 22))
configureDateLabels(beginAt: beginAt, endAt: endAt)
}
fileprivate func configureDateLabels(beginAt: String, endAt: String) {
beginAtLabel = UILabel()
guard let beginAtLabel = beginAtLabel else { return }
beginAtLabel.text = beginAt
beginAtLabel.textColor = .darkGrayStant
beginAtLabel.font = .systemFont(ofSize: 12)
dateView?.addSubview(beginAtLabel)
beginAtLabel.anchor(top: dateView?.topAnchor,
leading: dateView?.leadingAnchor,
bottom: dateView?.bottomAnchor,
padding: UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 0))
separatorView = UIView()
guard let separatorView = separatorView else { return }
separatorView.backgroundColor = .darkGrayStant
separatorView.layer.cornerRadius = 2
dateView?.addSubview(separatorView)
separatorView.anchor(top: dateView?.topAnchor,
leading: beginAtLabel.trailingAnchor,
padding: UIEdgeInsets(top: 9, left: 4, bottom: 0, right: 0),
size: CGSize(width: 4, height: 4))
endAtLabel = UILabel()
guard let endAtLabel = endAtLabel else { return }
endAtLabel.text = endAt
endAtLabel.textColor = .darkGrayStant
endAtLabel.font = .systemFont(ofSize: 12)
dateView?.addSubview(endAtLabel)
endAtLabel.anchor(top: dateView?.topAnchor,
leading: separatorView.trailingAnchor,
bottom: dateView?.bottomAnchor,
padding: UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 0))
}
}
| 41.761062 | 108 | 0.530409 |
6a7c2bd3c9339c8d10bc4801b7c6e97e1c764835 | 4,193 | //
// ViewController.swift
// ColoredSquare
//
// Created by burt on 2016. 2. 26..
// Copyright © 2016년 BurtK. All rights reserved.
//
import UIKit
import GLKit
class GLKUpdater : NSObject, GLKViewControllerDelegate {
weak var glkViewController : GLKViewController!
init(glkViewController : GLKViewController) {
self.glkViewController = glkViewController
}
func glkViewControllerUpdate(_ controller: GLKViewController) {
}
}
class ViewController: GLKViewController {
var glkView: GLKView!
var glkUpdater: GLKUpdater!
var vertexBuffer : GLuint = 0
var indexBuffer: GLuint = 0
var shader : BaseEffect!
let vertices : [Vertex] = [
Vertex( 1.0, -1.0, 0, 1.0, 0.0, 0.0, 1.0),
Vertex( 1.0, 1.0, 0, 0.0, 1.0, 0.0, 1.0),
Vertex(-1.0, 1.0, 0, 0.0, 0.0, 1.0, 1.0),
Vertex(-1.0, -1.0, 0, 1.0, 1.0, 0.0, 1.0)
]
let indices : [GLubyte] = [
0, 1, 2,
2, 3, 0
]
override func viewDidLoad() {
super.viewDidLoad()
setupGLcontext()
setupGLupdater()
setupShader()
setupVertexBuffer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func glkView(_ view: GLKView, drawIn rect: CGRect) {
glClearColor(1.0, 0.0, 0.0, 1.0);
glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
// shader.begin() 이 더 나은거 같다.
shader.prepareToDraw()
// 이렇게 하면 매 드로잉 콜마다
// 정점과 인덱스 데이터를 CPU에서 GPU로 복사해야 하므로 성능이 떨이지는 단점이 있다.
// 이를 해결하기 위해서 VertexArrayObject를 사용하는 것이다.
// 프로그램 초기에 VAO를 GPU만들어서 거기에 모든 데이터를 CPU에서 GPU로 한번 설정한다.
// 그리고 매 드로잉콜에서는 VAO를 바인딩해서 사용하면 된다.
// 즉, 그리고자 하는 모델이 VAO를 가지고 있으면 된다.
// 모델이 생성될 때, 정점 등의 데이터를 읽어서 자신의 VAO를 GPU에 만들고
// VAO에 데이터를 전송하면 매 드로잉콜마다 데이터를 전송할 필요 없이
// 자신의 VAO를 바인딩해서 사용하며 된다.
glEnableVertexAttribArray(VertexAttributes.position.rawValue)
glVertexAttribPointer(
VertexAttributes.position.rawValue,
3,
GLenum(GL_FLOAT),
GLboolean(GL_FALSE),
GLsizei(MemoryLayout<Vertex>.size), BUFFER_OFFSET(0))
glEnableVertexAttribArray(VertexAttributes.color.rawValue)
glVertexAttribPointer(
VertexAttributes.color.rawValue,
4,
GLenum(GL_FLOAT),
GLboolean(GL_FALSE),
GLsizei(MemoryLayout<Vertex>.size), BUFFER_OFFSET(3 * MemoryLayout<GLfloat>.size)) // x, y, z | r, g, b, a :: offset is 3*sizeof(GLfloat)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBuffer)
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), indexBuffer)
glDrawElements(GLenum(GL_TRIANGLES), GLsizei(indices.count), GLenum(GL_UNSIGNED_BYTE), nil)
glDisableVertexAttribArray(VertexAttributes.position.rawValue)
}
}
extension ViewController {
func setupGLcontext() {
glkView = self.view as! GLKView
glkView.context = EAGLContext(api: .openGLES2)!
EAGLContext.setCurrent(glkView.context)
}
func setupGLupdater() {
self.glkUpdater = GLKUpdater(glkViewController: self)
self.delegate = self.glkUpdater
}
func setupShader() {
self.shader = BaseEffect(vertexShader: "SimpleVertexShader.glsl", fragmentShader: "SimpleFragmentShader.glsl")
}
func setupVertexBuffer() {
glGenBuffers(GLsizei(1), &vertexBuffer)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBuffer)
let count = vertices.count
let size = MemoryLayout<Vertex>.size
glBufferData(GLenum(GL_ARRAY_BUFFER), count * size, vertices, GLenum(GL_STATIC_DRAW))
glGenBuffers(GLsizei(1), &indexBuffer)
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), indexBuffer)
glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), indices.count * MemoryLayout<GLubyte>.size, indices, GLenum(GL_STATIC_DRAW))
}
func BUFFER_OFFSET(_ n: Int) -> UnsafeRawPointer? {
return UnsafeRawPointer(bitPattern: n)
}
}
| 30.605839 | 149 | 0.618412 |
dd1c4f37f5e46d0f86a9bd923fff577614971ea7 | 2,737 | //
// BigInt Exponentiation.swift
//
// Created by pebble8888 on 2017/05/13.
//
//
import Foundation
import BigInt
extension BigInt {
// 0 or 1
public func parity() -> Int {
return self.magnitude.parity()
}
public init(word: Word) {
let m = BigUInt(word)
self.init(sign: .plus, magnitude: m)
}
}
extension BigUInt {
// return value: 0 or 1
public func parity() -> Int {
let a = self % BigUInt(2)
let b = a & 1
return Int(b)
}
}
extension BigInt {
/* python, ruby
>>> 7 % 3
1
>>> 7 % -3
-2
>>> -7 % 3
2
>>> -7 % -3
-1
*/
public func modulo(_ divider: BigInt) -> BigInt {
let v = self.magnitude % divider.magnitude
if v == 0 {
return 0
}
if self.sign == .plus {
if divider.sign == .plus {
return BigInt(sign: .plus, magnitude: v)
} else {
return BigInt(sign: .plus, magnitude: v) + divider
}
} else {
if divider.sign == .plus {
return BigInt(sign: .minus, magnitude: v) + divider
} else {
return BigInt(sign: .minus, magnitude: v)
}
}
}
/** python, ruby
>>> 7 / 2
3
>>> 7 / -2
-4
>>> -7 / 2
-4
>>> -7 / -2
3
*/
public func divide(_ divider: BigInt) -> BigInt {
let v = self.magnitude / divider.magnitude
if self.sign == .plus {
if divider.sign == .plus {
return BigInt(sign: .plus, magnitude: v)
} else {
if (self.magnitude % divider.magnitude) == 0 {
return BigInt(sign: .minus, magnitude: v)
} else {
return BigInt(sign: .minus, magnitude: v+1)
}
}
} else {
if divider.sign == .plus {
if (self.magnitude % divider.magnitude) == 0 {
return BigInt(sign: .minus, magnitude: v)
} else {
return BigInt(sign: .minus, magnitude: v+1)
}
} else {
return BigInt(sign: .plus, magnitude: v)
}
}
}
// return val is less than q
public static func expmod(_ b: BigInt, _ e: BigInt, _ q: BigInt) -> BigInt {
if e == 0 { return 1 }
var t = expmod(b, e.divide(2), q).power(2).modulo(q)
if e.parity() != 0 {
t = (t*b).modulo(q)
}
return t
}
// return val is less than q
public static func inv(_ x: BigInt, _ q: BigInt) -> BigInt {
return expmod(x, q-2, q)
}
}
| 24.008772 | 80 | 0.448666 |
fe654a8439888133204dde89a6ba1b2c88b582a5 | 214 | //
// AddTagImageError.swift
// wallpapper
//
// Created by Marcin Czachurski on 11/07/2018.
// Copyright © 2018 Marcin Czachurski. All rights reserved.
//
import Foundation
class AddTagImageError: Error {
}
| 16.461538 | 60 | 0.719626 |
e578e0225f6b741149857bb7dec3722170d90a9f | 630 | extension TextOutputStream {
public mutating func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
let print = unsafeBitCast(
Swift.print(_:separator:terminator:to:) as VPrintFunction<Self>,
to: PrintFunction<Self>.self
)
print(items, separator, terminator, &self)
}
public mutating func debugPrint(_ items: Any..., separator: String = " ", terminator: String = "\n") {
let print = unsafeBitCast(
Swift.debugPrint(_:separator:terminator:to:) as VPrintFunction<Self>,
to: PrintFunction<Self>.self
)
print(items, separator, terminator, &self)
}
}
| 35 | 104 | 0.668254 |
e565fe8c40ed85d18f8aa7fbfa2048c1e6f8755a | 1,807 | //
// OpportunityDetailViewController.swift
// helloworld-ios-app
//
// Created by Marco Metting on 08.03.18.
// Copyright © 2018 FeedHenry. All rights reserved.
//
import UIKit
import FeedHenry
class OpportunityDetailViewController: UIViewController {
@IBOutlet weak var subscribeButton: UIButton!
@IBOutlet weak var dealSize: UILabel!
@IBOutlet weak var status: UILabel!
@IBOutlet weak var name: UILabel!
var opp : Opportunity!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
self.dealSize.text = String(describing: self.opp.dealSize)
self.name.text = self.opp.name
self.status.text = self.opp.status
if (self.opp.subscribed) {
self.subscribeButton.isHidden = true
} else {
self.subscribeButton.isHidden = false
}
}
@IBAction func subscribePressed(_ sender: Any) {
let args = ["data": self.opp.toJson()] as [String : AnyObject]
UIApplication.shared.isNetworkActivityIndicatorVisible = true
FH.cloud(path: "opportunities/subscribe",
method: HTTPMethod.POST,
args: args,
completionHandler: {(resp: Response, error: NSError?) -> Void in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if error != nil {
print("Cloud Call Failed: " + (error?.localizedDescription)!)
return
}
print("Success")
self.navigationController?.popViewController(animated: true)
})
}
}
| 30.116667 | 85 | 0.566685 |
f811e6d08dbecf38995dabc5162c90a5983bc0de | 7,981 | //
// CountryPickerView.swift
// CountryPickerView
//
// Created by Kizito Nwose on 18/09/2017.
// Copyright © 2017 Kizito Nwose. All rights reserved.
//
import UIKit
public typealias CPVCountry = Country
public enum SearchBarPosition {
case tableViewHeader, navigationBar, hidden
}
public struct Country: Equatable {
public let name: String
public let code: String
public let phoneCode: String
public func localizedName(_ locale: Locale = Locale.current) -> String? {
return locale.localizedString(forRegionCode: code)
}
public var flag: UIImage {
return UIImage(named: "CountryPickerView.bundle/Images/\(code.uppercased())",
in: Bundle(for: CountryPickerView.self), compatibleWith: nil)!
}
}
public func ==(lhs: Country, rhs: Country) -> Bool {
return lhs.code == rhs.code
}
public func !=(lhs: Country, rhs: Country) -> Bool {
return lhs.code != rhs.code
}
public class CountryPickerView: NibView {
@IBOutlet weak var spacingConstraint: NSLayoutConstraint!
@IBOutlet public weak var flagImageView: UIImageView! {
didSet {
flagImageView.clipsToBounds = true
flagImageView.layer.masksToBounds = true
flagImageView.layer.cornerRadius = 2
}
}
@IBOutlet public weak var countryDetailsLabel: UILabel!
/// Show/Hide the country code on the view.
public var showCountryCodeInView = true {
didSet {
if showCountryNameInView && showCountryCodeInView {
showCountryNameInView = false
} else {
setup()
}
}
}
/// Show/Hide the phone code on the view.
public var showPhoneCodeInView = true {
didSet { setup() }
}
/// Show/Hide the country name on the view.
public var showCountryNameInView = false {
didSet {
if showCountryCodeInView && showCountryNameInView {
showCountryCodeInView = false
} else {
setup()
}
}
}
/// Change the font of phone code
public var font = UIFont.systemFont(ofSize: 17.0) {
didSet { setup() }
}
/// Change the text color of phone code
public var textColor = UIColor.black {
didSet { setup() }
}
/// The spacing between the flag image and the text.
public var flagSpacingInView: CGFloat {
get {
return spacingConstraint.constant
}
set {
spacingConstraint.constant = newValue
}
}
weak public var dataSource: CountryPickerViewDataSource?
weak public var delegate: CountryPickerViewDelegate?
weak public var hostViewController: UIViewController?
fileprivate var _selectedCountry: Country?
internal(set) public var selectedCountry: Country {
get {
return _selectedCountry
?? countries.first(where: { $0.code == Locale.current.regionCode })
?? countries.first!
}
set {
_selectedCountry = newValue
delegate?.countryPickerView(self, didSelectCountry: newValue)
setup()
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
flagImageView.image = selectedCountry.flag
countryDetailsLabel.font = font
countryDetailsLabel.textColor = textColor
if showCountryCodeInView && showPhoneCodeInView {
countryDetailsLabel.text = "(\(selectedCountry.code)) \(selectedCountry.phoneCode)"
} else if showCountryNameInView && showPhoneCodeInView {
countryDetailsLabel.text = "(\(selectedCountry.localizedName() ?? selectedCountry.name)) \(selectedCountry.phoneCode)"
} else if showCountryCodeInView || showPhoneCodeInView || showCountryNameInView {
countryDetailsLabel.text = showCountryCodeInView ? selectedCountry.code
: showPhoneCodeInView ? selectedCountry.phoneCode
: selectedCountry.localizedName() ?? selectedCountry.name
} else {
countryDetailsLabel.text = nil
}
}
@IBAction func openCountryPickerController(_ sender: Any) {
if let hostViewController = hostViewController {
showCountriesList(from: hostViewController)
return
}
if let vc = window?.topViewController {
if let tabVc = vc as? UITabBarController,
let selectedVc = tabVc.selectedViewController {
showCountriesList(from: selectedVc)
} else {
showCountriesList(from: vc)
}
}
}
public func showCountriesList(from viewController: UIViewController) {
let countryVc = CountryPickerViewController(style: .grouped)
countryVc.countryPickerView = self
if let viewController = viewController as? UINavigationController {
delegate?.countryPickerView(self, willShow: countryVc)
viewController.pushViewController(countryVc, animated: true) {
self.delegate?.countryPickerView(self, didShow: countryVc)
}
} else {
let navigationVC = UINavigationController(rootViewController: countryVc)
delegate?.countryPickerView(self, willShow: countryVc)
viewController.present(navigationVC, animated: true) {
self.delegate?.countryPickerView(self, didShow: countryVc)
}
}
}
public let countries: [Country] = {
var countries = [Country]()
let bundle = Bundle(for: CountryPickerView.self)
guard let jsonPath = bundle.path(forResource: "CountryPickerView.bundle/Data/CountryCodes", ofType: "json"),
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) else {
return countries
}
if let jsonObjects = (try? JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization
.ReadingOptions.allowFragments)) as? Array<Any> {
for jsonObject in jsonObjects {
guard let countryObj = jsonObject as? Dictionary<String, Any> else {
continue
}
guard let name = countryObj["name"] as? String,
let code = countryObj["code"] as? String,
let phoneCode = countryObj["dial_code"] as? String else {
continue
}
let country = Country(name: name, code: code, phoneCode: phoneCode)
countries.append(country)
}
}
return countries
}()
}
//MARK: Helper methods
extension CountryPickerView {
public func setCountryByName(_ name: String) {
if let country = countries.first(where: { $0.name == name }) {
selectedCountry = country
}
}
public func setCountryByPhoneCode(_ phoneCode: String) {
if let country = countries.first(where: { $0.phoneCode == phoneCode }) {
selectedCountry = country
}
}
public func setCountryByCode(_ code: String) {
if let country = countries.first(where: { $0.code == code }) {
selectedCountry = country
}
}
public func getCountryByName(_ name: String) -> Country? {
return countries.first(where: { $0.name == name })
}
public func getCountryByPhoneCode(_ phoneCode: String) -> Country? {
return countries.first(where: { $0.phoneCode == phoneCode })
}
public func getCountryByCode(_ code: String) -> Country? {
return countries.first(where: { $0.code == code })
}
}
| 33.961702 | 130 | 0.603433 |
ab65d4ef5de052e72c37453e192a3c41fda4395d | 921 | //
// NewsLoadingFooter.swift
// NewsClient
//
// Created by chihhao on 2019-06-15.
// Copyright © 2019 ChihHao. All rights reserved.
//
import UIKit
class NewsLoadingFooter: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
let aiv = UIActivityIndicatorView(style: .large)
aiv.color = .darkGray
aiv.startAnimating()
let loadingLabel = UILabel(text: "Loading...", font: UIFont.preferredFont(forTextStyle: .body), color: .label)
let verticalStack = VerticalStackView(arrangedSubviews: [aiv, loadingLabel], spacing: 8)
addSubview(verticalStack)
verticalStack.centerInSuperview(size: .init(width: 200, height: 0))
verticalStack.alignment = .center
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 27.909091 | 112 | 0.647123 |
fb2ac5874eff91d879eac17d5b123e223204194c | 291 | import Foundation
import CoreData
extension Photo {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Photo> {
return NSFetchRequest<Photo>(entityName: "Photo")
}
@NSManaged public var photoID: String?
@NSManaged public var remoteURL: NSObject?
}
| 14.55 | 72 | 0.697595 |
8fe0e24615fb0bcc9a2617c2ad94de1109261b61 | 121 | //
// Cost.swift
// Example
//
import Foundation
struct Cost {
let amount: Decimal
let currency: Currency
}
| 9.307692 | 26 | 0.636364 |
3a9b825226dffa4977473cf8057cc0277085f65b | 860 | import Foundation
import WebKit
import ServiceWorkerContainer
import ServiceWorker
import PromiseKit
class ServiceWorkerRegistrationCommands {
static func unregister(eventStream: EventStream, json: AnyObject?) throws -> Promise<Any?>? {
guard let registrationID = json?["id"] as? String else {
throw ErrorMessage("Must provide registration ID in JSON body")
}
return eventStream.container.getRegistrations()
.then { registrations in
guard let registration = registrations.first(where: { $0.id == registrationID }) else {
throw ErrorMessage("Registration does not exist")
}
return registration.unregister()
}
.then {
[
"success": true
]
}
}
}
| 27.741935 | 103 | 0.582558 |
e917ab337295ca1e865af2105a49aedc3df608c3 | 4,338 | //
// Copyright (c) 2021 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import SwiftUI
#if canImport(SwiftUI) && canImport(Combine)
/// :nodoc:
@available(iOS 13.0, *)
public extension View {
/// Present a `ViewController` modally.
///
/// - Parameter viewController: A `Binding<UIViewController?>` instance,
/// set the `wrappedValue` to a view controller instance to dismiss the previous view controller if it had previously a value
/// and presents the new one,
/// set it to `nil` to dismiss the previous view Controller if any.
func present(viewController: Binding<UIViewController?>) -> some View {
modifier(ViewControllerPresenter(viewController: viewController))
}
}
/// :nodoc:
@available(iOS 13.0, *)
internal struct ViewControllerPresenter: ViewModifier {
@Binding internal var viewController: UIViewController?
internal func body(content: Content) -> some View {
ZStack {
FullScreenView(viewController: $viewController)
content
}
}
}
/// :nodoc:
@available(iOS 13.0, *)
internal final class FullScreenView: UIViewControllerRepresentable {
@Binding internal var viewController: UIViewController?
internal init(viewController: Binding<UIViewController?>) {
self._viewController = viewController
}
internal final class Coordinator {
fileprivate var currentlyPresentedViewController: UIViewController?
}
internal func makeUIViewController(context: UIViewControllerRepresentableContext<FullScreenView>) -> UIViewController {
UIViewController()
}
internal func makeCoordinator() -> Coordinator {
Coordinator()
}
internal func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<FullScreenView>) {
if let viewController = viewController, viewController !== context.coordinator.currentlyPresentedViewController {
dismissIfNeededThenPresent(viewController: viewController, presenter: uiViewController, context: context)
} else if context.coordinator.currentlyPresentedViewController != nil, viewController == nil {
dismiss(presenter: uiViewController, context: context, completion: nil)
}
}
private func dismissIfNeededThenPresent(viewController: UIViewController,
presenter: UIViewController,
context: UIViewControllerRepresentableContext<FullScreenView>) {
if context.coordinator.currentlyPresentedViewController != nil {
dismiss(presenter: presenter, context: context) { [weak self] in
self?.present(viewController: viewController, presenter: presenter, context: context)
}
} else {
present(viewController: viewController, presenter: presenter, context: context)
}
}
private func present(viewController: UIViewController,
presenter: UIViewController,
context: UIViewControllerRepresentableContext<FullScreenView>) {
guard !viewController.isBeingPresented, !viewController.isBeingDismissed else { return }
presenter.present(viewController, animated: true) {
context.coordinator.currentlyPresentedViewController = viewController
}
}
private func dismiss(presenter: UIViewController,
context: UIViewControllerRepresentableContext<FullScreenView>,
completion: (() -> Void)?) {
guard let viewController = context.coordinator.currentlyPresentedViewController else { return }
guard !viewController.isBeingPresented, !viewController.isBeingDismissed else { return }
presenter.dismiss(animated: true) {
context.coordinator.currentlyPresentedViewController = nil
completion?()
}
}
}
#endif
| 40.166667 | 147 | 0.635546 |
75e84d03575c1c39c3a34d703ccc67bad274df69 | 550 | //
// DemoViewModel.swift
// Demo
//
// Created by Bruno Oliveira on 17/01/2019.
// Copyright © 2019 Ash Furrow. All rights reserved.
//
import Foundation
import Moya
import Moya_ObjectMapper
import RxSwift
extension Reactive where Base: RxDemoViewModel {
func downloadRepositories(_ username: String) -> Single<[Repository]> {
return base.networking.rx.request(.userRepositories(username))
.mapArray(Repository.self)
}
func downloadZen() -> Single<String> {
return base.networking.rx.request(.zen)
.mapString()
}
}
| 21.153846 | 73 | 0.716364 |
03d919420d345aedc063de7dd0eb4a1e39d21dd5 | 2,125 | //
// AppGroupStore.swift
// FirstApp
//
// Created by Cédric Bahirwe on 15/09/2021.
//
import Foundation
/**
This class enforces the fact that App Group applications get and set data at the same spot.
It uses UserDefaults to store DeviceToken.
And with the help of the `FileHelper` a shared `FileManager` container to store a custom text.
**/
enum UserDefaultsKey: String {
case userSessionData, deviceToken
}
public class AppGroupStore: ObservableObject {
private let userDefaults: UserDefaults?
private let fileHelper: FileHelper
public struct UserModel: Codable {
var username: String
var email: String
}
public init(appGroupName: String) {
self.userDefaults = UserDefaults(suiteName: appGroupName)
self.fileHelper = FileHelper(appGroupName: appGroupName, fileName: "CustomText")
}
public private(set) var userSession: UserModel? {
get {
guard let data = userDefaults?.data(forKey: UserDefaultsKey.userSessionData.rawValue) else { return nil }
return try? JSONDecoder().decode(UserModel.self, from: data)
} set {
let data = try? JSONEncoder().encode(newValue)
userDefaults?.set(data, forKey: UserDefaultsKey.userSessionData.rawValue)
objectWillChange.send()
}
}
public var deviceToken: String? {
get {
userDefaults?.string(forKey: UserDefaultsKey.deviceToken.rawValue)
}
set {
userDefaults?.set(newValue, forKey: UserDefaultsKey.deviceToken.rawValue)
objectWillChange.send()
}
}
public var customText: String? {
get {
return fileHelper.contentOfFile()
}
set {
fileHelper.write(message: newValue)
objectWillChange.send()
}
}
public func storeSessionLocally(for user: UserModel) {
userSession = user
}
public func removeCurrentSession() {
userSession = nil
}
public func refreshSession() {
userSession = userSession
}
}
| 26.234568 | 117 | 0.633882 |
1a89f5a8092e4799eb285aa3065a6d678a1185b8 | 2,677 | //
// LimaBandClient.swift
// Lima
//
// Created by Leandro Tami on 4/20/17.
// Copyright © 2017 LateralView. All rights reserved.
//
import Foundation
public typealias ScanHandler = (_ success: Bool, _ devices: [BluetoothDevice]?) -> Void
public typealias ConnectHandler = (_ success: Bool, _ fitnessDevice: FitnessDevice?) -> Void
public typealias DisconnectHandler = (_ fitnessDevice: FitnessDevice?) -> Void
public class LimaBandClient: FitnessDeviceManagerDelegate
{
public static let shared = LimaBandClient()
public static var verbose = false
private var manager : FitnessDeviceManager!
public var isBluetoothAvailable : Bool {
return manager.isBluetoothAvailable
}
public var currentDevice : FitnessDevice? {
return manager.fitnessDevice
}
public var rssiFilterValue: Double = -80.0 {
didSet {
manager.rssiFilterValue = rssiFilterValue
}
}
private var scanHandler : ScanHandler?
private var connectHandler : ConnectHandler?
private var disconnectHandler : DisconnectHandler?
private init()
{
}
static func log(_ text: String) {
if LimaBandClient.verbose {
print("[-] LimaBandClient: \(text)")
}
}
static func error(_ text: String) {
print("[X] LimaBandClient: \(text)")
}
public func start()
{
manager = FitnessDeviceManager()
manager.delegate = self
}
public func scan(filterBySignalLevel: Bool, handler: @escaping ScanHandler)
{
// wait some time until Bluetooth is ready
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.scanHandler = handler
self.manager.scan(filterBySignalLevel: filterBySignalLevel)
}
}
public func connect(device: BluetoothDevice, handler: @escaping ConnectHandler)
{
self.connectHandler = handler
manager.connect(toDevice: device)
}
public func notifyDisconnection(handler: @escaping DisconnectHandler)
{
self.disconnectHandler = handler
}
// MARK: - FitnessDeviceManagerDelegate
func didFind(success: Bool, devices: [BluetoothDevice])
{
scanHandler?(success, devices)
scanHandler = nil
}
func didConnect(success: Bool, fitnessDevice: FitnessDevice?)
{
connectHandler?(success, fitnessDevice)
connectHandler = nil
}
func didDisconnect(fitnessDevice: FitnessDevice?)
{
scanHandler?(false, nil)
scanHandler = nil
disconnectHandler?(fitnessDevice)
}
}
| 25.990291 | 95 | 0.639148 |
9bea9709f118fb03881ce0190dbf6f4d6a7022b2 | 1,880 | //
// BoolExpressionTests.swift
// UltramarineTests
//
import XCTest
import Ultramarine
class BoolExpressionTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testAnd() throws {
let isBird = false.subject()
let isMale = false.subject()
let isMaleBird = isBird && isMale
XCTAssertFalse(isMaleBird.value)
isBird <<= true
XCTAssertTrue(isBird.value)
XCTAssertFalse(isMale.value)
XCTAssertFalse(isMaleBird.value)
isMale <<= true
XCTAssertTrue(isBird.value)
XCTAssertTrue(isMale.value)
XCTAssertTrue(isMaleBird.value)
}
func testOr() throws {
let isLoadingA = false.subject()
let isLoadingB = false.subject()
let isNowLoading = isLoadingA || isLoadingB
XCTAssertFalse(isNowLoading.value)
isLoadingA <<= true
isLoadingB <<= false
XCTAssertTrue(isLoadingA.value)
XCTAssertFalse(isLoadingB.value)
XCTAssertTrue(isNowLoading.value)
isLoadingA <<= false
isLoadingB <<= true
XCTAssertFalse(isLoadingA.value)
XCTAssertTrue(isLoadingB.value)
XCTAssertTrue(isNowLoading.value)
}
func testNot() throws {
let isHead = true.subject()
let isTail = !isHead
XCTAssertTrue(isHead.value)
XCTAssertFalse(isTail.value)
isHead <<= false
XCTAssertFalse(isHead.value)
XCTAssertTrue(isTail.value)
}
}
| 26.111111 | 111 | 0.607447 |
5011e41dae80e294e8e3c8eb4e67b440e2165c14 | 3,527 | //
// HCLHCPSearchWebServices.swift
// HealthCareLocatorSDK
//
// Created by Truong Le on 11/10/20.
//
import Foundation
import Apollo
/**
The APIs class which used to perform request to the server and retrieve the result without UI required in case you want to build your own search UI
- Example: This show how to use the **HCLManager**
````
let manager = HCLManager.share
manager.initialize(apiKey: <YOUR_API_KEY>)
let webservices = manager.getHCPSearchViewController()
````
- Important:
The APIs must be access through HCLManager instance after initialize with the api key
*/
public class HCLHCPSearchWebServices: SearchAPIsProtocol {
private let manager: HCLServiceManager!
required init(manager: HCLServiceManager) {
self.manager = manager
}
/**
Fetch detail information of an activity
*/
public func fetchActivityWith(id: String!,
locale: String?,
userId: String?,
completionHandler: @escaping ((Activity?, Error?) -> Void)) {
manager.fetchActivityWith(id: id, locale: locale, userId: userId, completionHandler: completionHandler)
}
/**
Fetch the list of specialties which can be used to perform activities searching
*/
public func fetchCodesByLabel(info: GeneralQueryInput,
criteria: String!,
codeTypes: [String],
userId: String?,
completionHandler: @escaping (([Code]?, Error?) -> Void)) {
manager.fetchCodesByLabel(info: info, criteria: criteria, codeTypes: codeTypes, userId: userId, completionHandler: completionHandler)
}
/**
Fetch detail info for a code to get its name
*/
public func fetchLabelBy(code: String, completionHandler: @escaping ((Code?, Error?) -> Void)) {
manager.fetchLabelBy(code: code, completionHandler: completionHandler)
}
/**
Fetch the list of simple individual objects
- Note: This API does not return the full detail of individual but it light enough to perform quick suggestion on list
*/
public func fetchIndividualsByNameWith(info: GeneralQueryInput,
county: String?,
criteria: String!,
userId: String?,
completionHandler: @escaping (([IndividualWorkPlaceDetails]?, Error?) -> Void)) {
manager.fetchIndividualsByNameWith(info: info, county: county, criteria: criteria, userId: userId, completionHandler: completionHandler)
}
/**
Fetch the list of activities by using specialties codes or criteria text which input by user
- Note: specialties codes or criteria text can only provide one to make the request works as expected
*/
public func fetchActivitiesWith(info: GeneralQueryInput,
specialties: [String]?,
location: GeopointQuery?,
county: String?,
criteria: String?,
userId: String?,
completionHandler: @escaping (([ActivityResult]?, Error?) -> Void)) {
manager.fetchActivitiesWith(info: info, specialties: specialties, location: location, county: county, criteria: criteria, userId: userId, completionHandler: completionHandler)
}
}
| 41.011628 | 183 | 0.612135 |
220072fa25c20f11d51a4a6fb387938dea625848 | 3,559 | //
// PinCodeWrongAnimationOption.swift
// PasscodeLock
//
// Created by VitaliyK on 10/25/18.
// Copyright © 2018 Yanko Dimitrov. All rights reserved.
//
import Foundation
public typealias PinCodeShakeAnimationOptions = Array<PinCodeShakeAnimationOptionItem>
public let PinCodeShakeAnimationOptionsDefault: PinCodeShakeAnimationOptions = [
.direction(.default),
.duration(1.0),
.animationType(.easeOut),
.swingLength(20.0),
.swingCount(4),
.isDamping(true)
]
public enum PinCodeShakeAnimationOptionItem {
/// default 'horizontal'
case direction(PinCodeShakeDirection)
/// default '1.0'
case duration(TimeInterval)
/// default 'easeOut'
case animationType(PinCodeShakeAnimationType)
/// default '20.0'
case swingLength(Double)
/// default '4'
case swingCount(Int)
/// default 'true'
case isDamping(Bool)
}
precedencegroup ItemComparisonPrecedence {
associativity: none
higherThan: LogicalConjunctionPrecedence
}
infix operator <== : ItemComparisonPrecedence
func <== (lhs: PinCodeShakeAnimationOptionItem, rhs: PinCodeShakeAnimationOptionItem) -> Bool {
switch (lhs, rhs) {
case (.direction(_), .direction(_)): return true
case (.duration(_), .duration(_)): return true
case (.animationType(_), .animationType(_)): return true
case (.swingLength(_), .swingLength(_)): return true
case (.swingCount(_), .swingCount(_)): return true
case (.isDamping(_), .isDamping(_)): return true
default: return false
}
}
extension Collection where Iterator.Element == PinCodeShakeAnimationOptionItem {
func lastMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? {
return reversed().first { $0 <== target }
}
func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] {
return filter { !($0 <== target) }
}
}
public extension Collection where Iterator.Element == PinCodeShakeAnimationOptionItem {
public var direction: PinCodeShakeDirection {
if let item = lastMatchIgnoringAssociatedValue(.direction(.default)),
case .direction(let direction) = item
{
return direction
}
return .default
}
public var duration: TimeInterval {
if let item = lastMatchIgnoringAssociatedValue(.duration(TimeInterval(1.0))),
case .duration(let duration) = item
{
return duration
}
return TimeInterval(1.0)
}
public var animationType: PinCodeShakeAnimationType {
if let item = lastMatchIgnoringAssociatedValue(.animationType(.default)),
case .animationType(let animationType) = item
{
return animationType
}
return .default
}
public var swingLength: CGFloat {
if let item = lastMatchIgnoringAssociatedValue(.swingLength(20.0)),
case .swingLength(let swingLength) = item
{
return CGFloat(swingLength)
}
return 20.0
}
public var swingCount: Int {
if let item = lastMatchIgnoringAssociatedValue(.swingCount(4)),
case .swingCount(let swingCount) = item
{
return swingCount
}
return 4
}
public var isDamping: Bool {
if let item = lastMatchIgnoringAssociatedValue(.isDamping(true)),
case .isDamping(let isDamping) = item
{
return isDamping
}
return true
}
}
| 27.804688 | 100 | 0.650183 |
89ba58c96936bce8dafd7abc9df73aba528bd5d3 | 496 | //
// RestOffer.swift
// Empyr
//
// Created by Jarrod Cuzens on 4/10/18.
//
import Foundation
enum OfferRewardType : String, Codable {
case FIXED
case PERCENT
}
@objc( EMPOffer ) public class RestOffer: NSObject, Codable {
@objc public var id: Int = 0
@objc public var rewardValue: Double = 0
var rewardType: OfferRewardType = .FIXED
var rewardMax: Double?
@objc public var requiresActivation = false
@objc public var basic = false
@objc public var details: RestOfferDetails?
}
| 19.84 | 61 | 0.721774 |
efea7fa3972bc66acbab63ae5512dbfbee4570c9 | 2,508 | //
// OSLogSink.swift
// Logbook
//
// Created by Stefan Wieland on 28.11.19.
// Copyright © 2019 allaboutapps GmbH. All rights reserved.
//
import Foundation
import os
public class OSLogSink: LogSink {
public let level: LevelMode
public let categories: LogCategoryFilter
public var itemSeparator: String = " "
public var format: String = "\(LogPlaceholder.category) \(LogPlaceholder.date) [\(LogPlaceholder.file) \(LogPlaceholder.function): \(LogPlaceholder.line)] - \(LogPlaceholder.messages)"
public var dateFormatter = DateFormatter()
private let customLog: OSLog
private let isPublic: Bool
public init(level: LevelMode, categories: LogCategoryFilter = .all, isPublic: Bool = false) {
self.level = level
self.categories = categories
self.isPublic = isPublic
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .medium
customLog = OSLog(subsystem: Bundle.main.bundleIdentifier ?? "at.allaboutapps.logbook", category: "Logbook")
}
public func send(_ message: LogMessage) {
let messages = message.messages.joined(separator: message.separator ?? itemSeparator)
var final = format
final = final.replacingOccurrences(of: LogPlaceholder.category, with: message.category.prefix ?? "")
final = final.replacingOccurrences(of: LogPlaceholder.level, with: "")
final = final.replacingOccurrences(of: LogPlaceholder.date, with: dateFormatter.string(from: message.header.date))
final = final.replacingOccurrences(of: LogPlaceholder.file, with: message.header.file.name)
final = final.replacingOccurrences(of: LogPlaceholder.function, with: message.header.function)
final = final.replacingOccurrences(of: LogPlaceholder.line, with: "\(message.header.line)")
final = final.replacingOccurrences(of: LogPlaceholder.messages, with: messages)
if isPublic {
os_log("%{public}s", log: customLog, type: message.level.osLogType, final)
} else {
os_log("%{private}s", log: customLog, type: message.level.osLogType, final)
}
}
}
extension LogLevel {
fileprivate var osLogType: OSLogType {
switch self {
case .debug: return .debug
case .verbose: return .info
case .info: return .info
case .warning: return .info
case .error: return .error
}
}
}
| 35.828571 | 188 | 0.655901 |
e9155a7d6a909787873e59c957b4360b4db36f0d | 18,934 | // FieldRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol InputTypeInitiable {
init?(string stringValue: String)
}
public protocol FieldRowConformance : FormatterConformance {
var titlePercentage : CGFloat? { get set }
var placeholder : String? { get set }
var placeholderColor : UIColor? { get set }
}
extension Int: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue, radix: 10)
}
}
extension Float: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension String: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension URL: InputTypeInitiable {}
extension Double: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
open class FormatteableRow<Cell: CellType>: Row<Cell>, FormatterConformance where Cell: BaseCell, Cell: TextInputCell {
/// A formatter to be used to format the user's input
open var formatter: Formatter?
/// If the formatter should be used while the user is editing the text.
open var useFormatterDuringInput = false
open var useFormatterOnDidBeginEditing: Bool?
public required init(tag: String?) {
super.init(tag: tag)
displayValueFor = { [unowned self] value in
guard let v = value else { return nil }
guard let formatter = self.formatter else { return String(describing: v) }
if (self.cell.textInput as? UIView)?.isFirstResponder == true {
return self.useFormatterDuringInput ? formatter.editingString(for: v) : String(describing: v)
}
return formatter.string(for: v)
}
}
}
open class FieldRow<Cell: CellType>: FormatteableRow<Cell>, FieldRowConformance, KeyboardReturnHandler where Cell: BaseCell, Cell: TextFieldCell {
/// Configuration for the keyboardReturnType of this row
open var keyboardReturnType: KeyboardReturnTypeConfiguration?
/// The percentage of the cell that should be occupied by the textField
@available (*, deprecated, message: "Use titleLabelPercentage instead")
open var textFieldPercentage : CGFloat? {
get {
return titlePercentage.map { 1 - $0 }
}
set {
titlePercentage = newValue.map { 1 - $0 }
}
}
/// The percentage of the cell that should be occupied by the title (i.e. the titleLabel and optional imageView combined)
open var titlePercentage: CGFloat?
/// The placeholder for the textField
open var placeholder: String?
/// The textColor for the textField's placeholder
open var placeholderColor: UIColor?
public required init(tag: String?) {
super.init(tag: tag)
}
}
/**
* Protocol for cells that contain a UITextField
*/
public protocol TextInputCell {
var textInput: UITextInput { get }
}
public protocol TextFieldCell: TextInputCell {
var textField: UITextField! { get }
}
extension TextFieldCell {
public var textInput: UITextInput {
return textField
}
}
open class _FieldCell<T> : Cell<T>, UITextFieldDelegate, TextFieldCell where T: Equatable, T: InputTypeInitiable {
@IBOutlet public weak var textField: UITextField!
@IBOutlet public weak var titleLabel: UILabel?
fileprivate var observingTitleText = false
private var awakeFromNibCalled = false
open var dynamicConstraints = [NSLayoutConstraint]()
private var calculatedTitlePercentage: CGFloat = 0.7
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
let textField = UITextField()
self.textField = textField
textField.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupTitleLabel()
contentView.addSubview(titleLabel!)
contentView.addSubview(textField)
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard me.observingTitleText else { return }
me.titleLabel?.removeObserver(me, forKeyPath: "text")
me.observingTitleText = false
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard !me.observingTitleText else { return }
me.titleLabel?.addObserver(me, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
me.observingTitleText = true
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil) { [weak self] _ in
self?.setupTitleLabel()
self?.setNeedsUpdateConstraints()
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
awakeFromNibCalled = true
}
deinit {
textField?.delegate = nil
textField?.removeTarget(self, action: nil, for: .allEvents)
guard !awakeFromNibCalled else { return }
if observingTitleText {
titleLabel?.removeObserver(self, forKeyPath: "text")
}
imageView?.removeObserver(self, forKeyPath: "image")
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil)
}
open override func setup() {
super.setup()
selectionStyle = .none
if !awakeFromNibCalled {
titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
observingTitleText = true
imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
}
textField.addTarget(self, action: #selector(_FieldCell.textFieldDidChange(_:)), for: .editingChanged)
}
open override func update() {
super.update()
detailTextLabel?.text = nil
if !awakeFromNibCalled {
if let title = row.title {
textField.textAlignment = title.isEmpty ? .left : .right
textField.clearButtonMode = title.isEmpty ? .whileEditing : .never
} else {
textField.textAlignment = .left
textField.clearButtonMode = .whileEditing
}
}
textField.delegate = self
textField.text = row.displayValueFor?(row.value)
textField.isEnabled = !row.isDisabled
textField.textColor = row.isDisabled ? .gray : .black
textField.font = .preferredFont(forTextStyle: .body)
if let placeholder = (row as? FieldRowConformance)?.placeholder {
if let color = (row as? FieldRowConformance)?.placeholderColor {
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedStringKey.foregroundColor: color])
} else {
textField.placeholder = (row as? FieldRowConformance)?.placeholder
}
}
if row.isHighlighted {
textLabel?.textColor = tintColor
}
}
open override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && textField?.canBecomeFirstResponder == true
}
open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool {
return textField?.becomeFirstResponder() ?? false
}
open override func cellResignFirstResponder() -> Bool {
return textField?.resignFirstResponder() ?? true
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey],
((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) &&
(changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
// MARK: Helpers
open func customConstraints() {
guard !awakeFromNibCalled else { return }
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
var views: [String: AnyObject] = ["textField": textField]
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[textField]-11-|", options: .alignAllLastBaseline, metrics: nil, views: views)
if let label = titleLabel, let text = label.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[titleLabel]-11-|", options: .alignAllLastBaseline, metrics: nil, views: ["titleLabel": label])
dynamicConstraints.append(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: textField, attribute: .centerY, multiplier: 1, constant: 0))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["label"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[label]-[textField]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
}
else{
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
}
}
else{
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["label"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-[textField]-|", options: [], metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
}
else{
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views)
}
}
contentView.addConstraints(dynamicConstraints)
}
open override func updateConstraints() {
customConstraints()
super.updateConstraints()
}
@objc open func textFieldDidChange(_ textField: UITextField) {
guard let textValue = textField.text else {
row.value = nil
return
}
guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
return
}
if fieldRow.useFormatterDuringInput {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
guard var selStartPos = textField.selectedTextRange?.start else { return }
let oldVal = textField.text
textField.text = row.displayValueFor?(row.value)
selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text) ?? selStartPos
textField.selectedTextRange = textField.textRange(from: selStartPos, to: selStartPos)
return
}
} else {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
} else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
}
}
}
// MARK: Helpers
private func setupTitleLabel() {
titleLabel = self.textLabel
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
titleLabel?.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
titleLabel?.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
}
private func displayValue(useFormatter: Bool) -> String? {
guard let v = row.value else { return nil }
if let formatter = (row as? FormatterConformance)?.formatter, useFormatter {
return textField?.isFirstResponder == true ? formatter.editingString(for: v) : formatter.string(for: v)
}
return String(describing: v)
}
// MARK: TextFieldDelegate
open func textFieldDidBeginEditing(_ textField: UITextField) {
formViewController()?.beginEditing(of: self)
formViewController()?.textInputDidBeginEditing(textField, cell: self)
if let fieldRowConformance = row as? FormatterConformance, let _ = fieldRowConformance.formatter, fieldRowConformance.useFormatterOnDidBeginEditing ?? fieldRowConformance.useFormatterDuringInput {
textField.text = displayValue(useFormatter: true)
} else {
textField.text = displayValue(useFormatter: false)
}
}
open func textFieldDidEndEditing(_ textField: UITextField) {
formViewController()?.endEditing(of: self)
formViewController()?.textInputDidEndEditing(textField, cell: self)
textFieldDidChange(textField)
textField.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil)
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return formViewController()?.textInput(textField, shouldChangeCharactersInRange:range, replacementString:string, cell: self) ?? true
}
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldClear(textField, cell: self) ?? true
}
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let row = (row as? FieldRowConformance) else { return }
defer {
// As titleLabel is the textLabel, iOS may re-layout without updating constraints, for example:
// swiping, showing alert or actionsheet from the same section.
// thus we need forcing update to use customConstraints()
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
guard let titlePercentage = row.titlePercentage else { return }
var targetTitleWidth = bounds.size.width * titlePercentage
if let imageView = imageView, let _ = imageView.image, let titleLabel = titleLabel {
var extraWidthToSubtract = titleLabel.frame.minX - imageView.frame.minX // Left-to-right interface layout
if #available(iOS 9.0, *) {
if UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft {
extraWidthToSubtract = imageView.frame.maxX - titleLabel.frame.maxX
}
}
targetTitleWidth -= extraWidthToSubtract
}
calculatedTitlePercentage = targetTitleWidth / contentView.bounds.size.width
}
}
| 43.930394 | 204 | 0.664941 |
1ac8150df409b17b3c5e984197a35f69f2294257 | 2,669 | //
// MachineService.swift
// PokemonAPI
//
// Created by Christopher Jennewein on 6/13/20.
// Copyright © 2020 Prismatic Games. All rights reserved.
//
import Combine
import Foundation
protocol PKMMachineService: HTTPWebService {
func fetchMachineList<T>(paginationState: PaginationState<T>, completion: @escaping (_ result: Result<PKMPagedObject<T>, Error>) -> Void) where T: PKMMachine
func fetchMachine(_ machineID: Int, completion: @escaping (_ result: Result<PKMMachine, Error>) -> Void)
@available(OSX 10.15, iOS 13, tvOS 13.0, watchOS 6.0, *)
func fetchMachineList<T>(paginationState: PaginationState<T>) -> AnyPublisher<PKMPagedObject<T>, Error> where T: PKMMachine
@available(OSX 10.15, iOS 13, tvOS 13.0, watchOS 6.0, *)
func fetchMachine(_ machineID: Int) -> AnyPublisher<PKMMachine, Error>
}
// MARK: - Web Services
public struct MachineService: PKMMachineService {
public enum API: APICall {
case fetchMachineList
case fetchMachine(Int)
var path: String {
switch self {
case .fetchMachineList:
return "/machine"
case .fetchMachine(let id):
return "/machine/\(id)"
}
}
}
public var session: URLSession
public var baseURL: String = "https://pokeapi.co/api/v2"
/**
Fetch Machines list
*/
public func fetchMachineList<T>(paginationState: PaginationState<T> = .initial(pageLimit: 20), completion: @escaping (_ result: Result<PKMPagedObject<T>, Error>) -> Void) where T: PKMMachine {
callPaginated(endpoint: API.fetchMachineList, paginationState: paginationState, completion: completion)
}
/**
Fetch Machine Information
- parameter machineID: Machine ID
*/
public func fetchMachine(_ machineID: Int, completion: @escaping (_ result: Result<PKMMachine, Error>) -> Void) {
call(endpoint: API.fetchMachine(machineID)) { result in
result.decode(completion: completion)
}
}
}
// MARK: - Combine Services
extension MachineService {
@available(OSX 10.15, iOS 13, tvOS 13.0, watchOS 6.0, *)
public func fetchMachineList<T>(paginationState: PaginationState<T> = .initial(pageLimit: 20)) -> AnyPublisher<PKMPagedObject<T>, Error> where T: PKMMachine {
callPaginated(endpoint: API.fetchMachineList, paginationState: paginationState)
}
@available(OSX 10.15, iOS 13, tvOS 13.0, watchOS 6.0, *)
public func fetchMachine(_ machineID: Int) -> AnyPublisher<PKMMachine, Error> {
call(endpoint: API.fetchMachine(machineID))
}
}
| 32.156627 | 196 | 0.658674 |
f864b834a2e297b9c4b883f86e80558cf01aaa1f | 1,721 | //
// HomeInteractor.swift
// coronasurveys-ios
//
// Created by Josep Bordes Jové on 18/05/2020.
// Copyright (c) 2020 Inqbarna. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol HomeBusinessLogic {
func prepareView(request: Home.PrepareView.Request)
func updateCountryCode(request: Home.UpdateCountryCode.Request)
}
protocol HomeDataStore: DependencyInjectable {
var countryCode: String? { get }
var languageCode: String? { get }
}
class HomeInteractor: HomeBusinessLogic, HomeDataStore {
var presenter: HomePresentationLogic?
// MARK: Data store
var context: [Dependency: Any?]?
var countryCode: String? {
preferencesWorker.retrieveSelectedCountry() ?? NSLocale.current.regionCode
}
var languageCode: String? {
preferencesWorker.retrieveSelectedLanguage() ?? NSLocale.current.languageCode
}
// MARK: Worker
var preferencesWorker = PreferencesWorker(store: PreferencesStore())
// MARK: Business logic
func prepareView(request: Home.PrepareView.Request) {
let response = Home.PrepareView.Response(countryCode: countryCode?.uppercased())
presenter?.presentView(response: response)
}
func updateCountryCode(request: Home.UpdateCountryCode.Request) {
if let newCountryCode = request.newCountryCode {
preferencesWorker.saveSelectedCountry(newCountryCode)
let response = Home.UpdateCountryCode.Response(countryCode: newCountryCode)
presenter?.presentCountryCode(response: response)
}
}
}
| 28.683333 | 88 | 0.715282 |
18180a546d2af0cf68fd36d9984663ca560845df | 6,867 | //
// SHSecurityViewController.swift
// Smart-Bus
//
// Created by Mark Liu on 2017/10/12.
// Copyright © 2018 SmartHome. All rights reserved.
//
import UIKit
/// 安防区域的cell重用标示
private let securityZoneViewCellReuseIdentifier =
"SHSecurityZoneViewCell"
class SHSecurityViewController: SHViewController {
/// 安防区域
private lazy var allSecurityZones = [SHSecurityZone]()
@IBOutlet weak var listView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// 导航栏
navigationItem.title = SHLanguageText.securityTitle
navigationItem.rightBarButtonItem =
UIBarButtonItem(imageName: "addDevice_navigationbar",
hightlightedImageName: "addDevice_navigationbar",
addTarget: self,
action: #selector(addMoreSecurityZone),
isLeft: false
)
// 初始化列表
listView.register(UINib(
nibName: securityZoneViewCellReuseIdentifier,
bundle: nil),
forCellWithReuseIdentifier: securityZoneViewCellReuseIdentifier
)
// 增加手势
let longPress = UILongPressGestureRecognizer(
target: self,
action: #selector(settingSecurityZone(longPressGestureRecognizer:))
)
listView.addGestureRecognizer(longPress)
}
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
allSecurityZones =
SHSQLiteManager.shared.getSecurityZones()
listView.reloadData()
if allSecurityZones.isEmpty {
SVProgressHUD.showError(withStatus: SHLanguageText.noData)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let itemMarign: CGFloat = 1
let totalCols = isPortrait ? 3 : 5
let itemWidth = (listView.frame_width - (CGFloat(totalCols) * itemMarign)) / CGFloat(totalCols)
let flowLayout = listView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
flowLayout.minimumLineSpacing = itemMarign
flowLayout.minimumInteritemSpacing = itemMarign
}
}
// MARK: - 安防模块的配置
extension SHSecurityViewController {
/// 编辑
@objc fileprivate func settingSecurityZone(longPressGestureRecognizer: UILongPressGestureRecognizer) {
if SHAuthorizationViewController.isOperatorDisable() {
return
}
if longPressGestureRecognizer.state != .began {
return
}
let selectIndexPath = listView.indexPathForItem(
at: longPressGestureRecognizer.location(in: listView)
)
guard let index = selectIndexPath?.item else {
return
}
let alertView = TYCustomAlertView(title: nil,
message: nil,
isCustom: true
)
let editAction = TYAlertAction(title: SHLanguageText.edit, style: .default) { (action) in
let editSecurityZoneController = SHDeviceArgsViewController()
editSecurityZoneController.securityZone = self.allSecurityZones[index]
self.navigationController?.pushViewController(
editSecurityZoneController,
animated: true
)
}
alertView?.add(editAction)
let deleteAction =
TYAlertAction(title: SHLanguageText.delete,
style: .destructive) { (action) in
let securityZone = self.allSecurityZones[index]
self.allSecurityZones.remove(at: index)
_ = SHSQLiteManager.shared.deleteSecurityZone(
securityZone
)
self.listView.reloadData()
}
alertView?.add(deleteAction)
let cancelAction =
TYAlertAction(title: SHLanguageText.cancel,
style: .cancel,
handler: nil
)
alertView?.add(cancelAction)
let alertController =
TYAlertController(alert: alertView!,
preferredStyle: .alert,
transitionAnimation: .custom
)
alertController?.backgoundTapDismissEnable = true
present(alertController!, animated: true, completion: nil)
}
/// 增加
@objc fileprivate func addMoreSecurityZone() {
if SHAuthorizationViewController.isOperatorDisable() {
return
}
let securityZone = SHSecurityZone()
securityZone.id =
SHSQLiteManager.shared.getMaxSecurityID() + 1
securityZone.zoneNameOfSecurity = "Security"
_ = SHSQLiteManager.shared.insertSecurityZone(
securityZone
)
let editSecuriytZoneController = SHDeviceArgsViewController()
editSecuriytZoneController.securityZone = securityZone
navigationController?.pushViewController(
editSecuriytZoneController,
animated: true
)
}
}
// MARK: - UICollectionViewDataSource
extension SHSecurityViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return allSecurityZones.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell =
collectionView.dequeueReusableCell(
withReuseIdentifier: securityZoneViewCellReuseIdentifier,
for: indexPath
) as! SHSecurityZoneViewCell
cell.securityZone = allSecurityZones[indexPath.item]
return cell
}
}
// MARK: - UICollectionViewDelegate
extension SHSecurityViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let securityControlViewController = SHSecurityControlViewController()
securityControlViewController.securityZone = allSecurityZones[indexPath.item]
navigationController?.pushViewController(
securityControlViewController,
animated: true
)
}
}
| 29.9869 | 121 | 0.586573 |
39061bfa32d67c1173293ca60615f807fde6cc06 | 102 | //
// NetworkHelper.swift
//
//
// Created by Elizabeth Peraza on 8/10/19.
//
import Foundation
| 11.333333 | 44 | 0.637255 |
20a0e03677803ee25a1aaccd8ca7a50bcd0d8422 | 1,882 | import Foundation
import Combine
import Harvest
// MARK: AuthState/Input
enum AuthState: String, CustomStringConvertible
{
case loggedOut
case loggingIn
case loggedIn
case loggingOut
var description: String { return self.rawValue }
}
/// - Note:
/// `LoginOK` and `LogoutOK` should only be used internally
/// (but Swift can't make them as `private case`)
enum AuthInput: String, CustomStringConvertible
{
case login
case loginOK
case logout
case forceLogout
case logoutOK
var description: String { return self.rawValue }
}
/// Subset of `AuthInput` that can be sent from external.
enum ExternalAuthInput
{
case login
case logout
case forceLogout
static func toInternal(externalInput: ExternalAuthInput) -> AuthInput
{
switch externalInput {
case .login:
return .login
case .logout:
return .logout
case .forceLogout:
return .forceLogout
}
}
}
// MARK: CountState/Input
typealias CountState = Int
enum CountInput: String, CustomStringConvertible
{
case increment
case decrement
var description: String { return self.rawValue }
}
// MARK: MyState/Input
enum MyState
{
case state0, state1, state2
}
enum MyInput
{
case input0, input1, input2
}
// MARK: - RequestEffectQueue
enum RequestEffectQueue: EffectQueueProtocol
{
case `default`
case request
var flattenStrategy: FlattenStrategy
{
switch self {
case .default: return .merge
case .request: return .latest
}
}
static var defaultEffectQueue: RequestEffectQueue
{
.default
}
}
// MARK: - Helpers
func asyncAfter(_ timeInterval: TimeInterval, completion: @escaping () -> Void)
{
DispatchQueue.main.asyncAfter(deadline: .now() + timeInterval) {
completion()
}
}
| 18.096154 | 79 | 0.662062 |
3ad606efd63eb230171117b8c09d661ddde08773 | 713 | //
// PieSlice.swift
// PieCharts
//
// Created by Ivan Schuetz on 30/12/2016.
// Copyright © 2016 Ivan Schuetz. All rights reserved.
//
import UIKit
public struct PieSlice: Hashable, CustomDebugStringConvertible {
public let view: PieSliceLayer
public internal(set) var data: PieSliceData
public init(data: PieSliceData, view: PieSliceLayer) {
self.data = data
self.view = view
}
public func hash(into hasher: inout Hasher) {
hasher.combine(data.id)
}
public var debugDescription: String {
return data.debugDescription
}
}
public func ==(slice1: PieSlice, slice2: PieSlice) -> Bool {
return slice1.data.id == slice2.data.id
}
| 22.28125 | 64 | 0.661992 |
11b3759a5b8771e2fa361aa10175b519f560dcde | 7,128 | // Copyright (c) 2015 - 2016 Yosuke Ishikawa
// 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.
//
// Session.swift
// POPAPIKit
//
// Copyright (c) 2017年 Hanguang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Result
private var taskRequestKey = 0
/// `Session` manages tasks for HTTP/HTTPS requests.
open class Session {
/// The client that connects `Session` instance and lower level backend.
public let client: SessionClient
/// The default callback queue for `send(_:handler:)`.
public let callbackQueue: CallbackQueue
/// Returns `Session` instance that is initialized with `client`.
/// - parameter client: The client that connects lower level backend with Session interface.
/// - parameter callbackQueue: The default callback queue for `send(_:handler:)`.
public init(client: SessionClient, callbackQueue: CallbackQueue = .main) {
self.client = client
self.callbackQueue = callbackQueue
}
/// Returns a default `Session`. A global constant `APIKit` is a shortcut of `Session.default`.
open static let `default` = Session()
// Shared session for class methods
private convenience init() {
let configuration = URLSessionConfiguration.default
let client = URLSessionClient(configuration: configuration)
self.init(client: client)
}
/// Sends a request and receives the result as the argument of `handler` closure. This method takes
/// a type parameter `Request` that conforms to `Request` protocol. The result of passed request is
/// expressed as `Result<Request.Response, SessionTaskError>`. Since the response type
/// `Request.Response` is inferred from `Request` type parameter, the it changes depending on the request type.
/// - parameter request: The request to be sent.
/// - parameter callbackQueue: The queue where the handler runs. If this parameters is `nil`, default `callbackQueue` of `Session` will be used.
/// - parameter handler: The closure that receives result of the request.
/// - returns: The new session task.
@discardableResult
open func send<Request: POPAPIKit.Request>(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result<Request.Response, SessionTaskError>) -> Void = { _ in }) -> SessionTask? {
let callbackQueue = callbackQueue ?? self.callbackQueue
let urlRequest: URLRequest
do {
urlRequest = try request.buildURLRequest()
} catch {
callbackQueue.execute {
let e = SessionTaskError.requestError(error)
request.handle(error: e)
handler(.failure(e))
}
return nil
}
let task = client.createTask(with: urlRequest) { data, urlResponse, error in
let result: Result<Request.Response, SessionTaskError>
switch (data, urlResponse, error) {
case (_, _, let error?):
result = .failure(.connectionError(error))
case (let data?, let urlResponse as HTTPURLResponse, _):
do {
result = .success(try request.parse(data: data as Data, urlResponse: urlResponse))
} catch {
result = .failure(.responseError(error))
}
default:
result = .failure(.responseError(ResponseError.nonHTTPURLResponse(urlResponse)))
}
callbackQueue.execute {
switch result {
case .failure(let e):
request.handle(error: e)
default: break
}
handler(result)
}
}
setRequest(request, forTask: task)
task.resume()
return task
}
/// Cancels requests that passes the test.
/// - parameter requestType: The request type to cancel.
/// - parameter test: The test closure that determines if a request should be cancelled or not.
open func cancelRequests<Request: POPAPIKit.Request>(with requestType: Request.Type, passingTest test: @escaping (Request) -> Bool = { _ in true }) {
client.getTasks { [weak self] tasks in
return tasks
.filter { task in
if let request = self?.requestForTask(task) as Request? {
return test(request)
} else {
return false
}
}
.forEach { $0.cancel() }
}
}
private func setRequest<Request: POPAPIKit.Request>(_ request: Request, forTask task: SessionTask) {
objc_setAssociatedObject(task, &taskRequestKey, request, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func requestForTask<Request: POPAPIKit.Request>(_ task: SessionTask) -> Request? {
return objc_getAssociatedObject(task, &taskRequestKey) as? Request
}
}
// MARK: - Default POPAPIKit
public let APIKit = Session.default
| 49.158621 | 463 | 0.6633 |
8ae19ce57aa671b35d3fb7182ac2fbf3655b5a41 | 1,574 | import Foundation
import SQLiteORM
struct KeyValue: Initializable {
var key: String = ""
var value: String = ""
}
let storage = try Storage(filename: "",
tables: Table<KeyValue>(name: "key_value",
columns:
Column(name: "key", keyPath: \KeyValue.key, constraints: primaryKey()),
Column(name: "value", keyPath: \KeyValue.value)))
try storage.syncSchema(preserve: true)
func set(value: String, for key: String) throws {
try storage.replace(KeyValue(key: key, value: value))
}
func getValue(for key: String) throws -> String? {
if let keyValue: KeyValue = try storage.get(id: key) {
return keyValue.value
} else {
return nil
}
}
func storedKeysCount() throws -> Int {
return try storage.count(all: KeyValue.self)
}
struct Keys {
static let userId = "userId"
static let userName = "userName"
static let userGender = "userGender"
}
try set(value: "6", for: Keys.userId)
try set(value: "Peter", for: Keys.userName)
let userId = try getValue(for: Keys.userId)
print("userId = \(String(describing: userId))")
let userName = try getValue(for: Keys.userName)
print("userName = \(String(describing: userName))")
let userGender = try getValue(for: Keys.userGender)
print("userGender = \(String(describing: userGender))")
let keyValuesCount = try storedKeysCount()
print("keyValuesCount = \(keyValuesCount)")
| 30.269231 | 131 | 0.602922 |
48566acee0e3dca50f896a4c5179babbea70fe8e | 1,748 | //
// BootpayItem.swift
// CryptoSwift
//
// Created by YoonTaesup on 2019. 4. 12..
//
//import "BootpayParams.swift"
import ObjectMapper
//MARK: Bootpay Models
public class BootpayItem: NSObject, BootpayParams, Mappable {
public override init() {}
@objc public var item_name = "" //아이템 이름
@objc public var qty: Int = 0 //상품 판매된 수량
@objc public var unique = "" //상품의 고유 PK
@objc public var price = Double(0) //상품 하나당 판매 가격
@objc public var cat1 = "" //카테고리 상
@objc public var cat2 = "" //카테고리 중
@objc public var cat3 = "" //카테고리 하
// public override init() {}
public required init?(map: Map) {
}
public func mapping(map: Map) {
item_name <- map["item_name"]
qty <- map["qty"]
unique <- map["unique"]
price <- map["price"]
cat1 <- map["cat1"]
cat2 <- map["cat2"]
cat3 <- map["cat3"]
}
func toString() -> String {
if item_name.isEmpty { return "" }
if qty == 0 { return "" }
if unique.isEmpty { return "" }
if price == Double(0) { return "" }
return [
"{",
"item_name: '\(item_name.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'"))',",
"qty: \(qty),",
"unique: '\(unique)',",
"price: \(Int(price)),",
"cat1: '\(cat1.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'"))',",
"cat2: '\(cat2.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'"))',",
"cat3: '\(cat3.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'"))'",
"}"
].reduce("", +)
}
}
| 30.666667 | 120 | 0.505149 |
757aa6ea375597b8df414c595e690e57b9257a8b | 37,973 | // 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
//
//import libxml2
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
import CoreFoundation
import CFXMLInterface
// initWithKind options
// NSXMLNodeOptionsNone
// NSXMLNodePreserveAll
// NSXMLNodePreserveNamespaceOrder
// NSXMLNodePreserveAttributeOrder
// NSXMLNodePreserveEntities
// NSXMLNodePreservePrefixes
// NSXMLNodeIsCDATA
// NSXMLNodeExpandEmptyElement
// NSXMLNodeCompactEmptyElement
// NSXMLNodeUseSingleQuotes
// NSXMLNodeUseDoubleQuotes
// Output options
// NSXMLNodePrettyPrint
/*!
@class NSXMLNode
@abstract The basic unit of an XML document.
*/
open class XMLNode: NSObject, NSCopying {
public enum Kind : UInt {
case invalid
case document
case element
case attribute
case namespace
case processingInstruction
case comment
case text
case DTDKind
case entityDeclaration
case attributeDeclaration
case elementDeclaration
case notationDeclaration
}
public struct Options : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let nodeIsCDATA = Options(rawValue: 1 << 0)
public static let nodeExpandEmptyElement = Options(rawValue: 1 << 1)
public static let nodeCompactEmptyElement = Options(rawValue: 1 << 2)
public static let nodeUseSingleQuotes = Options(rawValue: 1 << 3)
public static let nodeUseDoubleQuotes = Options(rawValue: 1 << 4)
public static let nodeNeverEscapeContents = Options(rawValue: 1 << 5)
public static let documentTidyHTML = Options(rawValue: 1 << 9)
public static let documentTidyXML = Options(rawValue: 1 << 10)
public static let documentValidate = Options(rawValue: 1 << 13)
public static let nodeLoadExternalEntitiesAlways = Options(rawValue: 1 << 14)
public static let nodeLoadExternalEntitiesSameOriginOnly = Options(rawValue: 1 << 15)
public static let nodeLoadExternalEntitiesNever = Options(rawValue: 1 << 19)
public static let documentXInclude = Options(rawValue: 1 << 16)
public static let nodePrettyPrint = Options(rawValue: 1 << 17)
public static let documentIncludeContentTypeDeclaration = Options(rawValue: 1 << 18)
public static let nodePreserveNamespaceOrder = Options(rawValue: 1 << 20)
public static let nodePreserveAttributeOrder = Options(rawValue: 1 << 21)
public static let nodePreserveEntities = Options(rawValue: 1 << 22)
public static let nodePreservePrefixes = Options(rawValue: 1 << 23)
public static let nodePreserveCDATA = Options(rawValue: 1 << 24)
public static let nodePreserveWhitespace = Options(rawValue: 1 << 25)
public static let nodePreserveDTD = Options(rawValue: 1 << 26)
public static let nodePreserveCharacterReferences = Options(rawValue: 1 << 27)
public static let nodePromoteSignificantWhitespace = Options(rawValue: 1 << 28)
public static let nodePreserveEmptyElements = Options([.nodeExpandEmptyElement, .nodeCompactEmptyElement])
public static let nodePreserveQuotes = Options([.nodeUseSingleQuotes, .nodeUseDoubleQuotes])
public static let nodePreserveAll = Options(rawValue: 0xFFF00000).union([.nodePreserveNamespaceOrder, .nodePreserveAttributeOrder, .nodePreserveEntities, .nodePreservePrefixes, .nodePreserveCDATA, .nodePreserveEmptyElements, .nodePreserveQuotes, .nodePreserveWhitespace, .nodePreserveDTD, .nodePreserveCharacterReferences])
}
open override func copy() -> Any {
return copy(with: nil)
}
internal let _xmlNode: _CFXMLNodePtr!
internal var _xmlDocument: XMLDocument?
open func copy(with zone: NSZone? = nil) -> Any {
let newNode = _CFXMLCopyNode(_xmlNode, true)
return XMLNode._objectNodeForNode(newNode)
}
@available(*, deprecated, message: "On Darwin, this initializer creates nodes that are valid objects but crash your process if used. The same behavior is replicated in swift-corelibs-foundation, but you should not use this initializer on either platform; use one of the class methods or initializers instead to create a specific kind of code.")
public convenience override init() {
// Match the Darwin behavior.
self.init(kind: .invalid)
}
/*!
@method initWithKind:
@abstract Invokes @link initWithKind:options: @/link with options set to NSXMLNodeOptionsNone
*/
public convenience init(kind: XMLNode.Kind) {
self.init(kind: kind, options: [])
}
/*!
@method initWithKind:options:
@abstract Inits a node with fidelity options as description NSXMLNodeOptions.h
*/
public init(kind: XMLNode.Kind, options: XMLNode.Options = []) {
setupXMLParsing()
switch kind {
case .document:
let docPtr = _CFXMLNewDoc("1.0")
_CFXMLDocSetStandalone(docPtr, false) // same default as on Darwin
_xmlNode = _CFXMLNodePtr(docPtr)
case .element:
_xmlNode = _CFXMLNewNode(nil, "")
case .attribute:
_xmlNode = _CFXMLNodePtr(_CFXMLNewProperty(nil, "", nil, ""))
case .DTDKind:
_xmlNode = _CFXMLNewDTD(nil, "", "", "")
case .namespace:
_xmlNode = _CFXMLNewNamespace("", "")
default:
_xmlNode = nil
}
super.init()
if let node = _xmlNode {
withOpaqueUnretainedReference {
_CFXMLNodeSetPrivateData(node, $0)
}
}
}
/*!
@method document:
@abstract Returns an empty document.
*/
open class func document() -> Any {
return XMLDocument(rootElement: nil)
}
/*!
@method documentWithRootElement:
@abstract Returns a document
@param element The document's root node.
*/
open class func document(withRootElement element: XMLElement) -> Any {
return XMLDocument(rootElement: element)
}
/*!
@method elementWithName:
@abstract Returns an element <tt><name></name></tt>.
*/
open class func element(withName name: String) -> Any {
return XMLElement(name: name)
}
/*!
@method elementWithName:URI:
@abstract Returns an element whose full QName is specified.
*/
open class func element(withName name: String, uri: String) -> Any {
return XMLElement(name: name, uri: uri)
}
/*!
@method elementWithName:stringValue:
@abstract Returns an element with a single text node child <tt><name>string</name></tt>.
*/
open class func element(withName name: String, stringValue string: String) -> Any {
return XMLElement(name: name, stringValue: string)
}
/*!
@method elementWithName:children:attributes:
@abstract Returns an element children and attributes <tt><name attr1="foo" attr2="bar"><-- child1 -->child2</name></tt>.
*/
open class func element(withName name: String, children: [XMLNode]?, attributes: [XMLNode]?) -> Any {
let element = XMLElement(name: name)
element.setChildren(children)
element.attributes = attributes
return element
}
/*!
@method attributeWithName:stringValue:
@abstract Returns an attribute <tt>name="stringValue"</tt>.
*/
open class func attribute(withName name: String, stringValue: String) -> Any {
let attribute = _CFXMLNewProperty(nil, name, nil, stringValue)
return XMLNode(ptr: attribute)
}
/*!
@method attributeWithLocalName:URI:stringValue:
@abstract Returns an attribute whose full QName is specified.
*/
open class func attribute(withName name: String, uri: String, stringValue: String) -> Any {
let attribute = _CFXMLNewProperty(nil, name, uri, stringValue)
return XMLNode(ptr: attribute)
}
/*!
@method namespaceWithName:stringValue:
@abstract Returns a namespace <tt>xmlns:name="stringValue"</tt>.
*/
open class func namespace(withName name: String, stringValue: String) -> Any {
let node = _CFXMLNewNamespace(name, stringValue)
return XMLNode(ptr: node)
}
/*!
@method processingInstructionWithName:stringValue:
@abstract Returns a processing instruction <tt><?name stringValue></tt>.
*/
public class func processingInstruction(withName name: String, stringValue: String) -> Any {
let node = _CFXMLNewProcessingInstruction(name, stringValue)
return XMLNode(ptr: node)
}
/*!
@method commentWithStringValue:
@abstract Returns a comment <tt><--stringValue--></tt>.
*/
open class func comment(withStringValue stringValue: String) -> Any {
let node = _CFXMLNewComment(stringValue)
return XMLNode(ptr: node)
}
/*!
@method textWithStringValue:
@abstract Returns a text node.
*/
open class func text(withStringValue stringValue: String) -> Any {
let node = _CFXMLNewTextNode(stringValue)
return XMLNode(ptr: node)
}
/*!
@method DTDNodeWithXMLString:
@abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string.
*/
open class func dtdNode(withXMLString string: String) -> Any? {
setupXMLParsing()
guard let node = _CFXMLParseDTDNode(string) else { return nil }
return XMLDTDNode(ptr: node)
}
/*!
@method kind
@abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string.
*/
open var kind: XMLNode.Kind {
switch _CFXMLNodeGetType(_xmlNode) {
case _kCFXMLTypeElement:
return .element
case _kCFXMLTypeAttribute:
return .attribute
case _kCFXMLTypeDocument:
return .document
case _kCFXMLTypeDTD:
return .DTDKind
case _kCFXMLDTDNodeTypeElement:
return .elementDeclaration
case _kCFXMLDTDNodeTypeEntity:
return .entityDeclaration
case _kCFXMLDTDNodeTypeNotation:
return .notationDeclaration
case _kCFXMLDTDNodeTypeAttribute:
return .attributeDeclaration
case _kCFXMLTypeNamespace:
return .namespace
case _kCFXMLTypeProcessingInstruction:
return .processingInstruction
case _kCFXMLTypeComment:
return .comment
case _kCFXMLTypeCDataSection: fallthrough
case _kCFXMLTypeText:
return .text
default:
return .invalid
}
}
internal var isCData: Bool {
return _CFXMLNodeGetType(_xmlNode) == _kCFXMLTypeCDataSection
}
/*!
@method name
@abstract Sets the nodes name. Applicable for element, attribute, namespace, processing-instruction, document type declaration, element declaration, attribute declaration, entity declaration, and notation declaration.
*/
open var name: String? {
get {
switch kind {
case .comment, .text:
// As with Darwin, name is always nil when the node is comment or text.
return nil
case .namespace:
return _CFXMLNamespaceCopyPrefix(_xmlNode).map({ unsafeBitCast($0, to: NSString.self) as String }) ?? ""
default:
return _CFXMLNodeCopyName(_xmlNode).map({ unsafeBitCast($0, to: NSString.self) as String })
}
}
set {
switch kind {
case .document:
// As with Darwin, ignore the name when the node is document.
break
case .notationDeclaration:
// Use _CFXMLNodeForceSetName because
// _CFXMLNodeSetName ignores the new name when the node is notation declaration.
_CFXMLNodeForceSetName(_xmlNode, newValue)
case .namespace:
_CFXMLNamespaceSetPrefix(_xmlNode, newValue, Int64(newValue?.utf8.count ?? 0))
default:
if let newName = newValue {
_CFXMLNodeSetName(_xmlNode, newName)
} else {
_CFXMLNodeSetName(_xmlNode, "")
}
}
}
}
private var _objectValue: Any? = nil
/*!
@method objectValue
@abstract Sets the content of the node. Setting the objectValue removes all existing children including processing instructions and comments. Setting the object value on an element creates a single text node child.
*/
open var objectValue: Any? {
get {
if let value = _objectValue {
return value
} else {
return stringValue
}
}
set {
_objectValue = newValue
if let describableValue = newValue as? CustomStringConvertible {
stringValue = "\(describableValue.description)"
} else if let value = newValue {
stringValue = "\(value)"
} else {
stringValue = nil
}
}
}
/*!
@method stringValue:
@abstract Sets the content of the node. Setting the stringValue removes all existing children including processing instructions and comments. Setting the string value on an element creates a single text node child. The getter returns the string value of the node, which may be either its content or child text nodes, depending on the type of node. Elements are recursed and text nodes concatenated in document order with no intervening spaces.
*/
open var stringValue: String? {
get {
switch kind {
case .entityDeclaration:
let returned = _CFXMLCopyEntityContent(_CFXMLEntityPtr(_xmlNode))
return returned == nil ? nil : unsafeBitCast(returned!, to: NSString.self) as String
case .namespace:
let returned = _CFXMLNamespaceCopyValue(_xmlNode)
return returned == nil ? nil : unsafeBitCast(returned!, to: NSString.self) as String
case .element:
// As with Darwin, children's string values are just concanated without spaces.
return children?.compactMap({ $0.stringValue }).joined() ?? ""
default:
let returned = _CFXMLNodeCopyContent(_xmlNode)
return returned == nil ? nil : unsafeBitCast(returned!, to: NSString.self) as String
}
}
set {
switch kind {
case .namespace:
if let newValue = newValue {
precondition(URL(string: newValue) != nil, "namespace stringValue must be a valid href")
}
_CFXMLNamespaceSetValue(_xmlNode, newValue, Int64(newValue?.utf8.count ?? 0))
case .comment, .text:
_CFXMLNodeSetContent(_xmlNode, newValue)
default:
_removeAllChildNodesExceptAttributes() // in case anyone is holding a reference to any of these children we're about to destroy
if let string = newValue {
let returned = _CFXMLEncodeEntities(_CFXMLNodeGetDocument(_xmlNode), string)
let newContent = returned == nil ? "" : unsafeBitCast(returned!, to: NSString.self) as String
_CFXMLNodeSetContent(_xmlNode, newContent)
} else {
_CFXMLNodeSetContent(_xmlNode, nil)
}
}
}
}
private func _removeAllChildNodesExceptAttributes() {
for node in _childNodes {
if node.kind != .attribute {
_CFXMLUnlinkNode(node._xmlNode)
_childNodes.remove(node)
}
}
}
internal func _removeAllChildren() {
var nextChild = _CFXMLNodeGetFirstChild(_xmlNode)
while let child = nextChild {
nextChild = _CFXMLNodeGetNextSibling(child)
_CFXMLUnlinkNode(child)
}
_childNodes.removeAll(keepingCapacity: true)
}
/*!
@method setStringValue:resolvingEntities:
@abstract Sets the content as with @link setStringValue: @/link, but when "resolve" is true, character references, predefined entities and user entities available in the document's dtd are resolved. Entities not available in the dtd remain in their entity form.
*/
open func setStringValue(_ string: String, resolvingEntities resolve: Bool) {
guard resolve else {
stringValue = string
return
}
_removeAllChildNodesExceptAttributes()
var entities: [(Range<Int>, String)] = []
var entityChars: [Character] = []
var inEntity = false
var startIndex = 0
for (index, char) in string.enumerated() {
if char == "&" {
inEntity = true
startIndex = index
continue
}
if char == ";" && inEntity {
inEntity = false
let min = startIndex
let max = index + 1
entities.append((min..<max, String(entityChars)))
startIndex = 0
entityChars.removeAll()
}
if inEntity {
entityChars.append(char)
}
}
var result: [Character] = Array(string)
let doc = _CFXMLNodeGetDocument(_xmlNode)!
for (range, entity) in entities {
var entityPtr = _CFXMLGetDocEntity(doc, entity)
if entityPtr == nil {
entityPtr = _CFXMLGetDTDEntity(doc, entity)
}
if entityPtr == nil {
entityPtr = _CFXMLGetParameterEntity(doc, entity)
}
if let validEntity = entityPtr {
let returned = _CFXMLCopyEntityContent(validEntity)
let replacement = returned == nil ? "" : unsafeBitCast(returned!, to: NSString.self) as String
result.replaceSubrange(range, with: replacement)
} else {
result.replaceSubrange(range, with: []) // This appears to be how Darwin Foundation does it
}
}
stringValue = String(result)
}
/*!
@method index
@abstract A node's index amongst its siblings.
*/
open var index: Int {
if let siblings = self.parent?.children,
let index = siblings.firstIndex(of: self) {
return index
}
return 0
}
/*!
@method level
@abstract The depth of the node within the tree. Documents and standalone nodes are level 0.
*/
open var level: Int {
var result = 0
var nextParent = _CFXMLNodeGetParent(_xmlNode)
while let parent = nextParent {
result += 1
nextParent = _CFXMLNodeGetParent(parent)
}
return result
}
/*!
@method rootDocument
@abstract The encompassing document or nil.
*/
open var rootDocument: XMLDocument? {
guard let doc = _CFXMLNodeGetDocument(_xmlNode) else { return nil }
return XMLNode._objectNodeForNode(_CFXMLNodePtr(doc)) as? XMLDocument
}
/*!
@method parent
@abstract The parent of this node. Documents and standalone Nodes have a nil parent; there is not a 1-to-1 relationship between parent and children, eg a namespace cannot be a child but has a parent element.
*/
/*@NSCopying*/ open var parent: XMLNode? {
guard let parentPtr = _CFXMLNodeGetParent(_xmlNode) else { return nil }
return XMLNode._objectNodeForNode(parentPtr)
}
/*!
@method childCount
@abstract The amount of children, relevant for documents, elements, and document type declarations.
*/
open var childCount: Int {
return self.children?.count ?? 0
}
/*!
@method children
@abstract An immutable array of child nodes. Relevant for documents, elements, and document type declarations.
*/
open var children: [XMLNode]? {
switch kind {
case .document:
fallthrough
case .element:
fallthrough
case .DTDKind:
return Array<XMLNode>(self as XMLNode)
default:
return nil
}
}
/*!
@method childAtIndex:
@abstract Returns the child node at a particular index.
*/
open func child(at index: Int) -> XMLNode? {
precondition(index >= 0)
precondition(index < childCount)
return self[self.index(startIndex, offsetBy: index)]
}
/*!
@method previousSibling:
@abstract Returns the previous sibling, or nil if there isn't one.
*/
/*@NSCopying*/ open var previousSibling: XMLNode? {
guard let prev = _CFXMLNodeGetPrevSibling(_xmlNode) else { return nil }
return XMLNode._objectNodeForNode(prev)
}
/*!
@method nextSibling:
@abstract Returns the next sibling, or nil if there isn't one.
*/
/*@NSCopying*/ open var nextSibling: XMLNode? {
guard let next = _CFXMLNodeGetNextSibling(_xmlNode) else { return nil }
return XMLNode._objectNodeForNode(next)
}
/*!
@method previousNode:
@abstract Returns the previous node in document order. This can be used to walk the tree backwards.
*/
/*@NSCopying*/ open var previous: XMLNode? {
if let previousSibling = self.previousSibling {
if let lastChild = _CFXMLNodeGetLastChild(previousSibling._xmlNode) {
return XMLNode._objectNodeForNode(lastChild)
} else {
return previousSibling
}
} else if let parent = self.parent {
return parent
} else {
return nil
}
}
/*!
@method nextNode:
@abstract Returns the next node in document order. This can be used to walk the tree forwards.
*/
/*@NSCopying*/ open var next: XMLNode? {
if let children = _CFXMLNodeGetFirstChild(_xmlNode) {
return XMLNode._objectNodeForNode(children)
} else if let next = nextSibling {
return next
} else if let parent = self.parent {
return parent.nextSibling
} else {
return nil
}
}
/*!
@method detach:
@abstract Detaches this node from its parent.
*/
open func detach() {
guard let parentPtr = _CFXMLNodeGetParent(_xmlNode) else { return }
_CFXMLUnlinkNode(_xmlNode)
guard let parentNodePtr = _CFXMLNodeGetPrivateData(parentPtr) else { return }
let parent = unsafeBitCast(parentNodePtr, to: XMLNode.self)
parent._childNodes.remove(self)
}
/*!
@method XPath
@abstract Returns the XPath to this node, for example foo/bar[2]/baz.
*/
open var xPath: String? {
guard _CFXMLNodeGetDocument(_xmlNode) != nil else { return nil }
let returned = _CFXMLCopyPathForNode(_xmlNode)
return returned == nil ? nil : unsafeBitCast(returned!, to: NSString.self) as String
}
/*!
@method localName
@abstract Returns the local name bar if this attribute or element's name is foo:bar
*/
open var localName: String? {
let returned = _CFXMLNodeCopyLocalName(_xmlNode)
return returned == nil ? nil : unsafeBitCast(returned!, to: NSString.self) as String
}
/*!
@method prefix
@abstract Returns the prefix foo if this attribute or element's name if foo:bar
*/
open var prefix: String? {
let returned = _CFXMLNodeCopyPrefix(_xmlNode)
return returned == nil ? nil : unsafeBitCast(returned!, to: NSString.self) as String
}
/*!
@method URI
@abstract Set the URI of this element, attribute, or document. For documents it is the URI of document origin. Getter returns the URI of this element, attribute, or document. For documents it is the URI of document origin and is automatically set when using initWithContentsOfURL.
*/
open var uri: String? {
get {
let returned = _CFXMLNodeCopyURI(_xmlNode)
return returned == nil ? nil : unsafeBitCast(returned!, to: NSString.self) as String
}
set {
if let URI = newValue {
_CFXMLNodeSetURI(_xmlNode, URI)
} else {
_CFXMLNodeSetURI(_xmlNode, nil)
}
}
}
/*!
@method localNameForName:
@abstract Returns the local name bar in foo:bar.
*/
open class func localName(forName name: String) -> String {
if let localName = _CFXMLSplitQualifiedName(name) {
return String(cString: localName)
} else {
return name
}
}
/*!
@method localNameForName:
@abstract Returns the prefix foo in the name foo:bar.
*/
open class func prefix(forName name: String) -> String? {
var size: size_t = 0
if _CFXMLGetLengthOfPrefixInQualifiedName(name, &size) {
return name.withCString {
$0.withMemoryRebound(to: UInt8.self, capacity: size) {
return String(decoding: UnsafeBufferPointer(start: $0, count: size), as: UTF8.self)
}
}
} else {
return nil
}
}
/*!
@method predefinedNamespaceForPrefix:
@abstract Returns the namespace belonging to one of the predefined namespaces xml, xs, or xsi
*/
private static func defaultNamespace(prefix: String, value: String) -> XMLNode {
let node = XMLNode(kind: .namespace)
node.name = prefix
node.objectValue = value
return node
}
private static let _defaultNamespaces: [XMLNode] = [
XMLNode.defaultNamespace(prefix: "xml", value: "http://www.w3.org/XML/1998/namespace"),
XMLNode.defaultNamespace(prefix: "xml", value: "http://www.w3.org/2001/XMLSchema"),
XMLNode.defaultNamespace(prefix: "xml", value: "http://www.w3.org/2001/XMLSchema-instance"),
]
internal static let _defaultNamespacesByPrefix: [String: XMLNode] =
Dictionary(XMLNode._defaultNamespaces.map { ($0.name!, $0) }, uniquingKeysWith: { old, _ in old })
internal static let _defaultNamespacesByURI: [String: XMLNode] =
Dictionary(XMLNode._defaultNamespaces.map { ($0.stringValue!, $0) }, uniquingKeysWith: { old, _ in old })
open class func predefinedNamespace(forPrefix name: String) -> XMLNode? {
return XMLNode._defaultNamespacesByPrefix[name]
}
/*!
@method description
@abstract Used for debugging. May give more information than XMLString.
*/
open override var description: String {
return xmlString
}
/*!
@method XMLString
@abstract The representation of this node as it would appear in an XML document.
*/
open var xmlString: String {
return xmlString(options: [])
}
/*!
@method XMLStringWithOptions:
@abstract The representation of this node as it would appear in an XML document, with various output options available.
*/
open func xmlString(options: Options) -> String {
return unsafeBitCast(_CFXMLCopyStringWithOptions(_xmlNode, UInt32(options.rawValue)), to: NSString.self) as String
}
/*!
@method canonicalXMLStringPreservingComments:
@abstract W3 canonical form (http://www.w3.org/TR/xml-c14n). The input option NSXMLNodePreserveWhitespace should be set for true canonical form.
*/
open func canonicalXMLStringPreservingComments(_ comments: Bool) -> String {
var result = ""
switch kind {
case .text:
let scanner = Scanner(string: self.stringValue ?? "")
let toReplace = CharacterSet(charactersIn: "&<>\r")
while let string = scanner.scanUpToCharacters(from: toReplace) {
result += string
if scanner.scanString("&") != nil {
result += "&"
} else if scanner.scanString("<") != nil {
result += "<"
} else if scanner.scanString(">") != nil {
result += ">"
} else if scanner.scanString("\r") != nil {
result += "
"
} else {
fatalError("We scanned up to one of the characters to replace, but couldn't find it when we went to consume it.")
}
}
result += scanner.string[scanner.currentIndex...]
case .comment:
if comments {
result = "<!--\(stringValue ?? "")-->"
}
default: break
}
return result
}
/*!
@method nodesForXPath:error:
@abstract Returns the nodes resulting from applying an XPath to this node using the node as the context item ("."). normalizeAdjacentTextNodesPreservingCDATA:NO should be called if there are adjacent text nodes since they are not allowed under the XPath/XQuery Data Model.
@returns An array whose elements are a kind of NSXMLNode.
*/
open func nodes(forXPath xpath: String) throws -> [XMLNode] {
guard let nodes = _CFXMLNodesForXPath(_xmlNode, xpath) else {
return []
}
var result: [XMLNode] = []
for i in 0..<_GetNSCFXMLBridge().CFArrayGetCount(nodes) {
let nodePtr = _GetNSCFXMLBridge().CFArrayGetValueAtIndex(nodes, i)!
result.append(XMLNode._objectNodeForNode(_CFXMLNodePtr(mutating: nodePtr)))
}
return result
}
/*!
@method objectsForXQuery:constants:error:
@abstract Returns the objects resulting from applying an XQuery to this node using the node as the context item ("."). Constants are a name-value dictionary for constants declared "external" in the query. normalizeAdjacentTextNodesPreservingCDATA:NO should be called if there are adjacent text nodes since they are not allowed under the XPath/XQuery Data Model.
@returns An array whose elements are kinds of NSArray, NSData, NSDate, NSNumber, NSString, NSURL, or NSXMLNode.
*/
@available(*, unavailable, message: "XQuery is not available in swift-corelibs-foundation")
open func objects(forXQuery xquery: String, constants: [String : Any]?) throws -> [Any] {
NSUnsupported()
}
@available(*, unavailable, message: "XQuery is not available in swift-corelibs-foundation")
open func objects(forXQuery xquery: String) throws -> [Any] {
NSUnsupported()
}
internal var _childNodes: Set<XMLNode> = []
deinit {
guard _xmlNode != nil else { return }
for node in _childNodes {
node.detach()
}
_xmlDocument = nil
switch kind {
case .document:
_CFXMLFreeDocument(_CFXMLDocPtr(_xmlNode))
case .DTDKind:
_CFXMLFreeDTD(_CFXMLDTDPtr(_xmlNode))
case .attribute:
_CFXMLFreeProperty(_xmlNode)
default:
_CFXMLFreeNode(_xmlNode)
}
}
internal init(ptr: _CFXMLNodePtr) {
setupXMLParsing()
precondition(_CFXMLNodeGetPrivateData(ptr) == nil, "Only one XMLNode per xmlNodePtr allowed")
_xmlNode = ptr
super.init()
if let parent = _CFXMLNodeGetParent(_xmlNode) {
let parentNode = XMLNode._objectNodeForNode(parent)
parentNode._childNodes.insert(self)
}
_CFXMLNodeSetPrivateData(_xmlNode, Unmanaged.passRetained(self).toOpaque())
if let documentPtr = _CFXMLNodeGetDocument(_xmlNode) {
if documentPtr != ptr {
_xmlDocument = XMLDocument._objectNodeForNode(documentPtr)
}
}
}
internal class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> XMLNode {
switch _CFXMLNodeGetType(node) {
case _kCFXMLTypeElement:
return XMLElement._objectNodeForNode(node)
case _kCFXMLTypeDocument:
return XMLDocument._objectNodeForNode(node)
case _kCFXMLTypeDTD:
return XMLDTD._objectNodeForNode(node)
case _kCFXMLDTDNodeTypeEntity:
fallthrough
case _kCFXMLDTDNodeTypeElement:
fallthrough
case _kCFXMLDTDNodeTypeNotation:
fallthrough
case _kCFXMLDTDNodeTypeAttribute:
return XMLDTDNode._objectNodeForNode(node)
default:
if let _private = _CFXMLNodeGetPrivateData(node) {
return unsafeBitCast(_private, to: XMLNode.self)
}
return XMLNode(ptr: node)
}
}
// libxml2 believes any node can have children, though XMLNode disagrees.
// Nevertheless, this belongs here so that XMLElement and XMLDocument can share
// the same implementation.
internal func _insertChild(_ child: XMLNode, atIndex index: Int) {
precondition(index >= 0)
precondition(index <= childCount)
precondition(child.parent == nil)
_childNodes.insert(child)
if index == 0 {
let first = _CFXMLNodeGetFirstChild(_xmlNode)!
_CFXMLNodeAddPrevSibling(first, child._xmlNode)
} else {
let currChild = self.child(at: index - 1)!._xmlNode
_CFXMLNodeAddNextSibling(currChild!, child._xmlNode)
}
}
// see above
internal func _insertChildren(_ children: [XMLNode], atIndex index: Int) {
for (childIndex, node) in children.enumerated() {
_insertChild(node, atIndex: index + childIndex)
}
}
/*!
@method removeChildAtIndex:atIndex:
@abstract Removes a child at a particular index.
*/
// See above!
internal func _removeChildAtIndex(_ index: Int) {
guard let child = child(at: index) else {
fatalError("index out of bounds")
}
_childNodes.remove(child)
_CFXMLUnlinkNode(child._xmlNode)
}
// see above
internal func _setChildren(_ children: [XMLNode]?) {
_removeAllChildren()
guard let children = children else {
return
}
for child in children {
_addChild(child)
}
}
/*!
@method addChild:
@abstract Adds a child to the end of the existing children.
*/
// see above
internal func _addChild(_ child: XMLNode) {
precondition(child.parent == nil)
_CFXMLNodeAddChild(_xmlNode, child._xmlNode)
_childNodes.insert(child)
}
/*!
@method replaceChildAtIndex:withNode:
@abstract Replaces a child at a particular index with another child.
*/
// see above
internal func _replaceChildAtIndex(_ index: Int, withNode node: XMLNode) {
let child = self.child(at: index)!
_childNodes.remove(child)
_CFXMLNodeReplaceNode(child._xmlNode, node._xmlNode)
_childNodes.insert(node)
}
}
internal protocol _NSXMLNodeCollectionType: Collection { }
extension XMLNode: _NSXMLNodeCollectionType {
public struct Index: Comparable {
fileprivate let node: _CFXMLNodePtr?
fileprivate let offset: Int?
}
public subscript(index: Index) -> XMLNode {
return XMLNode._objectNodeForNode(index.node!)
}
public var startIndex: Index {
let node = _CFXMLNodeGetFirstChild(_xmlNode)
return Index(node: node, offset: node.map { _ in 0 })
}
public var endIndex: Index {
return Index(node: nil, offset: nil)
}
public func index(after i: Index) -> Index {
precondition(i.node != nil, "can't increment endIndex")
let nextNode = _CFXMLNodeGetNextSibling(i.node!)
return Index(node: nextNode, offset: nextNode.map { _ in i.offset! + 1 } )
}
}
extension XMLNode.Index {
public static func ==(lhs: XMLNode.Index, rhs: XMLNode.Index) -> Bool {
return lhs.offset == rhs.offset
}
public static func <(lhs: XMLNode.Index, rhs: XMLNode.Index) -> Bool {
switch (lhs.offset, rhs.offset) {
case (nil, nil):
return false
case (nil, _?):
return false
case (_?, nil):
return true
case (let lhsOffset?, let rhsOffset?):
return lhsOffset < rhsOffset
}
}
}
| 35.555243 | 448 | 0.605378 |
2829375199d017c9dde9ac3ca1052956dc14014a | 637 | //
// TextFieldDelegateProxy.swift
// ViewComponent
//
// Created by lalawue on 2021/2/14.
//
import UIKit
/** for UITextField delegate, as inherit from NSObject
*/
class TextFieldDelegateProxy: NSObject, UITextFieldDelegate {
var changeCallback: ((String) -> Void)?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
let str = NSString(string: textField.text ?? "")
if let callback = changeCallback {
callback(str.replacingCharacters(in: range, with: string) as String)
}
return true
}
}
| 24.5 | 127 | 0.6719 |
acb2ec9924b285762f2c700c5beeaa72e20543ab | 1,261 | //
// CustomView.swift
// iUpload
//
// Created by MLeo on 2019/3/29.
// Copyright © 2019年 iChochy. All rights reserved.
//
import Cocoa
class CustomView: NSView {
init() {
super.init(frame: NSRect.init())
addProgress()
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
private func addProgress(){
let progress = NSProgressIndicator.init()
progress.style = NSProgressIndicator.Style.spinning
progress.startAnimation(nil)
self.addSubview(progress)
progress.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.widthAnchor.constraint(equalToConstant: 100),
self.heightAnchor.constraint(equalToConstant: 100),
progress.centerXAnchor.constraint(equalTo: self.centerXAnchor),
progress.centerYAnchor.constraint(equalTo: self.centerYAnchor),
progress.widthAnchor.constraint(equalToConstant: 40),
progress.heightAnchor.constraint(equalToConstant: 40)
])
}
}
| 28.022222 | 75 | 0.639968 |
16ed2579cda878f90f2b299a0f85e351e5a491b1 | 2,363 | //
// SceneDelegate.swift
// CaptionThatApp
//
// Created by Rebecca Slatkin on 2/9/20.
// Copyright © 2020 Syracuse University. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.759259 | 147 | 0.714769 |
dea471a630399fbbc55bff896c66ab64baacdec7 | 7,408 | //
// MACalendarBuilder.swift
// MACalendar
//
// Created by Mahjabin Alam on 2021/05/09.
//
import Foundation
class CalendarBuilder{
let calendarObj = NSCalendar(identifier: .gregorian)
func firstDay(ofMonth month: Int, andYear year: Int)->Date?{
var dateComponent = DateComponents()
dateComponent.day = 1
dateComponent.month = month
dateComponent.year = year
guard let date = calendarObj?.date(from: dateComponent) else{
return nil
}
return date
}
func lastDay(ofMonth month: Int, andYear year:Int)->Date?{
guard let firstDate = firstDay(ofMonth: month, andYear: year) else{
return nil
}
var dateComponent = DateComponents()
dateComponent.month = 1
dateComponent.day = -1
guard let lastDate = calendarObj?.date(byAdding: dateComponent, to: firstDate) else {
return nil
}
return lastDate
}
func getDateObject(fromDate date: Date)->MACalendarDay?{
let formatter = DateFormatter()
formatter.dateFormat = "E YYYY MM dd"
let dateString = formatter.string(from: date)
let components = dateString.split(separator: " ")
let weekDay = String(components[0])
guard let year = Int(components[1]) else{ return nil }
guard let month = Int(components[2]) else{ return nil }
guard let date = Int(components[3]) else{ return nil }
return MACalendarDay(day: weekDay, date: date, month: month, year: year)
}
func getFirstAndLastDayInterval(ofMonth month: Int, andYear year: Int)->Int?{
guard let firstDay = firstDay(ofMonth: month, andYear: year) else{
return nil
}
guard let lastDay = lastDay(ofMonth: month, andYear: year) else{
return nil
}
let differrence = calendarObj?.components([.day], from: firstDay, to: lastDay)
if let differenceInDays = differrence?.day{
return (differenceInDays + 1)
}
return nil
}
func nextDate(fromDate date:Date)->Date?{
var component = DateComponents()
component.day = 1
let nextDate = calendarObj?.date(byAdding: component, to: date)
return nextDate
}
func getDateComponent(_ date: Date)->[String]{
let formatter = DateFormatter()
formatter.dateFormat = "E YYYY MM dd"
let dateString = formatter.string(from: date)
let components = dateString.split(separator: " ").map{ return String($0)}
return components
}
func getMonth(from date: Date?)->Int?{
let formatter = DateFormatter()
formatter.dateFormat = "MM"
if let date = date{
guard let month = Int(formatter.string(from: date)) else{
return nil
}
return month
}
return nil
}
func currentMonth()->Int?{
let formatter = DateFormatter()
formatter.dateFormat = "MM"
let currentDate = Date()
guard let month = Int(formatter.string(from: currentDate)) else{
return nil
}
return month
}
func nextMonth(_ date: Date)->Int?{
let nextMonthDate = calendarObj?.date(byAdding: .month, value: 1, to: date)
return nextMonthDate?.month()
}
func previousMonth(_ date: Date)->Int?{
let previousMonthDate = calendarObj?.date(byAdding: .month, value: -1, to: date)
return previousMonthDate?.month()
}
func currentMonthAndYear()->MAMonthYearCombination?{
guard let month = currentMonth() else{
return nil
}
guard let year = currentYear() else {
return nil
}
return MAMonthYearCombination(month: month, year: year)
}
func previousMonthAndYear(fromMonth month: Int, andYear year: Int)->MAMonthYearCombination?{
var dateComponent = DateComponents()
dateComponent.month = month
dateComponent.year = year
if let date = calendarObj?.date(from: dateComponent){
let previousMonthAndYear = calendarObj?.date(byAdding: .month, value: -1, to: date)
if let prevMonth = previousMonthAndYear?.month(), let prevYear = previousMonthAndYear?.year(){
let monthAndYearCombination = MAMonthYearCombination(month: prevMonth, year: prevYear)
return monthAndYearCombination
}
}
return nil
}
func nextMonthAndYear(fromMonth month: Int, andYear year: Int)->MAMonthYearCombination?{
var dateComponent = DateComponents()
dateComponent.month = month
dateComponent.year = year
if let date = calendarObj?.date(from: dateComponent){
let nextMonthAndYear = calendarObj?.date(byAdding: .month, value: 1, to: date)
if let nextMonth = nextMonthAndYear?.month(), let nextYear = nextMonthAndYear?.year(){
let monthAndYearCombination = MAMonthYearCombination(month: nextMonth, year: nextYear)
return monthAndYearCombination
}
}
return nil
}
func currentYear()->Int?{
let currentDate = Date()
let formatter = DateFormatter()
formatter.dateFormat = "YYYY"
if let currentYear = Int(formatter.string(from: currentDate)){
return currentYear
}
return nil
}
func nextYear(_ date: Date)->Int?{
if let nextYearDate = calendarObj?.date(byAdding: .year, value: 1, to: date){
let formatter = DateFormatter()
formatter.dateFormat = "YYYY"
if let nextYear = Int(formatter.string(from: nextYearDate)){
return nextYear
}
}
return nil
}
func previousYear(_ date: Date)->Int?{
if let prevYearDate = calendarObj?.date(byAdding: .year, value: -1, to: date){
let formatter = DateFormatter()
formatter.dateFormat = "YYYY"
if let prevYear = Int(formatter.string(from: prevYearDate)){
return prevYear
}
}
return nil
}
}
extension Date{
func toString()->String{
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
return dateFormatter.string(from: self)
}
func printAsString(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
print(dateFormatter.string(from: self))
}
func date()->Int{
let formatter = DateFormatter()
formatter.dateFormat = "dd"
let dateString = formatter.string(from: self)
let components = dateString.split(separator: " ")
return Int(components[0]) ?? 0
}
func month()->Int{
let formatter = DateFormatter()
formatter.dateFormat = "MM"
let dateString = formatter.string(from: self)
let components = dateString.split(separator: " ")
return Int(components[0]) ?? 0
}
func year()->Int{
let formatter = DateFormatter()
formatter.dateFormat = "YYYY"
let dateString = formatter.string(from: self)
let components = dateString.split(separator: " ")
return Int(components[0]) ?? -1
}
}
| 33.672727 | 106 | 0.595707 |
e809dd37cbed0ad9acbfeaf87bd0dd38501c8f51 | 617 | //
// Bundle+Utility.swift
// AlternateIcons
//
// Created by Dolar, Ziga on 07/22/2019.
// Copyright (c) 2019 Dolar, Ziga. All rights reserved.
//
import Foundation
internal extension Bundle {
static func resourceBundle(for type: AnyClass) -> Bundle? {
let moduleBundle = Bundle(for: type)
let moduleName = moduleBundle.resourceURL?.deletingPathExtension().lastPathComponent
if let path = moduleBundle.path(forResource: moduleName, ofType: "bundle") {
if let bundle = Bundle(path: path) {
return bundle
}
}
return nil
}
}
| 26.826087 | 92 | 0.632091 |
72663313fc82c1dc318855893442252a09a157e8 | 1,049 | //
// OneTableViewCell.swift
// OneTableView
//
// Created by 陈荣超 on 2021/11/8.
//
import Foundation
import UIKit
class BaseOneTableViewCell: UITableViewCell {
class var cellHeight: CGFloat {
return 66
}
func setAnyObject(model: AnyObject?) {
// no op
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
initView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func initView() {
// no op
}
}
class OneTableViewCell<D>: BaseOneTableViewCell {
var model: D? {
didSet {
if let model = model {
didSetModel(model: model)
}
}
}
override func setAnyObject(model: AnyObject?) {
self.model = model as? D
}
open func didSetModel(model: D) {
// no op
}
}
| 19.425926 | 79 | 0.56816 |