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
|
---|---|---|---|---|---|
91e1f592d83fd2bfdf1c38d3ed9172e626e9c719 | 2,204 | //
// ActivityViewController.swift
// Stagram
//
// Created by Juliang Li on 2/24/16.
// Copyright © 2016 Juliang. All rights reserved.
//
import UIKit
import Parse
class ActivityViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var postedActivities: [PFObject]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UserMedia.fetchUserActivity { (objects, error) -> () in
if error == nil{
self.postedActivities = objects
self.tableView.reloadData()
}else{
print("Terrible thing just happened here")
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let postedActivities = self.postedActivities{
return postedActivities.count
}else{
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("ActivityCell", forIndexPath: indexPath) as! ActivityViewCell
let activityObject = postedActivities?[indexPath.row]
let activityString = activityObject?.objectForKey("activity") as? String
let timeString = getTimePastFromDate(activityObject!.createdAt!)
cell.activityLabel.text = activityString!
cell.timeLabel.text = timeString
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 32.411765 | 124 | 0.65971 |
6a8c1bcf658f1eeff6d18da2017ef62fa0c2b8ad | 4,513 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows how operations can be composed together to form new operations.
*/
import Foundation
/**
A subclass of `Operation` that executes zero or more operations as part of its
own execution. This class of operation is very useful for abstracting several
smaller operations into a larger operation. As an example, the `GetEarthquakesOperation`
is composed of both a `DownloadEarthquakesOperation` and a `ParseEarthquakesOperation`.
Additionally, `GroupOperation`s are useful if you establish a chain of dependencies,
but part of the chain may "loop". For example, if you have an operation that
requires the user to be authenticated, you may consider putting the "login"
operation inside a group operation. That way, the "login" operation may produce
subsequent operations (still within the outer `GroupOperation`) that will all
be executed before the rest of the operations in the initial chain of operations.
*/
open class GroupOperation: Operation {
private let internalQueue = OperationQueue()
private let startingOperation = Foundation.BlockOperation(block: {})
private let finishingOperation = Foundation.BlockOperation(block: {})
private var queue = DispatchQueue(label: "GroupOperationSyncQueue")
private var aggregatedErrors = [Error]()
public convenience init(operations: Foundation.Operation...) {
self.init(operations: operations)
}
public init(operations: [Foundation.Operation]) {
super.init()
internalQueue.name = "\(name ?? "Unknown Group Operation") queue"
internalQueue.isSuspended = true
internalQueue.delegate = self
internalQueue.addOperation(startingOperation)
for operation in operations {
internalQueue.addOperation(operation)
}
}
override open func cancel() {
internalQueue.cancelAllOperations()
super.cancel()
}
override open func execute() {
internalQueue.isSuspended = false
internalQueue.addOperation(finishingOperation)
}
open func addOperation(_ operation: Foundation.Operation) {
internalQueue.addOperation(operation)
}
/**
Note that some part of execution has produced an error.
Errors aggregated through this method will be included in the final array
of errors reported to observers and to the `finished(_:)` method.
*/
final public func aggregateError(_ error: Error) {
queue.sync { aggregatedErrors.append(error) }
}
open func operationDidFinish(_ operation: Foundation.Operation, withErrors errors: [Error]) {
// For use by subclassers.
}
}
extension GroupOperation: OperationQueueDelegate {
final public func operationQueue(_ operationQueue: OperationQueue, willAddOperation operation: Foundation.Operation) {
assert(!finishingOperation.isFinished && !finishingOperation.isExecuting, "cannot add new operations to a group after the group has completed")
/*
Some operation in this group has produced a new operation to execute.
We want to allow that operation to execute before the group completes,
so we'll make the finishing operation dependent on this newly-produced operation.
*/
if operation !== finishingOperation {
finishingOperation.addDependency(operation)
}
/*
All operations should be dependent on the "startingOperation".
This way, we can guarantee that the conditions for other operations
will not evaluate until just before the operation is about to run.
Otherwise, the conditions could be evaluated at any time, even
before the internal operation queue is unsuspended.
*/
if operation !== startingOperation {
operation.addDependency(startingOperation)
}
}
final public func operationQueue(_ operationQueue: OperationQueue, operationDidFinish operation: Foundation.Operation, withErrors errors: [Error]) {
queue.sync { aggregatedErrors += errors }
if operation === finishingOperation {
internalQueue.isSuspended = true
queue.sync { finish(aggregatedErrors) }
} else if operation !== startingOperation {
operationDidFinish(operation, withErrors: errors)
}
}
}
| 39.938053 | 152 | 0.700643 |
e64c31fa6df726de6c7bc7f581a86c83be4ff238 | 963 | //
// String+Extensions.swift
// ZeroStore
//
// Created by Kyle Bashour on 9/3/15.
// Copyright (c) 2015 Kyle Bashour. All rights reserved.
//
// From http://stackoverflow.com/questions/24099520/commonhmac-in-swift
// Modified to give back a base64 string
import Foundation
extension String {
func hmac(algorithm: CryptoAlgorithm, key: NSData) -> String {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = Int(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = algorithm.digestLength
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
let keyStr = UnsafePointer<CChar>(key.bytes)
let keyLen = key.length
CCHmac(algorithm.HMACAlgorithm, keyStr, keyLen, str!, strLen, result)
let base64 = NSData(bytes: result, length: digestLen).base64EncodedStringWithOptions([])
result.dealloc(digestLen)
return base64
}
}
| 30.09375 | 96 | 0.705088 |
75c07d41320f9788a34c6f2c60e8b4a1050de84d | 248 | // RUN: %incr-transfer-tree --expected-incremental-syntax-tree %S/Outputs/extend-identifier-at-eof.json %s
func foo() {}
// ATTENTION: This file is testing the EOF token.
// DO NOT PUT ANYTHING AFTER THE CHANGE, NOT EVEN A NEWLINE
_ = x<<<|||x>>> | 41.333333 | 106 | 0.701613 |
db03c92ba18376f8c03ff340de194cdcb3f112e2 | 693 | import Foundation
import CoreImage
public class CIRoundedRectangleGenerator: ImageFilter {
public init() {
super.init(name: "CIRoundedRectangleGenerator")
}
override public func inputColor(_ inputColor: CIColor?) -> CIRoundedRectangleGenerator {
filter.setValue(inputColor, forKey:"inputColor")
return self
}
public func inputRadius(_ inputRadius: Double) -> CIRoundedRectangleGenerator {
filter.setValue(inputRadius, forKey:"inputRadius")
return self
}
public func inputExtent(_ inputExtent: CIVector?) -> CIRoundedRectangleGenerator {
filter.setValue(inputExtent, forKey:"inputExtent")
return self
}
}
| 33 | 92 | 0.708514 |
502370f4e359ccbe8b0788c7d2ae53b749e3157a | 190 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{{(}{t
[[[{{let h=[{
| 27.142857 | 87 | 0.715789 |
48365cb236e55b1e255b3695e8d751a71c6233f5 | 1,432 | //
// AppDelegate.swift
// ArtifactExample
//
// Created by Michal Chudziak on 09/01/2020.
// Copyright © 2020 Michal Chudziak. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.684211 | 179 | 0.75 |
332a7bc9be86fa0a12f54858dde9d7b314cfea11 | 2,130 | //
// UITableViewExtension.swift
// GetStarted
//
// Created by Fabian Braach on 03.06.18.
//
import UIKit
public extension UITableView {
public func scrollToBottom(animated: Bool = true) {
guard numberOfSections > 0 else { return }
let section = numberOfSections - 1
let row = numberOfRows(inSection: section) - 1
guard section >= 0,
row >= 0 else { return }
DispatchQueue.main.async {
let indexPath = IndexPath(row: row, section: section)
self.scrollToRow(at: indexPath, at: .bottom, animated: animated)
}
}
public func scrollToTop(animated: Bool = true) {
guard numberOfSections > 0,
numberOfRows(inSection: numberOfSections - 1) > 0 else { return }
DispatchQueue.main.async {
let indexPath = IndexPath(row: 0, section: 0)
self.scrollToRow(at: indexPath, at: .top, animated: animated)
}
}
public func register<T: UITableViewCell>(_ cell: T.Type) {
register(cell, forCellReuseIdentifier: cell.className)
}
/// Set table header view & add Auto layout.
public func setTableHeaderView(headerView: UIView) {
headerView.translatesAutoresizingMaskIntoConstraints = false
// Set first.
self.tableHeaderView = headerView
// Then setup AutoLayout.
headerView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
headerView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
headerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
}
/// Update header view's frame.
public func updateHeaderViewFrame() {
guard let headerView = self.tableHeaderView else { return }
// Update the size of the header based on its internal content.
headerView.layoutIfNeeded()
// ***Trigger table view to know that header should be updated.
let header = self.tableHeaderView
self.tableHeaderView = header
}
}
| 32.272727 | 88 | 0.624883 |
8adae5eb45c8803812f94c5ea717ee237eed7bd1 | 812 | import SwiftUI
import WidgetKit
struct LatestTransactionView: View {
@Environment(\.widgetFamily) private var family
let transaction: LatestTransactionModel
var body: some View {
switch family {
case .systemSmall:
VStack {
Text(transaction.description)
.font(.circularStdBold(size: 20))
Text(transaction.amount)
}
case .systemMedium, .systemLarge, .systemExtraLarge:
VStack {
Text("Latest Transaction")
.font(.circularStdBold(size: 23))
.foregroundColor(.accentColor)
Spacer()
TransactionCellView(transaction: transaction)
}
@unknown default:
VStack {
Text(transaction.description)
.font(.circularStdBold(size: 20))
Text(transaction.amount)
}
}
}
}
| 23.882353 | 56 | 0.633005 |
75213a7dbd7b94ec811fcaa764dd03e6ccf52c02 | 1,930 | import Basic
import Foundation
@testable import TuistCoreTesting
@testable import TuistKit
import XCTest
final class LintingIssueTests: XCTestCase {
func test_description() {
let subject = LintingIssue(reason: "whatever", severity: .error)
XCTAssertEqual(subject.description, "whatever")
}
func test_equatable() {
let first = LintingIssue(reason: "whatever", severity: .error)
let second = LintingIssue(reason: "whatever", severity: .error)
let third = LintingIssue(reason: "whatever", severity: .warning)
XCTAssertEqual(first, second)
XCTAssertNotEqual(first, third)
}
func test_printAndThrowIfNeeded() throws {
let printer = MockPrinter()
let first = LintingIssue(reason: "error", severity: .error)
let second = LintingIssue(reason: "warning", severity: .warning)
XCTAssertThrowsError(try [first, second].printAndThrowIfNeeded(printer: printer))
XCTAssertEqual(printer.printWithColorArgs.first?.0, "The following issues have been found:")
XCTAssertEqual(printer.printWithColorArgs.first?.1, .yellow)
XCTAssertEqual(printer.printArgs.first, " - warning")
XCTAssertEqual(printer.printWithColorArgs.last?.0, "\nThe following critical issues have been found:")
XCTAssertEqual(printer.printWithColorArgs.last?.1, .red)
XCTAssertEqual(printer.printArgs.last, " - error")
}
func test_printAndThrowIfNeeded_whenErrorsOnly() throws {
let printer = MockPrinter()
let first = LintingIssue(reason: "error", severity: .error)
XCTAssertThrowsError(try [first].printAndThrowIfNeeded(printer: printer))
XCTAssertEqual(printer.printWithColorArgs.last?.0, "The following critical issues have been found:")
XCTAssertEqual(printer.printWithColorArgs.last?.1, .red)
XCTAssertEqual(printer.printArgs.last, " - error")
}
}
| 40.208333 | 110 | 0.703109 |
ddcafc68fcc787b9e23ea4d59cfd6bad03b55447 | 2,323 | //
// DictionaryTests.swift
// ZamzamCore
//
// Created by Basem Emara on 2020-03-24.
// Copyright © 2018 Zamzam Inc. All rights reserved.
//
import XCTest
import ZamzamCore
final class DictionaryTests: XCTestCase {
func testJSONString() throws {
// Given
let dictionary: [String: Any] = [
"id": 1,
"name": "Joe",
"friends": [
[
"id": 2,
"name": "Pat",
"pets": ["dog"]
],
[
"id": 3,
"name": "Sue",
"pets": ["bird", "fish"]
]
],
"pets": []
]
let expected: [String: Any]
// When
guard let json = dictionary.jsonString() else {
XCTFail("String could not be converted to JSON")
return
}
guard let data = json.data(using: .utf8),
let decoded = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
XCTFail("String could not be converted to JSON")
return
}
expected = decoded
// Then
XCTAssert(json.contains("\"id\":1"))
XCTAssert(json.contains("\"name\":\"Joe\""))
XCTAssert(json.contains("\"friends\":[{"))
XCTAssert(json.contains("\"pets\":[\"dog\"]"))
XCTAssert(json.contains("\"name\":\"Sue\""))
XCTAssert(json.contains("\"pets\":[\""))
XCTAssertNotNil(dictionary["id"] as? Int)
XCTAssertEqual(dictionary["id"] as? Int, expected["id"] as? Int)
XCTAssertNotNil(dictionary["name"] as? String)
XCTAssertEqual(dictionary["name"] as? String, expected["name"] as? String)
XCTAssertNotNil(dictionary["pets"] as? [String])
XCTAssertEqual(dictionary["pets"] as? [String], expected["pets"] as? [String])
XCTAssertNotNil(((dictionary["friends"] as? [[String: Any]])?.first)?["name"] as? String)
XCTAssertEqual(
((dictionary["friends"] as? [[String: Any]])?.first)?["name"] as? String,
((expected["friends"] as? [[String: Any]])?.first)?["name"] as? String
)
}
}
| 31.391892 | 108 | 0.484288 |
16f95c91b9ec12bd64fd5fb90c82bc3da495c3e8 | 8,209 | //
// Subscribers.Demand.swift
//
//
// Created by Sergej Jaskiewicz on 10.06.2019.
//
// swiftlint:disable shorthand_operator - because of false positives here
extension Subscribers {
/// A requested number of items, sent to a publisher from a subscriber via
/// the subscription.
///
/// - `unlimited`: A request for an unlimited number of items.
/// - `max`: A request for a maximum number of items.
public struct Demand: Equatable,
Comparable,
Hashable,
Codable,
CustomStringConvertible
{
private var rawValue: UInt
private static let _rawValueUnlimited = UInt(Int.max) + 1
private init<Integer: BinaryInteger>(_ rawValue: Integer) {
if rawValue < 0 {
self.rawValue = 0
} else if rawValue > Demand._rawValueUnlimited {
self.rawValue = Demand._rawValueUnlimited
} else {
self.rawValue = UInt(rawValue)
}
}
/// Requests as many values as the `Publisher` can produce.
public static let unlimited = Subscribers.Demand(_rawValueUnlimited)
/// Limits the maximum number of values.
/// The `Publisher` may send fewer than the requested number.
/// Negative values will result in a `fatalError`.
public static func max(_ value: Int) -> Subscribers.Demand {
return .init(UInt(value))
}
public var description: String {
if self == .unlimited {
return "unlimited"
} else {
return "max(\(rawValue))"
}
}
/// When adding any value to `.unlimited`, the result is `.unlimited`.
public static func + (lhs: Demand, rhs: Demand) -> Demand {
switch (lhs, rhs) {
case (.unlimited, _):
return .unlimited
case (_, .unlimited):
return .unlimited
default:
let (sum, isOverflow) = lhs.rawValue.addingReportingOverflow(rhs.rawValue)
return isOverflow ? .unlimited : .init(sum)
}
}
/// A demand for no items.
///
/// This is equivalent to `Demand.max(0)`.
public static let none: Demand = .max(0)
/// When adding any value to `.unlimited`, the result is `.unlimited`.
public static func += (lhs: inout Demand, rhs: Demand) {
lhs = lhs + rhs
}
/// When adding any value to` .unlimited`, the result is `.unlimited`.
public static func + (lhs: Demand, rhs: Int) -> Demand {
if lhs == .unlimited {
return .unlimited
}
return Demand(lhs.rawValue.advanced(by: rhs))
}
/// When adding any value to `.unlimited`, the result is `.unlimited`.
public static func += (lhs: inout Demand, rhs: Int) {
lhs = lhs + rhs
}
public static func * (lhs: Demand, rhs: Int) -> Demand {
if lhs == .unlimited {
return .unlimited
}
let (product, isOverflow) =
lhs.rawValue.multipliedReportingOverflow(by: UInt(rhs))
return isOverflow ? .unlimited : .init(product)
}
public static func *= (lhs: inout Demand, rhs: Int) {
lhs = lhs * rhs
}
/// When subtracting any value (including .unlimited) from .unlimited,
/// the result is still .unlimited. Subtracting unlimited from any value
/// (except unlimited) results in .max(0). A negative demand is not possible;
/// any operation that would result in a negative value is clamped to .max(0).
public static func - (lhs: Demand, rhs: Demand) -> Demand {
switch (lhs, rhs) {
case (.unlimited, _):
return .unlimited
case (_, .unlimited):
return .none
default:
let (difference, isOverflow) =
lhs.rawValue.subtractingReportingOverflow(rhs.rawValue)
return isOverflow ? .none : .init(difference)
}
}
/// When subtracting any value (including .unlimited) from .unlimited,
/// the result is still .unlimited. Subtracting unlimited from any value
/// (except unlimited) results in .max(0). A negative demand is not possible;
/// any operation that would result in a negative value is clamped to .max(0).
/// but be aware that it is not usable when requesting values in a subscription.
public static func -= (lhs: inout Demand, rhs: Demand) {
lhs = lhs - rhs
}
/// When subtracting any value from .unlimited, the result is still .unlimited.
/// A negative demand is not possible; any operation that would result in
/// a negative value is clamped to .max(0)
public static func - (lhs: Demand, rhs: Int) -> Demand {
if lhs == .unlimited {
return .unlimited
}
let (difference, isOverflow) =
Int(lhs.rawValue).subtractingReportingOverflow(rhs)
return isOverflow ? .none : .init(difference)
}
/// When subtracting any value from .unlimited, the result is still .unlimited.
/// A negative demand is not possible; any operation that would result in
/// a negative value is clamped to .max(0)
public static func -= (lhs: inout Demand, rhs: Int) {
lhs = lhs - rhs
}
public static func > (lhs: Demand, rhs: Int) -> Bool {
return lhs > .max(rhs)
}
public static func >= (lhs: Demand, rhs: Int) -> Bool {
return lhs >= .max(rhs)
}
public static func > (lhs: Int, rhs: Demand) -> Bool {
return .max(lhs) > rhs
}
public static func >= (lhs: Int, rhs: Demand) -> Bool {
return .max(lhs) >= rhs
}
public static func < (lhs: Demand, rhs: Int) -> Bool {
return lhs < .max(rhs)
}
public static func < (lhs: Int, rhs: Demand) -> Bool {
return .max(lhs) < rhs
}
public static func <= (lhs: Demand, rhs: Int) -> Bool {
return lhs <= .max(rhs)
}
public static func <= (lhs: Int, rhs: Demand) -> Bool {
return .max(lhs) <= rhs
}
/// If `lhs` is `.unlimited`, then the result is always `false`.
/// If `rhs` is `.unlimited` then the result is `false` iff `lhs` is `.unlimited`
/// Otherwise, the two `.max` values are compared.
public static func < (lhs: Demand, rhs: Demand) -> Bool {
if lhs == .unlimited {
return false
}
if rhs == .unlimited {
return true
}
return lhs.rawValue < rhs.rawValue
}
/// Returns `true` if `lhs` and `rhs` are equal. `.unlimited` is not equal to any
/// integer.
public static func == (lhs: Demand, rhs: Int) -> Bool {
return lhs == .max(rhs)
}
/// Returns `true` if `lhs` and `rhs` are not equal. `.unlimited` is not equal to
/// any integer.
public static func != (lhs: Demand, rhs: Int) -> Bool {
return lhs != .max(rhs)
}
/// Returns `true` if `lhs` and `rhs` are equal. `.unlimited` is not equal to any
/// integer.
public static func == (lhs: Int, rhs: Demand) -> Bool {
return .max(lhs) == rhs
}
/// Returns `true` if `lhs` and `rhs` are not equal. `.unlimited` is not equal to
/// any integer.
public static func != (lhs: Int, rhs: Demand) -> Bool {
return .max(lhs) != rhs
}
/// Returns the number of requested values, or `nil` if `.unlimited`.
public var max: Int? {
if self == .unlimited {
return nil
} else {
return Int(rawValue)
}
}
}
}
| 35.081197 | 90 | 0.528688 |
64dc1acb78dac35ed401540d604618810a16395a | 3,252 | //
// GridView.swift
// DVPNApp
//
// Created by Victoria Kostyleva on 04.10.2021.
//
import SwiftUI
enum GridViewModelType: Hashable {
case connectionInfo(ConnectionInfoViewModel)
case nodeInfo(NodeInfoViewModel)
}
struct GridView: View {
private let chunkedModels: [[GridViewModelType]]
private let borderColor = Asset.Colors.Redesign.gridBorder.color.asColor
init(
models: [GridViewModelType]
) {
self.chunkedModels = models.chunked(into: 2)
}
@ViewBuilder
var body: some View {
VStack(spacing: 0) {
ForEach(Array(zip(chunkedModels.indices, chunkedModels)), id: \.0) { index, modelPair in
VStack(spacing: 0) {
if index > 0, index < chunkedModels.count {
Circle()
.strokeBorder(borderColor, lineWidth: 1)
.background(Circle().foregroundColor(Asset.Colors.Redesign.backgroundColor.color.asColor))
.frame(width: 16, height: 16)
.padding(.top, -8)
}
HStack {
// TODO: @tori do not copy-pase
let modelType0 = modelPair[safe: 0]
if let modelType0 = modelType0 {
switch modelType0 {
case let .connectionInfo(model):
ConnectionInfoView(viewModel: model)
case let .nodeInfo(model):
NodeInfoView(viewModel: model)
}
}
Rectangle()
.fill(borderColor)
.frame(width: 1)
let modelType1 = modelPair[safe: 1]
if let modelType1 = modelType1 {
switch modelType1 {
case let .connectionInfo(model):
ConnectionInfoView(viewModel: model)
case let .nodeInfo(model):
NodeInfoView(viewModel: model)
}
}
}
if index < chunkedModels.count - 1 {
Rectangle()
.fill(borderColor)
.frame(height: 1)
}
}
}
}.fixedSize()
}
}
struct GridView_Previews: PreviewProvider {
static var previews: some View {
GridView(
models: [
.connectionInfo(.init(type: .download, value: "test 1", symbols: "aa")),
.connectionInfo(.init(type: .upload, value: "test 2", symbols: "bb")),
.connectionInfo(.init(type: .bandwidth, value: "test 3", symbols: "dd")),
.connectionInfo(.init(type: .duration, value: "test 4", symbols: "cc"))
]
)
}
}
| 35.347826 | 118 | 0.429889 |
08ab3edf090e0c43ce2e377a5dc1ea26e7eae6fd | 487 | //
// DateTimeUtils.swift
// dolandolen
//
// Created by Yusuf Umar Hanafi on 24/11/21.
//
public class DateTimeUtils {
public static let dateTextFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMMM yyyy"
return formatter
}()
public static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
return dateFormatter
}()
}
| 25.631579 | 58 | 0.652977 |
e2492327321caf61a278094f7a48ef365acee777 | 3,159 | //
// AddLocalAccountView.swift
// Multiplatform macOS
//
// Created by Stuart Breckenridge on 02/12/2020.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import SwiftUI
import Account
import RSCore
struct AddLocalAccountView: View {
@State private var newAccountName: String = ""
@Environment (\.presentationMode) var presentationMode
var body: some View {
#if os(macOS)
macBody
#else
NavigationView {
iosBody
}
#endif
}
#if os(iOS)
var iosBody: some View {
List {
Section(header: formHeader, content: {
TextField("Account Name", text: $newAccountName)
})
Section(footer: formFooter, content: {
Button(action: {
let newAccount = AccountManager.shared.createAccount(type: .onMyMac)
newAccount.name = newAccountName
presentationMode.wrappedValue.dismiss()
}, label: {
HStack {
Spacer()
Text("Add Account")
Spacer()
}
})
})
}.navigationBarItems(leading:
Button(action: {
presentationMode.wrappedValue.dismiss()
}, label: {
Text("Cancel")
})
)
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(Text(AccountType.onMyMac.localizedAccountName()))
.listStyle(InsetGroupedListStyle())
}
#endif
#if os(macOS)
var macBody: some View {
VStack {
HStack(spacing: 16) {
VStack(alignment: .leading) {
AccountType.onMyMac.image()
.resizable()
.frame(width: 50, height: 50)
Spacer()
}
VStack(alignment: .leading, spacing: 8) {
Text("Create a local account on your Mac.")
.font(.headline)
Text("Local accounts store their data on your Mac. They do not sync across your devices.")
.font(.callout)
.foregroundColor(.secondary)
HStack {
Text("Name: ")
TextField("Account Name", text: $newAccountName)
}.padding(.top, 8)
Spacer()
HStack(spacing: 8) {
Spacer()
Button(action: {
presentationMode.wrappedValue.dismiss()
}, label: {
Text("Cancel")
.frame(width: 60)
}).keyboardShortcut(.cancelAction)
Button(action: {
let newAccount = AccountManager.shared.createAccount(type: .onMyMac)
newAccount.name = newAccountName
presentationMode.wrappedValue.dismiss()
}, label: {
Text("Create")
.frame(width: 60)
}).keyboardShortcut(.defaultAction)
}
}
}
}
.padding()
.frame(minWidth: 400, maxWidth: 400, minHeight: 230, maxHeight: 260)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
#endif
var formHeader: some View {
HStack {
Spacer()
VStack(alignment: .center) {
AccountType.onMyMac.image()
.resizable()
.frame(width: 50, height: 50)
}
Spacer()
}.padding(.vertical)
}
var formFooter: some View {
HStack {
Spacer()
VStack(spacing: 8) {
Text("Local accounts do not sync your feeds across devices.").foregroundColor(.secondary)
}
.multilineTextAlignment(.center)
.font(.caption)
Spacer()
}.padding(.vertical)
}
}
struct AddLocalAccount_Previews: PreviewProvider {
static var previews: some View {
AddLocalAccountView()
}
}
| 22.404255 | 95 | 0.642292 |
295b8410a70154c1842c6ae56f529a114c2329c4 | 2,448 | //
// KeyValueStoreType.swift
// XcodeOpener
//
// Created by chen he on 2019/4/10.
// Copyright © 2019 chen he. All rights reserved.
//
import Foundation
public enum ApplicationMode: Int {
case menuAndDock
case menuOnly
case background
}
protocol KeyValueStoreType: class {
func bool(for key: String) -> Bool
func setBool(for key: String, _ flag: Bool)
func data(for key: String) -> Data?
func setData(for key: String, _ data: Data)
func int(for key: String) -> Int
func setInt(for key: String, _ value: Int)
}
extension KeyValueStoreType {
var startAtLogin: Bool {
get {
return bool(for: AppKeys.startAtLogin.rawValue)
}
set {
setBool(for: AppKeys.startAtLogin.rawValue, newValue)
}
}
var menuOnly: Bool {
get {
return bool(for: AppKeys.menuOnly.rawValue)
}
set {
setBool(for: AppKeys.menuOnly.rawValue, newValue)
}
}
var openRules: Array<XcodeRule> {
get {
guard let data = data(for: AppKeys.rules.rawValue) else { return [] }
guard let rules = try? JSONDecoder().decode([XcodeRule].self, from: data) else {
return []
}
return rules
}
set {
guard let data = try? JSONEncoder().encode(newValue) else {
return
}
setData(for: AppKeys.rules.rawValue, data)
}
}
var xcodeAliases: Array<XcodeAlias> {
get {
guard let data = data(for: AppKeys.xcodes.rawValue) else { return [] }
guard let xcodes = try? JSONDecoder().decode([XcodeAlias].self, from: data) else {
return []
}
return xcodes
}
set {
guard let data = try? JSONEncoder().encode(newValue) else {
return
}
setData(for: AppKeys.xcodes.rawValue, data)
}
}
var appMode: ApplicationMode {
get {
guard let mode = ApplicationMode(rawValue: int(for: AppKeys.appMode.rawValue)) else { return .menuAndDock }
return mode
}
set {
setInt(for: AppKeys.appMode.rawValue, newValue.rawValue)
}
}
}
| 24.979592 | 119 | 0.517974 |
019082a307dff09fa6289095919fa7a1e3ae4fa5 | 388 | //
// IntentHandler.swift
// MicNotes Shortcuts
//
// Created by Thatcher Clough on 1/3/21.
//
import Intents
class IntentHandler: INExtension {
override func handler(for intent: INIntent) -> Any {
switch intent {
case is GetNotesIntent:
return GetNotesHandler()
default:
fatalError("No handler for this intent")
}
}
}
| 19.4 | 56 | 0.610825 |
f430c90b81914ac4323a4f650f304eb1a862c054 | 1,999 | //
// Repeat.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
- seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html)
- parameter element: Element to repeat.
- parameter scheduler: Scheduler to run the producer loop on.
- returns: An observable sequence that repeats the given element infinitely.
*/
public static func repeatElement(_ element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RepeatElement(element: element, scheduler: scheduler)
}
}
final private class RepeatElement<Element>: Producer<Element> {
fileprivate let _element: Element
fileprivate let _scheduler: ImmediateSchedulerType
init(element: Element, scheduler: ImmediateSchedulerType) {
self._element = element
self._scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = RepeatElementSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final private class RepeatElementSink<O: ObserverType>: Sink<O> {
typealias Parent = RepeatElement<O.E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return self._parent._scheduler.scheduleRecursive(self._parent._element) { e, recurse in
self.forwardOn(.next(e))
recurse(e)
}
}
}
| 34.465517 | 145 | 0.688344 |
0ad2bed42f5e1b709f687bf870c929b7476762af | 511 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import Foundation
public class BookAuthor: Model {
public let id: Model.Identifier
// belongsTo
public var author: Author
// belongsTo
public let book: Book
public init(id: String = UUID().uuidString,
book: Book,
author: Author) {
self.id = id
self.book = book
self.author = author
}
}
| 17.62069 | 47 | 0.600783 |
71888dddc0f30b0962fc3ffa0f0d8128cda4cbb9 | 120 | import Foundation
extension NSNumber {
var isBool: Bool {
return CFBooleanGetTypeID() == CFGetTypeID(self)
}
}
| 15 | 52 | 0.708333 |
8fc1fcce7ecc37d8e8c33cde93d92f057f2901bd | 25,269 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY1 | %FileCheck %s -check-prefix=AVAILABILITY1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY2 | %FileCheck %s -check-prefix=AVAILABILITY2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD2 | %FileCheck %s -check-prefix=KEYWORD2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3 | %FileCheck %s -check-prefix=KEYWORD3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3_2 | %FileCheck %s -check-prefix=KEYWORD3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD4 | %FileCheck %s -check-prefix=KEYWORD4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD5 | %FileCheck %s -check-prefix=KEYWORD5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_GLOBALVAR | %FileCheck %s -check-prefix=ON_GLOBALVAR
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_INIT | %FileCheck %s -check-prefix=ON_INIT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PROPERTY | %FileCheck %s -check-prefix=ON_PROPERTY
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_METHOD | %FileCheck %s -check-prefix=ON_METHOD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PARAM_1 | %FileCheck %s -check-prefix=ON_PARAM
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PARAM_2 | %FileCheck %s -check-prefix=ON_PARAM
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_INDEPENDENT_1 | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_INDEPENDENT_2 | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_LAST | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_INDEPENDENT_1 | %FileCheck %s -check-prefix=KEYWORD_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_INDEPENDENT_2 | %FileCheck %s -check-prefix=KEYWORD_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_LAST | %FileCheck %s -check-prefix=KEYWORD_LAST
struct MyStruct {}
@available(#^AVAILABILITY1^#)
// NOTE: Please do not include the ", N items" after "Begin completions". The
// item count creates needless merge conflicts given that we use the "-NEXT"
// feature of FileCheck and because an "End completions" line exists for each
// test.
// AVAILABILITY1: Begin completions
// AVAILABILITY1-NEXT: Keyword/None: *[#Platform#]; name=*{{$}}
// AVAILABILITY1-NEXT: Keyword/None: iOS[#Platform#]; name=iOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: tvOS[#Platform#]; name=tvOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: watchOS[#Platform#]; name=watchOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: OSX[#Platform#]; name=OSX{{$}}
// AVAILABILITY1-NEXT: Keyword/None: iOSApplicationExtension[#Platform#]; name=iOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: tvOSApplicationExtension[#Platform#]; name=tvOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: watchOSApplicationExtension[#Platform#]; name=watchOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: OSXApplicationExtension[#Platform#]; name=OSXApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: macCatalyst[#Platform#]; name=macCatalyst
// AVAILABILITY1-NEXT: Keyword/None: macCatalystApplicationExtension[#Platform#]; name=macCatalystApplicationExtension
// AVAILABILITY1-NEXT: End completions
@available(*, #^AVAILABILITY2^#)
// AVAILABILITY2: Begin completions
// AVAILABILITY2-NEXT: Keyword/None: unavailable; name=unavailable{{$}}
// AVAILABILITY2-NEXT: Keyword/None: message: [#Specify message#]; name=message{{$}}
// AVAILABILITY2-NEXT: Keyword/None: renamed: [#Specify replacing name#]; name=renamed{{$}}
// AVAILABILITY2-NEXT: Keyword/None: introduced: [#Specify version number#]; name=introduced{{$}}
// AVAILABILITY2-NEXT: Keyword/None: deprecated: [#Specify version number#]; name=deprecated{{$}}
// AVAILABILITY2-NEXT: End completions
@#^KEYWORD2^# func method(){}
// KEYWORD2: Begin completions
// KEYWORD2-NEXT: Keyword/None: available[#Func Attribute#]; name=available{{$}}
// KEYWORD2-NEXT: Keyword/None: objc[#Func Attribute#]; name=objc{{$}}
// KEYWORD2-NEXT: Keyword/None: IBAction[#Func Attribute#]; name=IBAction{{$}}
// KEYWORD2-NEXT: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged{{$}}
// KEYWORD2-NEXT: Keyword/None: inline[#Func Attribute#]; name=inline{{$}}
// KEYWORD2-NEXT: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc{{$}}
// KEYWORD2-NEXT: Keyword/None: inlinable[#Func Attribute#]; name=inlinable{{$}}
// KEYWORD2-NEXT: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access{{$}}
// KEYWORD2-NEXT: Keyword/None: usableFromInline[#Func Attribute#]; name=usableFromInline
// KEYWORD2-NEXT: Keyword/None: discardableResult[#Func Attribute#]; name=discardableResult
// KEYWORD2-NEXT: Keyword/None: differentiable[#Func Attribute#]; name=differentiable
// KEYWORD2-NEXT: Keyword/None: IBSegueAction[#Func Attribute#]; name=IBSegueAction{{$}}
// KEYWORD2-NEXT: Keyword/None: derivative[#Func Attribute#]; name=derivative
// KEYWORD2-NEXT: Keyword/None: transpose[#Func Attribute#]; name=transpose
// KEYWORD2-NEXT: Keyword/None: noDerivative[#Func Attribute#]; name=noDerivative
// KEYWORD2-NOT: Keyword
// KEYWORD2: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// KEYWORD2: End completions
@#^KEYWORD3^# class C {}
// KEYWORD3: Begin completions
// KEYWORD3-NEXT: Keyword/None: available[#Class Attribute#]; name=available{{$}}
// KEYWORD3-NEXT: Keyword/None: objc[#Class Attribute#]; name=objc{{$}}
// KEYWORD3-NEXT: Keyword/None: dynamicCallable[#Class Attribute#]; name=dynamicCallable{{$}}
// KEYWORD3-NEXT: Keyword/None: main[#Class Attribute#]; name=main
// KEYWORD3-NEXT: Keyword/None: dynamicMemberLookup[#Class Attribute#]; name=dynamicMemberLookup{{$}}
// KEYWORD3-NEXT: Keyword/None: IBDesignable[#Class Attribute#]; name=IBDesignable{{$}}
// KEYWORD3-NEXT: Keyword/None: UIApplicationMain[#Class Attribute#]; name=UIApplicationMain{{$}}
// KEYWORD3-NEXT: Keyword/None: requires_stored_property_inits[#Class Attribute#]; name=requires_stored_property_inits{{$}}
// KEYWORD3-NEXT: Keyword/None: objcMembers[#Class Attribute#]; name=objcMembers{{$}}
// KEYWORD3-NEXT: Keyword/None: NSApplicationMain[#Class Attribute#]; name=NSApplicationMain{{$}}
// KEYWORD3-NEXT: Keyword/None: usableFromInline[#Class Attribute#]; name=usableFromInline
// KEYWORD3-NEXT: Keyword/None: propertyWrapper[#Class Attribute#]; name=propertyWrapper
// KEYWORD3-NEXT: Keyword/None: _functionBuilder[#Class Attribute#]; name=_functionBuilder
// KEYWORD3-NEXT: End completions
@#^KEYWORD3_2^#IB class C2 {}
// Same as KEYWORD3.
@#^KEYWORD4^# enum E {}
// KEYWORD4: Begin completions
// KEYWORD4-NEXT: Keyword/None: available[#Enum Attribute#]; name=available{{$}}
// KEYWORD4-NEXT: Keyword/None: objc[#Enum Attribute#]; name=objc{{$}}
// KEYWORD4-NEXT: Keyword/None: dynamicCallable[#Enum Attribute#]; name=dynamicCallable
// KEYWORD4-NEXT: Keyword/None: main[#Enum Attribute#]; name=main
// KEYWORD4-NEXT: Keyword/None: dynamicMemberLookup[#Enum Attribute#]; name=dynamicMemberLookup
// KEYWORD4-NEXT: Keyword/None: usableFromInline[#Enum Attribute#]; name=usableFromInline
// KEYWORD4-NEXT: Keyword/None: frozen[#Enum Attribute#]; name=frozen
// KEYWORD4-NEXT: Keyword/None: propertyWrapper[#Enum Attribute#]; name=propertyWrapper
// KEYWORD4-NEXT: Keyword/None: _functionBuilder[#Enum Attribute#]; name=_functionBuilder
// KEYWORD4-NEXT: End completions
@#^KEYWORD5^# struct S{}
// KEYWORD5: Begin completions
// KEYWORD5-NEXT: Keyword/None: available[#Struct Attribute#]; name=available{{$}}
// KEYWORD5-NEXT: Keyword/None: dynamicCallable[#Struct Attribute#]; name=dynamicCallable
// KEYWORD5-NEXT: Keyword/None: main[#Struct Attribute#]; name=main
// KEYWORD5-NEXT: Keyword/None: dynamicMemberLookup[#Struct Attribute#]; name=dynamicMemberLookup
// KEYWORD5-NEXT: Keyword/None: usableFromInline[#Struct Attribute#]; name=usableFromInline
// KEYWORD5-NEXT: Keyword/None: frozen[#Struct Attribute#]; name=frozen
// KEYWORD5-NEXT: Keyword/None: propertyWrapper[#Struct Attribute#]; name=propertyWrapper
// KEYWORD5-NEXT: Keyword/None: _functionBuilder[#Struct Attribute#]; name=_functionBuilder
// KEYWORD5-NEXT: End completions
@#^ON_GLOBALVAR^# var globalVar
// ON_GLOBALVAR: Begin completions
// ON_GLOBALVAR-DAG: Keyword/None: available[#Var Attribute#]; name=available
// ON_GLOBALVAR-DAG: Keyword/None: objc[#Var Attribute#]; name=objc
// ON_GLOBALVAR-DAG: Keyword/None: NSCopying[#Var Attribute#]; name=NSCopying
// ON_GLOBALVAR-DAG: Keyword/None: IBInspectable[#Var Attribute#]; name=IBInspectable
// ON_GLOBALVAR-DAG: Keyword/None: IBOutlet[#Var Attribute#]; name=IBOutlet
// ON_GLOBALVAR-DAG: Keyword/None: NSManaged[#Var Attribute#]; name=NSManaged
// ON_GLOBALVAR-DAG: Keyword/None: inline[#Var Attribute#]; name=inline
// ON_GLOBALVAR-DAG: Keyword/None: nonobjc[#Var Attribute#]; name=nonobjc
// ON_GLOBALVAR-DAG: Keyword/None: inlinable[#Var Attribute#]; name=inlinable
// ON_GLOBALVAR-DAG: Keyword/None: usableFromInline[#Var Attribute#]; name=usableFromInline
// ON_GLOBALVAR-DAG: Keyword/None: GKInspectable[#Var Attribute#]; name=GKInspectable
// ON_GLOBALVAR-DAG: Keyword/None: differentiable[#Var Attribute#]; name=differentiable
// ON_GLOBALVAR-DAG: Keyword/None: noDerivative[#Var Attribute#]; name=noDerivative
// ON_GLOBALVAR-NOT: Keyword
// ON_GLOBALVAR: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_GLOBALVAR: End completions
struct _S {
@#^ON_INIT^# init()
// ON_INIT: Begin completions
// ON_INIT-DAG: Keyword/None: available[#Constructor Attribute#]; name=available
// ON_INIT-DAG: Keyword/None: objc[#Constructor Attribute#]; name=objc
// ON_INIT-DAG: Keyword/None: inline[#Constructor Attribute#]; name=inline
// ON_INIT-DAG: Keyword/None: nonobjc[#Constructor Attribute#]; name=nonobjc
// ON_INIT-DAG: Keyword/None: inlinable[#Constructor Attribute#]; name=inlinable
// ON_INIT-DAG: Keyword/None: usableFromInline[#Constructor Attribute#]; name=usableFromInline
// ON_INIT-DAG: Keyword/None: discardableResult[#Constructor Attribute#]; name=discardableResult
// ON_INIT: End completions
@#^ON_PROPERTY^# var foo
// ON_PROPERTY: Begin completions
// ON_PROPERTY-DAG: Keyword/None: available[#Var Attribute#]; name=available
// ON_PROPERTY-DAG: Keyword/None: objc[#Var Attribute#]; name=objc
// ON_PROPERTY-DAG: Keyword/None: NSCopying[#Var Attribute#]; name=NSCopying
// ON_PROPERTY-DAG: Keyword/None: IBInspectable[#Var Attribute#]; name=IBInspectable
// ON_PROPERTY-DAG: Keyword/None: IBOutlet[#Var Attribute#]; name=IBOutlet
// ON_PROPERTY-DAG: Keyword/None: NSManaged[#Var Attribute#]; name=NSManaged
// ON_PROPERTY-DAG: Keyword/None: inline[#Var Attribute#]; name=inline
// ON_PROPERTY-DAG: Keyword/None: nonobjc[#Var Attribute#]; name=nonobjc
// ON_PROPERTY-DAG: Keyword/None: inlinable[#Var Attribute#]; name=inlinable
// ON_PROPERTY-DAG: Keyword/None: usableFromInline[#Var Attribute#]; name=usableFromInline
// ON_PROPERTY-DAG: Keyword/None: GKInspectable[#Var Attribute#]; name=GKInspectable
// ON_PROPERTY-DAG: Keyword/None: differentiable[#Var Attribute#]; name=differentiable
// ON_PROPERTY-DAG: Keyword/None: noDerivative[#Var Attribute#]; name=noDerivative
// ON_PROPERTY-NOT: Keyword
// ON_PROPERTY: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_PROPERTY-NOT: Decl[PrecedenceGroup]
// ON_PROPERTY: End completions
@#^ON_METHOD^# private
func foo()
// ON_METHOD: Begin completions
// ON_METHOD-DAG: Keyword/None: available[#Func Attribute#]; name=available
// ON_METHOD-DAG: Keyword/None: objc[#Func Attribute#]; name=objc
// ON_METHOD-DAG: Keyword/None: IBAction[#Func Attribute#]; name=IBAction
// ON_METHOD-DAG: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged
// ON_METHOD-DAG: Keyword/None: inline[#Func Attribute#]; name=inline
// ON_METHOD-DAG: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc
// ON_METHOD-DAG: Keyword/None: inlinable[#Func Attribute#]; name=inlinable
// ON_METHOD-DAG: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access
// ON_METHOD-DAG: Keyword/None: usableFromInline[#Func Attribute#]; name=usableFromInline
// ON_METHOD-DAG: Keyword/None: discardableResult[#Func Attribute#]; name=discardableResult
// ON_METHOD-DAG: Keyword/None: IBSegueAction[#Func Attribute#]; name=IBSegueAction
// ON_METHOD-DAG: Keyword/None: differentiable[#Func Attribute#]; name=differentiable
// ON_METHOD-DAG: Keyword/None: derivative[#Func Attribute#]; name=derivative
// ON_METHOD-DAG: Keyword/None: transpose[#Func Attribute#]; name=transpose
// ON_METHOD-DAG: Keyword/None: noDerivative[#Func Attribute#]; name=noDerivative
// ON_METHOD-NOT: Keyword
// ON_METHOD: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_METHOD: End completions
func bar(@#^ON_PARAM_1^#)
// ON_PARAM: Begin completions
// ON_PARAM-NOT: Keyword
// ON_PARAM: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_PARAM-NOT: Keyword
// ON_PARAM: End completions
func bar(
@#^ON_PARAM_2^#
arg: Int
)
// Same as ON_PARAM.
@#^ON_MEMBER_INDEPENDENT_1^#
func dummy1() {}
// Same as ON_MEMBER_LAST.
@#^ON_MEMBER_INDEPENDENT_2^#
func dummy2() {}
// Same as ON_MEMBER_LAST.
@#^ON_MEMBER_LAST^#
// ON_MEMBER_LAST: Begin completions
// ON_MEMBER_LAST-DAG: Keyword/None: available[#Declaration Attribute#]; name=available
// ON_MEMBER_LAST-DAG: Keyword/None: objc[#Declaration Attribute#]; name=objc
// ON_MEMBER_LAST-DAG: Keyword/None: dynamicCallable[#Declaration Attribute#]; name=dynamicCallable
// ON_MEMBER_LAST-DAG: Keyword/None: main[#Declaration Attribute#]; name=main
// ON_MEMBER_LAST-DAG: Keyword/None: dynamicMemberLookup[#Declaration Attribute#]; name=dynamicMemberLookup
// ON_MEMBER_LAST-DAG: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying
// ON_MEMBER_LAST-DAG: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction
// ON_MEMBER_LAST-DAG: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable
// ON_MEMBER_LAST-DAG: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable
// ON_MEMBER_LAST-DAG: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet
// ON_MEMBER_LAST-DAG: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged
// ON_MEMBER_LAST-DAG: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain
// ON_MEMBER_LAST-DAG: Keyword/None: inline[#Declaration Attribute#]; name=inline
// ON_MEMBER_LAST-DAG: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits
// ON_MEMBER_LAST-DAG: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc
// ON_MEMBER_LAST-DAG: Keyword/None: inlinable[#Declaration Attribute#]; name=inlinable
// ON_MEMBER_LAST-DAG: Keyword/None: objcMembers[#Declaration Attribute#]; name=objcMembers
// ON_MEMBER_LAST-DAG: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain
// ON_MEMBER_LAST-DAG: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access
// ON_MEMBER_LAST-DAG: Keyword/None: usableFromInline[#Declaration Attribute#]; name=usableFromInline
// ON_MEMBER_LAST-DAG: Keyword/None: discardableResult[#Declaration Attribute#]; name=discardableResult
// ON_MEMBER_LAST-DAG: Keyword/None: GKInspectable[#Declaration Attribute#]; name=GKInspectable
// ON_MEMBER_LAST-DAG: Keyword/None: IBSegueAction[#Declaration Attribute#]; name=IBSegueAction
// ON_MEMBER_LAST-DAG: Keyword/None: propertyWrapper[#Declaration Attribute#]; name=propertyWrapper
// ON_MEMBER_LAST-DAG: Keyword/None: _functionBuilder[#Declaration Attribute#]; name=_functionBuilder
// ON_MEMBER_LAST-DAG: Keyword/None: differentiable[#Declaration Attribute#]; name=differentiable
// ON_MEMBER_LAST-DAG: Keyword/None: derivative[#Declaration Attribute#]; name=derivative
// ON_MEMBER_LAST-DAG: Keyword/None: transpose[#Declaration Attribute#]; name=transpose
// ON_MEMBER_LAST-DAG: Keyword/None: noDerivative[#Declaration Attribute#]; name=noDerivative
// ON_MEMBER_LAST-NOT: Keyword
// ON_MEMBER_LAST: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_MEMBER_LAST-NOT: Decl[PrecedenceGroup]
// ON_MEMBER_LAST: End completions
}
@#^KEYWORD_INDEPENDENT_1^#
func dummy1() {}
// Same as KEYWORD_LAST.
@#^KEYWORD_INDEPENDENT_2^#
func dummy2() {}
// Same as KEYWORD_LAST.
@#^KEYWORD_LAST^#
// KEYWORD_LAST: Begin completions
// KEYWORD_LAST-NEXT: Keyword/None: available[#Declaration Attribute#]; name=available{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: objc[#Declaration Attribute#]; name=objc{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: dynamicCallable[#Declaration Attribute#]; name=dynamicCallable
// KEYWORD_LAST-NEXT: Keyword/None: main[#Declaration Attribute#]; name=main
// KEYWORD_LAST-NEXT: Keyword/None: dynamicMemberLookup[#Declaration Attribute#]; name=dynamicMemberLookup
// KEYWORD_LAST-NEXT: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: inline[#Declaration Attribute#]; name=inline{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: inlinable[#Declaration Attribute#]; name=inlinable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: objcMembers[#Declaration Attribute#]; name=objcMembers{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access
// KEYWORD_LAST-NEXT: Keyword/None: usableFromInline[#Declaration Attribute#]; name=usableFromInline{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: discardableResult[#Declaration Attribute#]; name=discardableResult
// KEYWORD_LAST-NEXT: Keyword/None: GKInspectable[#Declaration Attribute#]; name=GKInspectable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: frozen[#Declaration Attribute#]; name=frozen
// KEYWORD_LAST-NEXT: Keyword/None: propertyWrapper[#Declaration Attribute#]; name=propertyWrapper
// KEYWORD_LAST-NEXT: Keyword/None: _functionBuilder[#Declaration Attribute#]; name=_functionBuilder{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: differentiable[#Declaration Attribute#]; name=differentiable
// KEYWORD_LAST-NEXT: Keyword/None: IBSegueAction[#Declaration Attribute#]; name=IBSegueAction{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: derivative[#Declaration Attribute#]; name=derivative
// KEYWORD_LAST-NEXT: Keyword/None: transpose[#Declaration Attribute#]; name=transpose
// KEYWORD_LAST-NEXT: Keyword/None: noDerivative[#Declaration Attribute#]; name=noDerivative
// KEYWORD_LAST-NOT: Keyword
// KEYWORD_LAST: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// KEYWORD_LAST: End completions
| 83.672185 | 167 | 0.61985 |
22200f037a9591a4d20c6be7863c37f66b6dcf74 | 4,453 | //
// ChartDataSetConfigUtils.swift
// reactNativeCharts
//
// Created by xudong wu on 23/02/2017.
// Copyright wuxudong
//
import UIKit
import Charts
import SwiftyJSON
class ChartDataSetConfigUtils: NSObject {
static func commonConfig(_ dataSet: ChartDataSet, config: JSON) {
// Setting main color
if config["color"].int != nil {
dataSet.setColor(RCTConvert.uiColor(config["color"].intValue))
}
if config["colors"].array != nil {
dataSet.colors = BridgeUtils.parseColors(config["colors"].arrayValue)
}
if config["drawValues"].bool != nil {
dataSet.drawValuesEnabled = config["drawValues"].boolValue;
}
if config["highlightEnabled"].bool != nil {
dataSet.highlightEnabled = config["highlightEnabled"].boolValue;
}
if config["valueTextSize"].float != nil {
dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(config["valueTextSize"].floatValue))
}
if config["valueTextColor"].int != nil {
dataSet.valueTextColor = RCTConvert.uiColor(config["valueTextColor"].intValue)
}
if config["visible"].bool != nil {
dataSet.visible = config["visible"].boolValue
}
let valueFormatter = config["valueFormatter"];
if valueFormatter.string != nil {
if "largeValue" == valueFormatter.stringValue {
dataSet.valueFormatter = LargeValueFormatter();
} else if "percent" == valueFormatter.stringValue {
let percentFormatter = NumberFormatter()
percentFormatter.numberStyle = .percent
dataSet.valueFormatter = DefaultValueFormatter(formatter: percentFormatter);
} else if "date" == valueFormatter.stringValue {
let valueFormatterPattern = config["valueFormatterPattern"].stringValue;
dataSet.valueFormatter = ChartDateFormatter(pattern: valueFormatterPattern);
} else {
let customFormatter = NumberFormatter()
customFormatter.positiveFormat = valueFormatter.stringValue
customFormatter.negativeFormat = valueFormatter.stringValue
dataSet.valueFormatter = DefaultValueFormatter(formatter: customFormatter);
}
}
if config["axisDependency"].string != nil {
dataSet.axisDependency = BridgeUtils.parseAxisDependency(config["axisDependency"].stringValue)
}
}
static func commonBarLineScatterCandleBubbleConfig(_ dataSet: BarLineScatterCandleBubbleChartDataSet, config: JSON) {
if config["highlightColor"].int != nil {
dataSet.highlightColor = RCTConvert.uiColor(config["highlightColor"].intValue);
}
}
static func commonLineScatterCandleRadarConfig(_ dataSet: LineScatterCandleRadarChartDataSet, config: JSON) {
if config["drawHighlightIndicators"].bool != nil {
dataSet.setDrawHighlightIndicators(config["drawHighlightIndicators"].boolValue);
}
if config["drawVerticalHighlightIndicator"].bool != nil {
dataSet.drawVerticalHighlightIndicatorEnabled = config["drawVerticalHighlightIndicator"].boolValue;
}
if config["drawHorizontalHighlightIndicator"].bool != nil {
dataSet.drawHorizontalHighlightIndicatorEnabled = config["drawHorizontalHighlightIndicator"].boolValue;
}
if config["highlightLineWidth"].float != nil {
dataSet.highlightLineWidth = CGFloat(config["highlightLineWidth"].floatValue);
}
}
static func commonLineRadarConfig( _ dataSet:LineRadarChartDataSet, config:JSON) {
if config["fillColor"].int != nil {
dataSet.fillColor = RCTConvert.uiColor(config["fillColor"].intValue);
}
if config["fillAlpha"].number != nil {
dataSet.fillAlpha = BridgeUtils.toIOSAlpha(config["fillAlpha"].numberValue);
}
if config["drawFilled"].bool != nil {
dataSet.drawFilledEnabled = config["drawFilled"].boolValue;
}
if config["lineWidth"].float != nil {
dataSet.lineWidth = CGFloat(config["lineWidth"].floatValue);
}
}
}
| 37.420168 | 121 | 0.619582 |
d5b73d8d8dcd0181a9873e5108a3c03cbab56736 | 799 | //
// TMLBaseCard.swift
// Banking App
//
// Created by Jake Bryan Casino on 3/10/20.
// Copyright © 2020 Jake Bryan Casino. All rights reserved.
//
import SwiftUI
func TMLCard<Content>(@ViewBuilder content: @escaping () -> Content) -> some View where Content : View {
var body: some View {
VStack {
content()
}
.background(Color(UIColor.systemBackground))
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
.shadow(color: Color(UIColor(white: 0, alpha: 0.05)), radius: 6, x: 0, y: 1)
}
return body
}
struct TMLBaseCard_Previews: PreviewProvider {
static var previews: some View {
HStack {
TMLCard() {
Text("Hello")
}
}
.frame(width: 375, height: 375)
.background(Color("background"))
.previewLayout(.sizeThatFits)
}
}
| 21.594595 | 104 | 0.660826 |
eb6788e0cb8cafa3f2967e3398f547553ad1af02 | 754 | //
// DefaultMediaDetailUseCase.swift
// WhatToWatch
//
// Created by Denis Novitsky on 22.04.2021.
//
import Foundation
final class DefaultMediaDetailUseCase {
private let mediaRepository: MediaRepository
init(mediaRepository: MediaRepository) {
self.mediaRepository = mediaRepository
}
}
// MARK: - Media Detail Use Case
extension DefaultMediaDetailUseCase: MediaDetailUseCase {
func fetchMediaDetail(type: MediaType,
id: Int,
completion: @escaping CompletionHandler) -> Cancellable? {
return mediaRepository.fetchMedia(type: type,
id: id,
completion: completion)
}
}
| 22.848485 | 84 | 0.600796 |
ff0b50488d69b833e74365a48351e89cc47ab8c9 | 1,923 | //
// SpinnerAnimationController.swift
// PullToRefreshDemo
//
// Created by Mansi Vadodariya on 22/03/21.
//
import UIKit
import SSCustomPullToRefresh
final class SpinnerAnimationController: UIViewController {
// Variables
private var spinnerAnimation: SpinnerAnimationView?
private var cellsCount: Int = 1
// Outlets
@IBOutlet private weak var tableView: UITableView!
// Lofecycle
override func viewDidLoad() {
super.viewDidLoad()
setUpSpinnerAnimation()
}
}
// MARK: - Methods
fileprivate extension SpinnerAnimationController {
func setUpSpinnerAnimation() {
spinnerAnimation = SpinnerAnimationView(
viewData: .init(
resource: .loading(tintColor: .black)),
parentView: tableView,
startRefresh: { [weak self] in
self?.startRefresh()
},
endRefresh: { [weak self] in
self?.endRefresh()
}
)
spinnerAnimation?.setup()
}
func startRefresh() {
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
self.spinnerAnimation?.endRefreshing()
}
}
func endRefresh() {
cellsCount += 1
tableView.reloadData()
}
}
// MARK: - TableView
extension SpinnerAnimationController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellsCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "cellIdentifier"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = .init(style: .default, reuseIdentifier: cellIdentifier)
}
cell?.textLabel?.text = "Row \(indexPath.row + 1)"
return cell ?? .init()
}
}
| 24.341772 | 100 | 0.625065 |
d973e7eb3a2a142834eb349bf0e31c508c4ca449 | 1,284 | //
// ConveribleWithDoubleTests.swift
//
//
// Created by Joseph Heck on 3/31/22.
//
import Foundation
import SwiftVizScale
import XCTest
class ConveribleWithDoubleTests: XCTestCase {
// Int
func testForwardIntConversion() throws {
let value = 5
XCTAssertEqual(5.0, value.toDouble())
}
func testReverseIntConversion() throws {
let value = 5.0
XCTAssertEqual(5, Double.fromDouble(value))
}
// Float
func testForwardFloatConversion() throws {
let value: Float = 5
XCTAssertEqual(5.0, value.toDouble())
}
func testReverseFloatConversion() throws {
let value = 5.0
XCTAssertEqual(5.0, Float.fromDouble(value))
}
// CGFloat
func testForwardCGFloatConversion() throws {
let value: CGFloat = 5
XCTAssertEqual(5.0, value.toDouble())
}
func testReverseCGFloatConversion() throws {
let value = 5.0
XCTAssertEqual(5, CGFloat.fromDouble(value))
}
// Double
func testForwardDoubleConversion() throws {
let value: Double = 5
XCTAssertEqual(5.0, value.toDouble())
}
func testReverseDoubleConversion() throws {
let value = 5.0
XCTAssertEqual(5.0, Double.fromDouble(value))
}
}
| 21.04918 | 53 | 0.630841 |
ac4f7c1fee0f98eac1181a16f89ebb07b3db2155 | 700 | //
// LayoutAnchorPair+LayoutVariable.swift
// Layman
//
// Created by Brian Strobach on 1/23/19.
// Copyright © 2019 Brian Strobach. All rights reserved.
//
// MARK: - Anchor Pair
extension LayoutAnchorPair: LayoutVariable {
public typealias RightHandExpression = LayoutAnchorPairExpression<FA, SA>
//
// public func times(_ multiplier: LayoutConstant) -> RightHandExpression {
// return times(LayoutMultiplier(multiplier))
// }
public func times(_ multiplier: LayoutMultiplier) -> RightHandExpression {
let coefficients = LayoutCoefficientPair(.multiplier(multiplier))
return RightHandExpression(variable: self).with(coefficients: coefficients)
}
}
| 29.166667 | 83 | 0.725714 |
f77bd469f045f8989c78b6faa09e58223afb6076 | 534 | //
// OnboardingTemplate.swift
// Supplements
//
// Created by Tomasz Iwaszek on 4/11/19.
// Copyright © 2019 matchusolutions. All rights reserved.
//
import Foundation
import UIKit
protocol OnboardingViewProtocol: class {
func setTitleImageAndDescOfContentView(index: Int, title: String, desc: String, image: UIImage)
}
protocol OnboardingPresenterProtocol: class {
init(view: OnboardingViewProtocol, delegate: OnboardingViewDelegate)
func closeOnboarding()
func getTitleImageAndDescOfContentView(index: Int)
}
| 25.428571 | 98 | 0.771536 |
148cc354e3d822e7c79893a867297d48cca9a3aa | 1,355 | //
// DUYTableviewCell.swift
// DUYTableviewManager
//
// Created by Cao Khac Lu Dey on 7/1/20.
// Copyright © 2020 Duy Personal. All rights reserved.
//
import UIKit
extension UITableView {
func dequeueReusableCell<T: UITableViewCell>( with cellClass : T.Type) -> T? {
return self.dequeueReusableCell(withIdentifier: String.init(describing: cellClass)) as? T
}
}
public protocol DUYCellViewProtocol {
func setData(viewModel: DUYTableviewCellViewModelProtocol)
}
open class DUYTableviewCell: UITableViewCell, DUYCellViewProtocol {
override open func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override open func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
public init() {
super.init(style: .subtitle, reuseIdentifier: String.init(describing: DUYTableviewCell.self))
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
}
open func setData(viewModel: DUYTableviewCellViewModelProtocol) {
guard let viewModel = viewModel as? DUYTableViewCellViewModel else {return}
self.textLabel?.text = viewModel.mainTitle
self.detailTextLabel?.text = viewModel.subTitle
}
}
| 27.653061 | 101 | 0.692251 |
abcf4840b25d91c19614c544fafacc53ef4fe756 | 344 | // MIT license. Copyright (c) 2019 RadiantKit. All rights reserved.
import UIKit
public protocol RFWillDisplayCellDelegate {
func form_willDisplay(tableView: UITableView, forRowAtIndexPath indexPath: IndexPath)
}
@available(*, unavailable, renamed: "RFWillDisplayCellDelegate")
typealias WillDisplayCellDelegate = RFWillDisplayCellDelegate
| 31.272727 | 86 | 0.828488 |
fc56fd487fce2eb2ec1935ab21ddd4d4edf99270 | 3,776 | //
// UIView+JFRect.swift
// JRBaseKit
//
// Created by 逸风 on 2021/10/10.
//
import UIKit
import Foundation
extension UIView: JFCompatible {}
public extension JF where Base: UIView {
var top: CGFloat {
get { return base.jf_top }
set { base.jf_top = newValue }
}
var left: CGFloat {
get { return base.jf_left }
set { base.jf_left = newValue }
}
var bottom: CGFloat {
get { return base.jf_bottom }
set { base.jf_bottom = newValue }
}
var right: CGFloat {
get { return base.jf_right }
set { base.jf_right = newValue }
}
var centerX: CGFloat {
get { return base.jf_centerX }
set { base.jf_centerX = newValue }
}
var centerY: CGFloat {
get { return base.jf_centerY }
set { base.jf_centerY = newValue }
}
var width: CGFloat {
get { return base.jf_width }
set { base.jf_width = newValue }
}
var height: CGFloat {
get { return base.jf_height }
set { base.jf_height = newValue }
}
var origin: CGPoint {
get { return base.jf_origin }
set { base.jf_origin = newValue }
}
var size: CGSize {
get { return base.jf_size }
set { base.jf_size = newValue }
}
}
//MARK: - For OC
public extension UIView {
@objc var jf_top: CGFloat {
get {
return self.frame.origin.y
}
set {
var frame:CGRect = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
@objc var jf_left: CGFloat {
get {
return self.frame.origin.x
}
set {
var frame:CGRect = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
@objc var jf_bottom: CGFloat {
get {
return self.frame.origin.y + self.frame.size.height
}
set {
var frame:CGRect = self.frame
frame.origin.y = newValue - frame.size.height
self.frame = frame
}
}
@objc var jf_right: CGFloat {
get {
return self.frame.origin.x + self.frame.size.width
}
set {
var frame:CGRect = self.frame
frame.origin.x = newValue - frame.size.width
self.frame = frame
}
}
@objc var jf_centerX: CGFloat {
get {
return self.center.x
}
set {
self.center = .init(x: newValue, y: self.center.y)
}
}
@objc var jf_centerY: CGFloat {
get {
return self.center.y
}
set {
self.center = .init(x: self.center.x, y: newValue)
}
}
@objc var jf_width: CGFloat {
get {
return self.bounds.width
}
set {
var frame:CGRect = self.frame
frame.size.width = newValue
self.frame = frame
}
}
@objc var jf_height: CGFloat {
get {
return self.bounds.height
}
set {
var frame:CGRect = self.frame
frame.size.height = newValue
self.frame = frame
}
}
@objc var jf_origin: CGPoint {
get {
return self.frame.origin
}
set {
var frame:CGRect = self.frame
frame.origin = newValue
self.frame = frame
}
}
@objc var jf_size: CGSize {
get {
return self.frame.size
}
set {
var frame:CGRect = self.frame
frame.size = newValue
self.frame = frame
}
}
}
| 21.953488 | 63 | 0.487553 |
f9b2d66728f682f7503a862e55a51d8b57772d02 | 2,062 | //
// BeerListPresenter.swift
// BeerList
//
// Created by Tulio Parreiras on 26/01/21.
//
import Foundation
public protocol BeerListView {
func display(_ viewModel: BeerListViewModel)
}
public protocol BeerListLoadingView {
func display(_ viewModel: BeerListLoadingViewModel)
}
public protocol BeerListErrorView {
func display(_ viewModel: BeerListErrorViewModel)
}
public final class BeerListPresenter {
private let beerListView: BeerListView
private let loadingView: BeerListLoadingView
private let errorView: BeerListErrorView
public static var title: String {
return NSLocalizedString("BEER_LIST_VIEW_TITLE",
tableName: "BeerList",
bundle: Bundle(for: BeerListPresenter.self),
comment: "Title for the beer list view")
}
private var beerListLoadError: String {
return NSLocalizedString("BEER_LIST_CONNECTION_ERROR",
tableName: "BeerList",
bundle: Bundle(for: BeerListPresenter.self),
comment: "Error message presented when the beer list load from server fail")
}
public init(beerListView: BeerListView, loadingView: BeerListLoadingView,errorView: BeerListErrorView) {
self.beerListView = beerListView
self.loadingView = loadingView
self.errorView = errorView
}
public func didStartLoadingBeerList() {
errorView.display(.noError)
loadingView.display(BeerListLoadingViewModel(isLoading: true))
}
public func didFinishLoadingBeerList(with beerList: [Beer]) {
beerListView.display(BeerListViewModel(beerList: beerList))
loadingView.display(BeerListLoadingViewModel(isLoading: false))
}
public func didFinishLoadingBeerList(with error: Error) {
errorView.display(.error(message: beerListLoadError))
loadingView.display(BeerListLoadingViewModel(isLoading: false))
}
}
| 33.258065 | 109 | 0.663434 |
e9c85e84866b04265a69549a17ce3e23df84a0f3 | 1,720 | // Copyright © 2019 Poikile Creations. All rights reserved.
import XCTest
class CALayer_GeometryTests: XCTestCase {
func testCenterAtPointWithNonnegativePointOk() {
let layer = CALayer()
layer.frame = CGRect(x: 32.0, y: 100.0, width: 420.0, height: 99.0)
let center = CGPoint(x: 321.0, y: 411.0)
let newFrame = layer.center(at: center)
XCTAssertEqual(newFrame.origin.x, 111.0)
XCTAssertEqual(newFrame.origin.y, 361.5)
}
func testCenterAtZeroOk() {
let layer = CALayer()
layer.frame = CGRect(x: 32.0, y: 100.0, width: 420.0, height: 99.0)
let center = CGPoint(x: 0.0, y: 0.0)
let newFrame = layer.center(at: center)
XCTAssertEqual(newFrame.origin.x, -210.0)
XCTAssertEqual(newFrame.origin.y, -49.5)
}
func testCenterInSuperLayerOk() {
let superlayer = CALayer()
superlayer.frame = CGRect(x: 32.0, y: 100.0, width: 420.0, height: 99.0)
let sublayer = CALayer()
sublayer.frame = CGRect(x: 23.0, y: 66.0, width: 23.0, height: 200.0)
superlayer.addSublayer(sublayer)
let newSubframe = sublayer.centerInSuperlayer()
XCTAssertEqual(newSubframe.origin.x, 198.5)
XCTAssertEqual(newSubframe.origin.y, -50.5)
}
func testCenterInSuperlayerWithNoSuperlayerReturnsOriginalFrame() {
let layer = CALayer()
layer.frame = CGRect(x: 32.0, y: 100.0, width: 420.0, height: 99.0)
layer.centerInSuperlayer()
XCTAssertEqual(layer.frame.origin.x, 32.0)
XCTAssertEqual(layer.frame.origin.y, 100.0)
XCTAssertEqual(layer.frame.width, 420.0)
XCTAssertEqual(layer.frame.height, 99.0)
}
}
| 32.45283 | 80 | 0.634302 |
140ee512ab1ab916a5f24283b6c8368da87e4f70 | 1,247 | //
// stripeIntegrationTests.swift
// stripeIntegrationTests
//
// Created by cedcoss on 01/11/21.
//
import XCTest
@testable import stripeIntegration
class stripeIntegrationTests: XCTestCase {
//start of Added code
var stripeIntegration: stripeIntegration!
override func setUp() {
stripeIntegration = stripeIntegration()
}
func teststripe() {
XCTAssertEqual(stripeIntegration.callInitial())
}
//end of added code
//--Default methods
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
//--
}
| 24.94 | 111 | 0.65437 |
5dd7dc87d36da7bab1370b4d7e6c3e41aea67ce7 | 1,598 | //
// Logging.swift
// YAPI
//
// Created by Daniel Seitz on 11/15/17.
// Copyright © 2017 Daniel Seitz. All rights reserved.
//
import Foundation
private var systemLoggers: [Logger] = [ConsoleLogger()]
public func log(_ severity: LoggingSeverity, for domain: LoggingDomain = .general, message: String) {
guard domain.shouldLog else { return }
for logger in systemLoggers {
logger.log(severity, for: domain, message)
}
}
public func add(logger: Logger) {
systemLoggers.append(logger)
}
public protocol Logger {
func log( _ severity: LoggingSeverity, for domain: LoggingDomain, _ message: String)
}
public enum LoggingSeverity {
case success
case info
case warning
case error
}
public enum LoggingDomain {
case general
case network
case imageLoading
case caching
private var envKey: String {
switch self {
case .general:
return "LOG_GENERAL"
case .network:
return "LOG_NETWORK"
case .imageLoading:
return "LOG_IMAGES"
case .caching:
return "LOG_CACHE"
}
}
fileprivate var shouldLog: Bool {
return ProcessInfo.processInfo.environment[self.envKey] != nil
}
}
extension LoggingSeverity: CustomStringConvertible {
public var description: String {
switch self {
case .success: return "SUCCESS"
case .info: return "INFO"
case .warning: return "WARNING"
case .error: return "ERROR"
}
}
}
struct ConsoleLogger: Logger {
func log(_ severity: LoggingSeverity, for domain: LoggingDomain, _ message: String) {
print("\n[\(severity.description)]: \(message)\n")
}
}
| 21.026316 | 101 | 0.688986 |
09b4c6ce32d3606f8182831468f6660f67d3d716 | 1,309 | //
// PostTableViewCell.swift
// insta
//
// Created by Biswash Adhikari on 2/26/18.
// Copyright © 2018 Biswash Adhikari. All rights reserved.
//
import UIKit
import Parse
class PostTableViewCell: UITableViewCell {
@IBOutlet weak var imageOutlet: UIImageView!
@IBOutlet weak var captionOutlet: UILabel!
var post: PFObject? {
didSet {
//print("this is image \((post?["image"])!)")
getImage()
// imageOutlet.image = self.imageOutlet.image
captionOutlet.text = post?["caption"] as? String
}
}
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
}
func getImage() {
if let imageFile = post?.value(forKey: "image") {
// let imageFile = imageFile as! PFFile
(imageFile as! PFFile).getDataInBackground(block: { (imageData: Data?, error: Error?) in
let image = UIImage(data: imageData!)
if image != nil {
self.imageOutlet.image = image
}
})
}
}
}
| 27.270833 | 100 | 0.569901 |
db3f3ce6b2db5d7dea8d29b4e2eeab2b74b6959c | 2,375 | //
// TemporaryScheduleOverridePreset.swift
// Loop
//
// Created by Michael Pangburn on 1/2/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import Foundation
public struct TemporaryScheduleOverridePreset: Hashable {
public let id: UUID
public var symbol: String
public var name: String
public var settings: TemporaryScheduleOverrideSettings
public var duration: TemporaryScheduleOverride.Duration
public init(id: UUID = UUID(), symbol: String, name: String, settings: TemporaryScheduleOverrideSettings, duration: TemporaryScheduleOverride.Duration) {
self.id = id
self.symbol = symbol
self.name = name
self.settings = settings
self.duration = duration
}
public func createOverride(enactTrigger: TemporaryScheduleOverride.EnactTrigger, beginningAt date: Date = Date()) -> TemporaryScheduleOverride {
return TemporaryScheduleOverride(
context: .preset(self),
settings: settings,
startDate: date,
duration: duration,
enactTrigger: enactTrigger,
syncIdentifier: UUID()
)
}
}
extension TemporaryScheduleOverridePreset: RawRepresentable {
public typealias RawValue = [String: Any]
public init?(rawValue: RawValue) {
guard
let idString = rawValue["id"] as? String,
let id = UUID(uuidString: idString),
let symbol = rawValue["symbol"] as? String,
let name = rawValue["name"] as? String,
let settingsRawValue = rawValue["settings"] as? TemporaryScheduleOverrideSettings.RawValue,
let settings = TemporaryScheduleOverrideSettings(rawValue: settingsRawValue),
let durationRawValue = rawValue["duration"] as? TemporaryScheduleOverride.Duration.RawValue,
let duration = TemporaryScheduleOverride.Duration(rawValue: durationRawValue)
else {
return nil
}
self.init(id: id, symbol: symbol, name: name, settings: settings, duration: duration)
}
public var rawValue: RawValue {
return [
"id": id.uuidString,
"symbol": symbol,
"name": name,
"settings": settings.rawValue,
"duration": duration.rawValue
]
}
}
extension TemporaryScheduleOverridePreset: Codable {}
| 33.450704 | 157 | 0.654316 |
297e230beaaca90097510671caefa11c545944c3 | 3,385 | //
// ProductListStateViewModelImpl.swift
// Shlist
//
// Created by Pavel Lyskov on 09.04.2020.
// Copyright © 2020 Pavel Lyskov. All rights reserved.
//
import Action
import RxCocoa
import RxDataSources
import RxSwift
final class ProductListStateViewModelImpl: ProductListStateViewModel, ProductListStateViewModelInput, ProductListStateViewModelOutput {
// MARK: Inputs
var products: Observable<[Product]>
var searchActive: BehaviorRelay<Bool> = .init(value: false)
// MARK: Otputs
let repository: ProductRepository
var searchActiveDriver: Driver<Bool> {
return searchActive.asDriver()
}
var newProducts: Observable<[Product]> {
return repository.newItems
}
var completeProducts: Observable<[Product]> {
return repository.completeItems
}
var productSections: Observable<[SectionOfProducts]> {
products.flatMap { items -> Observable<[SectionOfProducts]> in
var result: [SectionOfProducts] = []
let newItems = items.filter { !$0.checked }
if !newItems.isEmpty {
let headProduct = Product(id: "Новые Заголовок", name: "Новые Заголовок", category: Category(name: "Служебные", colorHex: 0x000000, iconName: ""))
let sectionNewHeader = SectionOfProducts(header: "Новые Заголовок", items: [headProduct], type: .newHeader)
result.append(sectionNewHeader)
let sectionNew = SectionOfProducts(header: "Новые", items: newItems, type: .newContent)
result.append(sectionNew)
let footProduct = Product(id: "Новые Сумма", name: "Новые Сумма", category: Category(name: "Служебные", colorHex: 0x000000, iconName: ""))
let sectionNewSum = SectionOfProducts(header: "Новые Сумма", items: [footProduct], type: .newFooter)
result.append(sectionNewSum)
}
let completeItems = items.filter { $0.checked }
if !completeItems.isEmpty {
let headProductComp = Product(id: "Comp Заголовок", name: "Comp Заголовок", category: Category(name: "Служебные", colorHex: 0x000000, iconName: ""))
let sectionCompHeader = SectionOfProducts(header: "Comp Заголовок", items: [headProductComp], type: .completeHeader)
result.append(sectionCompHeader)
let sectionComplete = SectionOfProducts(header: "В корзине", items: completeItems, type: .completeContent)
result.append(sectionComplete)
let footProductComp = Product(id: "Comp Сумма", name: "Comp Сумма", category: Category(name: "Служебные", colorHex: 0x000000, iconName: ""))
let sectionCompSum = SectionOfProducts(header: "Comp Сумма", items: [footProductComp], type: .completeFooter)
result.append(sectionCompSum)
}
return Observable<[SectionOfProducts]>.just(result)
}
}
var bag = DisposeBag()
init(repository: ProductRepository) {
self.repository = repository
self.products = repository.items.asObservable()
}
}
| 37.611111 | 164 | 0.604431 |
acaa1b0ec335398ece40f8e443ab661fcb541d5f | 545 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{ b{let
<{
}
}
struct B{
class b=f{
"
var b
let a = b{
}o}
{{
enum S< {{
}struct S<T where f: d{B{
{
}
} {}
var _ =a
class c {
enum b {
let a= c
a
| 18.166667 | 79 | 0.682569 |
20869856d0cf46f58cfc7b4f8e2cd111507f0334 | 1,326 | import MongoSwiftMobile
/**
* A credential which can be used to log in as a Stitch user
* using the Google authentication provider.
*/
public struct GoogleCredential: StitchCredential {
// MARK: Initializer
/**
* Initializes this credential with the name of the provider, and a Google OAuth2 authentication code.
*/
public init(withProviderName providerName: String = providerType.name,
withAuthCode authCode: String) {
self.providerName = providerName
self.authCode = authCode
}
// MARK: Properties
/**
* The name of the provider for this credential.
*/
public var providerName: String
/**
* The type of the provider for this credential.
*/
public static let providerType: StitchProviderType = .google
/**
* The contents of this credential as they will be passed to the Stitch server.
*/
public var material: Document {
return ["authCode": authCode]
}
/**
* The behavior of this credential when logging in.
*/
public var providerCapabilities: ProviderCapabilities =
ProviderCapabilities.init(reusesExistingSession: false)
/**
* The Google OAuth2 authentication code contained within this credential.
*/
private let authCode: String
}
| 27.061224 | 106 | 0.662896 |
1e654883a63a594c61b500f9a47c8ceaf0664342 | 596 | // Problem code
func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
let sorted = nums.sorted()
var closeSum = Int.max
var closeDiff = Int.max
for current in 0..<sorted.count - 2 {
var left = current + 1
var right = sorted.count - 1
while left < right {
let sum = sorted[current] + sorted[left] + sorted[right]
let diff = abs(sum - target)
if sum == target {
return sum
} else if sum > target {
right -= 1
} else if sum < target {
left += 1
}
if diff < closeDiff {
closeSum = sum
closeDiff = diff
}
}
}
return closeSum
}
| 19.225806 | 59 | 0.590604 |
e533fea6ecf6d559e2a75b271873216661d24fd7 | 2,739 | //
// SceneDelegate.swift
// Demo
//
// Copyright © 2020 Pokanop Apps. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView(store: AnimationsStore())
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.796875 | 147 | 0.706827 |
0ac419234123189b927e5fa058165aeab59bf4e3 | 2,623 | //
// HostingCell.swift
//
//
// Created by Q Trang on 7/20/20.
//
import SwiftUI
public class HostingCell<Content: View>: UITableViewCell {
private var hostingController: UIHostingController<Content>?
public var removePadding = false
public var content: Content? {
get {
return hostingController?.rootView
}
set {
guard let content = newValue else { return }
guard hostingController == nil else {
hostingController?.rootView = content
hostingController?.view.setNeedsLayout()
hostingController?.view.layoutIfNeeded()
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
hostingController?.view.setNeedsUpdateConstraints()
hostingController?.view.updateConstraintsIfNeeded()
setNeedsDisplay()
hostingController?.view.setNeedsDisplay()
return
}
hostingController = UIHostingController(rootView: content)
let view = hostingController!.view!
view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(hostingController!.view)
if removePadding {
NSLayoutConstraint.activate([view.leftAnchor.constraint(equalTo: contentView.leftAnchor),
view.rightAnchor.constraint(equalTo: contentView.rightAnchor),
view.topAnchor.constraint(equalTo: contentView.topAnchor),
view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)])
} else {
NSLayoutConstraint.activate([view.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
view.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
view.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor),
view.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor)])
}
}
}
public override func didMoveToSuperview() {
super.didMoveToSuperview()
layoutIfNeeded()
}
public override func layoutSubviews() {
super.layoutSubviews()
layoutIfNeeded()
}
}
| 35.931507 | 132 | 0.563858 |
ff541f7473878dcc2402e02e4ea6c397010c698e | 2,095 | //
// TextAttributes.swift
// TextAttributes
//
// Created by Boris Bielik on 19/04/2018.
// Copyright © 2018 Boris Bielik. All rights reserved.
//
import Foundation
#if canImport(UIKit)
import UIKit
public typealias TextAttributes = [NSAttributedString.Key: Any]
public extension Collection where Iterator.Element == (key: NSAttributedString.Key, value: Any) {
var textAttributes: TextAttributes? {
return (self as? TextAttributes)
}
/// Text Attributes
///
/// - Parameters:
/// - font: font
/// - color: color
/// - backgroundColor: background color
/// - kerning: kerning of the text
/// - Returns: text attributes
static func attributes(font: UIFont,
color: UIColor,
backgroundColor: UIColor? = nil,
kerning: Float? = nil) -> TextAttributes {
var attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: color
]
if backgroundColor != nil {
attributes[.backgroundColor] = backgroundColor
}
if let kerning = kerning {
attributes[.kern] = NSNumber(value: kerning)
}
return attributes
}
/// Font
var font: UIFont? {
return textAttributes?[.font] as? UIFont
}
/// Text Color
var color: UIColor? {
return textAttributes?[.foregroundColor] as? UIColor
}
/// Background color
var backgroundColor: UIColor? {
return textAttributes?[.backgroundColor] as? UIColor
}
/// Kerning
var kerning: Float? {
return (textAttributes?[.kern] as? NSNumber)?.floatValue
}
/// Set text color
mutating func setColor(_ color: UIColor?) {
var attributes = textAttributes
attributes?[.foregroundColor] = color
}
/// Set background color
mutating func setBackgroundColor(_ color: UIColor?) {
var attributes = textAttributes
attributes?[.backgroundColor] = color
}
}
#endif
| 24.647059 | 97 | 0.588067 |
e93488fdff889fc71e3412546cad4ababa987479 | 1,246 | //
// ViewController.swift
// Sample
//
// Created by Magic on 9/5/2016.
// Copyright © 2016 Magic. All rights reserved.
//
import UIKit
import SwipeMenu
class ViewController: UIViewController {
var menu: SwipeMenu = SwipeMenu()
let names = ["Apple", "Microsoft", "Facebook", "Twitter", "Github", "Tencent"]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .random
menu.dataSource = self
menu.delegate = self
view.addSubview(menu)
}
}
extension ViewController: SwipeMenuDataSource, SwipeMenuDelegate {
func numberOfItems(in menu: SwipeMenu) -> Int {
return names.count
}
func menu(_ menu: SwipeMenu, titleForRow row: Int) -> String {
return names[row]
}
func menu(_ menu: SwipeMenu, indicatorIconForRow row: Int) -> UIImage {
return UIImage(named: names[row])!
}
func menu(_ menu: SwipeMenu, didSelectRow row: Int) {
print("Select Row: ", row)
view.backgroundColor = .random
}
}
extension UIColor {
class var random: UIColor {
return UIColor(hue: CGFloat(arc4random_uniform(255)) / 255, saturation: 1, brightness: 1, alpha: 1)
}
}
| 23.961538 | 107 | 0.623596 |
b96b5315ce7845c3f1d44a459413cf2822ea9abe | 27,880 | //
// BBMetalCamera.swift
// BBMetalImage
//
// Created by Kaibo Lu on 4/8/19.
// Copyright © 2019 Kaibo Lu. All rights reserved.
//
import AVFoundation
/// Camera photo delegate defines handling taking photo result behaviors
public protocol BBMetalCameraPhotoDelegate: AnyObject {
/// Called when camera did take a photo and get Metal texture
///
/// - Parameters:
/// - camera: camera to use
/// - texture: Metal texture of the original photo which is not filtered
func camera(_ camera: BBMetalCamera, didOutput texture: MTLTexture)
/// Called when camera fail taking a photo
///
/// - Parameters:
/// - camera: camera to use
/// - error: error for taking the photo
func camera(_ camera: BBMetalCamera, didFail error: Error)
}
public protocol BBMetalCameraMetadataObjectDelegate: AnyObject {
/// Called when camera did get metadata objects
///
/// - Parameters:
/// - camera: camera to use
/// - metadataObjects: metadata objects
func camera(_ camera: BBMetalCamera, didOutput metadataObjects: [AVMetadataObject])
}
/// Camera capturing image and providing Metal texture
public class BBMetalCamera: NSObject {
/// Image consumers
public var consumers: [BBMetalImageConsumer] {
lock.wait()
let c = _consumers
lock.signal()
return c
}
private var _consumers: [BBMetalImageConsumer]
/// A block to call before processing each video sample buffer
public var preprocessVideo: ((CMSampleBuffer) -> Void)? {
get {
lock.wait()
let p = _preprocessVideo
lock.signal()
return p
}
set {
lock.wait()
_preprocessVideo = newValue
lock.signal()
}
}
private var _preprocessVideo: ((CMSampleBuffer) -> Void)?
/// A block to call before transmiting texture to image consumers
public var willTransmitTexture: ((MTLTexture, CMTime) -> Void)? {
get {
lock.wait()
let w = _willTransmitTexture
lock.signal()
return w
}
set {
lock.wait()
_willTransmitTexture = newValue
lock.signal()
}
}
private var _willTransmitTexture: ((MTLTexture, CMTime) -> Void)?
/// Camera position
public var position: AVCaptureDevice.Position { return camera.position }
/// Whether to run benchmark or not.
/// Running benchmark records frame duration.
/// False by default.
public var benchmark: Bool {
get {
lock.wait()
let b = _benchmark
lock.signal()
return b
}
set {
lock.wait()
_benchmark = newValue
lock.signal()
}
}
private var _benchmark: Bool
/// Average frame duration, or 0 if not valid value.
/// To get valid value, set `benchmark` to true.
public var averageFrameDuration: Double {
lock.wait()
let d = capturedFrameCount > ignoreInitialFrameCount ? totalCaptureFrameTime / Double(capturedFrameCount - ignoreInitialFrameCount) : 0
lock.signal()
return d
}
private var capturedFrameCount: Int
private var totalCaptureFrameTime: Double
private let ignoreInitialFrameCount: Int
private let lock: DispatchSemaphore
private var session: AVCaptureSession!
private var camera: AVCaptureDevice!
private var videoInput: AVCaptureDeviceInput!
private var videoOutput: AVCaptureVideoDataOutput!
private var videoOutputQueue: DispatchQueue!
private let multitpleSessions: Bool
private var audioSession: AVCaptureSession!
private var audioInput: AVCaptureDeviceInput!
private var audioOutput: AVCaptureAudioDataOutput!
private var audioOutputQueue: DispatchQueue!
/// Audio consumer processing audio sample buffer.
/// Set this property to nil (default value) if not recording audio.
/// Set this property to a given audio consumer if recording audio.
public var audioConsumer: BBMetalAudioConsumer? {
get {
lock.wait()
let a = _audioConsumer
lock.signal()
return a
}
set {
lock.wait()
_audioConsumer = newValue
if newValue != nil {
if !addAudioInputAndOutput() { _audioConsumer = nil }
} else {
removeAudioInputAndOutput()
}
lock.signal()
}
}
private var _audioConsumer: BBMetalAudioConsumer?
private var photoOutput: AVCapturePhotoOutput!
/// Whether can take photo or not.
/// Set this property to true before calling `takePhoto()` method.
public var canTakePhoto: Bool {
get {
lock.wait()
let c = _canTakePhoto
lock.signal()
return c
}
set {
lock.wait()
_canTakePhoto = newValue
if newValue {
if !addPhotoOutput() { _canTakePhoto = false }
} else {
removePhotoOutput()
}
lock.signal()
}
}
private var _canTakePhoto: Bool
/// Camera photo delegate handling taking photo result.
/// To take photo, this property should not be nil.
public weak var photoDelegate: BBMetalCameraPhotoDelegate? {
get {
lock.wait()
let p = _photoDelegate
lock.signal()
return p
}
set {
lock.wait()
_photoDelegate = newValue
lock.signal()
}
}
private weak var _photoDelegate: BBMetalCameraPhotoDelegate?
private var _needPhoto: Bool
private var _capturePhotoCompletion: BBMetalFilterCompletion?
private var metadataOutput: AVCaptureMetadataOutput!
private var metadataOutputQueue: DispatchQueue!
public weak var metadataObjectDelegate: BBMetalCameraMetadataObjectDelegate? {
get {
lock.wait()
let m = _metadataObjectDelegate
lock.signal()
return m
}
set {
lock.wait()
_metadataObjectDelegate = newValue
lock.signal()
}
}
private weak var _metadataObjectDelegate: BBMetalCameraMetadataObjectDelegate?
/// When this property is false, received video/audio sample buffer will not be processed
public var isPaused: Bool {
get {
lock.wait()
let p = _isPaused
lock.signal()
return p
}
set {
lock.wait()
_isPaused = newValue
lock.signal()
}
}
private var _isPaused: Bool
private var textureCache: CVMetalTextureCache!
/// Creates a camera
/// - Parameters:
/// - sessionPreset: a constant value indicating the quality level or bit rate of the output
/// - position: camera position
/// - multitpleSessions: whether to use independent video session and audio session (false by default). Switching camera position while recording leads to the video and audio out of sync.
/// Set true if we allow the user to switch camera position while recording.
public init?(sessionPreset: AVCaptureSession.Preset = .high, position: AVCaptureDevice.Position = .back, multitpleSessions: Bool = false) {
_consumers = []
_canTakePhoto = false
_needPhoto = false
_isPaused = false
_benchmark = false
capturedFrameCount = 0
totalCaptureFrameTime = 0
ignoreInitialFrameCount = 5
self.multitpleSessions = multitpleSessions
lock = DispatchSemaphore(value: 1)
super.init()
guard let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position),
let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice) else { return nil }
session = AVCaptureSession()
session.beginConfiguration()
session.sessionPreset = sessionPreset
if !session.canAddInput(videoDeviceInput) {
session.commitConfiguration()
return nil
}
session.addInput(videoDeviceInput)
camera = videoDevice
videoInput = videoDeviceInput
let videoDataOutput = AVCaptureVideoDataOutput()
videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String : kCVPixelFormatType_32BGRA]
videoOutputQueue = DispatchQueue(label: "com.Kaibo.BBMetalImage.Camera.videoOutput")
videoDataOutput.setSampleBufferDelegate(self, queue: videoOutputQueue)
if !session.canAddOutput(videoDataOutput) {
session.commitConfiguration()
return nil
}
session.addOutput(videoDataOutput)
videoOutput = videoDataOutput
guard let connection = videoDataOutput.connections.first,
connection.isVideoOrientationSupported else {
session.commitConfiguration()
return nil
}
connection.videoOrientation = .portrait
session.commitConfiguration()
#if !targetEnvironment(simulator)
if CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, BBMetalDevice.sharedDevice, nil, &textureCache) != kCVReturnSuccess ||
textureCache == nil {
return nil
}
#endif
}
@discardableResult
private func addAudioInputAndOutput() -> Bool {
if audioOutput != nil { return true }
var session: AVCaptureSession = self.session
if multitpleSessions {
session = AVCaptureSession()
audioSession = session
}
session.beginConfiguration()
defer { session.commitConfiguration() }
guard let audioDevice = AVCaptureDevice.default(.builtInMicrophone, for: .audio, position: .unspecified),
let input = try? AVCaptureDeviceInput(device: audioDevice),
session.canAddInput(input) else {
print("Can not add audio input")
return false
}
session.addInput(input)
audioInput = input
let output = AVCaptureAudioDataOutput()
let outputQueue = DispatchQueue(label: "com.Kaibo.BBMetalImage.Camera.audioOutput")
output.setSampleBufferDelegate(self, queue: outputQueue)
guard session.canAddOutput(output) else {
_removeAudioInputAndOutput()
print("Can not add audio output")
return false
}
session.addOutput(output)
audioOutput = output
audioOutputQueue = outputQueue
return true
}
private func removeAudioInputAndOutput() {
session.beginConfiguration()
_removeAudioInputAndOutput()
session.commitConfiguration()
}
private func _removeAudioInputAndOutput() {
let session: AVCaptureSession = multitpleSessions ? audioSession : self.session
if let input = audioInput {
session.removeInput(input)
audioInput = nil
}
if let output = audioOutput {
session.removeOutput(output)
audioOutput = nil
}
if audioOutputQueue != nil {
audioOutputQueue = nil
}
if audioSession != nil {
audioSession = nil
}
}
@discardableResult
private func addPhotoOutput() -> Bool {
if photoOutput != nil { return true }
session.beginConfiguration()
defer { session.commitConfiguration() }
let output = AVCapturePhotoOutput()
if !session.canAddOutput(output) {
print("Can not add photo output")
return false
}
session.addOutput(output)
photoOutput = output
return true
}
private func removePhotoOutput() {
session.beginConfiguration()
if let output = photoOutput { session.removeOutput(output) }
session.commitConfiguration()
}
@discardableResult
public func addMetadataOutput(with types: [AVMetadataObject.ObjectType]) -> Bool {
var result = false
lock.wait()
if metadataOutput != nil {
lock.signal()
return result
}
session.beginConfiguration()
let output = AVCaptureMetadataOutput()
let outputQueue = DispatchQueue(label: "com.Kaibo.BBMetalImage.Camera.metadataOutput")
output.setMetadataObjectsDelegate(self, queue: outputQueue)
if session.canAddOutput(output) {
session.addOutput(output)
let validTypes = types.filter { output.availableMetadataObjectTypes.contains($0) }
output.metadataObjectTypes = validTypes
metadataOutput = output
metadataOutputQueue = outputQueue
result = true
}
session.commitConfiguration()
lock.signal()
return result
}
public func removeMetadataOutput() {
lock.wait()
if metadataOutput == nil {
lock.signal()
return
}
session.beginConfiguration()
session.removeOutput(metadataOutput)
metadataOutput = nil
metadataOutputQueue = nil
session.commitConfiguration()
lock.signal()
}
/// Captures frame texture as a photo.
/// Get original frame texture in the completion closure.
/// To get filtered texture, use `addCompletedHandler(_:)` method of `BBMetalBaseFilter`, check whether the filtered texture is camera photo.
/// This method is much faster than `takePhoto()` method.
/// - Parameter completion: a closure to call after capturing. If success, get original frame texture. If failure, get error.
public func capturePhoto(completion: BBMetalFilterCompletion? = nil) {
lock.wait()
_needPhoto = true
_capturePhotoCompletion = completion
lock.signal()
}
/// Takes a photo.
/// Before calling this method, set `canTakePhoto` property to true and `photoDelegate` property to nonnull.
/// Get original frame texture in `camera(_:didOutput:)` method of `BBMetalCameraPhotoDelegate`.
/// To get filtered texture, use `capturePhoto(completion:)` method, or create new filter to process the original frame texture.
public func takePhoto() {
lock.wait()
if let output = photoOutput,
_photoDelegate != nil {
let currentSettings = AVCapturePhotoSettings(format: [kCVPixelBufferPixelFormatTypeKey as String : kCVPixelFormatType_32BGRA])
output.capturePhoto(with: currentSettings, delegate: self)
}
lock.signal()
}
/// Switches camera position (back to front, or front to back)
///
/// - Returns: true if succeed, or false if fail
@discardableResult
public func switchCameraPosition() -> Bool {
lock.wait()
session.beginConfiguration()
defer {
session.commitConfiguration()
lock.signal()
}
var position: AVCaptureDevice.Position = .back
if camera.position == .back { position = .front }
guard let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position),
let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice) else { return false }
session.removeInput(videoInput)
guard session.canAddInput(videoDeviceInput) else {
session.addInput(videoInput)
return false
}
session.addInput(videoDeviceInput)
camera = videoDevice
videoInput = videoDeviceInput
guard let connection = videoOutput.connections.first,
connection.isVideoOrientationSupported else { return false }
connection.videoOrientation = .portrait
return true
}
/// Sets camera frame rate
///
/// - Parameter frameRate: camera frame rate
/// - Returns: true if succeed, or false if fail
@discardableResult
public func setFrameRate(_ frameRate: Float64) -> Bool {
var success = false
lock.wait()
do {
try camera.lockForConfiguration()
var targetFormat: AVCaptureDevice.Format?
let dimensions = CMVideoFormatDescriptionGetDimensions(camera.activeFormat.formatDescription)
for format in camera.formats {
let newDimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription)
if dimensions.width == newDimensions.width,
dimensions.height == newDimensions.height {
for range in format.videoSupportedFrameRateRanges {
if range.maxFrameRate >= frameRate,
range.minFrameRate <= frameRate {
targetFormat = format
break
}
}
if targetFormat != nil { break }
}
}
if let format = targetFormat {
camera.activeFormat = format
camera.activeVideoMaxFrameDuration = CMTime(value: 1, timescale: CMTimeScale(frameRate))
camera.activeVideoMinFrameDuration = CMTime(value: 1, timescale: CMTimeScale(frameRate))
success = true
} else {
print("Can not find valid format for camera frame rate \(frameRate)")
}
camera.unlockForConfiguration()
} catch {
print("Error for camera lockForConfiguration: \(error)")
}
lock.signal()
return success
}
/// Configures camera.
/// Configure camera in the block, without calling `lockForConfiguration` and `unlockForConfiguration` methods.
///
/// - Parameter block: closure configuring camera
public func configureCamera(_ block: (AVCaptureDevice) -> Void) {
lock.wait()
do {
try camera.lockForConfiguration()
block(camera)
camera.unlockForConfiguration()
} catch {
print("Error for camera lockForConfiguration: \(error)")
}
lock.signal()
}
/// Starts capturing
public func start() {
lock.wait()
session.startRunning()
if multitpleSessions, let session = audioSession { session.startRunning() }
lock.signal()
}
/// Stops capturing
public func stop() {
lock.wait()
session.stopRunning()
if multitpleSessions, let session = audioSession { session.stopRunning() }
lock.signal()
}
/// Resets benchmark record data
public func resetBenchmark() {
lock.wait()
capturedFrameCount = 0
totalCaptureFrameTime = 0
lock.signal()
}
}
extension BBMetalCamera: BBMetalImageSource {
@discardableResult
public func add<T: BBMetalImageConsumer>(consumer: T) -> T {
lock.wait()
_consumers.append(consumer)
lock.signal()
consumer.add(source: self)
return consumer
}
public func add(consumer: BBMetalImageConsumer, at index: Int) {
lock.wait()
_consumers.insert(consumer, at: index)
lock.signal()
consumer.add(source: self)
}
public func remove(consumer: BBMetalImageConsumer) {
lock.wait()
if let index = _consumers.firstIndex(where: { $0 === consumer }) {
_consumers.remove(at: index)
lock.signal()
consumer.remove(source: self)
} else {
lock.signal()
}
}
public func removeAllConsumers() {
lock.wait()
let consumers = _consumers
_consumers.removeAll()
lock.signal()
for consumer in consumers {
consumer.remove(source: self)
}
}
}
extension BBMetalCamera: AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate {
public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// Audio
if output is AVCaptureAudioDataOutput {
lock.wait()
let paused = _isPaused
let currentAudioConsumer = _audioConsumer
lock.signal()
if !paused,
let consumer = currentAudioConsumer {
consumer.newAudioSampleBufferAvailable(sampleBuffer)
}
return
}
// Video
lock.wait()
let paused = _isPaused
let consumers = _consumers
let willTransmit = _willTransmitTexture
let preprocessVideo = _preprocessVideo
let cameraPosition = camera.position
let isCameraPhoto = _needPhoto
if _needPhoto { _needPhoto = false }
let capturePhotoCompletion = _capturePhotoCompletion
if _capturePhotoCompletion != nil { _capturePhotoCompletion = nil }
let startTime = _benchmark ? CACurrentMediaTime() : 0
lock.signal()
guard !paused, !consumers.isEmpty else { return }
preprocessVideo?(sampleBuffer)
guard let texture = texture(with: sampleBuffer) else {
if let completion = capturePhotoCompletion {
let error = NSError(domain: "BBMetalCameraErrorDomain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Can not get Metal texture"])
let info = BBMetalFilterCompletionInfo(result: .failure(error),
sampleTime: CMSampleBufferGetPresentationTimeStamp(sampleBuffer),
cameraPosition: cameraPosition,
isCameraPhoto: isCameraPhoto)
completion(info)
}
return
}
let sampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
if let completion = capturePhotoCompletion {
var result: Result<MTLTexture, Error>
let filter = BBMetalPassThroughFilter(createTexture: true)
if let metalTexture = filter.filteredTexture(with: texture.metalTexture) {
result = .success(metalTexture)
} else {
let error = NSError(domain: "BBMetalCameraErrorDomain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Can not get Metal texture"])
result = .failure(error)
}
let info = BBMetalFilterCompletionInfo(result: result,
sampleTime: sampleTime,
cameraPosition: cameraPosition,
isCameraPhoto: isCameraPhoto)
completion(info)
}
willTransmit?(texture.metalTexture, sampleTime)
let output = BBMetalDefaultTexture(metalTexture: texture.metalTexture,
sampleTime: sampleTime,
cameraPosition: cameraPosition,
isCameraPhoto: isCameraPhoto,
cvMetalTexture: texture.cvMetalTexture)
for consumer in consumers { consumer.newTextureAvailable(output, from: self) }
// Benchmark
if startTime != 0 {
lock.wait()
capturedFrameCount += 1
if capturedFrameCount > ignoreInitialFrameCount {
totalCaptureFrameTime += CACurrentMediaTime() - startTime
}
lock.signal()
}
}
public func captureOutput(_ output: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
print("Camera drops \(output is AVCaptureAudioDataOutput ? "audio" : "video") sample buffer")
}
private func texture(with sampleBuffer: CMSampleBuffer) -> BBMetalVideoTextureItem? {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
#if !targetEnvironment(simulator)
var cvMetalTextureOut: CVMetalTexture?
let result = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
imageBuffer,
nil,
.bgra8Unorm, // camera ouput BGRA
width,
height,
0,
&cvMetalTextureOut)
if result == kCVReturnSuccess,
let cvMetalTexture = cvMetalTextureOut,
let texture = CVMetalTextureGetTexture(cvMetalTexture) {
return BBMetalVideoTextureItem(metalTexture: texture, cvMetalTexture: cvMetalTexture)
}
#endif
return nil
}
}
extension BBMetalCamera: AVCapturePhotoCaptureDelegate {
public func photoOutput(_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?,
previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?,
resolvedSettings: AVCaptureResolvedPhotoSettings,
bracketSettings: AVCaptureBracketedStillImageSettings?,
error: Error?) {
guard let delegate = photoDelegate else { return }
if let error = error {
delegate.camera(self, didFail: error)
} else if let sampleBuffer = photoSampleBuffer,
let texture = texture(with: sampleBuffer),
let rotatedTexture = rotatedTexture(with: texture.metalTexture, angle: 90) {
// Setting `videoOrientation` of `AVCaptureConnection` dose not work. So rotate texture here.
delegate.camera(self, didOutput: rotatedTexture)
} else {
delegate.camera(self, didFail: NSError(domain: "BBMetalCamera.Photo", code: 0, userInfo: [NSLocalizedDescriptionKey : "Can not get Metal texture"]))
}
}
private func rotatedTexture(with inTexture: MTLTexture, angle: Float) -> MTLTexture? {
let source = BBMetalStaticImageSource(texture: inTexture)
let filter = BBMetalRotateFilter(angle: angle, fitSize: true)
source.add(consumer: filter).runSynchronously = true
source.transmitTexture()
return filter.outputTexture
}
}
extension BBMetalCamera: AVCaptureMetadataOutputObjectsDelegate {
public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
metadataObjectDelegate?.camera(self, didOutput: metadataObjects)
}
}
| 36.396867 | 193 | 0.592575 |
61b28578439bfa73458584de871a0b1e1286c580 | 329 | //
// MockURLSessionDataTask.swift
// SGUVIndexTests
//
// Created by Henry Javier Serrano Echeverria on 2/1/21.
//
import Foundation
final class MockURLSessionDataTask: URLSessionDataTask {
override init() { }
var resumeWasCalledCount = 0
override func resume() {
resumeWasCalledCount += 1
}
}
| 18.277778 | 57 | 0.683891 |
337c91c980b698c73e50daa6e9115469171968f3 | 9,291 | //
// ArtAddress.swift
//
//
// Created by Jorge Loc Rubio on 3/18/20.
//
import Foundation
/**
A Controller or monitorind device on the network can reprogram numerous controls of a node remotely.
This, for example, would allow the lighting console to re-route DMX512 data at remote locations. This is achieved by sending an ArtAddress packet to the Node's IP Address. ( The IP address is returned in the ArPoll packet).
The node replies with an ArtPollReply packet.
Fields `5` to `13` contain the data that will be programmed into the node.
*/
public struct ArtAddress: ArtNetPacket, Equatable, Hashable, Codable {
/// ArtNet packet code.
public static var opCode: OpCode { return .address }
public static let formatting = ArtNetFormatting(
string: [
CodingKeys.shortName: .fixedLength(18),
CodingKeys.longName: .fixedLength(64)
]
)
// MARK: - Properties
/// Art-Net protocol revision.
public let protocolVersion: ProtocolVersion
/// Bits 14-8 of the 15 bit Port-Address are encoded into the bottom 7 bits of this field.
/// This is used in combination with SubSwitch and SwIn[] or SwOut[] to produce the full universe address.
/// This value is ignored unless bit 7 is high. i.e to program a value `0x07`, send the value as `0x87`.
/// Send `0x00` to reset this value to the physical switch settig.
/// Use value `0x7f` for no change
public var netSwitch: ArtNet.PortAddress.Net
/// The BindIndex definesthe bound node which originated this packed.
/// In combination with Port and Source IP address, it uniquely identifies the sender.
/// This must match the BindIndex field in ArtPollReply.
/// This number represents the order of bound devices.
/// A lower number means closer to root device. A value of 1 means root device.
public var bindingIndex: UInt8
/// The array represents a null terminated short name for the Node.
///
/// The Controller uses the ArtAddress packet to program this string.
/// Max length is 17 characters plus the null.
/// The Node will ignore this value if the string is null.
/// This is a fixed length field, although the string it contains can be shorter than the field.
public var shortName: String
/// The array represents a null terminated long name for the Node.
///
/// The Controller uses the ArtAddress packet to program this string.
/// Max length is 63 characters plus the null.
/// The Node will ignore this value if the strung is null.
/// This is a fixed length field, although the string it contains can be shorter than the field.
public var longName: String
/// Bits 3-0 of the 15 bit Port-Address for a given input port are encoded into the bottom 4 bits of this field.
/// This is used in combination with NetSwitch and SubSwitch to produce the full universe address.
/// This value is ignored unless bit 7 is high. i.e to program a value `0x07`, send the value as `0x87`.
/// Send `0x00` to reset this value to the physical switch settig.
/// Use value `0x7f` for no change
public var inputAddresses: ChannelArray<PortAddress>
/// Bits 3-0 of the 15 bit Port-Address for a given output port are encoded into the bottom 4 bits of this field.
/// This is used in combination with NetSwitch and SubSwitch to produce the full universe address.
/// This value is ignored unless bit 7 is high. i.e to program a value `0x07`, send the value as `0x87`.
/// Send `0x00` to reset this value to the physical switch settig.
/// Use value `0x7f` for no change
public var outputAddresses: ChannelArray<PortAddress>
/// Bits 7-4 of the 15 bit Port-Address are encoded into the bottom 4 bits of this field.
/// This is used in combination with NetSwitch and SwIn[] or SwOut[] to produce the full universe address.
/// This value is ignored unless bit 7 is high. i.e to program a value `0x07`, send the value as `0x87`.
/// Send `0x00` to reset this value to the physical switch settig.
/// Use value `0x7f` for no change
public var subSwitch: ArtNet.PortAddress.SubNet
/// Reserved,
public var video: UInt8
/// Node configuration command
public var command: Command
// MARK: - Initialization
init(netSwitch: ArtNet.PortAddress.Net = 0,
bindingIndex: UInt8 = 0,
shortName: String,
longName: String,
inputAddresses: ChannelArray<PortAddress> = [],
outputAddresses: ChannelArray<PortAddress> = [],
subSwitch: ArtNet.PortAddress.SubNet = 0,
video: UInt8 = 0,
command: Command) {
self.protocolVersion = .current
self.netSwitch = netSwitch
self.bindingIndex = bindingIndex
self.shortName = shortName
self.longName = longName
self.inputAddresses = inputAddresses
self.outputAddresses = outputAddresses
self.subSwitch = subSwitch
self.video = video
self.command = command
}
}
// MARK: - Supporting Types
// MARK: - Command
public extension ArtAddress {
/// Command
enum Command: UInt8, Codable {
/// No action
case none = 0x00
/// If Node is currently in merge mode, cancel merge mode upon receipt of next ArtDmx packet.
/// See discussion of merge mode operation.
case cancelMerge = 0x01
/// The front panel indicators of the Node operate normally.
case ledNormal = 0x02
/// The front panel indicators of the Node are disabled and switched off.
case ledMute = 0x03
/// Rapid flashing of the Node's front panel indicators.
/// It is intended as an outlet identifier for large installations.
case ledLocate = 0x04
/// Resets the Node's Sip, Text, Test and data error flags.
/// If an outout shot is beign flagged, forces the test to re-run.
case resetRxFlags = 0x05
/// Node configuration commands:
///
/// Note that Ltp / Htp settings should be retained by the node during power cycling.
/// Set DMX Port 0 to Merge in LTP mode.
case mergeLtp0 = 0x10
/// Set DMX Port 1 to Merge in LTP mode.
case mergeLtp1 = 0x11
/// Set DMX Port 2 to Merge in LTP mode.
case mergeLtp2 = 0x12
/// Set DMX Port 3 to Merge in LTP mode.
case mergeLtp3 = 0x13
/// Set DMX Port 0 to Merge in HTP (default) mode.
case mergeHtp0 = 0x50
/// Set DMX Port 1 to Merge in HTP (default) mode.
case mergeHtp1 = 0x51
/// Set DMX Port 2 to Merge in HTP (default) mode.
case mergeHtp2 = 0x52
/// Set DMX Port 3 to Merge in HTP (default) mode.
case mergeHtp3 = 0x53
/// Set DMX Port 0 to outout both DMX512 and RDM packets from the Art-net protocol (default).
case artNetSelected0 = 0x60
/// Set DMX Port 1 to outout both DMX512 and RDM packets from the Art-net protocol (default).
case artNetSelected1 = 0x61
/// Set DMX Port 2 to outout both DMX512 and RDM packets from the Art-net protocol (default).
case artNetSelected2 = 0x62
/// Set DMX Port 3 to outout both DMX512 and RDM packets from the Art-net protocol (default).
case artNetSelected3 = 0x63
/// Set DMX Port 0 to output DMX512 data from the sACN protocol and RDM data from the Art-Net protocol.
case acnSelected0 = 0x70
/// Set DMX Port 1 to output DMX512 data from the sACN protocol and RDM data from the Art-Net protocol.
case acnSelected1 = 0x71
/// Set DMX Port 2 to output DMX512 data from the sACN protocol and RDM data from the Art-Net protocol.
case acnSelected2 = 0x72
/// Set DMX Port 3 to output DMX512 data from the sACN protocol and RDM data from the Art-Net protocol.
case acnSelected3 = 0x73
/// Clear DMX Output buffer for Port 0
case clearOutput0 = 0x90
/// Clear DMX Output buffer for Port 1
case clearOutput1 = 0x91
/// Clear DMX Output buffer for Port 2
case clearOutput2 = 0x92
/// Clear DMX Output buffer for Port 3
case clearOutput3 = 0x93
}
}
// MARK: - PortAddress
public extension ArtAddress {
struct PortAddress: RawRepresentable, Codable, Equatable, Hashable {
public let rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}
}
// MARK: CustomStringConvertible
extension ArtAddress.PortAddress: CustomStringConvertible {
public var description: String {
return "0x" + rawValue.toHexadecimal()
}
}
// MARK: ExpressibleByIntegerLiteral
extension ArtAddress.PortAddress: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt8) {
self.init(rawValue: value)
}
}
| 37.015936 | 227 | 0.640082 |
ed6a0ff2c1c817deb14562c7a825def3e48e2e11 | 1,821 | //
// CKMTwitterContact+CoreDataProperties.swift
// DropBit
//
// Created by BJ Miller on 5/17/19.
// Copyright © 2019 Coin Ninja, LLC. All rights reserved.
//
//
import Foundation
import CoreData
extension CKMTwitterContact {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CKMTwitterContact> {
return NSFetchRequest<CKMTwitterContact>(entityName: "CKMTwitterContact")
}
@NSManaged public var identityHash: String
@NSManaged public var displayName: String
@NSManaged public var displayScreenName: String
@NSManaged public var profileImageData: Data?
@NSManaged public var verificationStatus: UserIdentityVerificationStatus
@NSManaged public var verifiedTwitterUser: Bool
@NSManaged public var transactions: Set<CKMTransaction>
@NSManaged public var invitations: Set<CKMInvitation>
@NSManaged public var walletEntries: Set<CKMWalletEntry>
}
// MARK: Generated accessors for transactions
extension CKMTwitterContact {
@objc(addTransactionsObject:)
@NSManaged public func addToTransactions(_ value: CKMTransaction)
@objc(removeTransactionsObject:)
@NSManaged public func removeFromTransactions(_ value: CKMTransaction)
@objc(addTransactions:)
@NSManaged public func addToTransactions(_ values: NSSet)
@objc(removeTransactions:)
@NSManaged public func removeFromTransactions(_ values: NSSet)
}
// MARK: Generated accessors for invitations
extension CKMTwitterContact {
@objc(addInvitationsObject:)
@NSManaged public func addToInvitations(_ value: CKMInvitation)
@objc(removeInvitationsObject:)
@NSManaged public func removeFromInvitations(_ value: CKMInvitation)
@objc(addInvitations:)
@NSManaged public func addToInvitations(_ values: NSSet)
@objc(removeInvitations:)
@NSManaged public func removeFromInvitations(_ values: NSSet)
}
| 28.453125 | 82 | 0.787479 |
294ee37b4b71cf264432f8a8c4613e4e7b2f33e7 | 568 | import Foundation
extension Version: Comparable {
public static func < (lhs: Version, rhs: Version) -> Bool {
guard lhs.major >= rhs.major else { return true }
guard lhs.minor >= rhs.minor else { return true }
guard lhs.patch >= rhs.patch else { return true }
return prereleaseCompare(lhs.prerelease, rhs.prerelease)
}
}
func prereleaseCompare(_ lhs: [String], _ rhs: [String]) -> Bool {
guard lhs.count > rhs.count else { return true }
guard lhs.description >= rhs.description else { return true }
return false
}
| 33.411765 | 66 | 0.658451 |
724d79b97d4cbe903033344dbd219c4b9bca0599 | 339 | //
// {module}DefaultView.swift
// {project}
//
// Created by {author} on {date}.
//
import Foundation
import UIKit
class {module}DefaultView: UIViewController {
var presenter: {module}Presenter?
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension {module}DefaultView: {module}View {
}
| 14.125 | 45 | 0.640118 |
d68c2477ed443edcb34f0b834f9651612337a200 | 761 | //
// RepoCollectionCell.swift
// CleanArchitecture
//
// Created by Tuan Truong on 7/9/18.
// Copyright © 2018 Framgia. All rights reserved.
//
import UIKit
final class RepoCollectionCell: UICollectionViewCell, NibReusable {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var avatarURLStringImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
func bindViewModel(_ viewModel: RepoViewModel?) {
if let viewModel = viewModel {
nameLabel.text = viewModel.name
avatarURLStringImageView.sd_setImage(with: viewModel.url, completed: nil)
} else {
nameLabel.text = ""
avatarURLStringImageView.image = nil
}
}
}
| 25.366667 | 85 | 0.65046 |
11406c847aa9910fa4d4adaba18d79c9db6ba2b7 | 1,177 | //
// AppleEventUtils.swift
// NetNewsWireTests
//
// Created by Olof Hellman on 1/7/18.
// Copyright © 2018 Olof Hellman. All rights reserved.
//
import Foundation
/*
@function FourCharCode()
@brief FourCharCode values like OSType, DescType or AEKeyword are really just
4 byte values commonly represented as values like 'odoc' where each byte is
represented as its ASCII character. This function turns a swift string into
its FourCharCode equivalent, as swift doesn't recognize FourCharCode types
natively just yet. With this extension, one can use
"odoc".FourCharCode()
where one would really want to use 'odoc'
*/
extension String {
func FourCharCode() -> FourCharCode {
var sum: UInt32 = 0
guard ( self.count == 4) else {
print ("error: FourCharCode() expected a 4 character string")
return 0
}
for scalar in self.unicodeScalars {
sum = (sum * 256) + scalar.value
}
return (sum)
}
}
extension Int {
func FourCharCode() -> FourCharCode {
return (UInt32(self))
}
}
| 29.425 | 89 | 0.615123 |
33b60d5ee9dd3572543ab05046d4f666e5b6c60c | 1,010 | //
// SearchTextfieldImageView.swift
// Brandingdong
//
// Created by 이진욱 on 2020/08/23.
// Copyright © 2020 jwlee. All rights reserved.
//
import UIKit
class SearchTextfieldImageView: UIView {
// MARK: - Property
private let textfieldImageView = UIImageView()
// MARK: - Init View
override init(frame: CGRect) {
super.init(frame: frame)
setUI()
setConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Setup Layout
private func setUI() {
textfieldImageView.image = UIImage(systemName: "magnifyingglass")?
.withTintColor(.lightGray, renderingMode: .alwaysOriginal)
self.addSubview(textfieldImageView)
}
private func setConstraints() {
let padding: CGFloat = 10
textfieldImageView.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.leading.equalToSuperview().offset(padding)
$0.trailing.equalToSuperview().offset(-padding)
}
}
}
| 21.956522 | 70 | 0.671287 |
ed6e00fc5f1614e82387629a875ec775a00855ea | 2,644 | //
// API.swift
// GaongilroMobile
//
// Created by Minki on 2018. 1. 16..
// Copyright © 2018년 devming. All rights reserved.
//
import Foundation
protocol API {
func getSubwayDirection(stationName: String)
func getToiletDirection()
}
//struct APIService: API {
// func getSubwayDirection(stationName: String) {
// <#code#>
// }
//
// func getToiletDirection() {
// <#code#>
// }
//
//}
enum APIRouter {
case getSubwayDirection(stationName: String)
case getToiletDirection()
}
//extension APIRouter: URLRequestConvertible {
// static let baseURLString: String = "http://ec2-52-79-233-2.ap-northeast-2.compute.amazonaws.com:8080/OhJooYeoMVC"
// static let manager: Alamofire.SessionManager = {
// let configuration = URLSessionConfiguration.default
// configuration.timeoutIntervalForRequest = 30 // seconds
// configuration.timeoutIntervalForResource = 30
// configuration.httpCookieStorage = HTTPCookieStorage.shared
// configuration.urlCache = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
// let manager = Alamofire.SessionManager(configuration: configuration)
// return manager
// }()
//
// var method: HTTPMethod {
// switch self {
// case .getWorshipIdList:
// return .get
// case .getRecentDatas:
// return .post
// case .getPharseMessages:
// return .post
// }
// }
//
// var path: String {
// switch self {
// case .getWorshipIdList():
// return "/worship-list"
// case let .getRecentDatas(worshipId, version, _):
// return "/worship-id/\(worshipId)/check/version/\(version)"
// case .getPharseMessages(_, _):
// return "/phrase"
// }
// }
//
// func asURLRequest() throws -> URLRequest {
// let url = try APIRouter.baseURLString.asURL()
//
// var urlRequest = URLRequest(url: url.appendingPathComponent(path))
// urlRequest.httpMethod = method.rawValue
// urlRequest.addValue("Content-Type", forHTTPHeaderField: "application/json;charset=UTF-8")
//
// switch self {
// case .getWorshipIdList():
// urlRequest = try URLEncoding.default.encode(urlRequest, with: nil)
// case let .getRecentDatas(_, _, parameters):
// urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
// case let .getPharseMessages(_, parameters):
// urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
// }
//
// return urlRequest
// }
//}
| 30.744186 | 119 | 0.621407 |
03a03a999a5a59f83bac0036019672271b4451d2 | 546 | //
// Array+Extensions.swift
// Utilities
//
// Created by Caio Mello on 6/2/19.
// Copyright © 2019 Caio Mello. All rights reserved.
//
import Foundation
extension Array {
public func split(itemsPerSegment: Int) -> [[Element]] {
let sequence = stride(from: startIndex, to: endIndex, by: itemsPerSegment)
return sequence.map({
let rangeEndIndex = $0.advanced(by: itemsPerSegment) > endIndex ? endIndex : $0.advanced(by: itemsPerSegment)
return Array(self[$0..<rangeEndIndex])
})
}
}
| 26 | 121 | 0.641026 |
03ef9690552f1a5416694722650e36bd35240e89 | 211 | #if !os(macOS)
import UIKit
public protocol UITableViewable: UIScrollViewable {
var _tableView: UITableView { get }
}
extension UITableViewable {
public var _scrollView: UIView { _tableView }
}
#endif
| 17.583333 | 51 | 0.744076 |
bb0c80ffddfcceb3d01739ab0bfb452c3c3d85da | 2,058 | //
// Group+Assert.swift
//
// Created by Hans Seiffert on 31.01.21.
//
// ---
// MIT License
//
// Copyright © 2021 Hans Seiffert
//
// 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
//
import Foundation
import XCTest
import QAMenu
extension ItemGroup {
internal static func _assertInitProperties(
_ _sut: ItemGroup,
title: String? = nil,
items: [MockItem] = [],
footerText: String? = nil,
file: StaticString = #file,
line: UInt = #line
) {
XCTAssertEqual(_sut.title?.unboxed, title, file: file, line: line)
XCTAssertEqual(_sut.items.unboxed.count, items.count, file: file, line: line)
var itemIndex = 0
items.forEach { item in
XCTAssertEqual(
_sut.items.unboxed[itemIndex] as? MockItem,
item,
file: file,
line: line
)
itemIndex += 1
}
XCTAssertEqual(_sut.footerText?.unboxed, footerText, file: file, line: line)
}
}
| 35.482759 | 85 | 0.665695 |
f5aa5aa2887272721aa74d0a08fdaf5210a7d67c | 1,023 | //
// DeletableList.swift
// DPCExplorer
//
// Created by Nicholas Robison on 1/10/20.
// Copyright © 2020 Nicholas Robison. All rights reserved.
//
import SwiftUI
struct DeletableList<Elements, ID, Content: View>: View where Elements: RandomAccessCollection, ID: Hashable {
var elements: Elements
let id: KeyPath<Elements.Element, ID>
let factory: (_ element: Elements.Element) -> Content
let deleteHandler: (_ offsets: IndexSet) -> Void
var body: some View {
List {
ForEach(elements, id: id) { element in
self.factory(element)
}
.onDelete(perform: self.deleteHandler)
}
}
}
struct DeletableList_Previews: PreviewProvider {
static var previews: some View {
DeletableList(
elements: ["Hello", "World"],
id: \.self,
factory: {element in
Text(element)
},
deleteHandler: {_ in
// Nothing yet
})
}
}
| 24.357143 | 111 | 0.572825 |
87e93f0a4eaadaad04352d2d5046b0bdd1684c95 | 8,196 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
struct _StringBufferIVars {
internal init(_elementWidth: Int) {
_sanityCheck(_elementWidth == 1 || _elementWidth == 2)
usedEnd = nil
capacityAndElementShift = _elementWidth - 1
}
internal init(
_usedEnd: UnsafeMutablePointer<_RawByte>,
byteCapacity: Int,
elementWidth: Int
) {
_sanityCheck(elementWidth == 1 || elementWidth == 2)
_sanityCheck((byteCapacity & 0x1) == 0)
self.usedEnd = _usedEnd
self.capacityAndElementShift = byteCapacity + (elementWidth - 1)
}
// This stored property should be stored at offset zero. We perform atomic
// operations on it using _HeapBuffer's pointer.
var usedEnd: UnsafeMutablePointer<_RawByte>
var capacityAndElementShift: Int
var byteCapacity: Int {
return capacityAndElementShift & ~0x1
}
var elementShift: Int {
return capacityAndElementShift & 0x1
}
}
// FIXME: Wanted this to be a subclass of
// _HeapBuffer<_StringBufferIVars,UTF16.CodeUnit>, but
// <rdar://problem/15520519> (Can't call static method of derived
// class of generic class with dependent argument type) prevents it.
public struct _StringBuffer {
// Make this a buffer of UTF-16 code units so that it's properly
// aligned for them if that's what we store.
typealias _Storage = _HeapBuffer<_StringBufferIVars, UTF16.CodeUnit>
typealias HeapBufferStorage
= _HeapBufferStorage<_StringBufferIVars, UTF16.CodeUnit>
init(_ storage: _Storage) {
_storage = storage
}
public init(capacity: Int, initialSize: Int, elementWidth: Int) {
_sanityCheck(elementWidth == 1 || elementWidth == 2)
_sanityCheck(initialSize <= capacity)
// We don't check for elementWidth overflow and underflow because
// elementWidth is known to be 1 or 2.
let elementShift = elementWidth &- 1
// We need at least 1 extra byte if we're storing 8-bit elements,
// because indexing will always grab 2 consecutive bytes at a
// time.
let capacityBump = 1 &- elementShift
// Used to round capacity up to nearest multiple of 16 bits, the
// element size of our storage.
let divRound = 1 &- elementShift
_storage = _Storage(
HeapBufferStorage.self,
_StringBufferIVars(_elementWidth: elementWidth),
(capacity + capacityBump + divRound) >> divRound
)
self.usedEnd = start + (initialSize << elementShift)
_storage.value.capacityAndElementShift
= ((_storage._capacity() - capacityBump) << 1) + elementShift
}
@warn_unused_result
static func fromCodeUnits<
Input : Collection, // Sequence?
Encoding : UnicodeCodec
where Input.Iterator.Element == Encoding.CodeUnit
>(
input: Input, encoding: Encoding.Type, repairIllFormedSequences: Bool,
minimumCapacity: Int = 0
) -> (_StringBuffer?, hadError: Bool) {
// Determine how many UTF-16 code units we'll need
let inputStream = input.makeIterator()
guard let (utf16Count, isAscii) = UTF16.transcodedLength(
of: inputStream,
decodedAs: encoding,
repairingIllFormedSequences: repairIllFormedSequences) else {
return (nil, true)
}
// Allocate storage
let result = _StringBuffer(
capacity: max(utf16Count, minimumCapacity),
initialSize: utf16Count,
elementWidth: isAscii ? 1 : 2)
if isAscii {
var p = UnsafeMutablePointer<UTF8.CodeUnit>(result.start)
let sink: (UTF32.CodeUnit) -> Void = {
p.pointee = UTF8.CodeUnit($0)
p += 1
}
let hadError = transcode(
input.makeIterator(),
from: encoding, to: UTF32.self,
stoppingOnError: true,
sendingOutputTo: sink)
_sanityCheck(!hadError, "string cannot be ASCII if there were decoding errors")
return (result, hadError)
}
else {
var p = result._storage.baseAddress
let sink: (UTF16.CodeUnit) -> Void = {
p.pointee = $0
p += 1
}
let hadError = transcode(
input.makeIterator(),
from: encoding, to: UTF16.self,
stoppingOnError: !repairIllFormedSequences,
sendingOutputTo: sink)
return (result, hadError)
}
}
/// A pointer to the start of this buffer's data area.
public // @testable
var start: UnsafeMutablePointer<_RawByte> {
return UnsafeMutablePointer(_storage.baseAddress)
}
/// A past-the-end pointer for this buffer's stored data.
var usedEnd: UnsafeMutablePointer<_RawByte> {
get {
return _storage.value.usedEnd
}
set(newValue) {
_storage.value.usedEnd = newValue
}
}
var usedCount: Int {
return (usedEnd - start) >> elementShift
}
/// A past-the-end pointer for this buffer's available storage.
var capacityEnd: UnsafeMutablePointer<_RawByte> {
return start + _storage.value.byteCapacity
}
/// The number of elements that can be stored in this buffer.
public var capacity: Int {
return _storage.value.byteCapacity >> elementShift
}
/// 1 if the buffer stores UTF-16; 0 otherwise.
var elementShift: Int {
return _storage.value.elementShift
}
/// The number of bytes per element.
var elementWidth: Int {
return elementShift + 1
}
// Return `true` iff we have the given capacity for the indicated
// substring. This is what we need to do so that users can call
// reserveCapacity on String and subsequently use that capacity, in
// two separate phases. Operations with one-phase growth should use
// "grow()," below.
@warn_unused_result
func hasCapacity(
cap: Int, forSubRange r: Range<UnsafePointer<_RawByte>>
) -> Bool {
// The substring to be grown could be pointing in the middle of this
// _StringBuffer.
let offset = (r.startIndex - UnsafePointer(start)) >> elementShift
return cap + offset <= capacity
}
/// Attempt to claim unused capacity in the buffer.
///
/// Operation succeeds if there is sufficient capacity, and either:
/// - the buffer is uniquely-referenced, or
/// - `oldUsedEnd` points to the end of the currently used capacity.
///
/// - parameter bounds: Range of the substring that the caller tries
/// to extend.
/// - parameter newUsedCount: The desired size of the substring.
mutating func grow(
oldBounds bounds: Range<UnsafePointer<_RawByte>>, newUsedCount: Int
) -> Bool {
var newUsedCount = newUsedCount
// The substring to be grown could be pointing in the middle of this
// _StringBuffer. Adjust the size so that it covers the imaginary
// substring from the start of the buffer to `oldUsedEnd`.
newUsedCount += (bounds.startIndex - UnsafePointer(start)) >> elementShift
if _slowPath(newUsedCount > capacity) {
return false
}
let newUsedEnd = start + (newUsedCount << elementShift)
if _fastPath(self._storage.isUniquelyReferenced()) {
usedEnd = newUsedEnd
return true
}
// Optimization: even if the buffer is shared, but the substring we are
// trying to grow is located at the end of the buffer, it can be grown in
// place. The operation should be implemented in a thread-safe way,
// though.
//
// if usedEnd == bounds.endIndex {
// usedEnd = newUsedEnd
// return true
// }
let usedEndPhysicalPtr =
UnsafeMutablePointer<UnsafeMutablePointer<_RawByte>>(_storage._value)
var expected = UnsafeMutablePointer<_RawByte>(bounds.endIndex)
if _stdlib_atomicCompareExchangeStrongPtr(
object: usedEndPhysicalPtr, expected: &expected, desired: newUsedEnd) {
return true
}
return false
}
var _anyObject: AnyObject? {
return _storage.storage != nil ? _storage.storage! : nil
}
var _storage: _Storage
}
| 32.915663 | 85 | 0.671791 |
29f000d1186e0cb33361e77d201daa95d0757057 | 3,015 | //
// Constants.swift
// On the Spot
//
// Created by Ramesh Parthasarathy on 4/12/17.
// Copyright © 2017 Ramesh Parthasarathy. All rights reserved.
//
import Foundation
import UIKit
// MARK: Constants
struct Constants {
static let metersPerMile = 1609.34
// MARK: Device
struct Device {
static let phoneSE = "phoneSE"
static let phone = "phone"
static let phonePlus = "phonePlus"
}
// MARK: Screen Height
struct ScreenHeight {
static let phoneSE: CGFloat = 568.0
static let phone: CGFloat = 667.0
static let phonePlus: CGFloat = 736.0
}
// MARK: Table Row Height
struct RowHeight {
static let phoneSE: CGFloat = 72.0
static let phone: CGFloat = 84.0
static let phonePlus: CGFloat = 93.0
}
// MARK: Font Size
struct FontSize {
struct Title {
static let phoneSE: CGFloat = 14.0
static let phone: CGFloat = 16.0
static let phonePlus: CGFloat = 17.0
}
struct Setting {
struct Small {
static let phoneSE: CGFloat = 11.0
static let phone: CGFloat = 13.0
static let phonePlus: CGFloat = 14.0
}
struct Medium {
static let phoneSE: CGFloat = 12.0
static let phone: CGFloat = 14.0
static let phonePlus: CGFloat = 15.0
}
struct Large {
static let phoneSE: CGFloat = 13.0
static let phone: CGFloat = 15.0
static let phonePlus: CGFloat = 16.0
}
}
struct Places {
struct Small {
static let phoneSE: CGFloat = 11.0
static let phone: CGFloat = 13.0
static let phonePlus: CGFloat = 14.0
}
struct Medium {
static let phoneSE: CGFloat = 12.0
static let phone: CGFloat = 14.0
static let phonePlus: CGFloat = 15.0
}
struct Large {
static let phoneSE: CGFloat = 13.0
static let phone: CGFloat = 15.0
static let phonePlus: CGFloat = 16.0
}
}
struct PlaceTable {
struct Small {
static let phoneSE: CGFloat = 10.0
static let phone: CGFloat = 12.0
static let phonePlus: CGFloat = 13.0
}
struct Medium {
static let phoneSE: CGFloat = 12.0
static let phone: CGFloat = 14.0
static let phonePlus: CGFloat = 15.0
}
struct Large {
static let phoneSE: CGFloat = 13.0
static let phone: CGFloat = 15.0
static let phonePlus: CGFloat = 16.0
}
}
}
}
| 27.916667 | 63 | 0.486567 |
e8e76f7f70a306a5382e587e3d57316f48d5bde5 | 1,110 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "PHTelegramPicker",
platforms: [
.iOS("10.0")
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "PHTelegramPicker",
targets: ["PHTelegramPicker"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "PHTelegramPicker",
dependencies: []),
.testTarget(
name: "PHTelegramPickerTests",
dependencies: ["PHTelegramPicker"]),
]
)
| 34.6875 | 122 | 0.624324 |
ff41f40fbdc8888b1ea5211b69a61c6f9a2527a7 | 1,257 | //
// Money
// File created on 15/09/2017.
//
// Copyright (c) 2015-2017 Daniel Thorpe
//
// Money is licensed under the MIT License. Read the full license at
// https://github.com/danthorpe/Money/blob/master/LICENSE
//
import XCTest
@testable import Money
extension MoneyTestCase {
func test__money_subtraction() {
money = 10
let result = money - Money(decimal: Decimal(integerLiteral: 10))
XCTAssertEqual(result, 0)
}
func test__money_subtraction_by_integer_literals() {
money = 10
let result = 3 - money - 2
XCTAssertEqual(result, -9)
}
func test__money_subtraction_by_float_literals() {
money = 10
let result = 3.5 - money - 2.5
XCTAssertEqual(result, -9)
}
}
extension MoneyTestCase {
func test__iso_subtraction() {
gbp = 10
let result = gbp - GBP(decimal: Decimal(integerLiteral: 10))
XCTAssertEqual(result, 0)
}
func test__iso_subtraction_by_integer_literals() {
gbp = 10
let result = 3 - gbp - 2
XCTAssertEqual(result, -9)
}
func test__iso_subtraction_by_float_literals() {
gbp = 10
let result = 3.5 - gbp - 2.5
XCTAssertEqual(result, -9)
}
}
| 22.446429 | 72 | 0.621321 |
8fe0985852626470ddd1024b737bca00e61902ba | 4,710 | //
// PhotosViewController.swift
// TumblerFeed
//
// Created by Amzad Chowdhury on 9/12/18.
// Copyright © 2018 Amzad Chowdhury. All rights reserved.
//
import UIKit
import AlamofireImage
class PhotosViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var posts: [[String: Any]] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
fetchImages()
// Do any additional setup after loading the view.
}
func fetchImages() {
let url = URL(string: "https://api.tumblr.com/v2/blog/humansofnewyork.tumblr.com/posts/photo?api_key=Q6vHoaVm5L1u2ZAW1fqv3Jw48gFzYVg9P0vH0VHl3GVy6quoGV")!
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
session.configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
let task = session.dataTask(with: url) { (data, response, error) in
if let error = error {
let alertController = UIAlertController(title: "Unable to Connect", message: "No network connection", preferredStyle: .alert)
let tryAgainAction = UIAlertAction(title: "Try again", style: .default, handler: {
(action) in self.fetchImages()
})
alertController.addAction(tryAgainAction)
self.present(alertController, animated: true) {
}
print(error.localizedDescription)
} else if let data = data,
let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
// print("Found")
let responseDictionary = dataDictionary["response"] as! [String: Any]
self.posts = responseDictionary["posts"] as! [[String: Any]]
self.tableView.reloadData()
}
}
task.resume()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
let post = posts[indexPath.section]
if let photos = post["photos"] as? [[String: Any]] {
let photo = photos[0]
let originalSize = photo["original_size"] as! [String: Any]
let urlString = originalSize["url"] as! String
let url = URL(string: urlString)
cell.photoView.af_setImage(withURL: url!)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
headerView.backgroundColor = UIColor(white: 1, alpha: 0.9)
let profileView = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
profileView.clipsToBounds = true
profileView.layer.cornerRadius = 15;
profileView.layer.borderColor = UIColor(white: 0.7, alpha: 0.8).cgColor
profileView.layer.borderWidth = 1;
headerView.addSubview(profileView)
profileView.af_setImage(withURL: URL(string: "https://api.tumblr.com/v2/blog/humansofnewyork.tumblr.com/avatar")!)
let dateLabel = UILabel(frame: CGRect(x: 50, y: 10, width: 300, height: 30))
let post = posts[section]
let date = post["date"] as? String
dateLabel.text = date
headerView.addSubview(dateLabel)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let photoDetailViewController = segue.destination as! PhotoDetailsViewController
let cell = sender as! PhotoCell
photoDetailViewController.image = cell.photoView.image
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 37.68 | 162 | 0.623142 |
f8c7122ffc768a170da2a9abe39a7d10935e7fa5 | 1,698 | //
// JCMessageType.swift
// JChat
//
// Created by deng on 10/04/2017.
// Copyright © 2017 HXHG. All rights reserved.
//
import Foundation
import JMessage
@objc public enum MessageTargetType: Int {
case single = 0
case group
}
@objc public protocol JCMessageType: class {
var name: String { get }
var identifier: UUID { get }
var msgId: String { get }
var date: Date { get }
var sender: JMSGUser? { get }
var senderAvator: UIImage? { get }
var receiver: JMSGUser? { get }
var content: JCMessageContentType { get }
var options: JCMessageOptions { get }
var updateSizeIfNeeded: Bool { get }
var unreadCount: Int { get }
var targetType: MessageTargetType { get }
}
@objc public protocol JCMessageDelegate: NSObjectProtocol {
@objc optional func message(message: JCMessageType, videoData data: Data?)
@objc optional func message(message: JCMessageType, voiceData data: Data?, duration: Double)
@objc optional func message(message: JCMessageType, fileData data: Data?, fileName: String?, fileType: String?)
@objc optional func message(message: JCMessageType, location address: String?, lat: Double, lon: Double)
@objc optional func message(message: JCMessageType, image: UIImage?)
// user 对象是为了提高效率,如果 user 已经加载出来了,就直接使用,不需要重新去获取一次
@objc optional func message(message: JCMessageType, user: JMSGUser?, businessCardName: String, businessCardAppKey: String)
@objc optional func clickTips(message: JCMessageType)
@objc optional func tapAvatarView(message: JCMessageType)
@objc optional func longTapAvatarView(message: JCMessageType)
@objc optional func tapUnreadTips(message: JCMessageType)
}
| 36.913043 | 126 | 0.720848 |
e5f4246e5f49adb033244c5f3e4f4cec5f5025cf | 8,070 | //
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
public extension Date {
// MARK: - Comparing Close
/// Decides whether a Date is "close by" another one passed in parameter,
/// where "Being close" is measured using a precision argument
/// which is initialized a 300 seconds, or 5 minutes.
///
/// - Parameters:
/// - refDate: reference date compare against to.
/// - precision: The precision of the comparison (default is 5 minutes, or 300 seconds).
/// - Returns: A boolean; true if close by, false otherwise.
func compareCloseTo(_ refDate: Date, precision: TimeInterval = 300) -> Bool {
return (abs(timeIntervalSince(refDate)) < precision)
}
// MARK: - Extendend Compare
/// Compare the date with the rule specified in the `compareType` parameter.
///
/// - Parameter compareType: comparison type.
/// - Returns: `true` if comparison succeded, `false` otherwise
func compare(_ compareType: DateComparisonType) -> Bool {
return inDefaultRegion().compare(compareType)
}
/// Returns a ComparisonResult value that indicates the ordering of two given dates based on
/// their components down to a given unit granularity.
///
/// - parameter date: date to compare.
/// - parameter granularity: The smallest unit that must, along with all larger units be less for the given dates
/// - returns: `ComparisonResult`
func compare(toDate refDate: Date, granularity: Calendar.Component) -> ComparisonResult {
return inDefaultRegion().compare(toDate: refDate.inDefaultRegion(), granularity: granularity)
}
/// Compares whether the receiver is before/before equal `date` based on their components down to a given unit granularity.
///
/// - Parameters:
/// - refDate: reference date
/// - orEqual: `true` to also check for equality
/// - granularity: smallest unit that must, along with all larger units, be less for the given dates
/// - Returns: Boolean
func isBeforeDate(_ refDate: Date, orEqual: Bool = false, granularity: Calendar.Component) -> Bool {
return inDefaultRegion().isBeforeDate(refDate.inDefaultRegion(), orEqual: orEqual, granularity: granularity)
}
/// Compares whether the receiver is after `date` based on their components down to a given unit granularity.
///
/// - Parameters:
/// - refDate: reference date
/// - orEqual: `true` to also check for equality
/// - granularity: Smallest unit that must, along with all larger units, be greater for the given dates.
/// - Returns: Boolean
func isAfterDate(_ refDate: Date, orEqual: Bool = false, granularity: Calendar.Component) -> Bool {
return inDefaultRegion().isAfterDate(refDate.inDefaultRegion(), orEqual: orEqual, granularity: granularity)
}
/// Returns a value between 0.0 and 1.0 or nil, that is the position of current date between 2 other dates.
///
/// - Parameters:
/// - startDate: range upper bound date
/// - endDate: range lower bound date
/// - Returns: `nil` if current date is not between `startDate` and `endDate`. Otherwise returns position between `startDate` and `endDate`.
func positionInRange(date startDate: Date, and endDate: Date) -> Double? {
return inDefaultRegion().positionInRange(date: startDate.inDefaultRegion(), and: endDate.inDefaultRegion())
}
/// Return true if receiver date is contained in the range specified by two dates.
///
/// - Parameters:
/// - startDate: range upper bound date
/// - endDate: range lower bound date
/// - orEqual: `true` to also check for equality on date and date2
/// - granularity: smallest unit that must, along with all larger units, be greater for the given dates.
/// - Returns: Boolean
func isInRange(date startDate: Date, and endDate: Date, orEqual: Bool = false, granularity: Calendar.Component = .nanosecond) -> Bool {
return inDefaultRegion().isInRange(date: startDate.inDefaultRegion(), and: endDate.inDefaultRegion(), orEqual: orEqual, granularity: granularity)
}
/// Compares equality of two given dates based on their components down to a given unit
/// granularity.
///
/// - parameter date: date to compare
/// - parameter granularity: The smallest unit that must, along with all larger units, be equal for the given
/// dates to be considered the same.
///
/// - returns: `true` if the dates are the same down to the given granularity, otherwise `false`
func isInside(date: Date, granularity: Calendar.Component) -> Bool {
return (compare(toDate: date, granularity: granularity) == .orderedSame)
}
// MARK: - Date Earlier/Later
/// Return the earlier of two dates, between self and a given date.
///
/// - Parameter date: The date to compare to self
/// - Returns: The date that is earlier
func earlierDate(_ date: Date) -> Date {
return timeIntervalSince(date) <= 0 ? self : date
}
/// Return the later of two dates, between self and a given date.
///
/// - Parameter date: The date to compare to self
/// - Returns: The date that is later
func laterDate(_ date: Date) -> Date {
return timeIntervalSince(date) >= 0 ? self : date
}
}
extension Date {
/// Returns the difference in the calendar component given (like day, month or year)
/// with respect to the other date as a positive integer
public func difference(in component: Calendar.Component, from other: Date) -> Int? {
let (max, min) = orderDate(with: other)
let result = calendar.dateComponents([component], from: min, to: max)
return getValue(of: component, from: result)
}
/// Returns the differences in the calendar components given (like day, month and year)
/// with respect to the other date as dictionary with the calendar component as the key
/// and the diffrence as a positive integer as the value
public func differences(in components: Set<Calendar.Component>, from other: Date) -> [Calendar.Component: Int] {
let (max, min) = orderDate(with: other)
let differenceInDates = calendar.dateComponents(components, from: min, to: max)
var result = [Calendar.Component: Int]()
for component in components {
if let value = getValue(of: component, from: differenceInDates) {
result[component] = value
}
}
return result
}
private func getValue(of component: Calendar.Component, from dateComponents: DateComponents) -> Int? {
switch component {
case .era:
return dateComponents.era
case .year:
return dateComponents.year
case .month:
return dateComponents.month
case .day:
return dateComponents.day
case .hour:
return dateComponents.hour
case .minute:
return dateComponents.minute
case .second:
return dateComponents.second
case .weekday:
return dateComponents.weekday
case .weekdayOrdinal:
return dateComponents.weekdayOrdinal
case .quarter:
return dateComponents.quarter
case .weekOfMonth:
return dateComponents.weekOfMonth
case .weekOfYear:
return dateComponents.weekOfYear
case .yearForWeekOfYear:
return dateComponents.yearForWeekOfYear
case .nanosecond:
return dateComponents.nanosecond
case .calendar, .timeZone:
return nil
@unknown default:
assert(false, "unknown date component")
}
return nil
}
private func orderDate(with other: Date) -> (Date, Date) {
let first = self.timeIntervalSince1970
let second = other.timeIntervalSince1970
if first >= second {
return (self, other)
}
return (other, self)
}
}
| 40.149254 | 153 | 0.678067 |
8ff2a71d3c5830613d87d8e6dd8830f31ec6b7d4 | 358 | //
// TagModel.swift
// Cozy
//
// Created by Uladzislau Volchyk on 9/3/20.
// Copyright © 2020 Uladzislau Volchyk. All rights reserved.
//
import Foundation
class TagModel {
var isSelected: Bool
let value: String
init(value: String, isSelected: Bool = false) {
self.value = value
self.isSelected = isSelected
}
}
| 17.047619 | 61 | 0.636872 |
394636e8881b9ee89bd8fa118c5786d9e5cc296c | 229 |
import Foundation
struct WeatherData: Decodable {
let name: String
let main: Main
let weather: [Weather]
}
struct Main: Decodable {
let temp: Double
}
struct Weather: Decodable {
let description: String
}
| 13.470588 | 31 | 0.68559 |
8ad9d1272d6f40bf3c41ca1dd715391ca044ed15 | 154 | //
// Sort.swift
// Created by hg on 13/10/2020.
//
import Foundation
public protocol Sort {
func sort<T: Comparable>(_ array: inout [T])
}
| 11.846154 | 48 | 0.616883 |
03dabd81fedf1f3cf8be88bc36af7d0b9c5655fd | 298 | //
// Application.swift
// PrinterStatus
//
// Created by Islam Sharabash on 1/19/22.
//
import AppKit
import Bugsnag
import Foundation
class Application: NSApplication {
func reportException(exception: NSException) {
Bugsnag.notify(exception)
super.reportException(exception)
}
}
| 16.555556 | 48 | 0.734899 |
7564a3076d10d92f0960038f11e195a939a9f220 | 481 | //
// ViewController.swift
// TransitionView
//
// Created by Lorrayne Paraiso C Flor on 28/02/18.
// Copyright © 2018 ZupIT. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 18.5 | 74 | 0.723493 |
28d206a3451bc552db1ddc8d29b47254e900809e | 4,149 | // Copyright 2019 Bryant Luk
//
// 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 Dispatch
import Logging
internal protocol BNSChannelHandlerLoggable: BNSLoggable {}
internal protocol BNSOnlyLoggerChannelHandlerLoggable: BNSChannelHandlerLoggable {
var logger: Logger? { get }
}
internal extension BNSOnlyLoggerChannelHandlerLoggable where Self: BNSOnlyQueuePossiblyQueueable {
func logTrace(_ message: @escaping @autoclosure () -> Logger.Message) {
if var logger = self.logger {
switch logger.logLevel {
case .debug, .info, .notice, .warning, .error, .critical:
break
case .trace:
logger[metadataKey: "handler"] = "\(type(of: self))"
let resolvedMessage = message()
self.withQueueIfPossible { logger.trace(resolvedMessage) }
}
}
}
func logDebug(_ message: @escaping @autoclosure () -> Logger.Message) {
if var logger = self.logger {
switch logger.logLevel {
case .info, .notice, .warning, .error, .critical:
break
case .debug, .trace:
logger[metadataKey: "handler"] = "\(type(of: self))"
let resolvedMessage = message()
self.withQueueIfPossible { logger.debug(resolvedMessage) }
}
}
}
func logError(_ message: @escaping @autoclosure () -> Logger.Message) {
if var logger = self.logger {
switch logger.logLevel {
case .trace, .debug, .info, .notice, .warning, .critical:
break
case .error:
logger[metadataKey: "handler"] = "\(type(of: self))"
let resolvedMessage = message()
self.withQueueIfPossible { logger.error(resolvedMessage) }
}
}
}
}
internal protocol BNSWithLoggableInstanceChannelHandlerLoggable: BNSChannelHandlerLoggable {
associatedtype Loggable: BNSEventLoopProtectedLoggable
var eventLoopProtectedLoggable: Loggable? { get }
}
internal extension BNSWithLoggableInstanceChannelHandlerLoggable {
func logTrace(_ message: @escaping @autoclosure () -> Logger.Message) {
if let eventLoopProtectedLoggable = eventLoopProtectedLoggable {
eventLoopProtectedLoggable.eventLoop.assertInEventLoop()
if var logger = eventLoopProtectedLoggable.eventLoopProtectedLogger {
switch logger.logLevel {
case .debug, .info, .notice, .warning, .error, .critical:
break
case .trace:
logger[metadataKey: "handler"] = "\(type(of: self))"
let resolvedMessage = message()
eventLoopProtectedLoggable.withQueueIfPossible { logger.trace(resolvedMessage) }
}
}
}
}
func logDebug(_ message: @escaping @autoclosure () -> Logger.Message) {
if let eventLoopProtectedLoggable = eventLoopProtectedLoggable {
eventLoopProtectedLoggable.eventLoop.assertInEventLoop()
if var logger = eventLoopProtectedLoggable.eventLoopProtectedLogger {
switch logger.logLevel {
case .info, .notice, .warning, .error, .critical:
break
case .debug, .trace:
logger[metadataKey: "handler"] = "\(type(of: self))"
let resolvedMessage = message()
eventLoopProtectedLoggable.withQueueIfPossible { logger.debug(resolvedMessage) }
}
}
}
}
}
| 39.141509 | 100 | 0.615088 |
1cc189ffcf485d8f837a337e11435760e83c3e0c | 125 | //___FILEHEADER___
import StanwoodCore
import SourceModel
class ___VARIABLE_productName___DataSource: TableDataSource {
}
| 13.888889 | 61 | 0.856 |
71c9c984165d9784b1c0f79e2fcaef94a9ea70d3 | 1,629 | //
// Withable.swift
// Declarative_UIKit
//
// Created by Geri Borbás on 28/11/2020.
// http://www.twitter.com/Geri_Borbas
//
import Foundation
// MARK: - Withable for Objects
public protocol ObjectWithable: class {
associatedtype T
/// Provides a closure to configure instances inline.
/// - Parameter closure: A closure `self` as the argument.
/// - Returns: Simply returns the instance after called the `closure`.
@discardableResult func with(_ closure: (_ instance: T) -> Void) -> T
}
public extension ObjectWithable {
@discardableResult func with(_ closure: (_ instance: Self) -> Void) -> Self {
closure(self)
return self
}
}
extension NSObject: ObjectWithable { }
// MARK: - Withable for Values
public protocol Withable {
associatedtype T
/// Provides a closure to configure instances inline.
/// - Parameter closure: A closure with a mutable copy of `self` as the argument.
/// - Returns: Simply returns the mutated copy of the instance after called the `closure`.
@discardableResult func with(_ closure: (_ instance: inout T) -> Void) -> T
}
public extension Withable {
@discardableResult func with(_ closure: (_ instance: inout Self) -> Void) -> Self {
var copy = self
closure(©)
return copy
}
}
// MARK: - Examples
struct Point: Withable {
var x: Int = 0
var y: Int = 0
}
extension PersonNameComponents: Withable { }
struct Test {
let formatter = DateFormatter().with {
$0.dateStyle = .medium
}
let point = Point().with {
$0.x = 10
$0.y = 10
}
let name = PersonNameComponents().with {
$0.givenName = "Geri"
$0.familyName = "Borbás"
}
}
| 19.865854 | 91 | 0.682014 |
d7d46f264ab33225a4a1a0e1583353b197e8a854 | 1,703 | //
// UdacityClientConstants.swift
// On the Map
//
// Created by Adland Lee on 3/24/16.
// Copyright © 2016 Adland Lee. All rights reserved.
//
// MARK: UdacityClient (Constants)
extension UdacityClient {
// Mark Constants
struct Constants {
// MARK: API Key
static let APIKey: String = ""
// MARK: URL information
static let APIScheme = "https"
static let APIHost = "www.udacity.com"
static let APIPath = "/api"
static let AuthorizationURL = ""
}
// MARK: Resources
struct Resources {
// MARK: Users
static let UserId = "/users/{user_id}"
// MARK: Authentication
static let Session = "/session"
}
// MARK: URL Keys
struct URLKeys {
static let UserId = "user_id"
}
// MARK: Parameter Keys
struct ParameterKeys {
}
struct JSONBodyKeys {
static let Udacity = "udacity"
static let Username = "username"
static let Password = "password"
static let FacebookMobile = "facebook_mobile"
static let AccessToken = "access_token"
}
// MARK: JSON Response Keys
struct JSONResponseKeys {
// MARK: Authorization
static let Session = "session"
static let SessionId = "id"
static let Account = "account"
static let AccountKey = "key"
// MARK: User
static let User = "user"
}
// MARK: JSON Response Keys
struct UserKeys {
static let FirstName = "first_name"
static let LastName = "last_name"
static let Key = "key"
}
} | 23.013514 | 53 | 0.553729 |
2fbbf059fa67a379daadb5e5bf1b41d181426f26 | 771 | //
// Analytic.swift
// StripeCore
//
// Created by Mel Ludowise on 3/12/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
/// An analytic that can be logged to our analytics system
@_spi(STP) public protocol Analytic {
var event: STPAnalyticEvent { get }
var params: [String: Any] { get }
}
/**
A generic analytic type.
- NOTE: This should only be used to support legacy analytics.
Any new analytic events should create a new type and conform to `Analytic`.
*/
@_spi(STP) public struct GenericAnalytic: Analytic {
public let event: STPAnalyticEvent
public let params: [String : Any]
public init(event: STPAnalyticEvent, params: [String: Any]) {
self.event = event
self.params = params
}
}
| 24.870968 | 76 | 0.683528 |
1dd4483c32e182953c8495be661bf6d7738bc3f6 | 11,094 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
/// The simplest possible `OCKSchedulable`, representing a single event that repeats at
/// fixed intervals. It may have fixed duration or repeat indefinitely.
public struct OCKScheduleElement: Codable, Equatable {
// Disabled because nested types are an internal implementation detail.
/// A duration describing the length of an event. Options include all day, or a deterministic number of hours, minutes, or seconds.
public enum Duration: Codable, Equatable {
/// Describes an duration that fills an entire date
case allDay
/// Describes a fixed duration in seconds
case seconds(Double)
/// Creates a duration that represents a given number of hours.
public static func hours(_ hours: Double) -> Duration {
.seconds(60 * 60 * hours)
}
/// Creates a duration that represents a given number of minutes.
public static func minutes(_ minutes: Double) -> Duration {
.seconds(60 * minutes)
}
private enum CodingKeys: CodingKey {
case isAllDay
case seconds
}
var seconds: TimeInterval {
switch self {
case .allDay: return 0
case .seconds(let seconds): return seconds
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self == .allDay, forKey: .isAllDay)
if case .seconds(let seconds) = self {
try container.encode(seconds, forKey: .seconds)
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if try container.decodeIfPresent(Bool.self, forKey: .isAllDay) == true {
self = .allDay
return
}
if let seconds = try container.decodeIfPresent(Double.self, forKey: .seconds) {
self = .seconds(seconds)
return
}
throw DecodingError.dataCorruptedError(forKey: CodingKeys.seconds, in: container, debugDescription: "No seconds or allDay key was found!")
}
}
/// An text about the time this element represents.
/// e.g. before breakfast on Tuesdays, 5PM every day, etc.
public var text: String?
/// The amount of time that the event should take, in seconds.
public var duration: Duration
/// The date and time the first event occurs.
// Note: This must remain a constant because its value is modified by the `isAllDay` flag during initialization.
public let start: Date
/// The latest possible time for an event to occur.
/// - Note: Depending on the interval chosen, it is not guaranteed that an event
/// will fall on this date.
/// - Note: If no date is provided, the schedule will repeat indefinitely.
public var end: Date?
/// The amount of time between events specified using `DateCoponents`.
/// - Note: `DateComponents` are chose over `TimeInterval` to account for edge
/// edge cases like daylight savings time and leap years.
public var interval: DateComponents
/// An array of values that specify what values the user is expected to record.
/// For example, for a medication, it may be the dose that the patient is expected to take.
public var targetValues: [OCKOutcomeValue]
/// Create a `ScheduleElement` by specifying the start date, end date, and interval.
///
/// - Parameters:
/// - start: Date specifying the exact day and time that the first occurrence of this task happens.
/// - end: Date specifying when the task ends. The end date is not inclusive.
/// - interval: DateComponents specifying the frequency at which the schedule repeats.
/// - text: A textual representation of this schedule element. Examples: "After breakfast", "08:00", "As needed throughout the day".
/// - targetValues: An array of values that represents goals for this schedule element.
/// - duration: A duration in seconds specifying how long the window to complete this event is.
public init(start: Date, end: Date?, interval: DateComponents, text: String? = nil,
targetValues: [OCKOutcomeValue] = [], duration: Duration = .hours(0)) {
assert(end == nil || start < end!, "Start date must be before the end date!")
assert(interval.movesForwardInTime, "Interval must not progress backwards in time!")
self.start = duration == .allDay ? Calendar.current.startOfDay(for: start) : start
self.end = end
self.interval = interval
self.text = text
self.duration = duration
self.targetValues = targetValues
}
/// Returns the Nth event of this schedule.
///
/// - Parameter occurrence: The Nth occurrence.
public subscript(occurrence: Int) -> OCKScheduleEvent {
makeScheduleEvent(on: date(ofOccurrence: occurrence)!, for: occurrence)
}
@available(*, deprecated, message: "OCKScheduleElement.elements has been deprecated")
public var elements: [OCKScheduleElement] {
return [self]
}
/// - Returns: a new instance of with all event times offset by the given value.
public func offset(by dateComponents: DateComponents) -> OCKScheduleElement {
let newStart = Calendar.current.date(byAdding: dateComponents, to: start)!
let newEnd = end == nil ? nil : Calendar.current.date(byAdding: dateComponents, to: end!)!
return OCKScheduleElement(start: newStart, end: newEnd, interval: interval,
text: text, targetValues: targetValues, duration: duration)
}
/// - Returns: An array containing either an schedule event or nil
/// - Remark: Lower bound is inclusive, upper bound is exclusive.
public func events(betweenOccurrenceIndex startIndex: Int, and stopIndex: Int) -> [OCKScheduleEvent?] {
assert(stopIndex > startIndex, "Stop index must be greater than or equal to start index")
let numberOfEvents = stopIndex - startIndex
var currentOccurrence = 0
var events = [OCKScheduleEvent?](repeating: nil, count: numberOfEvents)
// Move to start index
var currentDate = start
for _ in 0..<startIndex {
currentDate = Calendar.current.date(byAdding: interval, to: currentDate)!
currentOccurrence += 1
}
// Calculate the event at each index in between start and top indices
for index in 0..<numberOfEvents {
if let endDate = end, currentDate > endDate { continue }
events[index] = makeScheduleEvent(on: currentDate, for: currentOccurrence)
currentDate = Calendar.current.date(byAdding: interval, to: currentDate)!
currentOccurrence += 1
}
return events
}
public func events(from start: Date, to end: Date) -> [OCKScheduleEvent] {
let stopDate = determineStopDate(onOrBefore: end)
var current = self.start
var dates = [Date]()
while current < stopDate {
dates.append(current)
current = Calendar.current.date(byAdding: interval, to: current)!
}
let events = dates.enumerated().map { index, date in makeScheduleEvent(on: date, for: index) }
return events.filter { event in
if duration == .allDay {
return event.end > start
}
return event.start + duration.seconds >= start
}
}
/// Computes the date of the Nth occurrence of a schedule element. If the Nth occurrence is beyond the end date, then nil will be returned.
public func date(ofOccurrence occurrence: Int) -> Date? {
assert(occurrence >= 0, "Schedule events cannot have negative occurrence indices")
var currentDate = start
for _ in 0..<occurrence {
guard let nextDate = Calendar.current.date(byAdding: interval, to: currentDate) else { fatalError("Invalid date!") }
if let endDate = end, nextDate <= endDate { return nil }
currentDate = nextDate
}
return currentDate
}
/// Determines the last date at which an event could possibly occur
private func determineStopDate(onOrBefore date: Date) -> Date {
let stopDay = min(date, end ?? date)
guard duration == .allDay else {
return stopDay
}
let morningOfStopDay = Calendar.current.startOfDay(for: stopDay)
let endOfStopDay = Calendar.current.date(byAdding: .init(day: 1, second: -1), to: morningOfStopDay)!
return endOfStopDay
}
private func makeScheduleEvent(on date: Date, for occurrence: Int) -> OCKScheduleEvent {
let startDate = duration == .allDay ? Calendar.current.startOfDay(for: date) : date
let endDate = duration == .allDay ?
Calendar.current.date(byAdding: DateComponents(day: 1, second: -1), to: startDate)! :
startDate.addingTimeInterval(duration.seconds)
return OCKScheduleEvent(start: startDate, end: endDate, element: self, occurrence: occurrence)
}
}
private extension DateComponents {
var movesForwardInTime: Bool {
let now = Date()
let then = Calendar.current.date(byAdding: self, to: now)!
return then > now
}
}
| 45.842975 | 150 | 0.667298 |
8aa6b9fefb44147df99d45340b5488c167521139 | 62 | extension Int {
public var bool: Bool { self > 0 }
}
| 12.4 | 38 | 0.548387 |
0951bc05e0d03ff917a1b90b938b42a571a86134 | 2,727 | import UIKit
import UBottomSheet
class MapsViewController: UIViewController {
var sheetCoordinator: UBottomSheetCoordinator!
var backView: PassThroughView?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard sheetCoordinator == nil else {return}
sheetCoordinator = UBottomSheetCoordinator(parent: self,
delegate: self)
let vc = AppleMapsSheetViewController()
vc.sheetCoordinator = sheetCoordinator
sheetCoordinator.addSheet(vc, to: self, didContainerCreate: { container in
let f = self.view.frame
let rect = CGRect(x: f.minX, y: f.minY, width: f.width, height: f.height)
container.roundCorners(corners: [.topLeft, .topRight], radius: 10, rect: rect)
})
sheetCoordinator.setCornerRadius(10)
}
private func addBackDimmingBackView(below container: UIView){
backView = PassThroughView()
self.view.insertSubview(backView!, belowSubview: container)
backView!.translatesAutoresizingMaskIntoConstraints = false
backView!.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
backView!.bottomAnchor.constraint(equalTo: container.topAnchor, constant: 10).isActive = true
backView!.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
backView!.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
}
}
extension MapsViewController: UBottomSheetCoordinatorDelegate {
func bottomSheet(_ container: UIView?, didPresent state: SheetTranslationState) {
// self.addBackDimmingBackView(below: container!)
self.sheetCoordinator.addDropShadowIfNotExist()
self.handleState(state)
}
func bottomSheet(_ container: UIView?, didChange state: SheetTranslationState) {
handleState(state)
}
func bottomSheet(_ container: UIView?, finishTranslateWith extraAnimation: @escaping ((CGFloat) -> Void) -> Void) {
extraAnimation({ percent in
self.backView?.backgroundColor = UIColor.black.withAlphaComponent(percent/100 * 0.8)
})
}
func handleState(_ state: SheetTranslationState){
switch state {
case .progressing(_, let percent):
self.backView?.backgroundColor = UIColor.black.withAlphaComponent(percent/100 * 0.8)
case .finished(_, let percent):
self.backView?.backgroundColor = UIColor.black.withAlphaComponent(percent/100 * 0.8)
default:
break
}
}
}
| 38.957143 | 119 | 0.668133 |
67219be2404acf0ef03434723a129724b8a9dff9 | 4,275 | //
// CacheFeedUseCaseTests.swift
// EssentialFeedTests
//
// Created by panditpakhurde on 27/04/20.
// Copyright © 2020 Quikr. All rights reserved.
//
import XCTest
import EssentialFeed
class CacheFeedUseCaseTests: XCTestCase {
func test_init_doesNotMessageStoreUponCreation() {
let (_, store) = makeSUT()
XCTAssertEqual(store.receivedMessages, [])
}
func test_save_requestCacheDeletion() {
let (sut, store) = makeSUT()
sut.save(uniqueImageFeed().models) { _ in }
XCTAssertEqual(store.receivedMessages, [.deleteCacheFeed])
}
func test_save_doesNotRequestCacheInsertionOnDeletionError() {
let (sut, store) = makeSUT()
let deletionError = anyNSError()
sut.save(uniqueImageFeed().models) { _ in }
store.completeDeletion(with: deletionError)
XCTAssertEqual(store.receivedMessages, [.deleteCacheFeed])
}
func test_save_requestsNewCacheInsertionWithTimestampOnSuccessfulDeletion() {
let timestamp = Date()
let feed = uniqueImageFeed()
let (sut, store) = makeSUT(currentDate: { timestamp })
sut.save(feed.models) { _ in }
store.completeDeletionSuccessfully()
XCTAssertEqual(store.receivedMessages, [.deleteCacheFeed, .insert(feed.local, timestamp)])
}
func test_save_failsOnDeletionError() {
let (sut, store) = makeSUT()
let deletionError = anyNSError()
expect(sut, toCompleteWithError: deletionError) {
store.completeDeletion(with: deletionError)
}
}
func test_save_failsOnInsertionError() {
let (sut, store) = makeSUT()
let insertionError = anyNSError()
expect(sut, toCompleteWithError: anyNSError()) {
store.completeDeletionSuccessfully()
store.completeInsertion(with: insertionError)
}
}
func test_save_succeedOnSuccessfulCacheInsertionError() {
let (sut, store) = makeSUT()
expect(sut, toCompleteWithError: nil) {
store.completeDeletionSuccessfully()
store.completeInsertionSuccessfully()
}
}
func test_save_doesNotDeliverDeletionErrorAfterSUTInstanceHasBeenDeallocated() {
let feedStore = FeedStoreSpy()
var sut: LocalFeedLoader? = LocalFeedLoader(store: feedStore, currentDate: Date.init)
var receivedResults = [LocalFeedLoader.SaveResult]()
sut?.save(uniqueImageFeed().models, completion: {receivedResults.append($0)})
sut = nil
feedStore.completeDeletion(with: anyNSError())
XCTAssertTrue(receivedResults.isEmpty)
}
func test_save_doesNotDeliverInsertionErrorAfterSUTInstanceHasBeenDeallocated() {
let feedStore = FeedStoreSpy()
var sut: LocalFeedLoader? = LocalFeedLoader(store: feedStore, currentDate: Date.init)
var receivedResults = [LocalFeedLoader.SaveResult]()
sut?.save(uniqueImageFeed().models, completion: {receivedResults.append($0)})
feedStore.completeDeletionSuccessfully()
sut = nil
feedStore.completeInsertion(with: anyNSError())
XCTAssertTrue(receivedResults.isEmpty)
}
//MARK: Helpers
private func expect(_ sut: LocalFeedLoader, toCompleteWithError expectedError: NSError?, when action: () -> Void) {
let exp = expectation(description: "Waiting for save completion")
var receivedError: Error?
sut.save(uniqueImageFeed().models) { result in
if case let Result.failure(error) = result { receivedError = error}
exp.fulfill()
}
action()
wait(for: [exp], timeout: 1.0)
XCTAssertEqual(receivedError as NSError?, expectedError)
}
private func makeSUT(currentDate: @escaping () -> Date = Date.init, file: StaticString = #file, line: UInt = #line) -> (sut: LocalFeedLoader, store: FeedStoreSpy){
let store = FeedStoreSpy()
let sut = LocalFeedLoader(store: store, currentDate: currentDate)
trackForMemoryLeaks(store, file: file, line: line)
trackForMemoryLeaks(sut, file: file, line: line)
return (sut, store)
}
}
| 33.661417 | 167 | 0.650994 |
76643b54761a514ed506d33fd176b7bdb1eda27d | 2,093 | //
// AppDelegate.swift
// ExampleTvOS
//
// Created by Daniele Margutti on 20/05/2018.
// Copyright © 2018 SwiftRichString. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the 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:.
}
}
| 44.531915 | 279 | 0.787864 |
16d1ff0b601fe1d0392f689ef57adacadafe7a04 | 4,561 | //
// PreferredFontButton.swift
// Vesting
//
// Created by David Keegan on 1/11/15.
// Copyright (c) 2015 David Keegan. All rights reserved.
//
import UIKit
private extension Selector {
static let contentSizeCategoryDidChange = #selector(PreferredFontButton.contentSizeCategoryDidChange(notification:))
static let preferredFontManagerDidChange = #selector(PreferredFontButton.preferredFontManagerDidChange(notification:))
}
/// Subclass of `UIButton` whos font is controlled by
/// the `textStyle` and `preferredFontManager` properties.
/// The font used is automaticly updated when the user changes
/// their accesability text size setting.
open class PreferredFontButton: UIButton {
// TODO: before iOS 10 this may not behave as expected
private var lastSizeCategory: UIContentSizeCategory = .medium
private var sizeCategory: UIContentSizeCategory {
if #available(iOSApplicationExtension 10.0, *) {
// TODO: is this always unspecified
if self.traitCollection.preferredContentSizeCategory != .unspecified {
return self.traitCollection.preferredContentSizeCategory
}
}
return self.lastSizeCategory
}
/// The text style to be used.
/// Defaults to `UIFontTextStyleBody`.
open var textStyle: UIFont.TextStyle = UIFont.TextStyle.body {
didSet {
self.updateFont()
}
}
/// The preferred font manager object to use.
/// Defaults to `PreferredFontManager.sharedManager()`.
open var preferredFontManager: PreferredFontManager? = PreferredFontManager.shared {
didSet {
self.updateFont()
}
}
private var hasMovedToSuperview = false
open override func didMoveToSuperview() {
super.didMoveToSuperview()
// HACK: The buttonType convenience init
// cannot be overwritten, so this is a hack
// to update the font when the button is
// first moved to a superview
if !self.hasMovedToSuperview && self.buttonType == .system {
self.hasMovedToSuperview = true
self.updateFont()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
/// Initialize a `PreferredFontButton` object with a given textStyle.
public convenience init(textStyle: UIFont.TextStyle) {
self.init(frame: CGRect.zero)
self.textStyle = textStyle
self.updateFont()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// This `setup` method is called when initalized.
/// Override this method to customize the setup of the button object.
/// Be sure to call `super.setup()` in your implementation.
open func setup() {
self.updateFont()
NotificationCenter.default.addObserver(
self, selector: .contentSizeCategoryDidChange,
name: UIContentSizeCategory.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(
self, selector: .preferredFontManagerDidChange,
name: NSNotification.Name(rawValue: PreferredFontManagerDidChangeNotification), object: nil)
}
private func updateFont() {
if let font = self.preferredFontManager?.preferredFont(forTextStyle: self.textStyle, sizeCategory: self.sizeCategory) {
self.titleLabel?.font = font
} else {
self.titleLabel?.font = UIFont.preferredFont(forTextStyle: self.textStyle)
}
}
@objc fileprivate func preferredFontManagerDidChange(notification: Notification) {
guard let object = notification.object as? [String: Any] else {
return
}
let preferredFontManager = object[PreferredFontManagerObjectKey] as? PreferredFontManager
let textStyle = object[PreferredFontManagerTextStyleKey] as? UIFont.TextStyle
if preferredFontManager == self.preferredFontManager && textStyle == self.textStyle {
self.updateFont()
}
}
@objc fileprivate func contentSizeCategoryDidChange(notification: Notification) {
if let object = notification.object as? [String: Any] {
if let sizeCategory = object[UIContentSizeCategory.newValueUserInfoKey] as? UIContentSizeCategory {
self.lastSizeCategory = sizeCategory
}
}
self.updateFont()
}
}
| 35.356589 | 127 | 0.670029 |
f9cfab68d8e3a7a1a47f022570f1e7459b9d1f04 | 973 | //
// MovieViewModel.swift
// TheMovieDb
//
// Created by Misael Chávez on 18/11/21.
//
import Foundation
struct MovieViewModel {
let id: Int
let title: String
let posterPath: String
let mediaType: String
let releaseDate: String
let overview: String
let rating: String
let baseURL: String
init(movie: MovieItem, configuration: ConfigurationImage) {
self.id = movie.id ?? 0
self.title = movie.title ?? ""
self.posterPath = movie.posterPath ?? ""
self.mediaType = movie.mediaType ?? ""
self.releaseDate = movie.releaseDate ?? ""
self.overview = movie.overview ?? ""
if let voteAverage = movie.voteAverage {
self.rating = String(voteAverage)
} else {
self.rating = ""
}
self.baseURL = configuration.getSecureBasePosterURL()
}
func getPosterURL() -> URL? {
return URL(string: baseURL + posterPath)
}
}
| 24.948718 | 63 | 0.601233 |
11fc38ffca60b91a6bf574500c4202231b61df81 | 1,949 | //
// SafariWebExtensionHandler.swift
// URL Linker Extension
//
// Created by horimislime on 2021/09/07.
// Copyright © 2021 horimislime. All rights reserved.
//
import SafariServices
import os.log
final class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
private let userDefaults = UserDefaults(suiteName: "group.me.horimisli.URLLinker")!
func beginRequest(with context: NSExtensionContext) {
let item = context.inputItems[0] as! NSExtensionItem
guard let message = item.userInfo?[SFExtensionMessageKey] as? [String: AnyObject],
let requestType = message["request"] as? String else {
os_log(.default, "Invalid native request payload")
return
}
os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@", message as CVarArg)
let setting = Setting.load(from: userDefaults) ?? Setting.default
let response = NSExtensionItem()
switch requestType {
case "getFormats":
let formats = setting.urlFormats.map { ["name": $0.name, "command": $0.commandName] }
response.userInfo = [SFExtensionMessageKey: formats]
case "copy":
let payload = message["payload"] as! [String: String]
let title = payload["title"]!
let link = payload["link"]!
let command = payload["command"]!
guard let format = setting.urlFormats.first(where: { $0.commandName == command }) else { return }
let formattedString = format.pattern
.replacingOccurrences(of: "%URL", with: link)
.replacingOccurrences(of: "%TITLE", with: title)
UIPasteboard.general.string = formattedString
default:
preconditionFailure("Request \(requestType) is not supported.")
}
context.completeRequest(returningItems: [response], completionHandler: nil)
}
}
| 39.77551 | 109 | 0.643407 |
22d4ec43bb6653ba2a4a7d8897c2cfa6571ff163 | 390 | //
// MyAppApp.swift
// MyApp
//
// Created by Bogdan Poplauschi on 01.11.2021.
//
import MyFramework
import SwiftUI
@main
struct MyAppApp: App {
var dependency: MyFrameworkClass {
let result = MyFrameworkClass()
result.someFrameworkAPI()
return result
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 15.6 | 47 | 0.589744 |
23212b81b0791f757fe2ab99a446420dbd3437d4 | 184 | // Int4+Raisable.swift
// Extensions
//
// Copyright © 2021-2022 Alexandre H. Saad
// Licensed under Apache License v2.0 with Runtime Library Exception
//
extension Int4: Raisable {}
| 20.444444 | 68 | 0.733696 |
4b56098107cf9a4da18770e92a23828d5ffb2b47 | 353 | // passed
// Another solution: build a set.
class Solution {
func containsDuplicate(_ nums: [Int]) -> Bool {
if nums.count < 2 { return false }
let nums = nums.sorted()
for i in 0..<nums.count-1 {
if nums[i] == nums[i+1] {
return true
}
}
return false
}
} | 22.0625 | 51 | 0.473088 |
e2771eb91629dff92822b99f9b3e195d8ce2c0e8 | 9,188 | import KsApi
import Library
import Prelude
import UIKit
internal final class DiscoveryPageViewController: UITableViewController {
fileprivate var emptyStatesController: EmptyStatesViewController?
fileprivate let dataSource = DiscoveryProjectsDataSource()
fileprivate let loadingIndicatorView = UIActivityIndicatorView()
fileprivate let viewModel: DiscoveryPageViewModelType = DiscoveryPageViewModel()
internal static func configuredWith(sort: DiscoveryParams.Sort) -> DiscoveryPageViewController {
let vc = Storyboard.DiscoveryPage.instantiate(DiscoveryPageViewController.self)
vc.viewModel.inputs.configureWith(sort: sort)
return vc
}
internal func change(filter: DiscoveryParams) {
self.viewModel.inputs.selectedFilter(filter)
}
internal override func viewDidLoad() {
super.viewDidLoad()
self.tableView.addSubview(self.loadingIndicatorView)
self.tableView.dataSource = self.dataSource
NotificationCenter.default
.addObserver(forName: Notification.Name.ksr_sessionStarted, object: nil, queue: nil) { [weak self] _ in
self?.viewModel.inputs.userSessionStarted()
}
NotificationCenter.default
.addObserver(forName: Notification.Name.ksr_sessionEnded, object: nil, queue: nil) { [weak self] _ in
self?.viewModel.inputs.userSessionEnded()
}
let emptyVC = EmptyStatesViewController.configuredWith(emptyState: nil)
self.emptyStatesController = emptyVC
emptyVC.delegate = self
self.addChildViewController(emptyVC)
self.view.addSubview(emptyVC.view)
NSLayoutConstraint.activate([
emptyVC.view.topAnchor.constraint(equalTo: self.view.topAnchor),
emptyVC.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
emptyVC.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
emptyVC.view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
])
emptyVC.didMove(toParentViewController: self)
}
internal override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.viewModel.inputs.viewWillAppear()
}
internal override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.viewModel.inputs.viewDidAppear()
}
internal override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.viewModel.inputs.viewDidDisappear(animated: animated)
}
internal override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.loadingIndicatorView.center = self.tableView.center
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableControllerStyle(estimatedRowHeight: 200.0)
_ = self.loadingIndicatorView
|> UIActivityIndicatorView.lens.hidesWhenStopped .~ true
|> UIActivityIndicatorView.lens.activityIndicatorViewStyle .~ .white
|> UIActivityIndicatorView.lens.color .~ .ksr_navy_900
}
// swiftlint:disable function_body_length
internal override func bindViewModel() {
super.bindViewModel()
self.loadingIndicatorView.rac.animating = self.viewModel.outputs.projectsAreLoading
self.viewModel.outputs.activitiesForSample
.observeForUI()
.observeValues { [weak self] activities in
self?.dataSource.load(activities: activities)
self?.tableView.reloadData()
}
self.viewModel.outputs.asyncReloadData
.observeForUI()
.observeValues { [weak self] in
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
self.viewModel.outputs.goToActivityProject
.observeForControllerAction()
.observeValues { [weak self] in self?.goTo(project: $0, refTag: $1) }
self.viewModel.outputs.goToProjectPlaylist
.observeForControllerAction()
.observeValues { [weak self] in self?.goTo(project: $0, initialPlaylist: $1, refTag: $2) }
self.viewModel.outputs.goToProjectUpdate
.observeForControllerAction()
.observeValues { [weak self] project, update in self?.goTo(project: project, update: update) }
self.viewModel.outputs.projects
.observeForUI()
.observeValues { [weak self] projects in
self?.dataSource.load(projects: projects)
self?.tableView.reloadData()
}
self.viewModel.outputs.showOnboarding
.observeForUI()
.observeValues { [weak self] in
self?.dataSource.show(onboarding: $0)
self?.tableView.reloadData()
}
self.viewModel.outputs.setScrollsToTop
.observeForUI()
.observeValues { [weak self] in
_ = self?.tableView ?|> UIScrollView.lens.scrollsToTop .~ $0
}
self.viewModel.outputs.showEmptyState
.observeForUI()
.observeValues { [weak self] emptyState in
self?.showEmptyState(emptyState)
}
self.viewModel.outputs.hideEmptyState
.observeForUI()
.observeValues { [weak self] in
self?.emptyStatesController?.view.alpha = 0
self?.emptyStatesController?.view.isHidden = true
if let discovery = self?.parent?.parent as? DiscoveryViewController {
discovery.setSortsEnabled(true)
}
}
}
// swiftlint:enable function_body_length
internal override func tableView(_ tableView: UITableView,
willDisplay cell: UITableViewCell,
forRowAt indexPath: IndexPath) {
if let cell = cell as? ActivitySampleBackingCell, cell.delegate == nil {
cell.delegate = self
} else if let cell = cell as? ActivitySampleFollowCell, cell.delegate == nil {
cell.delegate = self
} else if let cell = cell as? ActivitySampleProjectCell, cell.delegate == nil {
cell.delegate = self
} else if let cell = cell as? DiscoveryOnboardingCell, cell.delegate == nil {
cell.delegate = self
}
self.viewModel.inputs.willDisplayRow(self.dataSource.itemIndexAt(indexPath),
outOf: self.dataSource.numberOfItems())
}
internal override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
if let project = self.dataSource.projectAtIndexPath(indexPath) {
self.viewModel.inputs.tapped(project: project)
} else if let activity = self.dataSource.activityAtIndexPath(indexPath) {
self.viewModel.inputs.tapped(activity: activity)
}
}
fileprivate func goTo(project: Project, refTag: RefTag) {
let vc = ProjectNavigatorViewController.configuredWith(project: project, refTag: refTag)
self.present(vc, animated: true, completion: nil)
}
fileprivate func goTo(project: Project, initialPlaylist: [Project], refTag: RefTag) {
let vc = ProjectNavigatorViewController.configuredWith(project: project,
refTag: refTag,
initialPlaylist: initialPlaylist,
navigatorDelegate: self)
self.present(vc, animated: true, completion: nil)
}
fileprivate func goTo(project: Project, update: Update) {
let vc = UpdateViewController.configuredWith(project: project, update: update)
self.navigationController?.pushViewController(vc, animated: true)
}
fileprivate func showEmptyState(_ emptyState: EmptyState) {
guard let emptyVC = self.emptyStatesController else { return }
emptyVC.setEmptyState(emptyState)
emptyVC.view.isHidden = false
self.view.bringSubview(toFront: emptyVC.view)
UIView.animate(withDuration: 0.3, animations: {
self.emptyStatesController?.view.alpha = 1.0
})
if let discovery = self.parent?.parent as? DiscoveryViewController {
discovery.setSortsEnabled(false)
}
}
}
extension DiscoveryPageViewController: ActivitySampleBackingCellDelegate, ActivitySampleFollowCellDelegate,
ActivitySampleProjectCellDelegate {
internal func goToActivity() {
guard let root = self.tabBarController as? RootTabBarViewController else { return }
root.switchToActivities()
}
}
extension DiscoveryPageViewController: DiscoveryOnboardingCellDelegate {
internal func discoveryOnboardingTappedSignUpLoginButton() {
let loginTout = LoginToutViewController.configuredWith(loginIntent: .discoveryOnboarding)
let nav = UINavigationController(rootViewController: loginTout)
nav.modalPresentationStyle = .formSheet
self.present(nav, animated: true, completion: nil)
}
}
extension DiscoveryPageViewController: EmptyStatesViewControllerDelegate {
func emptyStatesViewController(_ viewController: EmptyStatesViewController,
goToDiscoveryWithParams params: DiscoveryParams?) {
self.view.window?.rootViewController
.flatMap { $0 as? RootTabBarViewController }
.doIfSome { $0.switchToDiscovery(params: params) }
}
func emptyStatesViewControllerGoToFriends() {
let vc = FindFriendsViewController.configuredWith(source: .discovery)
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension DiscoveryPageViewController: ProjectNavigatorDelegate {
}
| 35.474903 | 109 | 0.710057 |
dd84e065b43c2bfac246af8590e60cbbd1b290bf | 898 | //
// TableViewCellSeparatorStyle.swift
// ReactantUI
//
// Created by Matouš Hýbl on 09/03/2018.
//
import Foundation
public enum TableViewCellSeparatorStyle: String, EnumPropertyType, AttributeSupportedPropertyType {
public static let enumName = "UITableViewCell.SeparatorStyle"
case none
case singleLine
}
#if canImport(UIKit)
import UIKit
extension TableViewCellSeparatorStyle {
public func runtimeValue(context: SupportedPropertyTypeContext) -> Any? {
#if os(iOS)
switch self {
case .none:
return UITableViewCell.SeparatorStyle.none.rawValue
case .singleLine:
return UITableViewCell.SeparatorStyle.singleLine.rawValue
}
#else
fatalError("UITableViewCellSeparatorStyle is not available on tvOS")
#endif
}
}
#endif
| 25.657143 | 99 | 0.651448 |
8fb6b6e7dd38f725c7f5d42dd4ea9bca3989e381 | 6,483 | //
// VHalfModalDemoView.swift
// VComponentsDemo
//
// Created by Vakhtang Kontridze on 12/30/20.
//
import SwiftUI
import VComponents
// MARK:- V HalfModal Demo View
struct VHalfModalDemoView: View {
// MARK: Properties
static let navBarTitle: String = "Half Modal"
@State private var isPresented: Bool = false
@State private var heightType: VModalHeightTypeHelper = VHalfModalModel.Layout.HeightType.default.helperType
@State private var hasTitle: Bool = true
@State private var dismissType: Set<VHalfModalDismissTypeHelper> = .init(
Set<VHalfModalModel.Misc.DismissType>.default
.filter { $0 != .navigationViewCloseButton }
.map { $0.helperType }
)
@State private var hasDivider: Bool = VHalfModalModel.Layout().headerDividerHeight > 0
private var model: VHalfModalModel {
var model: VHalfModalModel = .init()
model.layout.height = heightType.heightType
model.layout.headerDividerHeight = hasDivider ? (model.layout.headerDividerHeight == 0 ? 1 : model.layout.headerDividerHeight) : 0
model.colors.headerDivider = hasDivider ? (model.colors.headerDivider == .clear ? .gray : model.colors.headerDivider) : .clear
model.misc.dismissType = .init(dismissType.map { $0.dismissType })
return model
}
}
// MARK:- Body
extension VHalfModalDemoView {
var body: some View {
VBaseView(title: Self.navBarTitle, content: {
DemoView(component: component, settings: settings)
})
}
private func component() -> some View {
VSecondaryButton(action: { isPresented = true }, title: "Present")
.if(hasTitle,
ifTransform: {
$0
.vHalfModal(isPresented: $isPresented, halfModal: {
VHalfModal(
model: model,
headerTitle: "Lorem ipsum dolor sit amet",
content: { halfModalContent }
)
})
}, elseTransform: {
$0
.vHalfModal(isPresented: $isPresented, halfModal: {
VHalfModal(
model: model,
content: { halfModalContent }
)
})
}
)
}
@ViewBuilder private func settings() -> some View {
VSegmentedPicker(selection: $heightType, headerTitle: "Height")
ToggleSettingView(isOn: $hasTitle, title: "Title")
VStack(spacing: 3, content: {
VText(type: .oneLine, font: .callout, color: ColorBook.primary, title: "Dismiss Method:")
.frame(maxWidth: .infinity, alignment: .leading)
HStack(content: {
ForEach(VHalfModalDismissTypeHelper.allCases, id: \.rawValue, content: { position in
dimissTypeView(position)
})
})
.frame(maxWidth: .infinity, alignment: .leading)
})
ToggleSettingView(isOn: $hasDivider, title: "Divider")
}
private func dimissTypeView(_ position: VHalfModalDismissTypeHelper) -> some View {
VCheckBox(
isOn: .init(
get: { dismissType.contains(position) },
set: { isOn in
switch isOn {
case false: dismissType.remove(position)
case true: dismissType.insert(position)
}
}
),
title: position.title
)
}
private var halfModalContent: some View {
ZStack(content: {
ColorBook.accent
if dismissType.isEmpty {
VStack(content: {
VText(
type: .multiLine(limit: nil, alignment: .center),
font: .system(size: 14, weight: .semibold),
color: ColorBook.primary,
title: "When close button is \"none\", Half Modal can only be dismissed programatically"
)
VSecondaryButton(action: { isPresented = false }, title: "Dismiss")
})
.frame(maxHeight: .infinity, alignment: .bottom)
.padding(16)
}
})
}
}
// MARK:- Helpers
private enum VModalHeightTypeHelper: Int, VPickableTitledItem {
case fixed
case dynamic
var pickerTitle: String {
switch self {
case .fixed: return "Fixed"
case .dynamic: return "Dynamic"
}
}
var heightType: VHalfModalModel.Layout.HeightType {
switch self {
case .fixed: return .fixed(500)
case .dynamic: return .default
}
}
}
private extension VHalfModalModel.Layout.HeightType {
var helperType: VModalHeightTypeHelper {
switch self {
case .fixed: return .fixed
case .dynamic: return .dynamic
@unknown default: fatalError()
}
}
}
private enum VHalfModalDismissTypeHelper: Int, CaseIterable {
case leading
case trailing
case backTap
case pullDown
var title: String {
switch self {
case .leading: return "Leading"
case .trailing: return "Trailing"
case .backTap: return "Back Tap"
case .pullDown: return "Pull Down"
}
}
var dismissType: VHalfModalModel.Misc.DismissType {
switch self {
case .leading: return .leadingButton
case .trailing: return .trailingButton
case .backTap: return .backTap
case .pullDown: return .pullDown
}
}
}
private extension VHalfModalModel.Misc.DismissType {
var helperType: VHalfModalDismissTypeHelper {
switch self {
case .leadingButton: return .leading
case .trailingButton: return .trailing
case .backTap: return .backTap
case .pullDown: return .pullDown
case .navigationViewCloseButton: fatalError()
@unknown default: fatalError()
}
}
}
// MARK:- Preview
struct VHalfModalDemoView_Previews: PreviewProvider {
static var previews: some View {
VHalfModalDemoView()
}
}
| 32.094059 | 138 | 0.5499 |
5658d63deffc75660137be9eac5dfaecaff2cc74 | 1,794 | //
// FLNetworkManager.swift
// FLMusic_iOS
//
// Created by 冯里 on 2018/5/24.
// Copyright © 2018年 fengli. All rights reserved.
//
import UIKit
import Alamofire
class FLNetworkManager {
static let shareManager = FLNetworkManager()
private let sessionManager: SessionManager
private init() {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 5
sessionManager = Alamofire.SessionManager(configuration: configuration)
}
static func getRequest(url: String, parameters: [String : Any]? = nil, success: ((Any) -> ())? , fail: ((Error) -> ())?) {
let manager = FLNetworkManager.shareManager
manager.sessionManager.request(url, method: .get, parameters: parameters).responseJSON { response in
switch response.result {
case .success(let value):
if let success = success {
success(value)
}
case .failure(let error):
if let fail = fail {
fail(error)
}
}
}
}
static func postRequest(url: String, parameters: [String : Any]? = nil, success: ((Any) -> ())? , fail: ((Error) -> ())?) {
let manager = FLNetworkManager.shareManager
manager.sessionManager.request(url, method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success(let value):
if let success = success {
success(value)
}
case .failure(let error):
if let fail = fail {
fail(error)
}
}
}
}
}
| 30.931034 | 127 | 0.542921 |
227130af7a9829a169e9109a343ebbb01b90760b | 1,271 | import XCTest
import MobilliumDateFormatter
extension Date.Format {
static let dateTime = Date.Format.custom(rawValue: "yyyy-MM-dd HH:mm:ss")
}
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testStringToDate() {
// Value
let dateString = "2001-01-01 01:01:00"
// Create a Date
let date = Date.from(dateString, format: .dateTime)
// Check
XCTAssertNotNil(date)
}
func testDateToString() {
// Value
let date = Date()
// Create a String
let dateString = date.to(.MMMM)
// Check
XCTAssertNotNil(dateString)
}
func testTimeIntervalToString() {
// Value
let timeInterval = TimeInterval(exactly: 1549611277)!
// Create a Date
let date = Date.from(timeInterval)
// Check
XCTAssertNotNil(date)
}
}
| 23.537037 | 111 | 0.56727 |
de4dd00aba5e3177372aa1283eb4bb5d3968b4c7 | 1,235 | //
// TippyUITests.swift
// TippyUITests
//
// Created by Jessica Yeh on 6/20/17.
// Copyright © 2017 Jessica Yeh. All rights reserved.
//
import XCTest
class TippyUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.378378 | 182 | 0.659919 |
bb9e74172aa5000c2d3efa5fdbe406a8137fddbf | 2,191 | //
// ViewController.swift
// iBeaconAPI
//
// Created by Selvaganesh Ilango on 2/25/18.
// Copyright © 2018 Nifty Campaingns. All rights reserved.
//
import UIKit
import CoreLocation
import CoreBluetooth
public class iBeaconController: NSObject, CBPeripheralManagerDelegate {
var localBeacon: CLBeaconRegion!
var beaconPeripheralData: NSDictionary!
var peripheralManager: CBPeripheralManager!
public func startScanning() -> CLBeaconRegion {
let uuid = UUID(uuidString: "2f234454-cf6d-4a0f-adf2-f4911ba9ffa7")!
let beaconRegion = CLBeaconRegion(proximityUUID: uuid, identifier: "MyBeacon")
beaconRegion.notifyEntryStateOnDisplay = true
beaconRegion.notifyOnExit = true
beaconRegion.notifyOnEntry = true
return beaconRegion
}
public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
print("StatusUpdate")
if peripheral.state == .poweredOn {
print("Power On");
peripheralManager.startAdvertising(beaconPeripheralData as! [String: AnyObject]!)
} else if peripheral.state == .poweredOff {
peripheralManager.stopAdvertising()
}
}
public func initLocalBeacon(localBeaconUUID: String, identifier: String) {
if localBeacon != nil {
stopLocalBeacon()
}
//let localBeaconUUID = "5A4BCFCE-174E-4BAC-A814-092E77F6B7E5"
let localBeaconMajor: CLBeaconMajorValue = 123
let localBeaconMinor: CLBeaconMinorValue = 456
let uuid = UUID(uuidString: localBeaconUUID)!
localBeacon = CLBeaconRegion(proximityUUID: uuid, major: localBeaconMajor, minor: localBeaconMinor, identifier: identifier)
beaconPeripheralData = localBeacon.peripheralData(withMeasuredPower: nil)
peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
print("InitLocalBeacon")
}
func stopLocalBeacon() {
peripheralManager.stopAdvertising()
peripheralManager = nil
beaconPeripheralData = nil
localBeacon = nil
}
}
| 32.701493 | 131 | 0.671383 |
e9da442b0f3cc8375c015e6e2c248261f3af27a1 | 2,386 | //
// PersistenceSettingBase.swift
// RxPersistenceSettings
//
// Created by Tomas Friml on 5/04/18.
//
// MIT License
//
// Copyright (c) 2018 Tomas Friml
//
// 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 RxSwift
/// Generic protocol representing persisted setting. Supports meta data, observe changes,
/// increase, decrease value, etc.
public protocol PersistenceSettingBase: class {
/// Title of the setting.
var titleString: String { get }
/// Detailed info for the setting.
var infoString: String { get }
/// Formatted value to be shown in the UI.
var formattedValueString: String { get }
/// Determines if setting is of numerical value (rather than set of distinct values).
var isNumeric: Bool { get }
/// Determine if value is minimal allowed value.
var isAtMin: Bool { get }
/// Determine if value is maximal allowed value.
var isAtMax: Bool { get }
/// Increase the value.
func increase()
/// Increase the value.
func decrease()
/// Observable of formatted value change.
var formattedValueChanged: Observable<String> { get }
}
public extension Reactive where Base: PersistenceSettingBase {
/// Observable of formatted value change.
var formattedValueChanged: Observable<String> {
return base.formattedValueChanged
}
}
| 34.57971 | 89 | 0.718776 |
e6dbc545018e75aec87bfcf82742dafc45c7a8b6 | 235 | func entries<K, V>(fromDictionary dictionary: [K: V]) -> [(key: K, value: V)] {
var result: [(key: K, value: V)] = []
for (key ,value) in dictionary {
result.append((key: key, value: value))
}
return result
}
| 23.5 | 79 | 0.557447 |
5640b06d62af50ed6ee125d5696c93a0d7fc823c | 1,208 | import UIKit
class StartButton: UIButton {
internal override init(frame: CGRect) {
super.init(frame: frame)
}
internal required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public convenience init(window: UIWindow) {
let heightBtn = window.frame.height * 0.4
let widthBtn = heightBtn
self.init(frame: CGRect(x: 0, y: 0, width: widthBtn, height: heightBtn))
self.setImage(UIImage(named: "Images/play"), for: .normal)
self.imageView?.contentMode = .scaleAspectFit
self.center = window.center
let animationBtn = CABasicAnimation(keyPath: "transform.scale")
animationBtn.duration = 1.0
animationBtn.fromValue = 0.92
animationBtn.toValue = 1
animationBtn.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
animationBtn.autoreverses = true
animationBtn.repeatCount = .greatestFiniteMagnitude
self.layer.add(animationBtn, forKey: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
Player.shared.click()
}
}
| 32.648649 | 81 | 0.649007 |
cc0e5392a869492c6c65c0dd59d09740a2921002 | 1,496 | import Foundation
import UIKit
public enum SliderMode: String {
case heating = "Heating"
case cooling = "Cooling"
case fan = "Fan Only"
case auto = "Auto"
case emergency = "Emergency Heat"
case off = "Off"
case geoFencing = "Geo Fencing"
public var color: UIColor {
switch self {
case .heating:
return SliderStateColor.heatingStateColor
case .cooling:
return SliderStateColor.coolingStateColor
case .fan:
return SliderStateColor.fanStateColor
case .auto :
return SliderStateColor.unknownStateColor
case .emergency:
return SliderStateColor.heatingStateColor
case .off:
return SliderStateColor.offStateColor
case .geoFencing:
return SliderStateColor.geoFencingColor
}
}
}
public struct SliderStateColor {
static let heatingStateColor = UIColor.orange
static let coolingStateColor = UIColor.red
static let disabledStateColor = UIColor.gray
static let fanStateColor = UIColor.gray
static let fanStepColor = UIColor.white
static let unknownStateColor = UIColor.white
static let offStateColor = UIColor.clear
static let geoFencingColor = UIColor.white
}
public struct ThumbImageName {
static let verticalImageName = "bubble_vertical"
static let horizontalImageName = "bubble_horizontal"
}
| 30.530612 | 57 | 0.64639 |
0ee4030d4d4974c7913eba3173bec5617f974660 | 222 | //
// Major.swift
// Notissu
//
// Copyright © 2021 Notissu. All rights reserved.
//
import Foundation
struct Major {
var majorCode: DeptCode?
// var majorName: DeptName?
// var majorNameEng: DeptNameEng?
}
| 14.8 | 50 | 0.662162 |
ef8f3fd739ee87cdb710f356440b0867fb556710 | 402 | //
// ViewController.swift
// Budget-macOS
//
// Created by Developer on 23/5/19.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| 14.888889 | 58 | 0.606965 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.