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
|
---|---|---|---|---|---|
f7607ec10d98ccb33582f884655d318e2cfef0fb | 2,229 | //
// AppDelegate.swift
// MLKit Final Project
//
// Created by Sai Kambampati on 5/20/18.
// Copyright © 2018 AppCoda. All rights reserved.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.489796 | 285 | 0.754598 |
e43a866eeb3979bd6f33f87b331cf5dc4648a6fc | 6,133 | import Foundation
// swiftlint:disable type_name
public class lang_kn: RelativeFormatterLang {
/// Kannada
public static let identifier: String = "kn"
public required init() {}
public func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? {
return (value >= 0 && value <= 1 ? .one : .other)
}
public var flavours: [String: Any] {
return [
RelativeFormatter.Flavour.long.rawValue: _long,
RelativeFormatter.Flavour.narrow.rawValue: _narrow,
RelativeFormatter.Flavour.short.rawValue: _short
]
}
private var _short: [String: Any] {
return [
"year": [
"previous": "ಕಳೆದ ವರ್ಷ",
"current": "ಈ ವರ್ಷ",
"next": "ಮುಂದಿನ ವರ್ಷ",
"past": [
"one": "{0} ವರ್ಷದ ಹಿಂದೆ",
"other": "{0} ವರ್ಷಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ವರ್ಷದಲ್ಲಿ",
"other": "{0} ವರ್ಷಗಳಲ್ಲಿ"
]
],
"quarter": [
"previous": "ಕಳೆದ ತ್ರೈಮಾಸಿಕ",
"current": "ಈ ತ್ರೈಮಾಸಿಕ",
"next": "ಮುಂದಿನ ತ್ರೈಮಾಸಿಕ",
"past": [
"one": "{0} ತ್ರೈ.ಮಾ. ಹಿಂದೆ",
"other": "{0} ತ್ರೈಮಾಸಿಕಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ತ್ರೈ.ಮಾ.ದಲ್ಲಿ",
"other": "{0} ತ್ರೈಮಾಸಿಕಗಳಲ್ಲಿ"
]
],
"month": [
"previous": "ಕಳೆದ ತಿಂಗಳು",
"current": "ಈ ತಿಂಗಳು",
"next": "ಮುಂದಿನ ತಿಂಗಳು",
"past": [
"one": "{0} ತಿಂಗಳು ಹಿಂದೆ",
"other": "{0} ತಿಂಗಳುಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ತಿಂಗಳಲ್ಲಿ",
"other": "{0} ತಿಂಗಳುಗಳಲ್ಲಿ"
]
],
"week": [
"previous": "ಕಳೆದ ವಾರ",
"current": "ಈ ವಾರ",
"next": "ಮುಂದಿನ ವಾರ",
"past": [
"one": "{0} ವಾರದ ಹಿಂದೆ",
"other": "{0} ವಾರಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ವಾರದಲ್ಲಿ",
"other": "{0} ವಾರಗಳಲ್ಲಿ"
]
],
"day": [
"previous": "ನಿನ್ನೆ",
"current": "ಇಂದು",
"next": "ನಾಳೆ",
"past": [
"one": "{0} ದಿನದ ಹಿಂದೆ",
"other": "{0} ದಿನಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ದಿನದಲ್ಲಿ",
"other": "{0} ದಿನಗಳಲ್ಲಿ"
]
],
"hour": [
"current": "ಈ ಗಂಟೆ",
"past": [
"one": "{0} ಗಂಟೆ ಹಿಂದೆ",
"other": "{0} ಗಂಟೆಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ಗಂಟೆಯಲ್ಲಿ",
"other": "{0} ಗಂಟೆಗಳಲ್ಲಿ"
]
],
"minute": [
"current": "ಈ ನಿಮಿಷ",
"past": [
"one": "{0} ನಿಮಿಷದ ಹಿಂದೆ",
"other": "{0} ನಿಮಿಷಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ನಿಮಿಷದಲ್ಲಿ",
"other": "{0} ನಿಮಿಷಗಳಲ್ಲಿ"
]
],
"second": [
"current": "ಈಗ",
"past": [
"one": "{0} ಸೆಕೆಂಡ್ ಹಿಂದೆ",
"other": "{0} ಸೆಕೆಂಡುಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ಸೆಕೆಂಡ್ನಲ್ಲಿ",
"other": "{0} ಸೆಕೆಂಡ್ಗಳಲ್ಲಿ"
]
],
"now": "ಈಗ"
]
}
private var _narrow: [String: Any] {
return [
"year": [
"previous": "ಕಳೆದ ವರ್ಷ",
"current": "ಈ ವರ್ಷ",
"next": "ಮುಂದಿನ ವರ್ಷ",
"past": [
"one": "{0} ವರ್ಷದ ಹಿಂದೆ",
"other": "{0} ವರ್ಷಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ವರ್ಷದಲ್ಲಿ",
"other": "{0} ವರ್ಷಗಳಲ್ಲಿ"
]
],
"quarter": [
"previous": "ಕಳೆದ ತ್ರೈಮಾಸಿಕ",
"current": "ಈ ತ್ರೈಮಾಸಿಕ",
"next": "ಮುಂದಿನ ತ್ರೈಮಾಸಿಕ",
"past": [
"one": "{0} ತ್ರೈ.ಮಾ. ಹಿಂದೆ",
"other": "{0} ತ್ರೈಮಾಸಿಕಗಳ ಹಿಂದೆ"
],
"future": "{0} ತ್ರೈಮಾಸಿಕಗಳಲ್ಲಿ"
],
"month": [
"previous": "ಕಳೆದ ತಿಂಗಳು",
"current": "ಈ ತಿಂಗಳು",
"next": "ಮುಂದಿನ ತಿಂಗಳು",
"past": [
"one": "{0} ತಿಂಗಳ ಹಿಂದೆ",
"other": "{0} ತಿಂಗಳುಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ತಿಂಗಳಲ್ಲಿ",
"other": "{0} ತಿಂಗಳುಗಳಲ್ಲಿ"
]
],
"week": [
"previous": "ಕಳೆದ ವಾರ",
"current": "ಈ ವಾರ",
"next": "ಮುಂದಿನ ವಾರ",
"past": [
"one": "{0} ವಾರದ ಹಿಂದೆ",
"other": "{0} ವಾರಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ವಾರದಲ್ಲಿ",
"other": "{0} ವಾರಗಳಲ್ಲಿ"
]
],
"day": [
"previous": "ನಿನ್ನೆ",
"current": "ಇಂದು",
"next": "ನಾಳೆ",
"past": [
"one": "{0} ದಿನದ ಹಿಂದೆ",
"other": "{0} ದಿನಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ದಿನದಲ್ಲಿ",
"other": "{0} ದಿನಗಳಲ್ಲಿ"
]
],
"hour": [
"current": "ಈ ಗಂಟೆ",
"past": [
"one": "{0} ಗಂಟೆ ಹಿಂದೆ",
"other": "{0} ಗಂಟೆಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ಗಂಟೆಯಲ್ಲಿ",
"other": "{0} ಗಂಟೆಗಳಲ್ಲಿ"
]
],
"minute": [
"current": "ಈ ನಿಮಿಷ",
"past": [
"one": "{0} ನಿಮಿಷದ ಹಿಂದೆ",
"other": "{0} ನಿಮಿಷಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ನಿಮಿಷದಲ್ಲಿ",
"other": "{0} ನಿಮಿಷಗಳಲ್ಲಿ"
]
],
"second": [
"current": "ಈಗ",
"past": [
"one": "{0} ಸೆಕೆಂಡ್ ಹಿಂದೆ",
"other": "{0} ಸೆಕೆಂಡುಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ಸೆಕೆಂಡ್ನಲ್ಲಿ",
"other": "{0} ಸೆಕೆಂಡ್ಗಳಲ್ಲಿ"
]
],
"now": "ಈಗ"
]
}
private var _long: [String: Any] {
return [
"year": [
"previous": "ಹಿಂದಿನ ವರ್ಷ",
"current": "ಈ ವರ್ಷ",
"next": "ಮುಂದಿನ ವರ್ಷ",
"past": [
"one": "{0} ವರ್ಷದ ಹಿಂದೆ",
"other": "{0} ವರ್ಷಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ವರ್ಷದಲ್ಲಿ",
"other": "{0} ವರ್ಷಗಳಲ್ಲಿ"
]
],
"quarter": [
"previous": "ಹಿಂದಿನ ತ್ರೈಮಾಸಿಕ",
"current": "ಈ ತ್ರೈಮಾಸಿಕ",
"next": "ಮುಂದಿನ ತ್ರೈಮಾಸಿಕ",
"past": [
"one": "{0} ತ್ರೈಮಾಸಿಕದ ಹಿಂದೆ",
"other": "{0} ತ್ರೈಮಾಸಿಕಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ತ್ರೈಮಾಸಿಕದಲ್ಲಿ",
"other": "{0} ತ್ರೈಮಾಸಿಕಗಳಲ್ಲಿ"
]
],
"month": [
"previous": "ಕಳೆದ ತಿಂಗಳು",
"current": "ಈ ತಿಂಗಳು",
"next": "ಮುಂದಿನ ತಿಂಗಳು",
"past": [
"one": "{0} ತಿಂಗಳ ಹಿಂದೆ",
"other": "{0} ತಿಂಗಳುಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ತಿಂಗಳಲ್ಲಿ",
"other": "{0} ತಿಂಗಳುಗಳಲ್ಲಿ"
]
],
"week": [
"previous": "ಕಳೆದ ವಾರ",
"current": "ಈ ವಾರ",
"next": "ಮುಂದಿನ ವಾರ",
"past": [
"one": "{0} ವಾರದ ಹಿಂದೆ",
"other": "{0} ವಾರಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ವಾರದಲ್ಲಿ",
"other": "{0} ವಾರಗಳಲ್ಲಿ"
]
],
"day": [
"previous": "ನಿನ್ನೆ",
"current": "ಇಂದು",
"next": "ನಾಳೆ",
"past": [
"one": "{0} ದಿನದ ಹಿಂದೆ",
"other": "{0} ದಿನಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ದಿನದಲ್ಲಿ",
"other": "{0} ದಿನಗಳಲ್ಲಿ"
]
],
"hour": [
"current": "ಈ ಗಂಟೆ",
"past": [
"one": "{0} ಗಂಟೆ ಹಿಂದೆ",
"other": "{0} ಗಂಟೆಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ಗಂಟೆಯಲ್ಲಿ",
"other": "{0} ಗಂಟೆಗಳಲ್ಲಿ"
]
],
"minute": [
"current": "ಈ ನಿಮಿಷ",
"past": [
"one": "{0} ನಿಮಿಷದ ಹಿಂದೆ",
"other": "{0} ನಿಮಿಷಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ನಿಮಿಷದಲ್ಲಿ",
"other": "{0} ನಿಮಿಷಗಳಲ್ಲಿ"
]
],
"second": [
"current": "ಈಗ",
"past": [
"one": "{0} ಸೆಕೆಂಡ್ ಹಿಂದೆ",
"other": "{0} ಸೆಕೆಂಡುಗಳ ಹಿಂದೆ"
],
"future": [
"one": "{0} ಸೆಕೆಂಡ್ನಲ್ಲಿ",
"other": "{0} ಸೆಕೆಂಡ್ಗಳಲ್ಲಿ"
]
],
"now": "ಈಗ"
]
}
}
| 18.472892 | 83 | 0.409098 |
01516a16bba154cbcee3794f5d481a20141540b7 | 917 | //
// CombustifierTests.swift
// CombustifierTests
//
// Created by Prakhar Trivedi on 11/12/21.
//
import XCTest
@testable import Combustifier
class CombustifierTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.970588 | 111 | 0.670665 |
0a0e022092523c6af1a2dfa0a6d45914f0995b5b | 1,205 | //
// CallTableViewCell.swift
// ChatMe
//
// Created by Spas Belev on 14.09.18.
// Copyright © 2018 Spas Belev. All rights reserved.
//
import UIKit
class CallTableViewCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var fullNameLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func generateCellWith(call: CallClass) {
dateLabel.text = formatCallTime(date: call.callDate)
statusLabel.text = ""
if call.callerId == User.currentId() {
statusLabel.text = "Outgoing"
fullNameLabel.text = call.withUserFullName
// add avatar if needed but makes it slow
// avatarImageView.image = UIImage(named: "Outgoing")
} else {
statusLabel.text = "Incoming"
fullNameLabel.text = call.callerFullName
// avatarImageView.image = UIImage(named: "Incoming")
}
}
}
| 28.023256 | 65 | 0.631535 |
fb1c660fe3f7a46752415a71477003e137183967 | 1,480 | /*
NSURL-SBAdditions.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
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.
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.
*/
extension NSURL {
var hasWebScheme: Bool {
return NSURLConnection.canHandleRequest(NSURLRequest(URL: self))
}
} | 44.848485 | 79 | 0.802027 |
724797267bbb1c670ace7660b7f5d667459645aa | 11,677 | import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private class RecordWithoutDatabaseTableName: Record { }
private class RecordWithInexistingDatabaseTable: Record {
override class var databaseTableName: String {
return "foo"
}
}
private class RecordWithEmptyPersistentDictionary : Record {
override class var databaseTableName: String {
return "records"
}
}
private class RecordWithNilPrimaryKey : Record {
override class var databaseTableName: String {
return "records"
}
override func encode(to container: inout PersistenceContainer) {
container["id"] = nil
}
}
private class RecordForTableWithoutPrimaryKey : Record {
override class var databaseTableName: String {
return "records"
}
override func encode(to container: inout PersistenceContainer) {
container["name"] = "foo"
}
}
private class RecordForTableWithMultipleColumnsPrimaryKey : Record {
override class var databaseTableName: String {
return "records"
}
override func encode(to container: inout PersistenceContainer) {
container["name"] = "foo"
}
}
private class RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary : Record {
override class var databaseTableName: String {
return "records"
}
override func encode(to container: inout PersistenceContainer) {
container["name"] = "foo"
}
}
class RecordCrashTests: GRDBCrashTestCase {
// =========================================================================
// MARK: - RecordWithoutDatabaseTableName
func testRecordWithoutDatabaseTableNameCanNotBeFetchedByID() {
assertCrash("subclass must override") {
dbQueue.inDatabase { db in
_ = RecordWithoutDatabaseTableName.fetchOne(db, key: 1)
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeFetchedByKey() {
assertCrash("subclass must override") {
dbQueue.inDatabase { db in
_ = RecordWithoutDatabaseTableName.fetchOne(db, key: ["foo": "bar"])
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeInserted() {
assertCrash("subclass must override") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().insert(db)
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeUpdated() {
assertCrash("subclass must override") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().update(db)
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeSaved() {
assertCrash("subclass must override") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().save(db)
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeDeleted() {
assertCrash("subclass must override") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().delete(db)
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeTestedForExistence() {
assertCrash("subclass must override") {
dbQueue.inDatabase { db in
RecordWithoutDatabaseTableName().exists(db)
}
}
}
// =========================================================================
// MARK: - RecordWithInexistingDatabaseTable
func testRecordWithInexistingDatabaseTableCanNotBeFetchedByID() {
assertCrash("no such table: foo") {
dbQueue.inDatabase { db in
_ = RecordWithInexistingDatabaseTable.fetchOne(db, key: 1)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeFetchedByKey() {
assertCrash("SQLite error 1 with statement `SELECT * FROM \"foo\" WHERE (\"id\" = ?)`: no such table: foo") {
dbQueue.inDatabase { db in
_ = RecordWithInexistingDatabaseTable.fetchOne(db, key: ["id": 1])
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeInserted() {
assertCrash("no such table: foo") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().insert(db)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeUpdated() {
assertCrash("no such table: foo") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().update(db)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeSaved() {
assertCrash("no such table: foo") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().save(db)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeDeleted() {
assertCrash("no such table: foo") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().delete(db)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeTestedForExistence() {
assertCrash("no such table: foo") {
dbQueue.inDatabase { db in
RecordWithInexistingDatabaseTable().exists(db)
}
}
}
// =========================================================================
// MARK: - RecordWithEmptyPersistentDictionary
func testRecordWithEmptyPersistentDictionaryCanNotBeInserted() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().insert(db)
}
}
}
func testRecordWithEmptyPersistentDictionaryCanNotBeUpdated() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().update(db)
}
}
}
func testRecordWithEmptyPersistentDictionaryCanNotBeSaved() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().save(db)
}
}
}
func testRecordWithEmptyPersistentDictionaryCanNotBeDeleted() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().delete(db)
}
}
}
func testRecordWithEmptyPersistentDictionaryCanNotBeTestedForExistence() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
RecordWithEmptyPersistentDictionary().exists(db)
}
}
}
// =========================================================================
// MARK: - RecordWithNilPrimaryKey
func testRecordWithNilPrimaryKeyCanNotBeUpdated() {
assertCrash("invalid primary key in <RecordWithNilPrimaryKey id:nil>") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithNilPrimaryKey().update(db)
}
}
}
func testRecordWithNilPrimaryKeyCanNotBeDeleted() {
assertCrash("invalid primary key in <RecordWithNilPrimaryKey id:nil>") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithNilPrimaryKey().delete(db)
}
}
}
func testRecordWithNilPrimaryKeyCanNotBeTestedForExistence() {
assertCrash("invalid primary key in <RecordWithNilPrimaryKey id:nil>") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
RecordWithNilPrimaryKey().exists(db)
}
}
}
// =========================================================================
// MARK: - RecordForTableWithoutPrimaryKey
func testRecordForTableWithoutPrimaryKeyCanNotBeFetchedByID() {
assertCrash("expected single column primary key in table: records") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
_ = RecordForTableWithoutPrimaryKey.fetchOne(db, key: 1)
}
}
}
func testRecordForTableWithoutPrimaryKeyCanNotBeUpdated() {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try RecordForTableWithoutPrimaryKey().update(db)
}
}
}
func testRecordForTableWithoutPrimaryKeyCanNotBeDeleted() {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try RecordForTableWithoutPrimaryKey().delete(db)
}
}
}
func testRecordForTableWithoutPrimaryKeyCanNotBeTestedForExistence() {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
RecordForTableWithoutPrimaryKey().exists(db)
}
}
}
// =========================================================================
// MARK: - RecordForTableWithMultipleColumnsPrimaryKey
func testRecordForTableWithMultipleColumnsPrimaryKeyCanNotBeFetchedByID() {
assertCrash("expected single column primary key in table: records") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (a TEXT, b TEXT, PRIMARY KEY(a,b))")
_ = RecordForTableWithMultipleColumnsPrimaryKey.fetchOne(db, key: 1)
}
}
}
// =========================================================================
// MARK: - RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary
func testRecordWithRowIDPrimaryKeyNotExposedInPersistentDictionaryCanNotBeInserted() {
assertCrash("invalid primary key in <RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY, name TEXT)")
try RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary().update(db)
}
}
}
}
| 35.277946 | 120 | 0.600325 |
20d8b3b198f058f93b59774d16b9be6cada30d49 | 1,056 | //
// NotificationController.swift
// Watch Extension
//
// Created by Alsey Coleman Miller on 8/28/19.
// Copyright © 2019 ColemanCDA. All rights reserved.
//
import WatchKit
import Foundation
import UserNotifications
final class NotificationController: WKUserNotificationInterfaceController {
override init() {
// Initialize variables here.
super.init()
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
override func didReceive(_ notification: UNNotification) {
// This method is called when a notification needs to be presented.
// Implement it if you use a dynamic notification interface.
// Populate your dynamic notification interface as quickly as possible.
}
}
| 27.789474 | 90 | 0.6875 |
ac40c20f62c12686f4e667da56b895c6d574e0f1 | 1,056 | //
// RemoteStorageManager.swift
// 361.Ventures Study Case
//
// Created by Giray UÇAR on 6.01.2022.
//
import Foundation
final class NetworkManager<T : Codable>: NetworkManagerProtocol {
typealias dataType = T
func makeTheRequest(using url: String, completionHandler: @escaping ((Result<T, Error>) -> Void)) {
guard let url = URL(string: url) else {
completionHandler(.failure(NetworkError.badURL))
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if error != nil {
completionHandler(.failure(NetworkError.generalError))
}
if let data = data {
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode(T.self, from: data)
completionHandler(.success(decodedData))
} catch {
completionHandler(.failure(NetworkError.decodingError))
}
}
}.resume()
}
}
| 28.540541 | 103 | 0.558712 |
6ab85379e8a8deadfa673fdfbbdd4214c356ab44 | 4,368 | //
// NewsfeedCellLayoutCalculator.swift
// VKNewsFeed
//
// Created by Алексей Черанёв on 02.09.2021.
//
import UIKit
struct Sizes: FeedCellSizes {
var postLabelFrame: CGRect
var moreTextButtonFrame: CGRect
var attachmentFrame: CGRect
var bottomViewFrame: CGRect
var totalHeight: CGFloat
}
protocol FeedCellLayoutCalculatorProtocol {
func sizes (postText: String?, photoAttachments: [FeedCellPhotoAttachmentViewModel], isFullSizedPost: Bool) -> FeedCellSizes
}
final class FeedCellLayoutCalculator: FeedCellLayoutCalculatorProtocol {
private let screenWidth: CGFloat
init(screenWidth: CGFloat = min(UIScreen.main.bounds.width, UIScreen.main.bounds.height)) {
self.screenWidth = screenWidth
}
func sizes (postText: String?, photoAttachments: [FeedCellPhotoAttachmentViewModel], isFullSizedPost: Bool) -> FeedCellSizes {
var showMoreTextButton = false
let cardViewWidth = screenWidth - Constants.cardInsets.left - Constants.cardInsets.right
//Mark: - Working with postLabelFrame
var postLabelFrame = CGRect(origin: CGPoint(x: Constants.postLabelInsets.left, y: Constants.postLabelInsets.top), size: .zero)
if let text = postText, !text.isEmpty {
let width = cardViewWidth - Constants.postLabelInsets.left - Constants.postLabelInsets.right
var height = text.height(width: width, font: Constants.postLabelFont)
let limitHeight = Constants.postLabelFont.lineHeight * Constants.minifiedPostLimitLines
if !isFullSizedPost && height > limitHeight
{
height = Constants.postLabelFont.lineHeight * Constants.minifiedPostLines
showMoreTextButton = true
}
postLabelFrame.size = CGSize(width: width, height: height)
}
//Mark: - Working with moreTextButtonFrame
var moreTextButtonSize = CGSize.zero
if showMoreTextButton {
moreTextButtonSize = Constants.moreTextButtonSize
}
let moreTextButtonOrigin = CGPoint(x: Constants.moreTextButtonInsets.left, y: postLabelFrame.maxY)
let moreTextButtonFrame = CGRect(origin: moreTextButtonOrigin, size: moreTextButtonSize)
//Mark: - Working with attachmentFrame
let attachmentTop = postLabelFrame.size == CGSize.zero ? Constants.postLabelInsets.top : moreTextButtonFrame.maxY + Constants.postLabelInsets.bottom
var attachmentFrame = CGRect(origin: CGPoint(x: 0, y: attachmentTop), size: CGSize.zero)
if let attachment = photoAttachments.first {
let photoHeight = Float(attachment.height)
let photoWidth = Float(attachment.width)
let ratio = photoHeight / photoWidth
if photoAttachments.count == 1
{
attachmentFrame.size = CGSize(
width: cardViewWidth,
height: cardViewWidth * CGFloat(ratio))
}
else if photoAttachments.count > 1
{
var photos = [CGSize]()
for photo in photoAttachments
{
let photoSize = CGSize(width: CGFloat(photo.width), height: CGFloat(photo.height))
photos.append(photoSize)
}
let rowHeight = RowLayout.rowHeightCounter(superviewWidth: cardViewWidth, photosArray: photos)
attachmentFrame.size = CGSize(width: cardViewWidth, height: rowHeight!)
}
}
//Mark: - Working with bottomViewFrame
let bottomViewTop = postLabelFrame.maxY > attachmentFrame.maxY ? postLabelFrame.maxY : attachmentFrame.maxY + 8
let bottomViewFrame = CGRect(origin: CGPoint(x: 0, y: bottomViewTop), size: CGSize(width: cardViewWidth, height: Constants.bottomViewHeight))
let totalHeight = bottomViewTop + Constants.bottomViewViewHeight + Constants.cardInsets.bottom
return Sizes(postLabelFrame: postLabelFrame, moreTextButtonFrame: moreTextButtonFrame, attachmentFrame: attachmentFrame, bottomViewFrame: bottomViewFrame, totalHeight: totalHeight)
}
}
| 40.82243 | 188 | 0.643315 |
1405f5a97a2c89cdc90b44798d4fab9ec75f5093 | 106 | // RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
#if a
#^A^#
| 21.2 | 92 | 0.698113 |
18a7864b4a42141dfc13ee02d213840ad1a829d7 | 1,419 | //
// MotorMixer.swift
// GoatRobot
//
// Created by Jens Utbult on 2016-03-06.
// Copyright © 2016 Jens Utbult. All rights reserved.
//
import Foundation
struct MotorMixer {
var output: ((left: Float, right: Float) -> Void)?
var steering: Float = 0
var throttle: Float = 0
mutating func setSteering(steering: Float) {
self.steering = steering
generateOutput()
}
mutating func setThrottle(throttle: Float) {
self.throttle = throttle
generateOutput()
}
private func generateOutput() {
print("Mix throttle: \(throttle) + steering: \(steering)")
guard let output = output else { return }
let absThrottle = abs(throttle)
if absThrottle > 0 {
var left = throttle + steering / 2
var right = throttle - steering / 2
if left < 0 {
right -= left
left = 0.1
}
if right < 0 {
left -= right
right = 0.1
}
if left > 1 {
right -= left - 1
left = 1
}
if right > 1 {
left -= right - 1
right = 1
}
output(left: left * throttle.sign(), right: right * throttle.sign())
} else {
output(left: steering, right: -steering)
}
}
} | 25.8 | 80 | 0.485553 |
2fbbe97b221aab6f83d37a4bfdd770ae727e1c96 | 2,189 | //
// ViewController.swift
// Virtual_Tourist
//
// Created by admin on 4/7/19.
// Copyright © 2019 admin. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class PinsMapController: UIViewController, MKMapViewDelegate, NSFetchedResultsControllerDelegate {
//MARK:- Injections from AppDelegate
var dataController: DataController! //injected from AppDelegate
//MARK:- UI Constraints - CONSTANTS
let bottomUILabelHeight: CGFloat = 70
let defaultTitleFontSize: CGFloat = 22
//MARK:- UI Constraints - DYNAMIC
var anchorMapTop_SafeAreaTop: NSLayoutConstraint?
var anchorMapTop_ShiftMapToShowDeletionLabel: NSLayoutConstraint?
var anchorMapBottom_ViewBottom: NSLayoutConstraint?
var anchorMapBottom_ShiftMapToShowDeletionLabel: NSLayoutConstraint?
//MARK:- UI
lazy var deletionLabel: UILabel = {
var label = UILabel()
label.backgroundColor = UIColor.red
let attributes: [NSAttributedString.Key:Any] = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: defaultTitleFontSize),
NSAttributedString.Key.foregroundColor: UIColor.white]
label.attributedText = NSAttributedString(string: "Tap Pins to Delete", attributes: attributes)
label.textAlignment = .center
label.heightAnchor.constraint(equalToConstant: bottomUILabelHeight).isActive = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
//MARK:- Gestures
lazy var myLongPressGesture: UILongPressGestureRecognizer = {
var longGesture = UILongPressGestureRecognizer()
longGesture.minimumPressDuration = 1
longGesture.addTarget(self, action: #selector(handleLongPress(_:)))
return longGesture
}()
var mapView = MKMapView()
var tapDeletesPin = false //determines if deletionLabel is shown in UI
var myFetchController: NSFetchedResultsController<Pin>!
var previousPinID: NSManagedObjectID? //To retreive object prior to changing Pin.coordinates
var delegate: CollectionMapViewControllerDelegate?
var downloadTask: URLSessionTask?
}
| 37.101695 | 103 | 0.723161 |
1d36ece378f4230b7189d3894f0c2baefdc5f76c | 3,257 | //
// Copyright (c) 2014 Justin M Fischer
//
// 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.
//
// Created by JUSTIN M FISCHER on 12/1/14.
// Copyright (c) 2013 Justin M Fischer. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 51.698413 | 285 | 0.759595 |
46b8878b4bf01b3e868dae6f65d1a72d10845639 | 6,762 | //
// EntryTest.swift
// CDAKit
//
// Created by Eric Whitley on 12/14/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
import XCTest
@testable import CDAKit
class EntryTest: XCTestCase {
var entry: CDAKEntry!
override func setUp() {
super.setUp()
// let entry = CDAKEntry()
entry = CDAKEntry()
var codes = CDAKCodedEntries()
let entries: [String:[String]] = [
"SNOMED-CT" : ["1234", "5678", "AABB"],
"LOINC" : ["CCDD", "EEFF"],
"ICD-9-CM" : ["GGHH"]
]
for (system, code_list) in entries {
for code in code_list {
codes.addCodes(system, code: code)
}
}
entry.codes = codes
// 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 test_preferred_code() {
//print(entry.codes)
var preferred_code = entry.preferred_code(["ICD-9-CM"])
XCTAssertEqual("ICD-9-CM", preferred_code!.codeSystem)
XCTAssertEqual("GGHH", preferred_code!.code)
preferred_code = entry.preferred_code(["LOINC"])
XCTAssertEqual("LOINC", preferred_code!.codeSystem)
XCTAssert(["CCDD", "EEFF"].contains(preferred_code!.code))
//sample from the view helper test case
let fields: [String:Any?] = [
"description" : "bacon > cheese",
"time" : 1234,
"codes" : ["CPT" : ["1234"]]
]
let entry_with_no_codes = CDAKEntry(event: fields)
print("preferred codes: ")
print(entry_with_no_codes.preferred_code([], codes_attribute: "codes", value_set_map: []))
print("end")
}
func test_translation_codes() {
let translation_codes = entry.translation_codes(["ICD-9-CM"])
print("test_translation_codes -> translation_codes: \(translation_codes)")
XCTAssertEqual(5, translation_codes.numberOfDistinctCodes)
//print("translation_codes = '\(translation_codes)'")
// XCTAssert(translation_codes.contains({ $0 == ["code_set" : "LOINC", "code" : "CCDD"] }))
// XCTAssert(!translation_codes.contains({ $0 == ["code_set" : "ICD-9-CM", "code" : "GGHH"] }))
XCTAssert(translation_codes.containsCode(withCodeSystem: "LOINC", andCode: "CCDD"))
XCTAssert(!translation_codes.containsCode(withCodeSystem: "ICD-9-CM", andCode: "GGHH"))
}
func test_is_usable() {
let entry = CDAKEntry()
entry.time = 1270598400
entry.add_code("314443004", code_system: "SNOMED-CT")
XCTAssert(entry.usable())
}
// func test_Entry_redo() {
// let hash: [String:Any?] = [
// "code" : 123, "code_set" : "RxNorm",
// "value" : 50, "unit" : "mm",
// "description" : "Test",
// "specifics" : "Specific",
// "status" : "active"
// ]
//
// let entry = CDAKEntry(from_hash: hash)
// print(entry)
//
// }
func test_from_event_hash() {
let hash: [String:Any?] = [
"code" : 123, "code_set" : "RxNorm",
"value" : 50, "unit" : "mm",
"description" : "Test",
"specifics" : "Specific",
"status" : "active"
]
let entry = CDAKEntry(from_hash: hash)
// print(String(hash["code"]!!))
// print(entry.codes[String(hash["code_set"]!!)]!)
// XCTAssertEqual([String(hash["code"]!)], entry.codes[String(hash["code_set"]!!)]!)
XCTAssertEqual([String(describing: hash["code"]!!)], [entry.codes["RxNorm"]!.first!.code])
XCTAssertEqual(String(describing: hash["value"]!!), (entry.values.first as! CDAKPhysicalQuantityResultValue).scalar)
XCTAssertEqual(String(describing: hash["unit"]!!), (entry.values.first as! CDAKPhysicalQuantityResultValue).units)
XCTAssertEqual(String(describing: hash["specifics"]!!), entry.specifics)
XCTAssertEqual(String(describing: hash["status"]!!), entry.status)
}
func test_unusable_without_time() {
let entry = CDAKEntry()
entry.add_code("314443004", code_system: "SNOMED-CT")
XCTAssert(!entry.usable())
}
func test_unusable_without_code() {
let entry = CDAKEntry()
entry.time = 1270598400
XCTAssert(!entry.usable())
}
func test_is_in_code_set() {
let entry = CDAKEntry()
entry.add_code("854935", code_system: "RxNorm")
entry.add_code("44556699", code_system: "RxNorm")
entry.add_code("1245", code_system: "Junk")
var some_codes = CDAKCodedEntries()
some_codes.addCodes("RxNorm", code: "854935")
some_codes.addCodes("RxNorm", code: "5440")
some_codes.addCodes("SNOMED-CT", code: "24601")
XCTAssert(entry.is_in_code_set([some_codes]))
// XCTAssert(entry.is_in_code_set([
// CDAKCodedEntries(entries: ["RxNorm": ["854935", "5440"], "SNOMED-CT" : ["24601"]])
// ]))
}
func test_is_not_in_code_set() {
let entry = CDAKEntry()
entry.add_code("44556699", code_system: "RxNorm")
entry.add_code("1245", code_system: "Junk")
var some_codes = CDAKCodedEntries()
some_codes.addCodes("RxNorm", code: "854935")
some_codes.addCodes("RxNorm", code: "5440")
some_codes.addCodes("SNOMED-CT", code: "24601")
XCTAssert(!entry.is_in_code_set([some_codes]))
// XCTAssert(!entry.is_in_code_set([
// CDAKCodedEntries(entries: ["RxNorm": ["854935", "5440"], "SNOMED-CT" : ["24601"]])
// ]))
}
func test_equality() {
let entry1 = CDAKEntry()
entry1.add_code("44556699", code_system: "RxNorm")
entry1.time = 1270598400
let entry2 = CDAKEntry()
entry2.add_code("44556699", code_system: "RxNorm")
entry2.time = 1270598400
let entry3 = CDAKEntry()
entry3.add_code("44556699", code_system: "RxNorm")
entry3.time = 1270598401
XCTAssertEqual(entry1, entry2)
XCTAssertEqual(entry2, entry1)
XCTAssert(entry2 != entry3)
XCTAssert(entry1 != entry3)
}
//removing this - will be removing this functionality and moving to JSON
/*
func test_to_hash() {
let entry = CDAKEntry()
entry.add_code("44556699", code_system: "RxNorm")
entry.time = 1270598400
entry.specifics = "specific"
let h = entry.to_hash()
print("test_to_hash h: \(h)")
XCTAssertEqual(1270598400, h["time"]! as? Double)
XCTAssert((h["codes"]! as! [String:[String]])["RxNorm"]!.contains("44556699"))
// XCTAssert((h["codes"]! as! [String:[String]])["RxNorm"]!.contains("44556699"))
}
*/
func test_identifier_id() {
let entry = CDAKEntry()
XCTAssertEqual(entry.id, entry.identifier as? String)
}
func test_identifier_cda_identifier() {
let identifier = CDAKCDAIdentifier(root: "1.2.3.4")
entry.cda_identifier = identifier
XCTAssertEqual(identifier, entry.identifier as? CDAKCDAIdentifier)
}
}
| 31.451163 | 120 | 0.641822 |
ab78b23350db1414ed882c3e32a326fb40132aaf | 33,873 | /*
* Copyright (c) 2020 Elastos Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
/**
* The interface to indicate how to get local did document, if this did is not published to chain.
*/
@objc(DIDBackend)
public class DIDBackend: NSObject {
private let TAG = NSStringFromClass(DIDBackend.self)
/// The default initial capacity for the resolve cache.
private static let DEFAULT_CACHE_INITIAL_CAPACITY = 16
/// The default maximum capacity for the resolve cache.
private static let DEFAULT_CACHE_MAX_CAPACITY = 64
/// The default cache T
private static let DEFAULT_CACHE_TTL = 10 * 60 * 1000
private var _random: String = ""
private static let TAG = NSStringFromClass(DIDBackend.self)
private var _adapter: DIDAdapter
public typealias ResolveHandle = (_ did: DID) -> DIDDocument?
// private var resolveHandle: ResolveHandle?
private var resolveHandle: LocalResolveHandle?
private static var instance: DIDBackend?
private var cache: LRUCache<ResolveRequest, ResolveResult>
class TransactionResult: NSObject {
private var _transactionId: String?
private var _status: Int
private var _message: String?
private var _filled: Bool
private let _semaphore: DispatchSemaphore
override init() {
self._status = 0
self._filled = false
self._semaphore = DispatchSemaphore(value: 0)
}
func update(_ transactionId: String, _ status: Int, _ message: String?) {
self._transactionId = transactionId
self._status = status
self._message = message
self._filled = true
self._semaphore.signal()
}
func update(_ transactionId: String) {
update(transactionId, 0, nil)
}
var transactionId: String {
return _transactionId!
}
var status: Int {
return _status
}
var message: String? {
return _message
}
var isEmpty: Bool {
return !_filled
}
override var description: String {
var str = ""
str.append("txid: ")
str.append(transactionId)
str.append("status: ")
str.append(String(status))
if status != 0 {
str.append("message: ")
str.append(message!)
}
return str
}
}
class DefaultResolver: NSObject, DIDResolver {
private var url: URL
init(_ resolver: String) throws {
guard !resolver.isEmpty else {
throw DIDError.UncheckedError.IllegalArgumentErrors.IllegalUsageError("resolver is empty")
}
url = URL(string: resolver)!
}
func resolve(_ requestId: String, _ did: String, _ all: Bool) throws -> Data {
Log.i(TAG, "Resolving {}...\(did.description)")
var request = URLRequest.init(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let parameters: [String: Any] = [
"jsonrpc": "2.0",
"method": "resolvedid",
"params": ["did":did, "all": all],
"id": requestId
]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch {
throw DIDError.UncheckedError.IllegalArgumentErrors.DataParsingError(error.localizedDescription)
}
let semaphore = DispatchSemaphore(value: 0)
var errDes: String?
var result: Data?
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let _ = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
errDes = error.debugDescription
semaphore.signal()
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
errDes = "Server eror (status code: \(response.statusCode)"
semaphore.signal()
return
}
result = data
semaphore.signal()
}
task.resume()
semaphore.wait()
guard let _ = result else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError(errDes ?? "Unknown error")
}
return result!
}
}
/// Construct a DIDBackend instance with the adapter and the cache specification.
/// - Parameters:
/// - adapter: a DIDAdapter implementation
/// - initialCacheCapacity: the initial cache size
/// - maxCacheCapacity: the maximum cache capacity
/// - cacheTtl: the live time for the cached entries
init(_ adapter: DIDAdapter, _ initialCacheCapacity: Int, _ maxCacheCapacity: Int, _ cacheTtl: Int) {
self._adapter = adapter
cache = LRUCache<ResolveRequest, ResolveResult>(initialCacheCapacity, maxCacheCapacity)
}
/// Initialize the DIDBackend with the given adapter and the cache specification.
/// - Parameter adapter: a DIDAdapter implementation
public class func initialize(_ adapter: DIDAdapter, _ initialCacheCapacity: Int, _ maxCacheCapacity: Int, _ cacheTtl: Int) throws {
try checkArgument(initialCacheCapacity <= maxCacheCapacity, "Invalid cache capacity")
let c = initialCacheCapacity < maxCacheCapacity ? initialCacheCapacity : maxCacheCapacity
instance = DIDBackend(adapter, c, maxCacheCapacity, cacheTtl)
}
/// Initialize the DIDBackend with the given adapter and the cache specification.
/// - Parameters:
/// - adapter: a DIDAdapter implementation
/// - maxCacheCapacity: the initial cache size
/// - cacheTtl: the maximum cache capacity
public class func initialize(_ adapter: DIDAdapter, _ maxCacheCapacity: Int, _ cacheTtl: Int) throws {
instance = DIDBackend(adapter, DEFAULT_CACHE_INITIAL_CAPACITY, maxCacheCapacity, cacheTtl)
}
/// Initialize the DIDBackend with the adapter and the cache specification.
/// - Parameters:
/// - adapter: a DIDAdapter implementation
/// - cacheTtl: the maximum cache capacity
public class func initialize(_ adapter: DIDAdapter, _ cacheTtl: Int) throws {
instance = DIDBackend(adapter, DEFAULT_CACHE_INITIAL_CAPACITY, DEFAULT_CACHE_MAX_CAPACITY, cacheTtl)
}
/// Initialize the DIDBackend with the adapter and the cache specification.
/// - Parameters:
/// - adapter: a DIDAdapter implementation
public class func initialize(_ adapter: DIDAdapter) throws {
instance = DIDBackend(adapter, DEFAULT_CACHE_INITIAL_CAPACITY, DEFAULT_CACHE_MAX_CAPACITY, DEFAULT_CACHE_TTL)
}
/// Get the previous initialized DIDBackend instance.
/// - Returns: the DIDBackend instance
@objc
public class func sharedInstance() throws -> DIDBackend {
if (instance == nil) {
throw DIDError.UncheckedError.IllegalStateError.IllegalStateError("DIDBackend not initialized.")
}
return instance!
}
/// Check if the DIDBackend already initialized.
/// - Returns: the DIDBackend initialized or not
public class func isInitialized() -> Bool {
return instance != nil
}
private func generateRequestId() -> String {
var requestId = ""
while requestId.count < 32 {
let randomStr = Int.decTohex(number: Int.randomCustom(min: 0, max: 32))
requestId.append(randomStr)
}
return requestId
}
var adapter: DIDAdapter {
return _adapter
}
public func setResolveHandle(_ handle: LocalResolveHandle) {
resolveHandle = handle
}
private func resolve(_ request: ResolveRequest) throws -> ResolveResult{
Log.d(TAG, "Resolving request ", request, "...")
let requestJson = request.serialize(true)
let re = try adapter.resolve(requestJson)
guard re.count > 0 else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Unknown error, got nil result.")
}
var response = ResolveResponse()
switch request.method {
case DIDResolveRequest.METHOD_NAME: do {
response = try DIDResolveResponse.deserialize(re)
break
}
case CredentialResolveRequest.METHOD_NAME: do {
response = try CredentialResolveResponse.deserialize(re)
break
}
case CredentialListRequest.METHOD_NAME: do {
response = try CredentialListResponse.deserialize(re)
break
}
default:
Log.e(TAG, "INTERNAL - unknown resolve method ", request.method)
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Unknown resolve method: \(request.method)")
}
if response.result != nil {
return response.result!
}
else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Server error: \(String(describing: response.errorCode)): \(String(describing: response.errorMessage))")
}
}
private func resolveDidBiography(_ did: DID, _ all: Bool, _ force: Bool) throws -> DIDBiography {
Log.i(TAG, "Resolving DID \(did.toString())", all, "=...")
let request = DIDResolveRequest(generateRequestId())
request.setParameters(did, all)
if force {
cache.removeValue(for: request)
}
let semaphore = DispatchSemaphore(value: 1)
var bio = cache.getValue(for: request)
if bio == nil {
bio = try resolve(request)
semaphore.signal()
}
semaphore.wait()
return bio as! DIDBiography
}
/// Resolve all transactions for a specific DID.
/// - Parameter did: the DID object to be resolve
/// - Returns: the DIDBiography object
func resolveDidBiography(_ did: DID) throws -> DIDBiography? {
let biography = try resolveDidBiography(did, true, false)
if biography.status == DIDBiographyStatus.STATUS_NOT_FOUND {
return nil
}
return biography
}
/// Resolve the specific DID.
/// - Parameters:
/// - did: the DID object to be resolve
/// - force: ignore the local cache and resolve from the ID chain if true;
/// try to use cache first if false.
/// - Returns: the DIDDocument object
func resolveDid(_ did: DID, _ force: Bool) throws -> DIDDocument? {
Log.d(TAG, "Resolving DID ", did.toString(), "...")
if resolveHandle != nil {
let doc = try resolveHandle!.resolve(did)
guard doc == nil else {
return doc
}
}
let bio = try resolveDidBiography(did, false, force)
var tx: DIDTransaction?
switch bio.status {
case .STATUS_VALID:
tx = bio.getTransaction(0)
break
case .STATUS_DEACTIVATED:
guard bio.count == 2 else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid DID biography, wrong transaction count.")
}
tx = bio.getTransaction(0)
guard tx?.request.operation == IDChainRequestOperation.DEACTIVATE else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid DID biography, wrong status.")
}
let doc = bio.getTransaction(1).request.document
guard doc != nil else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid DID biography, invalid trancations.")
}
// Avoid resolve current DID recursively
tx!.request._doc = tx!.request.document == nil ? doc : tx!.request.document!
let request = DIDRequest(tx!.request)
guard try request.isValid() else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid DID biography, transaction signature mismatch.")
}
tx = bio.getTransaction(1)
break
case .STATUS_NOT_FOUND:
return nil
default:
return nil
}
if tx?.request.operation != IDChainRequestOperation.CREATE && tx?.request.operation != IDChainRequestOperation.UPDATE && tx?.request.operation != IDChainRequestOperation.TRANSFER {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid ID transaction, unknown operation.")
}
if try (tx == nil || !tx!.request.isValid()) {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid ID transaction, signature mismatch.")
}
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
let doc = try tx!.request.document?.clone()
if let _ = doc {
let metadata = doc!.getMetadata()
metadata.setTransactionId(tx!.getTransactionId())
metadata.setSignature(doc!.proof.signature)
metadata.setPublishTime(tx!.getTimestamp())
if bio.status == DIDBiographyStatus.STATUS_DEACTIVATED {
metadata.setDeactivated(true)
}
doc!.setMetadata(metadata)
}
return doc
}
/// Resolve the specific DID.
/// - Parameter did: the DID object to be resolve
/// - Returns: the DIDDocument object
func resolveDid(_ did: DID) throws -> DIDDocument? {
return try resolveDid(did, false)
}
// TODO: to be remove in the future
public func resolveUntrustedDid(_ did: DID, _ force: Bool) throws -> DIDDocument? {
Log.d(TAG, "Resolving untrusted DID \(did.toString())...")
if (resolveHandle != nil) {
let doc = try resolveHandle!.resolve(did)
if (doc != nil) {
return doc!
}
}
let bio = try resolveDidBiography(did, false, force)
var tx: DIDTransaction? = nil
switch (bio.status) {
case .STATUS_VALID:
tx = bio.getTransaction(0)
break
case .STATUS_DEACTIVATED:
if (bio.count != 2) {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid DID biography, wrong transaction count.")
}
tx = bio.getTransaction(0)
if (tx?.request.operation != IDChainRequestOperation.DEACTIVATE) {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid DID biography, wrong status.")
}
let doc = bio.getTransaction(1).request.document
if (doc == nil) {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid DID biography, invalid trancations.")
}
tx = bio.getTransaction(1)
break
case .STATUS_NOT_FOUND:
return nil
default:
return nil
}
if (tx?.request.operation != IDChainRequestOperation.CREATE &&
tx?.request.operation != IDChainRequestOperation.UPDATE &&
tx?.request.operation != IDChainRequestOperation.TRANSFER) {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid ID transaction, unknown operation.")
}
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
let doc = try tx?.request.document!.clone()
let metadata = doc?.getMetadata()
metadata?.setTransactionId(tx!.getTransactionId())
metadata?.setSignature(doc?.proof.signature)
metadata?.setPublishTime(tx!.timestamp)
if (bio.status == DIDBiographyStatus.STATUS_DEACTIVATED) {
metadata?.setDeactivated(true)
}
return doc
}
private func resolveCredentialBiography(_ id: DIDURL, _ issuer: DID?, _ force: Bool) throws -> CredentialBiography {
Log.i(TAG, "Resolving credential ", id, ", issuer=\(String(describing: issuer))")
let request = CredentialResolveRequest(generateRequestId())
if issuer == nil {
request.setParameters(id)
}
else {
request.setParameters(id, issuer!)
}
if force {
cache.removeValue(for: request)
}
return try cache.getValue(for: request) { () -> ResolveResult? in
return try resolve(request)
} as! CredentialBiography
}
/// Resolve the all the credential transactions.
///
/// If the credential already declared on the ID chain, this method will
/// return all credential transactions include the revoke transaction.
/// The issuer parameter will be ignored in this case.
///
/// If the credential not declared on the ID chain, this method will
/// return the revoke transactions from the credential owner if it exists;
/// If an issuer DID is given, this method also will return the revoke
/// transactions from the given issuer if it exists
///
/// - Parameters:
/// - id: the credential id
/// - issuer: an optional issuer'd DID
/// - Throws: DIDResolveError if an error occurred when resolving the credential
/// - Returns: a CredentialBiography object
func resolveCredentialBiography(_ id: DIDURL, _ issuer: DID) throws -> CredentialBiography? {
return try resolveCredentialBiography(id, issuer, false)
}
/// Resolve the all the credential transactions.
///
/// If the credential already declared on the ID chain, this method will
/// return all credential transactions include the revoke transaction.
///
/// If the credential not declared on the ID chain, this method will
/// return the revoke transactions from the credential owner if it exists.
///
/// - Parameter id: the credential id
/// - Throws: DIDResolveError if an error occurred when resolving the credential
/// - Returns: a CredentialBiography object
func resolveCredentialBiography(_ id: DIDURL) throws -> CredentialBiography? {
return try resolveCredentialBiography(id, nil, false)
}
private func resolveCredential(id: DIDURL, issuer: DID?, force: Bool) throws -> VerifiableCredential? {
Log.d(TAG, "Resolving credential ", id)
let bio = try resolveCredentialBiography(id, issuer, force)
var tx: CredentialTransaction?
switch bio.status {
case .STATUS_VALID:
tx = bio.getTransaction(0)
break
case .STATUS_REVOKED:
tx = bio.getTransaction(0)
guard tx?.request.operation == IDChainRequestOperation.REVOKE else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid credential biography, wrong status.")
}
if bio.count < 1, bio.count > 2 {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid credential biography, transaction signature mismatch.")
}
guard bio.count != 1 else {
guard try tx!.request.isValid() else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid credential biography, transaction signature mismatch.")
}
return nil
}
let vc = bio.getTransaction(1).request.credential
// Avoid resolve current credential recursively
tx!.request.vc = tx!.request.credential == nil ? vc : tx!.request.credential!
let request = CredentialRequest(tx!.request)
guard try request.isValid() else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid credential biography, transaction signature mismatch.")
}
tx = bio.getTransaction(1)
break
case .STATUS_NOT_FOUND:
return nil
default:
return nil
}
guard tx!.request.operation == IDChainRequestOperation.DECLARE else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid credential transaction, unknown operation.")
}
guard try (tx!.request.isValid()) else {
throw DIDError.CheckedError.DIDBackendError.DIDResolveError("Invalid credential transaction, signature mismatch.")
}
let vc = tx!.request.credential
let metadata = CredentialMetadata(vc!.id!)
metadata.setTransactionId(tx!.getTransactionId())
metadata.setPublishTime(tx!.getTimestamp())
if (bio.status == CredentialBiographyStatus.STATUS_REVOKED) {
metadata.setRevoked(true)
}
vc!.setMetadata(metadata)
return vc
}
/// Resolve the specific credential.
/// - Parameters:
/// - id: the credential id
/// - issuer: an optional issuer'd DID
/// - force: ignore the local cache and resolve from the ID chain if true;
/// try to use cache first if false.
/// - Throws: DIDResolveError if an error occurred when resolving the credential
/// - Returns: the VerifiableCredential object
func resolveCredential(_ id: DIDURL, _ issuer: DID, _ force: Bool) throws -> VerifiableCredential? {
try resolveCredential(id: id, issuer: issuer, force: force)
}
/// Resolve the specific credential.
/// - Parameters:
/// - id: the credential id
/// - issuer: an optional issuer'd DID
/// - Throws: DIDResolveError if an error occurred when resolving the credential
/// - Returns: the VerifiableCredential object
func resolveCredential(_ id: DIDURL, _ issuer: DID) throws -> VerifiableCredential? {
return try resolveCredential(id: id, issuer: issuer, force: false)
}
/// Resolve the specific credential.
/// - Parameters:
/// - id: the credential id
/// - force: ignore the local cache and resolve from the ID chain if true;
/// try to use cache first if false.
/// - Throws: DIDResolveError if an error occurred when resolving the credential
/// - Returns: the VerifiableCredential object
func resolveCredential(_ id: DIDURL, _ force: Bool) throws -> VerifiableCredential? {
return try resolveCredential(id: id, issuer: nil, force: force)
}
/// Resolve the specific credential.
/// - Parameter id: the credential id
/// - Throws: DIDResolveError if an error occurred when resolving the credential
/// - Returns: the VerifiableCredential object
func resolveCredential(_ id: DIDURL) throws -> VerifiableCredential? {
return try resolveCredential(id: id, issuer: nil, force: false)
}
/// List the declared credentials that owned by the specific DID from
/// the ID chain.
/// - Parameters:
/// - did: the target DID
/// - skip: set to skip N credentials ahead in this request
/// (useful for pagination).
/// - limit: set the limit of credentials returned in the request
/// (useful for pagination).
/// - Throws: DIDResolveError
/// - Returns: an array of DIDURL denoting the credentials
func listCredentials(_ did: DID, _ skip: Int, _ limit: Int) throws -> [DIDURL] {
Log.i(TAG, "List credentials for ", did)
let request = CredentialListRequest(generateRequestId())
request.setParameters(did, skip, limit)
let list = try resolve(request) as? CredentialList
guard let _ = list, list!.count != 0 else {
return [ ]
}
return list!.credentialIds
}
private func createTransaction(_ request: IDChainRequest, _ adapter: DIDTransactionAdapter?) throws {
Log.i(TAG, "Create ID transaction...")
let payload = request.serialize(true)
Log.i(TAG, "Transaction paload: '", payload, "', memo: ")
var _adapter = adapter
if _adapter == nil {
_adapter = self.adapter
}
try _adapter!.createIdTransaction(payload, nil)
Log.i(TAG, "ID transaction complete.")
}
private func invalidDidCache(_ did: DID) {
let request = DIDResolveRequest(generateRequestId())
request.setParameters(did, true)
cache.removeValue(for: request)
request.setParameters(did, false)
cache.removeValue(for: request)
}
private func invalidCredentialCache(_ id: DIDURL, _ signer: DID?) {
let request = CredentialResolveRequest(generateRequestId())
if signer != nil {
request.setParameters(id, signer!)
cache.removeValue(for: request)
}
request.setParameters(id)
cache.removeValue(for: request)
}
/// Clear all data that cached by this DIDBackend instance.
public func clearCache() {
cache.clear()
}
/// Publish a new DID creation transaction to the ID chain.
/// - Parameters:
/// - doc: the DIDDocument object to be publish
/// - signKey: the key to sign the transaction
/// - storePassword: the password for DIDStore
/// - throws DIDTransactionError if an error when publish the transaction
/// - throws DIDStoreError if an error occurred when accessing the store
func createDid(_ doc: DIDDocument, _ signKey: DIDURL, _ storePassword: String, _ adapter: DIDTransactionAdapter?) throws {
let request = try DIDRequest.create(doc, signKey, storePassword)
try createTransaction(request, adapter)
invalidDidCache(doc.subject)
}
/// Publish a DID update transaction to the ID chain.
/// - Parameters:
/// - doc: the DIDDocument object to be update
/// - previousTxid: the previous transaction id string
/// - signKey: the key to sign the transaction
/// - storePassword: the password for DIDStore
/// - throws DIDTransactionError if an error when publish the transaction
/// - throws DIDStoreError if an error occurred when accessing the store
func updateDid(_ doc: DIDDocument, _ previousTxid: String, _ signKey: DIDURL, _ storePassword: String, _ adapter: DIDTransactionAdapter?) throws {
let request = try DIDRequest.update(doc, previousTxid, signKey, storePassword)
try createTransaction(request, adapter)
invalidDidCache(doc.subject)
}
/// Publish a customized DID transfer transaction to the ID chain.
/// - Parameters:
/// - doc: the new DIDDocument object after transfer
/// - ticket: the valid TransferTicket object
/// - signKey: the key to sign the transaction
/// - storePassword: the password for DIDStore
/// - adapter: a DIDTransactionAdapter instance or null for default
/// - Throws: DIDTransactionError if an error when publish the transaction
/// - Throws DIDStoreError if an error occurred when accessing the store
func transferDid(_ doc: DIDDocument, _ ticket: TransferTicket, _ signKey: DIDURL, _ storePassword: String, _ adapter: DIDTransactionAdapter?) throws {
let request = try DIDRequest.transfer(doc, ticket, signKey, storePassword)
try createTransaction(request, adapter)
invalidDidCache(doc.subject)
}
/// Publish a DID deactivate transaction to the ID chain.
/// - Parameters:
/// - doc: the DIDDocument object to be deactivate
/// - signKey: the key to sign the transaction
/// - storePassword: the password for DIDStore
/// - DIDTransactionException if an error when publish the transaction
/// - Throws DIDStoreError if an error occurred when accessing the store
func deactivateDid(_ doc: DIDDocument, _ signKey: DIDURL, _ storePassword: String, _ adapter: DIDTransactionAdapter?) throws {
let request = try DIDRequest.deactivate(doc, signKey, storePassword)
try createTransaction(request, adapter)
invalidDidCache(doc.subject)
}
/// Publish a DID deactivate transaction to the ID chain.
/// - Parameters:
/// - target: the target DIDDocument object to be deactivate
/// - targetSignKey: the authorization key of the target DIDDocument
/// - signer: the authorized DID document by the target DID
/// - signKey: the key to sign the transaction
/// - storePassword: the password for DIDStore
/// - adapter: a DIDTransactionAdapter instance or null for default
/// - Throws DIDTransactionExrror if an error when publish the transaction
/// - Throws DIDStoreError if an error occurred when accessing the store
func deactivateDid(_ target: DIDDocument, _ targetSignKey: DIDURL, _ signer: DIDDocument, _ signKey: DIDURL, _ storePassword: String, _ adapter: DIDTransactionAdapter?) throws {
let request = try DIDRequest.deactivate(target, targetSignKey, signer, signKey, storePassword)
try createTransaction(request, adapter)
invalidDidCache(target.subject)
}
/// Publish a credential declare transaction to the ID chain.
/// - Parameters:
/// - vc: a VerifiableCredential object to be declared
/// - signer: the credential controller's DIDDocument
/// - signKey: the key to sign the transaction
/// - storePassword: the password for DIDStore
/// - adapter: a DIDTransactionAdapter instance or null for default
/// - Throws: DIDTransactionError if an error when publish the transaction
/// - Throws DIDStoreError if an error occurred when accessing the store
func declareCredential(_ vc: VerifiableCredential, _ signer: DIDDocument, _ signKey: DIDURL, _ storePassword: String, _ adapter: DIDTransactionAdapter?) throws {
let request = try CredentialRequest.declare(vc, signer, signKey, storePassword)
try createTransaction(request, adapter)
invalidCredentialCache(vc.getId()!, nil)
invalidCredentialCache(vc.getId()!, vc.issuer)
}
/// Publish a credential revoke transaction to the ID chain.
/// - Parameters:
/// - vc: a VerifiableCredential object to be revoke
/// - signer: the credential controller or issuer's DIDDocument
/// - signKey: the key to sign the transaction
/// - storePassword: the password for DIDStore
/// - adapter: a DIDTransactionAdapter instance or null for default
/// - Throws: DIDTransactionError if an error when publish the transaction
/// - Throws DIDStoreError if an error occurred when accessing the store
func revokeCredential(_ vc: VerifiableCredential, _ signer: DIDDocument, _ signKey: DIDURL, _ storePassword: String, _ adapter: DIDTransactionAdapter?) throws {
let request = try CredentialRequest.revoke(vc, signer, signKey, storePassword)
try createTransaction(request, adapter)
invalidCredentialCache(vc.getId()!, nil)
invalidCredentialCache(vc.getId()!, vc.issuer)
}
/// Publish a credential revoke transaction to the ID chain.
/// - Parameters:
/// - vc: a VerifiableCredential id to be revoke
/// - signer: the credential controller or issuer's DIDDocument
/// - signKey: the key to sign the transaction
/// - storePassword: the password for DIDStore
/// - adapter: a DIDTransactionAdapter instance or null for default
/// - Throws: DIDTransactionError if an error when publish the transaction
/// - Throws DIDStoreError if an error occurred when accessing the store
func revokeCredential(_ vc: DIDURL, _ signer: DIDDocument, _ signKey: DIDURL, _ storePassword: String, _ adapter: DIDTransactionAdapter?) throws {
let request = try CredentialRequest.revoke(vc, signer, signKey, storePassword)
try createTransaction(request, adapter)
invalidCredentialCache(vc, nil)
invalidCredentialCache(vc, signer.subject)
}
}
| 43.260536 | 188 | 0.634724 |
4a2642c12c8d852769ff7ee84dc2b91cb0843455 | 329 | //
// File.swift
//
//
// Created by Aafaq on 08/12/2021.
//
import UIKit
extension UINavigationController {
public func popToViewController(ofClass: AnyClass, animated: Bool = true) {
if let vc = viewControllers.last(where: { $0.isKind(of: ofClass) }) {
popToViewController(vc, animated: animated)
}
}
}
| 19.352941 | 77 | 0.665653 |
69df7b629b93f3cc417180182662e11c965e4fab | 6,907 | //
// HAFKakaObject.swift
// Kaka
//
// Created by Jovi on 8/12/18.
// Copyright © 2018 Jovi. All rights reserved.
//
import Cocoa
enum UserActionType: Int {
case eLeftBtnClick
case eRightBtnClick
case eDoubleClick
case eDragToRightMargin
case eDragFromRightMargin
case eDragToTopMargin
case eDragFromTopMargin
case eExit
}
enum KakaStateType {
case eKakaStateNormal
case eKakaStateDragging
case eKakaStateHidden
}
class HAFKakaObject: NSObject {
var _state: KakaStateType
var _animationSequence: HAFAnimationSequence?
var _nextAnimationSequences: [HAFAnimationSequence]
var _nCurrentFrameCount: Int
var _nCurrentFrameIndex: Int
var _view: HAFAnimationView?
override init() {
_state = .eKakaStateNormal
_nextAnimationSequences = [HAFAnimationSequence]()
_animationSequence = HAFAnimationManager.sharedManager.happy
_nCurrentFrameCount = _animationSequence!.frameCount()
_nCurrentFrameIndex = 0
_view = nil
super.init()
}
func setAnimationView(_ view: HAFAnimationView) -> Void {
_view = view
_view?.setKakaObj(self)
_view?.stopPlaying()
_view?.startToPlay()
}
func skipCurrentAnimationSequenceChain() -> Void {
_view?.isHidden = true
if 0 == _nextAnimationSequences.count {
_animationSequence = tolerantAandomAnimationSequence()
}else{
_animationSequence = _nextAnimationSequences.remove(at: 0)
}
_nCurrentFrameCount = _animationSequence!.frameCount()
_nCurrentFrameIndex = 0
}
func doAction(actionType: UserActionType, clearFlag: Bool) -> Void {
if clearFlag {
_nextAnimationSequences.removeAll()
}
switch _state {
case .eKakaStateNormal:
handleUserActionInNormalState(actionType)
break
case .eKakaStateDragging:
handleUserActionInDraggingState(actionType)
break
case .eKakaStateHidden:
handleUserActionInHiddenState(actionType)
break
}
}
func currentAnimationFrame() -> NSImage? {
if nil != _animationSequence && _nCurrentFrameIndex < _nCurrentFrameCount {
return _animationSequence!.frameAtIndex(_nCurrentFrameIndex)
}
return nil
}
func currentAnimationAudio() -> URL? {
if nil != _animationSequence {
let audio = _animationSequence!.audio()
if audio.1 == _nCurrentFrameIndex{
return audio.0
}
}
return nil
}
func moveToNextAnimationFrame() -> Void {
if 0 == _nCurrentFrameIndex{
_view?.isHidden = false
}
_nCurrentFrameIndex += 1;
if _nCurrentFrameIndex < _nCurrentFrameCount {
return;
}
if nil != _animationSequence!.nextAnimationSequence{
_animationSequence = _animationSequence!.nextAnimationSequence
}else{
if 0 == _nextAnimationSequences.count {
_animationSequence = tolerantAandomAnimationSequence()
}else{
_animationSequence = _nextAnimationSequences.remove(at: 0)
}
}
_nCurrentFrameCount = _animationSequence!.frameCount()
_nCurrentFrameIndex = 0
}
func randomAnimationSequence() -> HAFAnimationSequence {
var rslt = HAFAnimationManager.sharedManager.randomAnimationSequence()
switch _state {
case .eKakaStateNormal:
break
case .eKakaStateDragging:
rslt = HAFAnimationManager.sharedManager.drag2
break
case .eKakaStateHidden:
rslt = HAFAnimationManager.sharedManager.hidden1
if 0 == arc4random_uniform(2){
rslt = HAFAnimationManager.sharedManager.hidden3
}
break
}
return rslt
}
func tolerantAandomAnimationSequence() -> HAFAnimationSequence {
var rslt: HAFAnimationSequence? = nil
var nTry: Int = 0
repeat{
rslt = randomAnimationSequence()
nTry += 1
}while _animationSequence == rslt && nTry <= 2
return rslt!
}
private func handleUserActionInNormalState(_ actionType: UserActionType) -> Void {
switch actionType {
case .eLeftBtnClick:
_nextAnimationSequences.append(tolerantAandomAnimationSequence())
break
case .eRightBtnClick:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.eatWatermelon)
break
case .eDoubleClick:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.grimace)
break
case .eDragToRightMargin:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.hidden1)
_state = .eKakaStateHidden
break
case .eDragFromRightMargin:
break
case .eDragToTopMargin:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.drag1)
_state = .eKakaStateDragging
break
case .eDragFromTopMargin:
break
case .eExit:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.bye)
break
}
}
private func handleUserActionInDraggingState(_ actionType: UserActionType) -> Void {
switch actionType {
case .eDragToRightMargin:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.hidden1)
_state = .eKakaStateHidden
break
case .eDragFromTopMargin:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.drag3)
_state = .eKakaStateNormal
break
case .eExit:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.bye)
break
default:
break
}
}
private func handleUserActionInHiddenState(_ actionType: UserActionType) -> Void {
switch actionType {
case .eDoubleClick:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.hidden3)
break
case .eDragFromRightMargin:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.hidden5)
_state = .eKakaStateNormal
break
case .eDragToTopMargin:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.drag1)
_state = .eKakaStateDragging
break
case .eExit:
_nextAnimationSequences.append(HAFAnimationManager.sharedManager.bye)
break
default:
break
}
}
}
| 31.683486 | 91 | 0.625163 |
e8562c4ab7d0ab337277f4643a5ac34f0fe26661 | 6,498 | //
// AccountsTableViewController.swift
// BudgetApp
//
// Created by Andrew Harris on 7/12/16.
// Copyright © 2016 AndrewFHarris. All rights reserved.
//
import UIKit
class AccountsTableViewController: UITableViewController {
/**
Shows a black loading view while fetchAccounts() is waiting
- Returns: Void
*/
func showLoadingView() {
if self.loadingView == nil {
// load layout
let loadingView = NSBundle.mainBundle().loadNibNamed("LoadingView", owner: self, options: nil).first as? UIView
// set frame equal to parent view frame (for sizing)
loadingView?.frame = self.view.frame
// allow auto resizing
loadingView?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.loadingView = loadingView
}
self.view.addSubview(self.loadingView!)
}
func removeLoadingView() {
// quickly fade out loadingView, then destroy
UIView.animateWithDuration(0.5, animations: {
self.loadingView?.alpha = CGFloat(0)
}, completion: {(completion:Bool) -> Void in
self.loadingView?.removeFromSuperview()
self.loadingView = nil
})
}
// MARK: - Properties
var accounts: NSArray? = nil
var loadingView: UIView?
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
self.fetchAuthors()
// hide empty cells with a footerView
self.tableView.tableFooterView = UIView()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func fetchAuthors() {
let accounts: NSMutableArray = NSMutableArray()
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let url = NSURL(string: "http://andrew-mbp:5000/api/accounts")
// show loading view
self.showLoadingView()
if url != nil {
let req = NSURLRequest(URL: url!)
let task = session.dataTaskWithRequest(req) {(data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
print(data)
if data != nil {
do {
let arr = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.init(rawValue: 0)) as? NSArray
if arr != nil {
for obj in arr! {
accounts.addObject(Account(obj: obj as! NSDictionary))
}
self.accounts = accounts
self.tableView.reloadData()
}
} catch let parseError {
print("Error: \(parseError)")
}
}
self.removeLoadingView() // remove loading view
})
}
task.resume()
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if self.accounts != nil {
return self.accounts!.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let account = self.accounts?[indexPath.row] as? Account
let cell = tableView.dequeueReusableCellWithIdentifier("account_cell", forIndexPath: indexPath)
// Configure the cell...
cell.backgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1.0);
cell.textLabel?.text = account?.nickname
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
/**
@brief Pass the selected Account model to DetailView controller
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let index = self.tableView.indexPathForSelectedRow?.row
if index != nil {
let account = self.accounts?.objectAtIndex(index!) as! Account
let destController = segue.destinationViewController as! AccountDetailViewController
destController.account = account
}
}
}
| 35.900552 | 157 | 0.600646 |
67385844c34c7d823452143d4e15689ad4e4008e | 283 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class c<d {
class a<D> : a {
protocol a {
struct c == B
}
struct c
| 20.214286 | 87 | 0.710247 |
9008b92c5f51cd1383c2b8f56f65823e42369e73 | 2,387 | //
// ViewController.swift
// Task12
//
// Created by Егор Зайнуллин on 09.01.2022.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
private var characters: [Character] = []
@IBOutlet weak var tableView: UITableView!
private var rowNumber: Int = 0
private var isAppeared = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (!isAppeared) {
Loader.loadCharacters(completion: { characters in
self.characters = characters
self.tableView.reloadData()
})
isAppeared = true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? CharacterViewController {
vc.character = characters[rowNumber]
debugPrint("Prepare")
print(rowNumber)
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return characters.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterTableViewCell") as! CharacterTableViewCell
let i = indexPath.row
cell.nameLabel.text = characters[i].name
cell.statusLabel.text = characters[i].status + " - " + characters[i].species
cell.planetLabel.text = characters[i].origin.name
cell.lastKnownLocationLabel.text = characters[i].location.name
let url = URL(string: characters[i].image)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
cell.characterImageView.image = UIImage(data: data!)
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("selected")
rowNumber = indexPath.row
self.performSegue(withIdentifier: "toCharacterSegue", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
}
| 30.602564 | 117 | 0.638877 |
4afb582834bf5e5fb6cec7fd9ab1113df74c1f92 | 2,187 | //
// AppDelegate.swift
// BluemixMobileServicesDemoApp
//
// Created by Conan Gammel on 7/5/16.
// Copyright © 2016 Conan Gammel. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//TODO put JSON here
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.531915 | 285 | 0.754458 |
2892844dc14bb49eb3e6055ce9ca85967baa5073 | 6,431 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// BufferTests.swift
//
import UIKit
import XCTest
class BufferTests: XCTestCase {
// On instancie deux objets de type Parameter
let paramPer = ATParam("model", value:{"[apple]-[ipad4,4]"}, type: .String)
let paramVol = ATParam("p", value: {"home"}, type: .String)
// On instancie deux tableaux contenant des objets de type Parameter
let arrayPer = NSMutableArray(objects:
ATParam("key0p", value: {"value0p"}, type: .String), ATParam("key1p", value: {"value1p"}, type: .String))
let arrayVol = NSMutableArray(objects:
ATParam("key0v", value: {"value0v"}, type: .String), ATParam("key1v", value: {"value1v"}, type: .String))
// Instance de buffer utilisée pour les tests
let buffer = ATBuffer(tracker: ATTracker(["log":"logp", "logSSL":"logs", "domain":"xiti.com", "pixelPath":"/hit.xiti", "site":"549808", "secure":"false", "identifier":"uuid"]))
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
// On vérifie qu'il est possible d'ajouter un paramètre persistant dans le buffer
func testAddParamPer() {
buffer.persistentParameters.addObject(paramPer)
XCTAssertEqual(buffer.persistentParameters.count, 15, "persistentParameters doit contenir un élément")
}
// On vérifie qu'il est possible d'ajouter un paramètre volatile dans le buffer
func testAddParamVol() {
buffer.volatileParameters.addObject(paramVol)
XCTAssertEqual(buffer.volatileParameters.count, 1, "volatileParameters doit contenir un élément")
}
// On vérifie qu'il est possible de récupérer un paramètre persistant depuis le buffer
func testGetParamPer() {
buffer.persistentParameters.addObject(paramPer)
let param = buffer.persistentParameters[14] as! ATParam
var testOK = true
if (param.key != paramPer.key || param.value() != paramPer.value()) {
testOK = false
}
XCTAssert(testOK, "param et paramPer doivent avoir la même valeur pour key et value")
}
// On vérifie qu'il est possible de récupérer un paramètre volatile depuis le buffer
func testGetParamVol() {
buffer.volatileParameters.addObject(paramVol)
let param = buffer.volatileParameters[0] as! ATParam
var testOK = true
if (param.key != paramVol.key || param.value() != paramVol.value()) {
testOK = false
}
XCTAssert(testOK, "param et paramVol doivent avoir la même valeur pour key et value")
}
// On vérifie qu'il est possible d'affecter un tableau de paramètres persistants
func testAddArrayPer() {
buffer.persistentParameters = arrayPer
XCTAssertEqual(buffer.persistentParameters.count, 2, "persistentParameters doit contenir deux éléments")
}
// On vérifie qu'il est possible d'affecter un tableau de paramètres volatiles
func testAddArrayVol() {
buffer.volatileParameters = arrayVol
XCTAssertEqual(buffer.volatileParameters.count, 2, "volatileParameters doit contenir deux éléments")
}
// On vérifie qu'il est possible de récupérer le tableau de paramètres persistants
func testGetArrayPer() {
buffer.persistentParameters = arrayPer
var testOK = true
var i = 0
for param in buffer.persistentParameters {
let tRefParam = param as! ATParam
let tTestParam = arrayPer[i] as! ATParam
if (tRefParam.key != tTestParam.key || tRefParam.value() != tTestParam.value()) {
testOK = false
}
i += 1
}
if (buffer.persistentParameters.count != arrayPer.count) {
testOK = false
}
XCTAssert(testOK, "persistentParameters et arrayPer doivent être identiques")
}
// On vérifie qu'il est possible de récupérer le tableau de paramètres volatiles
func testGetArrayVol() {
buffer.volatileParameters = arrayVol
var testOK = true
var i = 0
for param in buffer.volatileParameters {
let tRefParam = param as! ATParam
let tTestParam = arrayVol[i] as! ATParam
if (tRefParam.key != tTestParam.key || tRefParam.value() != tTestParam.value()) {
testOK = false
}
i += 1
}
if (buffer.volatileParameters.count != arrayVol.count) {
testOK = false
}
XCTAssert(testOK, "volatileParameters et arrayVol doivent être identiques")
}
// On vérifie qu'il est possible d'instancier plusieurs fois Buffer
func testMultiInstance() {
let buffer1 = ATBuffer(tracker: ATTracker(
["log":"logp", "logSSL":"logs", "domain":"xiti.com", "pixelPath":"/hit.xiti", "site":"549808", "secure":"false", "identifier":"uuid"]))
let buffer2 = ATBuffer(tracker: ATTracker(
["log":"logp", "logSSL":"logs", "domain":"xiti.com", "pixelPath":"/hit.xiti", "site":"549808", "secure":"false", "identifier":"uuid"]))
XCTAssert(buffer1 !== buffer2, "buffer1 et buffer2 ne doivent pas pointer vers la même référence")
}
}
| 42.03268 | 180 | 0.66817 |
08c64d1d729b7a5a08797f16f3a0b494fbab9885 | 17,155 | // Copyright SIX DAY LLC. All rights reserved.
import Foundation
import web3swift
import BigInt
// swiftlint:disable type_body_length
enum RPCServer: Hashable, CaseIterable {
case main
case kovan
case ropsten
case rinkeby
case poa
case sokol
case classic
case callisto
case xDai
case goerli
case artis_sigma1
case artis_tau1
case custom(CustomRPC)
var chainID: Int {
switch self {
case .main: return 1
case .kovan: return 42
case .ropsten: return 3
case .rinkeby: return 4
case .poa: return 99
case .sokol: return 77
case .classic: return 61
case .callisto: return 104729
case .xDai: return 100
case .goerli: return 5
case .artis_sigma1: return 246529
case .artis_tau1: return 246785
case .custom(let custom):
return custom.chainID
}
}
var name: String {
switch self {
case .main: return "Ethereum"
case .kovan: return "Kovan"
case .ropsten: return "Ropsten"
case .rinkeby: return "Rinkeby"
case .poa: return "POA Network"
case .sokol: return "Sokol"
case .classic: return "Ethereum Classic"
case .callisto: return "Callisto"
case .xDai: return "xDai"
case .goerli: return "Goerli"
case .artis_sigma1: return "ARTIS sigma1"
case .artis_tau1: return "ARTIS tau1"
case .custom(let custom):
return custom.name
}
}
var isTestnet: Bool {
switch self {
case .xDai, .classic, .main, .poa, .callisto:
return false
case .kovan, .ropsten, .rinkeby, .sokol, .goerli, .artis_sigma1, .artis_tau1, .custom:
return true
}
}
var getEtherscanURL: String? {
switch self {
case .main: return Constants.mainnetEtherscanAPI
case .ropsten: return Constants.ropstenEtherscanAPI
case .rinkeby: return Constants.rinkebyEtherscanAPI
case .kovan: return Constants.kovanEtherscanAPI
case .poa: return Constants.poaNetworkCoreAPI
case .sokol: return nil
case .classic: return Constants.classicEtherscanAPI
case .callisto: return nil
case .goerli: return Constants.goerliEtherscanAPI
case .xDai: return Constants.xDaiAPI
case .artis_sigma1: return nil
case .artis_tau1: return nil
case .custom: return nil
}
}
//TODO fix up all the networks
var getEtherscanURLERC20Events: String? {
switch self {
case .main: return Constants.mainnetEtherscanAPIErc20Events
case .ropsten: return Constants.ropstenEtherscanAPIErc20Events
case .rinkeby: return Constants.rinkebyEtherscanAPIErc20Events
case .kovan: return Constants.kovanEtherscanAPIErc20Events
case .poa: return Constants.poaNetworkCoreAPIErc20Events
case .sokol: return nil
case .classic: return Constants.classicAPIErc20Events
case .callisto: return nil
case .goerli: return Constants.goerliEtherscanAPIErc20Events
case .xDai: return Constants.xDaiAPIErc20Events
case .artis_sigma1: return nil
case .artis_tau1: return nil
case .custom: return nil
}
}
var etherscanContractDetailsWebPageURL: String {
switch self {
case .main: return Constants.mainnetEtherscanContractDetailsWebPageURL
case .ropsten: return Constants.ropstenEtherscanContractDetailsWebPageURL
case .rinkeby: return Constants.rinkebyEtherscanContractDetailsWebPageURL
case .kovan: return Constants.kovanEtherscanContractDetailsWebPageURL
case .xDai: return Constants.xDaiContractPage
case .goerli: return Constants.goerliContractPage
case .poa: return Constants.poaContractPage
case .sokol: return Constants.sokolContractPage
case .classic: return Constants.etcContractPage
case .callisto: return Constants.callistoContractPage
case .artis_sigma1: return Constants.artisSigma1ContractPage
case .artis_tau1: return Constants.artisTau1ContractPage
case .custom: return Constants.mainnetEtherscanContractDetailsWebPageURL
}
}
func etherscanAPIURLForTransactionList(for address: AlphaWallet.Address) -> URL? {
return getEtherscanURL.flatMap { URL(string: "\($0)\(address.eip55String)&apikey=\(Constants.Credentials.etherscanKey)") }
}
func etherscanAPIURLForERC20TxList(for address: AlphaWallet.Address) -> URL? {
return getEtherscanURLERC20Events.flatMap { URL(string: "\($0)\(address.eip55String)&apikey=\(Constants.Credentials.etherscanKey)") }
}
func etherscanContractDetailsWebPageURL(for address: AlphaWallet.Address) -> URL {
return URL(string: etherscanContractDetailsWebPageURL + address.eip55String)!
}
var priceID: AlphaWallet.Address {
switch self {
case .main, .ropsten, .rinkeby, .kovan, .sokol, .custom, .xDai, .goerli, .artis_sigma1, .artis_tau1:
return AlphaWallet.Address(string: "0x000000000000000000000000000000000000003c")!
case .poa:
return AlphaWallet.Address(string: "0x00000000000000000000000000000000000000AC")!
case .classic:
return AlphaWallet.Address(string: "0x000000000000000000000000000000000000003D")!
case .callisto:
return AlphaWallet.Address(string: "0x0000000000000000000000000000000000000334")!
}
}
var displayName: String {
if isTestNetwork {
return "\(name) (\(R.string.localizable.settingsNetworkTestLabelTitle()))"
} else {
return name
}
}
var isTestNetwork: Bool {
switch self {
case .main, .poa, .classic, .callisto, .custom, .xDai, .artis_sigma1: return false
case .kovan, .ropsten, .rinkeby, .sokol, .goerli, .artis_tau1: return true
}
}
var symbol: String {
switch self {
case .main: return "ETH"
case .classic: return "ETC"
case .callisto: return "CLO"
case .kovan, .ropsten, .rinkeby: return "ETH"
case .poa, .sokol: return "POA"
case .xDai: return "xDai"
case .goerli: return "ETH"
case .artis_sigma1, .artis_tau1: return "ATS"
case .custom(let custom):
return custom.symbol
}
}
var cryptoCurrencyName: String {
switch self {
case .main, .classic, .callisto, .kovan, .ropsten, .rinkeby, .poa, .sokol, .goerli, .custom:
return "Ether"
case .xDai:
return "xDai"
case .artis_sigma1, .artis_tau1:
return "ATS"
}
}
var decimals: Int {
return 18
}
var web3Network: Networks {
switch self {
case .main: return .Mainnet
case .kovan: return .Kovan
case .ropsten: return .Ropsten
case .rinkeby: return .Rinkeby
case .poa, .sokol, .classic, .callisto, .xDai, .goerli, .artis_sigma1, .artis_tau1:
return .Custom(networkID: BigUInt(chainID))
case .custom:
return .Custom(networkID: BigUInt(chainID))
}
}
var magicLinkPrefix: URL {
let urlString = "https://\(magicLinkHost)/"
return URL(string: urlString)!
}
var magicLinkHost: String {
switch self {
case .main:
return Constants.mainnetMagicLinkHost
case .kovan:
return Constants.kovanMagicLinkHost
case .ropsten:
return Constants.ropstenMagicLinkHost
case .rinkeby:
return Constants.rinkebyMagicLinkHost
case .poa:
return Constants.poaMagicLinkHost
case .sokol:
return Constants.sokolMagicLinkHost
case .classic:
return Constants.classicMagicLinkHost
case .callisto:
return Constants.callistoMagicLinkHost
case .goerli:
return Constants.goerliMagicLinkHost
case .xDai:
return Constants.xDaiMagicLinkHost
case .artis_sigma1:
return Constants.artisSigma1MagicLinkHost
case .artis_tau1:
return Constants.artisTau1MagicLinkHost
case .custom:
return Constants.customMagicLinkHost
}
}
var rpcURL: URL {
let urlString: String = {
switch self {
case .main: return "https://mainnet.infura.io/v3/\(Constants.Credentials.infuraKey)"
case .classic: return "https://www.ethercluster.com/etc"
case .callisto: return "https://callisto.network/" //TODO Add endpoint
case .kovan: return "https://kovan.infura.io/v3/\(Constants.Credentials.infuraKey)"
case .ropsten: return "https://ropsten.infura.io/v3/\(Constants.Credentials.infuraKey)"
case .rinkeby: return "https://rinkeby.infura.io/v3/\(Constants.Credentials.infuraKey)"
case .poa: return "https://core.poa.network"
case .sokol: return "https://sokol.poa.network"
case .goerli: return "https://goerli.infura.io/v3/\(Constants.Credentials.infuraKey)"
case .xDai: return "https://dai.poa.network"
case .artis_sigma1: return "https://rpc.sigma1.artis.network"
case .artis_tau1: return "https://rpc.tau1.artis.network"
case .custom(let custom):
return custom.endpoint
}
}()
return URL(string: urlString)!
}
var transactionInfoEndpoints: URL {
let urlString: String = {
switch self {
case .main: return "https://api-cn.etherscan.com"
case .classic: return "https://blockscout.com/etc/mainnet/api"
case .callisto: return "https://callisto.trustwalletapp.com"
case .kovan: return "https://api-kovan.etherscan.io"
case .ropsten: return "https://api-ropsten.etherscan.io"
case .rinkeby: return "https://api-rinkeby.etherscan.io"
case .poa: return "https://blockscout.com/poa/core/api"
case .xDai: return "https://blockscout.com/poa/dai/api"
case .sokol: return "https://blockscout.com/poa/sokol/api"
case .goerli: return "https://api-goerli.etherscan.io"
case .artis_sigma1: return "https://explorer.sigma1.artis.network/api"
case .artis_tau1: return "https://explorer.tau1.artis.network/api"
case .custom:
return "" // Enable? make optional
}
}()
return URL(string: urlString)!
}
var ensRegistrarContract: AlphaWallet.Address {
switch self {
case .main: return Constants.ENSRegistrarAddress
case .ropsten: return Constants.ENSRegistrarRopsten
case .rinkeby: return Constants.ENSRegistrarRinkeby
case .goerli: return Constants.ENSRegistrarGoerli
case .xDai, .kovan, .poa, .sokol, .classic, .callisto, .artis_sigma1, .artis_tau1, .custom:
return Constants.ENSRegistrarAddress
}
}
var networkRequestsQueuePriority: Operation.QueuePriority {
switch self {
case .main, .xDai:
return .normal
case .kovan, .ropsten, .rinkeby, .poa, .sokol, .classic, .callisto, .goerli, .artis_sigma1, .artis_tau1, .custom:
return .low
}
}
var blockChainName: String {
switch self {
case .xDai:
return R.string.localizable.blockchainXDAI()
case .artis_sigma1:
return R.string.localizable.blockchainARTISSigma1()
case .artis_tau1:
return R.string.localizable.blockchainARTISTau1()
case .main, .rinkeby, .ropsten, .custom, .callisto, .classic, .kovan, .sokol, .poa, .goerli:
return R.string.localizable.blockchainEthereum()
}
}
var blockChainNameColor: UIColor {
switch self {
case .main: return .init(red: 41, green: 134, blue: 175)
case .classic: return .init(red: 55, green: 137, blue: 55)
case .callisto: return .init(red: 88, green: 56, blue: 163)
case .kovan: return .init(red: 112, green: 87, blue: 141)
case .ropsten, .custom: return .init(red: 255, green: 74, blue: 141)
case .rinkeby: return .init(red: 246, green: 195, blue: 67)
case .poa: return .init(red: 88, green: 56, blue: 163)
case .sokol: return .init(red: 107, green: 53, blue: 162)
case .goerli: return .init(red: 187, green: 174, blue: 154)
case .xDai: return .init(red: 253, green: 176, blue: 61)
case .artis_sigma1: return .init(red: 83, green: 162, blue: 113)
case .artis_tau1: return .init(red: 249, green: 117, blue: 153)
}
}
var transactionDataCoordinatorType: SingleChainTransactionDataCoordinator.Type {
switch self {
case .main, .classic, .callisto, .kovan, .ropsten, .custom, .rinkeby, .poa, .sokol, .goerli, .xDai, .artis_sigma1, .artis_tau1:
return SingleChainTransactionEtherscanDataCoordinator.self
}
}
var iconImage: UIImage? {
switch self {
case .main:
return R.image.eth()!
case .xDai:
return R.image.xDai()!
case .poa:
return R.image.tokenPoa()!
case .classic:
return R.image.tokenEtc()!
case .callisto:
return R.image.tokenCallisto()!
case .artis_sigma1:
return R.image.tokenArtis()!
case .kovan, .ropsten, .rinkeby, .sokol, .goerli, .artis_tau1, .custom:
return nil
}
}
init(name: String) {
self = {
switch name {
case RPCServer.main.name: return .main
case RPCServer.classic.name: return .classic
case RPCServer.callisto.name: return .callisto
case RPCServer.kovan.name: return .kovan
case RPCServer.ropsten.name: return .ropsten
case RPCServer.rinkeby.name: return .rinkeby
case RPCServer.poa.name: return .poa
case RPCServer.sokol.name: return .sokol
case RPCServer.xDai.name: return .xDai
case RPCServer.goerli.name: return .goerli
case RPCServer.artis_sigma1.name: return .artis_sigma1
case RPCServer.artis_tau1.name: return .artis_tau1
default: return .main
}
}()
}
init(chainID: Int) {
self = {
switch chainID {
case RPCServer.main.chainID: return .main
case RPCServer.classic.chainID: return .classic
case RPCServer.callisto.chainID: return .callisto
case RPCServer.kovan.chainID: return .kovan
case RPCServer.ropsten.chainID: return .ropsten
case RPCServer.rinkeby.chainID: return .rinkeby
case RPCServer.poa.chainID: return .poa
case RPCServer.sokol.chainID: return .sokol
case RPCServer.xDai.chainID: return .xDai
case RPCServer.goerli.chainID: return .goerli
case RPCServer.artis_sigma1.chainID: return .artis_sigma1
case RPCServer.artis_tau1.chainID: return .artis_tau1
default: return .main
}
}()
}
init?(withMagicLinkHost magicLinkHost: String) {
var server: RPCServer? = {
switch magicLinkHost {
case RPCServer.main.magicLinkHost: return .main
case RPCServer.classic.magicLinkHost: return .classic
case RPCServer.callisto.magicLinkHost: return .callisto
case RPCServer.kovan.magicLinkHost: return .kovan
case RPCServer.ropsten.magicLinkHost: return .ropsten
case RPCServer.rinkeby.magicLinkHost: return .rinkeby
case RPCServer.poa.magicLinkHost: return .poa
case RPCServer.sokol.magicLinkHost: return .sokol
case RPCServer.xDai.magicLinkHost: return .xDai
case RPCServer.goerli.magicLinkHost: return .goerli
case RPCServer.artis_sigma1.magicLinkHost: return .artis_sigma1
case RPCServer.artis_tau1.magicLinkHost: return .artis_tau1
default: return nil
}
}()
//Special case to support legacy host name
if magicLinkHost == Constants.legacyMagicLinkHost {
server = .main
}
guard let createdServer = server else { return nil }
self = createdServer
}
init?(withMagicLink url: URL) {
guard let host = url.host, let server = RPCServer(withMagicLinkHost: host) else { return nil }
self = server
}
//We'll have to manually new cases here
static var allCases: [RPCServer] {
return [
.main,
.kovan,
.ropsten,
.rinkeby,
.poa,
.sokol,
.classic,
.xDai,
.goerli,
.artis_sigma1,
.artis_tau1
]
}
}
// swiftlint:enable type_body_length
| 37.869757 | 141 | 0.618595 |
1a9ff84c7d043100c90291a72fc2be2d0ab89ec7 | 231 | //
// Word+CoreDataClass.swift
// Gaffiot
//
// Created by Benoît Frisch on 23/10/2017.
// Copyright © 2017 Benoît Frisch. All rights reserved.
//
//
import Foundation
import CoreData
public class Word: NSManagedObject {
}
| 13.588235 | 56 | 0.701299 |
c17e7c8d19f38587938b77a7e26a53d11e0a7826 | 1,729 | //
// TabBarController.swift
// WeatherTest
//
// Created by Daniel Kouba on 15/02/15.
// Copyright (c) 2015 Daniel Kouba. All rights reserved.
//
import UIKit
class TabBarController: UITabBarController , UITabBarControllerDelegate {
@IBOutlet var locationButton: UIBarButtonItem!
var locations = DI.context.locations
var settings = DI.context.settings
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
// MARK: - Navigation
func nextTab()
{
if let itemCount = tabBar.items?.count {
selectedIndex = (selectedIndex+1) % itemCount
}
}
func prevTab()
{
if let itemCount = tabBar.items?.count {
let index = selectedIndex==0 ? itemCount : selectedIndex
selectedIndex = index-1
}
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
func showLocationVC(sender:AnyObject)
{
self.performSegueWithIdentifier("locations", sender: sender)
}
//MARK: - UITabBarControllerDelegate
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
if ( viewController is SettingsViewController ) {
self.navigationItem.rightBarButtonItem = nil
} else {
if ( self.navigationItem.rightBarButtonItem == nil ) {
self.navigationItem.rightBarButtonItem = locationButton
}
}
}
}
| 24.7 | 123 | 0.617698 |
0ef393f23d7cc07d8d5a85459b5247114927a664 | 5,291 | import AdaptiveCards_bridge
import AppKit
class RichTextBlockRenderer: NSObject, BaseCardElementRendererProtocol {
static let shared = RichTextBlockRenderer()
func render(element: ACSBaseCardElement, with hostConfig: ACSHostConfig, style: ACSContainerStyle, rootView: ACRView, parentView: NSView, inputs: [BaseInputHandler], config: RenderConfig) -> NSView {
guard let richTextBlock = element as? ACSRichTextBlock else {
logError("Element is not of type ACSRichTextBlock")
return NSView()
}
let textView = ACRTextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isEditable = false
textView.textContainer?.lineFragmentPadding = 0
textView.textContainerInset = .zero
textView.layoutManager?.usesFontLeading = false
textView.setContentHuggingPriority(.required, for: .vertical)
textView.backgroundColor = .clear
let linkAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: config.hyperlinkColorConfig.foregroundColor,
NSAttributedString.Key.underlineColor: config.hyperlinkColorConfig.underlineColor,
NSAttributedString.Key.underlineStyle: config.hyperlinkColorConfig.underlineStyle.rawValue,
NSAttributedString.Key.cursor: NSCursor.pointingHand
]
textView.linkTextAttributes = linkAttributes
// init content
let content = NSMutableAttributedString()
// parsing through the inlines
for inline in richTextBlock.getInlines() {
guard let textRun = inline as? ACSTextRun else {
logError("Not of type ACSTextRun")
continue
}
let markdownResult = BridgeTextUtils.processText(fromRichTextBlock: textRun, hostConfig: hostConfig)
let markdownString = TextUtils.getMarkdownString(for: rootView, with: markdownResult)
let textRunContent = TextUtils.addFontProperties(attributedString: markdownString, textProperties: BridgeTextUtils.convertTextRun(toRichTextElementProperties: textRun), hostConfig: hostConfig)
// Set paragraph style such as line break mode and alignment
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = ACSHostConfig.getTextBlockAlignment(from: richTextBlock.getHorizontalAlignment())
textRunContent.addAttributes([.paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: textRunContent.length))
// Obtain text color to apply to the attributed string
if let colorHex = hostConfig.getForegroundColor(style, color: textRun.getTextColor(), isSubtle: textRun.getIsSubtle()) {
let foregroundColor = ColorUtils.color(from: colorHex) ?? NSColor.darkGray
textRunContent.addAttributes([.foregroundColor: foregroundColor], range: NSRange(location: 0, length: textRunContent.length))
}
// apply highlight to textrun
if textRun.getHighlight() {
if let colorHex = hostConfig.getHighlightColor(style, color: textRun.getTextColor(), isSubtle: textRun.getIsSubtle()) {
if let highlightColor = ColorUtils.color(from: colorHex) {
textRunContent.addAttributes([.backgroundColor: highlightColor], range: NSRange(location: 0, length: textRunContent.length))
}
}
}
// Add SelectAction to textRun
if textRun.getSelectAction() != nil {
let target = textView.getTargetHandler(for: textRun.getSelectAction(), rootView: rootView)
if let actionTarget = target {
textRunContent.addAttributes([.selectAction: actionTarget], range: NSRange(location: 0, length: textRunContent.length))
textRunContent.addAttributes(linkAttributes, range: NSRange(location: 0, length: textRunContent.length))
textRunContent.addAttributes([.accessibilityLink: true], range: NSRange(location: 0, length: textRunContent.length))
// setup textView to handle selectAction events
textView.setupSelectAction(textRun.getSelectAction(), rootView: rootView)
}
}
// apply strikethrough to textrun
if textRun.getStrikethrough() {
textRunContent.addAttributes([.strikethroughStyle: 1], range: NSRange(location: 0, length: textRunContent.length))
}
// apply underline to textrun
if config.supportsSchemeV1_3, textRun.getUnderline() {
textRunContent.addAttributes([.underlineStyle: NSUnderlineStyle.single.rawValue], range: NSRange(location: 0, length: textRunContent.length))
}
content.append(textRunContent)
}
textView.textContainer?.lineBreakMode = .byTruncatingTail
textView.textStorage?.setAttributedString(content)
textView.textContainer?.widthTracksTextView = true
return textView
}
}
| 55.694737 | 204 | 0.658099 |
d9b8b8758b6818103a4b381889a4d2f3a9a75cea | 5,062 | //
// UIFont+Attributes.swift
// edX
//
// Created by Salman on 06/12/2018.
// Copyright © 2018 edX. All rights reserved.
//
import UIKit
extension UIFont {
var styleAttribute: UIFont.TextStyle? {
return fontDescriptor.object(forKey: UIFontDescriptor.AttributeName.textStyle) as? UIFont.TextStyle
}
var isPreferredSizeLarge: Bool {
return UIApplication.shared.isPreferredContentSizeCategoryLarge
}
var preferredFont: UIFont? {
guard let style = styleAttribute else {
return nil
}
return UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: style), size: preferredFontSize(textStyle: style))
}
func preferredDescriptor(name: String, size: CGFloat) -> UIFontDescriptor {
let style = textStyle(for: size)
let preferrredFontSize = preferredFontSize(textStyle: style)
return UIFontDescriptor(fontAttributes: [UIFontDescriptor.AttributeName.name: name, UIFontDescriptor.AttributeName.size: preferrredFontSize, UIFontDescriptor.AttributeName.textStyle: style])
}
func preferredFont(with style: UIFont.TextStyle) -> UIFont {
return UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: style), size: preferredFontSize(textStyle: style))
}
func preferredFontSize(descriptor: UIFontDescriptor) -> CGFloat {
if let style = descriptor.object(forKey: UIFontDescriptor.AttributeName.textStyle) as? UIFont.TextStyle {
return preferredFontSize(textStyle: style)
}
return preferredFontSize(textStyle: .body)
}
func preferredFontSize(textStyle: UIFont.TextStyle) -> CGFloat {
let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
let pointSize = fontDescriptor.pointSize - dynamicSizeAdjustmentFactor(with: textStyle)
switch textStyle {
case .caption2:
return pointSize > 19 ? 19 : pointSize
case .caption1:
return pointSize > 20 ? 20 : pointSize
case .footnote:
return pointSize > 21 ? 21 : pointSize
case .subheadline:
return pointSize > 24 ? 24 : pointSize
case .callout:
return pointSize > 24 ? 24 : pointSize
case .body:
return pointSize > 24 ? 24 : pointSize
case .title3:
return pointSize > 28 ? 28 : pointSize
case .title2:
return pointSize > 29 ? 29 : pointSize
case .title1:
return pointSize > 40 ? 40 : pointSize
default:
return 24
}
}
// This method is a bridge between apple standard sizes and edX standard sizes.
// For example Apple default size for callout style is 16 but edX mobile App default size is 14.
private func dynamicSizeAdjustmentFactor(with style: UIFont.TextStyle) -> CGFloat {
switch style {
case .caption2, .caption1, .footnote, .callout, .title3:
return 2
case .subheadline:
return 3
case .body, .title2:
return 1
case .title1:
return 4
default:
return 2
}
}
// We are supporting maximum dynamic size up to XXXLarge for each style
private func dynamicTextSize(for size: CGFloat) -> CGFloat {
let style = textStyle(for: size)
let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style)
let pointSize = fontDescriptor.pointSize - dynamicSizeAdjustmentFactor(with: style)
switch style {
case .caption2:
return pointSize > 19 ? 19 : pointSize
case .caption1:
return pointSize > 20 ? 20 : pointSize
case .footnote:
return pointSize > 21 ? 21 : pointSize
case .subheadline:
return pointSize > 24 ? 24 : pointSize
case .callout:
return pointSize > 24 ? 24 : pointSize
case .body:
return pointSize > 24 ? 24 : pointSize
case .title3:
return pointSize > 28 ? 28 : pointSize
case .title2:
return pointSize > 29 ? 29 : pointSize
case .title1:
return pointSize > 40 ? 40 : pointSize
default:
return 24
}
}
private func textStyle(for size: CGFloat) -> UIFont.TextStyle {
switch OEXTextStyle.textSize(forPointSize: Int32(size)) {
case .xxxSmall:
return .caption2
case .xxSmall:
return .caption1
case .xSmall:
return .footnote
case .small:
return .subheadline
case .base:
return .callout
case .large:
return .body
case .xLarge:
return .title3
case .xxLarge:
return .title2
case .xxxLarge:
return .title1
case .xxxxLarge:
return .title1
}
}
}
| 33.973154 | 198 | 0.607863 |
e4cb9ad75396355d36175cf67c23bd1d734212ee | 995 | struct ViewBlogTag: Encodable {
let tagID: Int
let name: String
let urlEncodedName: String
}
extension BlogTag {
func toViewBlogTag() throws -> ViewBlogTag {
guard let urlEncodedName = self.name.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
throw SteamPressError(identifier: "ViewBlogPost", "Failed to URL encode tag name")
}
guard let tagID = self.tagID else {
throw SteamPressError(identifier: "ViewBlogPost", "Tag has no ID")
}
return ViewBlogTag(tagID: tagID, name: self.name, urlEncodedName: urlEncodedName)
}
}
extension ViewBlogTag {
static func percentEncodedTagName(from name: String) throws -> String {
guard let percentEncodedName = name.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
throw SteamPressError(identifier: "BlogTag", "Unable to create tag from name \(name)")
}
return percentEncodedName
}
}
| 35.535714 | 113 | 0.684422 |
f44126a7531c7686f2193c2fec6daff0ff2797b0 | 3,447 | //
// Message.swift
// Pangea
//
// Created by Усман Туркаев on 20.08.2021.
//
import UIKit
import FirebaseDatabase
func formatMessageTime(_ messageDate: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.string(from: messageDate)
}
enum MessageContent {
case text(text: String)
case image(image: UIImage)
case location(location: Location)
}
enum MessageAttachment: Hashable {
case empty
case location(location: Location)
case image(url: String)
}
enum MessageType: String {
case text, image, location
}
enum MessageKind: String {
case incoming, outgoing
}
struct Message: Hashable {
var id: String
var type: MessageType
var text: String
var created: Date
var updated: Date
var senderID: String
var attachment: MessageAttachment
var dictionary: [String: Any] {
return [
"id": id,
"text": text,
"senderID": senderID,
"created": created,
"updated": updated
]
}
var placeholder: String {
switch type {
case .text:
return text
case .image:
return NSLocalizedString("Sent an image", comment: "")
case .location:
return NSLocalizedString("Sent a location", comment: "")
}
}
}
extension Message {
init?(dictionary: [String: Any]) {
guard let id = dictionary["id"] as? String,
let typeString = dictionary["type"] as? String,
let createTimestamp = dictionary["created"] as? TimeInterval,
let updateTimestamp = dictionary["updated"] as? TimeInterval,
let senderID = dictionary["senderID"] as? String
else { return nil }
guard let type = MessageType.init(rawValue: typeString) else { return nil }
switch type {
case .text:
guard let text = dictionary["text"] as? String else { return nil }
self.init(id: id, type: type, text: text, created: Date(timeIntervalSince1970: createTimestamp / 1000), updated: Date(timeIntervalSince1970: updateTimestamp / 1000), senderID: senderID, attachment: .empty)
case .image:
guard let url = dictionary["imageURL"] as? String else { return nil }
self.init(id: id, type: type, text: "", created: Date(timeIntervalSince1970: createTimestamp / 1000), updated: Date(timeIntervalSince1970: updateTimestamp / 1000), senderID: senderID, attachment: .image(url: url))
case .location:
guard let locationDict = dictionary["location"] as? [String : Any] else { return nil }
guard let longitude = locationDict["longitude"] as? String,
let latitude = locationDict["latitude"] as? String else { return nil }
let location = Location(name: "", latitude: latitude, longitude: longitude)
self.init(id: id, type: type, text: "", created: Date(timeIntervalSince1970: createTimestamp / 1000), updated: Date(timeIntervalSince1970: updateTimestamp / 1000), senderID: senderID, attachment: .location(location: location))
}
}
}
extension Message {
static func == (lhs: Message, rhs: Message) -> Bool {
return lhs.id == rhs.id
}
static func != (lhs: Message, rhs: Message) -> Bool {
return lhs.id != rhs.id
}
}
| 32.214953 | 238 | 0.617058 |
c19775315ed2b6f543c53628e8ee5516dc5fa416 | 1,917 | //
// Copyright (c) 2018 KxCoding <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/*:
# Failable Initializer

*/
// Failable Initializers -> Fail -> nil
struct Position {
let x: Double
let y: Double
init?(x: Double, y: Double) {
guard x >= 0.0, y >= 0.0 else { return nil }
self.x = x
self.y = y
}
init!(value: Double) {
guard value >= 0.0 else { return nil }
// self.x = value
// self.y = value
self.init(x: value, y: value)
}
// init(value: Double) { Error
// self.x = value
// self.y = value
// }
// init(value: Int) {
// self.x = value
// self.y = value
// }
}
var a = Position(x: 12, y: 34)
a = Position(x: -12, y: 0)
// Unexpectedly found nil while implicitly unwrapping an Optional value
var b: Position = Position(value: 12)
b
//b = Position(value: -12) Error
| 27.385714 | 81 | 0.688576 |
56496b5fc0cb9b1d32c6098b8a8ac15a5d3f5d7f | 8,951 | import XCTest
@testable import CredentialsMicrosoft
import Kitura
import KituraNet
import Credentials
import KituraSession
import SwiftJWT
struct MicrosoftPlist: Decodable {
let token: String // their "accessToken"; not a JWT
let idToken: String // the Oauth2 JWT
}
// In order to run these tests, you need to update plistFile with current token and idToken values. I've been getting these values from an iOS demo app -- SMMicrosoftSignIn, which so far (as of 10/27/19) runs only on iOS 12.
final class CredentialsMicrosoftTests: XCTestCase {
static let plistFile = "/Users/chris/Desktop/Apps/SyncServerII/Private/CredentialsMicrosoft/token.plist"
var router:Router!
let credentials = Credentials()
let microsoftCredentials = CredentialsMicrosoftToken(tokenTimeToLive: nil)
let tokenTypeKey = "X-token-type"
let realAccessTokenKey = "access_token"
let microsoftAccessTokenKey = "X-microsoft-access-token"
let authTokenType = "MicrosoftToken"
let tokens: MicrosoftPlist = CredentialsMicrosoftTests.getTokens()
static func getTokens() -> MicrosoftPlist {
// I know this is gross. Swift packages just don't have a good way to access resources right now. See (https://stackoverflow.com/questions/47177036/use-resources-in-unit-tests-with-swift-package-manager)
let url = URL(fileURLWithPath: CredentialsMicrosoftTests.plistFile)
guard let data = try? Data(contentsOf: url) else {
fatalError("Could not get data from url")
}
let decoder = PropertyListDecoder()
guard let microsoftToken = try? decoder.decode(MicrosoftPlist.self, from: data) else {
fatalError("Could not decode the plist")
}
return microsoftToken
}
override func setUp() {
super.setUp()
router = setupRouter()
}
func setupRouter() -> Router {
let router = Router()
router.all(middleware: KituraSession.Session(secret: "foobar"))
credentials.register(plugin: microsoftCredentials)
router.all { (request, response, next) in
self.credentials.handle(request: request, response: response, next: next)
}
router.get("handler") { (request, response, next) in
response.send("Done!")
}
return router
}
func testRequestFailsWithNoAuthHeader() {
performServerTest(router: router) { expectation in
self.performRequest(method: "get", path: "/handler", callback: { response in
guard response?.httpStatusCode == .unauthorized else {
XCTFail("response?.httpStatusCode.rawValue: \(String(describing: response?.httpStatusCode.rawValue))")
expectation.fulfill()
return
}
expectation.fulfill()
})
}
}
func testRequestFailsWithBadAuthHeader() {
let headers: [String: String] = [
microsoftAccessTokenKey: "foo",
tokenTypeKey: authTokenType
]
performServerTest(router: router) { expectation in
self.performRequest(method: "get", path: "/handler", headers: headers, callback: { response in
guard response?.httpStatusCode == .unauthorized else {
XCTFail("response?.httpStatusCode.rawValue: \(String(describing: response?.httpStatusCode.rawValue))")
expectation.fulfill()
return
}
expectation.fulfill()
})
}
}
func testRequestSucceedsWithValidAuthHeader() {
let headers: [String: String] = [
microsoftAccessTokenKey: tokens.token,
tokenTypeKey: authTokenType,
realAccessTokenKey: tokens.idToken
]
performServerTest(router: router) { expectation in
self.performRequest(method: "get", path: "/handler", headers: headers, callback: { response in
guard response?.httpStatusCode == .OK else {
XCTFail("response?.httpStatusCode.rawValue: \(String(describing: response?.httpStatusCode.rawValue))")
expectation.fulfill()
return
}
expectation.fulfill()
})
}
}
func testHTTPRequest() {
var requestOptions: [ClientRequest.Options] = []
requestOptions.append(.schema("https://"))
requestOptions.append(.hostname("graph.microsoft.com"))
requestOptions.append(.method("GET"))
requestOptions.append(.path("/v1.0/me"))
var headers = [String:String]()
headers["Authorization"] = "Bearer \(tokens.token)"
requestOptions.append(.headers(headers))
let expectation = self.expectation(0)
let req = HTTP.request(requestOptions) { response in
guard let response = response, response.statusCode == HTTPStatusCode.OK else {
XCTFail()
expectation.fulfill()
return
}
var data = Data()
do {
let size = try response.read(into: &data)
print("size of data: \(size)")
let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
print("dictionary: \(String(describing: dictionary))")
} catch let error {
XCTFail("\(error)")
}
expectation.fulfill()
}
req.end()
waitForExpectations(timeout: 10, handler: nil)
}
func testCredentialsDirectly() {
let expectation = self.expectation(0)
microsoftCredentials.expectedUserIdentifier = MicrosoftClaims.getUserIdentifier(idToken: tokens.idToken)
if microsoftCredentials.expectedUserIdentifier == nil {
XCTFail()
return
}
microsoftCredentials.generateNewProfile(token: tokens.token, options:[:]) { result in
switch result {
case .success(let userProfile):
XCTAssert(userProfile.id == self.microsoftCredentials.expectedUserIdentifier)
case .unprocessable:
XCTFail()
case .failure:
XCTFail()
}
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}
// Tests that when a request to a Codable route that includes this middleware does not
// contain the matching X-token-type header, the middleware skips authentication and a
// second handler is instead invoked.
func testMissingTokenType() {
let headers: [String: String] = [
microsoftAccessTokenKey: tokens.token,
realAccessTokenKey: tokens.idToken
]
performServerTest(router: router) { expectation in
self.performRequest(method: "get", path: "/handler", headers: headers, callback: { response in
guard response?.httpStatusCode == .unauthorized else {
XCTFail("response?.httpStatusCode.rawValue: \(String(describing: response?.httpStatusCode.rawValue))")
expectation.fulfill()
return
}
expectation.fulfill()
})
}
}
// Tests that when a request to a Codable route that includes this middleware contains
// the matching X-token-type header, but does not supply an access_token, the middleware
// fails authentication and returns unauthorized.
func testMissingAccessToken() {
let headers: [String: String] = [
tokenTypeKey: authTokenType,
realAccessTokenKey: tokens.idToken
]
performServerTest(router: router) { expectation in
self.performRequest(method: "get", path: "/handler", headers: headers, callback: { response in
guard response?.httpStatusCode == .unauthorized else {
XCTFail("response?.httpStatusCode.rawValue: \(String(describing: response?.httpStatusCode.rawValue))")
expectation.fulfill()
return
}
expectation.fulfill()
})
}
}
static var allTests = [
("testRequestFailsWithNoAuthHeader", testRequestFailsWithNoAuthHeader),
("testRequestFailsWithBadAuthHeader", testRequestFailsWithBadAuthHeader),
("testRequestSucceedsWithValidAuthHeader", testRequestSucceedsWithValidAuthHeader),
("testHTTPRequest", testHTTPRequest),
("testCredentialsDirectly", testCredentialsDirectly),
("testMissingTokenType", testMissingTokenType),
("testMissingAccessToken", testMissingAccessToken)
]
}
| 39.087336 | 224 | 0.606636 |
f70bad7233db86638c07d1154ffd8c6ba2ba3834 | 2,130 | //
// UIColorExtension.swift
// GFSwifKlineDemo
//
// Created by winterJiao on 2019/3/25.
// Copyright © 2019 Admin. All rights reserved.
//
import UIKit
class UIColorExtension: NSObject {
}
extension UIColor {
public convenience init(hex: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
var hex: String = hex
if hex.hasPrefix("#") {
let index = hex.index(hex.startIndex, offsetBy: 1)
hex = String(hex[index...])
}
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "")
}
} else {
print("Scan hex error")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
| 33.809524 | 121 | 0.483568 |
874460b70314f162ca0f3d3f76945f74a6083222 | 741 | // RUN: %target-swift-frontend %s -emit-ir
protocol ViewModel {}
protocol ViewModelCell {}
protocol CellAwareViewModel : ViewModel {
associatedtype CellType: ViewModelCell
}
protocol ConfigurableViewModelCell : ViewModelCell {
associatedtype DataType: CellAwareViewModel
}
func useType<T: ViewModelCell>(cellType: T.Type) {
}
class ConfigurableViewModelCellProvider<V, C> where V: CellAwareViewModel,
C: ConfigurableViewModelCell,
C.DataType == V,
V.CellType == C {
static func crasher() {
// IRGen for the metatype instruction
useType(cellType: C.self)
}
}
| 27.444444 | 81 | 0.591093 |
f83978f087875e5149059e24e22593c75234e1f8 | 2,176 | //
// Request.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2018 Alejandro Alonso. All rights reserved.
//
import Foundation
extension Sword {
/// Makes an HTTP Request to the land of Discord's API
///
/// - parameter endpoint: The specific endpoint to request
func request(
_ endpoint: Endpoint,
then: @escaping (Data?, Sword.Error?) -> ()
) {
/// Used to block thread to complete request
let requestSema = DispatchSemaphore(value: 0)
/// Setup request
var request = URLRequest(url: URL(string: endpoint.url)!)
request.httpMethod = endpoint.method.rawValue
request.addValue(
"DiscordBot (https://github.com/Azoy/Sword, 1.0.0)",
forHTTPHeaderField: "User-Agent"
)
/// Authorize this request with the bot's token
request.addValue("Bot " + token, forHTTPHeaderField: "Authorization")
/// Setup data task
let task = session.dataTask(with: request) {
[unowned self] data, response, error in
/// Handle any errors that happened during the request
guard error == nil else {
then(nil, Sword.Error(error!.localizedDescription))
requestSema.signal()
return
}
/// Handle the response first to do things like rate limiting
guard let response = response as? HTTPURLResponse else {
then(nil, Sword.Error("Unable to get a correct HTTP response."))
requestSema.signal()
return
}
self.handleRequestResponse(response, then)
/// Make sure we can safely unwrap the data
guard let data = data else {
then(nil, Sword.Error("Unable to safely extract received data."))
requestSema.signal()
return
}
then(data, nil)
requestSema.signal()
}
task.resume()
requestSema.wait()
}
/// Handles what to do when a request is complete (rate limiting)
///
/// - parameter response: The http response from the Discord
func handleRequestResponse(
_ response: HTTPURLResponse,
_ then: @escaping (Data?, Sword.Error?) -> ()) {
Sword.log(.warning, "Get pranked")
}
}
| 27.544304 | 73 | 0.626838 |
d7bb701a1dfa4d12848dce1a18c966ddd89ad946 | 158 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(configlyTests.allTests),
]
}
#endif
| 15.8 | 45 | 0.670886 |
8ff849f65e7107b695a39a88c33aa7374d63f1b3 | 1,810 | //
// xtra_operators.swift
// pons
//
// Created by Dan Kogai on 2/4/16.
// Copyright © 2016 Dan Kogai. All rights reserved.
//
// To be consistent with bitwise xor
infix operator ^^ { associativity left precedence 120 } // Conjunctive, same as &&
infix operator ^^= { associativity right precedence 90 } // Assignment, same as &&=
public func ^^(lhs:Bool, rhs:Bool)->Bool {
return Bool.xor(lhs, rhs)
}
public func ^^=(inout lhs:Bool, rhs:Bool) {
lhs = lhs ^^ rhs
}
infix operator ** { associativity right precedence 160 } // Exponentiative, same as << and >>
infix operator **= { associativity right precedence 90 } // Assignment, same as <<= and >>=
public func **<L:POInt, R:POInt>(lhs:L, rhs:R)->L {
return R.pow(lhs, rhs)
}
public func **=<L:POInt, R:POInt>(inout lhs:L, rhs:R) {
lhs = lhs ** rhs
}
public func **<L:POReal, R:POInt>(lhs:L, rhs:R)->L {
return L(Double.pow(lhs.toDouble(), rhs.toDouble()))
}
public func **=<L:POReal, R:POInt>(inout lhs:L, rhs:R) {
lhs = lhs ** rhs
}
public func **<R:POReal>(lhs:R, rhs:R)->R {
return R.pow(lhs, rhs)
}
public func **=<R:POReal>(inout lhs:R, rhs:R) {
lhs = lhs ** rhs
}
public func **<C:POComplexReal>(lhs:C, rhs:C)->C {
return C.pow(lhs, rhs)
}
public func **=<C:POComplexReal>(inout lhs:C, rhs:C) {
lhs = lhs ** rhs
}
public func **<C:POComplexReal>(lhs:C, rhs:C.RealType)->C {
return C.pow(lhs, rhs)
}
public func **=<C:POComplexReal>(inout lhs:C, rhs:C.RealType) {
lhs = lhs ** rhs
}
infix operator &/ {associativity left precedence 150} // Multiplicative, same as *, / and %
infix operator &% {associativity left precedence 150} // Multiplicative, same as *, / and %
public func &/<Q:PORational>(lhs:Q, rhs:Q) -> Q {
return Q.divideWithOverflow(lhs, rhs).0
}
| 29.672131 | 98 | 0.625414 |
de0e25d6552f5cfef5204523c65e2d703befa310 | 2,750 | //
// URLTrie.swift
// SortingHat
//
// Created by 少 on 2019/3/2.
//
import Foundation
struct URLTrie<Element> {
var element: Element?
var children: [String: URLTrie<Element>]
mutating func insert(element: Element, paths: ArraySlice<String>) {
guard let (head, tail) = paths.decomposed else {
return self.element = element
}
if children[head] != nil {
children[head]?.insert(element: element, paths: tail)
} else {
children[head] = URLTrie(element: element, paths: tail)
}
}
typealias FetchResult = (subTrie: URLTrie<Element>, paramsters: [String: Any])
/// 根据路径遍历整棵树,找到带有节点的子树并拼接参数
func fetch(paths: ArraySlice<String>) -> FetchResult? {
guard let (head, tail) = paths.decomposed else { return (self, [:]) }
// 先找Key严格匹配的子树,后找有PlaceHolder的子树
if let remainder = children[head], let result = remainder.fetch(paths: tail) {
return result
} else {
// 在遍历有PlaceHolder子树的时候把PlaceHolder和Key值一并放入参数列表中
let placeholderChildren = children.filter({$0.key.first == ":"})
guard !placeholderChildren.isEmpty else { return nil }
for (key, value) in placeholderChildren {
if let result = value.fetch(paths: tail) {
var params = result.paramsters
let newKey = String(key.dropFirst())
params.updateValue(head, forKey: newKey)
return (result.subTrie, params)
}
}
return nil
}
}
}
extension URLTrie {
init() {
element = nil
children = [:]
}
init(element: Element, paths: ArraySlice<String>) {
if let (head, tail) = paths.decomposed {
let children = [head: URLTrie(element: element, paths: tail)]
self = URLTrie(element: nil, children: children)
} else {
self = URLTrie(element: element, children: [:])
}
}
}
extension URLTrie {
/// use for debug to check trie.
var urlPatterns: [String] {
var result: [String] = element == nil ? [] : [""]
for (k, v) in children {
result += v.urlPatterns.map {
$0.isEmpty ? k : k + "/" + $0
}
}
return result
}
mutating func register(element: Element, with url: URL) {
insert(element: element, paths: url.completePaths.slice)
}
func parse(url: URL) -> (Element, [String: Any])? {
guard let result = fetch(paths: url.completePaths.slice),
let element = result.subTrie.element else { return nil }
return (element, result.paramsters)
}
}
| 31.609195 | 86 | 0.557091 |
185972dcc6ca11fc172ed6bd4f3c168095f790d5 | 519 | //
// ImageCell.swift
// snapshots
//
// Created by Alina Abidi on 6/29/17.
// Copyright © 2017 Alina Abidi. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class ImageCell: UICollectionViewCell {
@IBOutlet weak var postImageView: PFImageView!
var instaPost: PFObject! {
didSet {
self.postImageView.file = instaPost["media"] as? PFFile
self.postImageView.loadInBackground()
}
}
}
| 15.264706 | 67 | 0.576108 |
bb5d717364a63d913384eaa1efb619f8be36d0f9 | 2,756 | //
// SceneDelegate.swift
// FurnitureSwiftUI
//
// Created by Tarokh on 10/10/20.
// Copyright © 2020 Tarokh. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.4 | 147 | 0.706096 |
3971ab57e6fbf5291134b375fc355d42d1fda9a8 | 3,034 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import Photos
/**
Extension on UIViewController to simply presentation of BSImagePicker
*/
public extension UIViewController {
/**
Present a given image picker with closures, any of the closures can be nil.
- parameter imagePicker: a BSImagePickerViewController to present
- parameter animated: To animate the presentation or not
- parameter select: Closure to call when user selects an asset or nil
- parameter deselect: Closure to call when user deselects an asset or nil
- parameter cancel: Closure to call when user cancels or nil
- parameter finish: Closure to call when user finishes or nil
- parameter completion: presentation completed closure or nil
- parameter hitLimit: Closure to call when user hits selection limit or nil
*/
@objc func bs_presentImagePickerController(_ imagePicker: BSImagePickerViewController, animated: Bool, select: ((_ asset: PHAsset) -> Void)?, deselect: ((_ asset: PHAsset) -> Void)?, cancel: (([PHAsset]) -> Void)?, finish: (([PHAsset]) -> Void)?, completion: (() -> Void)?, hitLimit: ((Int) -> Void)? = nil) {
BSImagePickerViewController.authorize(fromViewController: self) { (authorized) -> Void in
// Make sure we are authorized before proceding
guard authorized == true else { return }
// Set blocks
imagePicker.photosViewController.selectionClosure = select
imagePicker.photosViewController.deselectionClosure = deselect
imagePicker.photosViewController.cancelClosure = cancel
imagePicker.photosViewController.finishClosure = finish
imagePicker.photosViewController.hitLimitClosure = hitLimit
// Present
self.present(imagePicker, animated: animated, completion: completion)
}
}
}
| 51.423729 | 313 | 0.710943 |
6a8372171233a96b4965e0d1b7a0287097c37d7b | 1,445 | infix operator ~=
/// Has suffix
public func ~= <Result, D>(lhs: KeyPath<Result, String>, rhs: String) -> FilterOperator<D, Result>
where D: QuerySupporting, D.QueryFilterMethod: SQLBinaryOperator
{
return .make(lhs, .like, ["%" + rhs])
}
/// Has suffix
public func ~= <Result, D>(lhs: KeyPath<Result, String?>, rhs: String) -> FilterOperator<D, Result>
where D: QuerySupporting, D.QueryFilterMethod: SQLBinaryOperator
{
return .make(lhs, .like, ["%" + rhs])
}
infix operator =~
/// Has prefix.
public func =~ <Result, D>(lhs: KeyPath<Result, String>, rhs: String) -> FilterOperator<D, Result>
where D: QuerySupporting, D.QueryFilterMethod: SQLBinaryOperator
{
return .make(lhs, .like, [rhs + "%"])
}
/// Has prefix.
public func =~ <Result, D>(lhs: KeyPath<Result, String?>, rhs: String) -> FilterOperator<D, Result>
where D: QuerySupporting, D.QueryFilterMethod: SQLBinaryOperator
{
return .make(lhs, .like, [rhs + "%"])
}
infix operator ~~
/// Contains.
public func ~~ <Result, D>(lhs: KeyPath<Result, String>, rhs: String) -> FilterOperator<D, Result>
where D: QuerySupporting, D.QueryFilterMethod: SQLBinaryOperator
{
return .make(lhs, .like, ["%" + rhs + "%"])
}
/// Contains.
public func ~~ <Result, D>(lhs: KeyPath<Result, String?>, rhs: String) -> FilterOperator<D, Result>
where D: QuerySupporting, D.QueryFilterMethod: SQLBinaryOperator
{
return .make(lhs, .like, ["%" + rhs + "%"])
}
| 34.404762 | 99 | 0.665052 |
11aad85f99edbbdfa0377764733fcbf8309141db | 28,634 | //
// FactoryCalibration.swift
// LibreDirect
//
import Foundation
// MARK: - FactoryCalibration
struct FactoryCalibration: Codable {
// MARK: Lifecycle
init(fram: Data) {
let i1 = readBits(fram, 2, 0, 3)
let i2 = readBits(fram, 2, 3, 0xa)
var i3 = Double(readBits(fram, 0x150, 0, 8))
if readBits(fram, 0x150, 0x21, 1) != 0 {
i3 = -i3
}
let i4 = Double(readBits(fram, 0x150, 8, 0xe))
let i5 = Double(readBits(fram, 0x150, 0x28, 0xc) << 2)
let i6 = Double(readBits(fram, 0x150, 0x34, 0xc) << 2)
self.i1 = i1
self.i2 = i2
self.i3 = i3
self.i4 = i4
self.i5 = i5
self.i6 = i6
}
init(i1: Int, i2: Int, i3: Double, i4: Double, i5: Double, i6: Double) {
self.i1 = i1
self.i2 = i2
self.i3 = i3
self.i4 = i4
self.i5 = i5
self.i6 = i6
}
// MARK: Internal
let i1: Int
let i2: Int
let i3: Double
let i4: Double
let i5: Double
let i6: Double
var description: String {
return [
i1.description,
i2.description,
i3.description,
i4.description,
i5.description,
i6.description,
].joined(separator: ", ")
}
func calibrate(rawValue: Double, rawTemperature: Double, rawTemperatureAdjustment: Double) -> Double {
let x: Double = 1000 + 71500
let y: Double = 1000
let ca = 0.0009180023
let cb = 0.0001964561
let cc = 0.0000007061775
let cd = 0.00000005283566
let rLeft = rawTemperature * x
let rRight = rawTemperatureAdjustment + Double(i6)
let R = (rLeft / rRight) - y
let logR = log(R)
let d = pow(logR, 3) * cd + pow(logR, 2) * cc + logR * cb + ca
let temperature = 1 / d - 273.15
let g1 = 65.0 * (rawValue - Double(i3)) / Double(i4 - i3)
let g2 = pow(1.045, 32.5 - temperature)
let g3 = g1 * g2
let v1 = t1[i2 - 1]
let v2 = t2[i2 - 1]
return round((g3 - v1) / v2)
}
// MARK: Private
}
private func readBits(_ buffer: Data, _ byteOffset: Int, _ bitOffset: Int, _ bitCount: Int) -> Int {
guard bitCount != 0 else {
return 0
}
var res = 0
for i in 0 ..< bitCount {
let totalBitOffset = byteOffset * 8 + bitOffset + i
let byte = Int(floor(Float(totalBitOffset) / 8))
let bit = totalBitOffset % 8
if byte >= 0, byte < buffer.count, ((Int(buffer[byte]) >> bit) & 0x1) == 1 {
res = res | (1 << i)
}
}
return res
}
private let t1 = [
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
]
private let t2 = [
0.037744199999999999, 0.037744199999999999, 0.037744199999999999, 0.037744199999999999, 0.037744199999999999, 0.037744199999999999, 0.037744199999999999, 0.037744199999999999,
0.038121700000000001, 0.038121700000000001, 0.038121700000000001, 0.038121700000000001, 0.038121700000000001, 0.038121700000000001, 0.038121700000000001, 0.038121700000000001,
0.0385029, 0.0385029, 0.0385029, 0.0385029, 0.0385029, 0.0385029, 0.0385029, 0.0385029,
0.038887900000000003, 0.038887900000000003, 0.038887900000000003, 0.038887900000000003, 0.038887900000000003, 0.038887900000000003, 0.038887900000000003, 0.038887900000000003,
0.039276800000000001, 0.039276800000000001, 0.039276800000000001, 0.039276800000000001, 0.039276800000000001, 0.039276800000000001, 0.039276800000000001, 0.039276800000000001,
0.039669599999999999, 0.039669599999999999, 0.039669599999999999, 0.039669599999999999, 0.039669599999999999, 0.039669599999999999, 0.039669599999999999, 0.039669599999999999,
0.040066299999999999, 0.040066299999999999, 0.040066299999999999, 0.040066299999999999, 0.040066299999999999, 0.040066299999999999, 0.040066299999999999, 0.040066299999999999,
0.0404669, 0.0404669, 0.0404669, 0.0404669, 0.0404669, 0.0404669, 0.0404669, 0.0404669,
0.040871600000000001, 0.040871600000000001, 0.040871600000000001, 0.040871600000000001, 0.040871600000000001, 0.040871600000000001, 0.040871600000000001, 0.040871600000000001,
0.041280299999999999, 0.041280299999999999, 0.041280299999999999, 0.041280299999999999, 0.041280299999999999, 0.041280299999999999, 0.041280299999999999, 0.041280299999999999,
0.041693099999999997, 0.041693099999999997, 0.041693099999999997, 0.041693099999999997, 0.041693099999999997, 0.041693099999999997, 0.041693099999999997, 0.041693099999999997,
0.042110000000000002, 0.042110000000000002, 0.042110000000000002, 0.042110000000000002, 0.042110000000000002, 0.042110000000000002, 0.042110000000000002, 0.042110000000000002,
0.042531100000000002, 0.042531100000000002, 0.042531100000000002, 0.042531100000000002, 0.042531100000000002, 0.042531100000000002, 0.042531100000000002, 0.042531100000000002,
0.042956500000000002, 0.042956500000000002, 0.042956500000000002, 0.042956500000000002, 0.042956500000000002, 0.042956500000000002, 0.042956500000000002, 0.042956500000000002,
0.043386000000000001, 0.043386000000000001, 0.043386000000000001, 0.043386000000000001, 0.043386000000000001, 0.043386000000000001, 0.043386000000000001, 0.043386000000000001,
0.043819900000000002, 0.043819900000000002, 0.043819900000000002, 0.043819900000000002, 0.043819900000000002, 0.043819900000000002, 0.043819900000000002, 0.043819900000000002,
0.044258100000000002, 0.044258100000000002, 0.044258100000000002, 0.044258100000000002, 0.044258100000000002, 0.044258100000000002, 0.044258100000000002, 0.044258100000000002,
0.044700700000000003, 0.044700700000000003, 0.044700700000000003, 0.044700700000000003, 0.044700700000000003, 0.044700700000000003, 0.044700700000000003, 0.044700700000000003,
0.045147699999999999, 0.045147699999999999, 0.045147699999999999, 0.045147699999999999, 0.045147699999999999, 0.045147699999999999, 0.045147699999999999, 0.045147699999999999,
0.045599099999999997, 0.045599099999999997, 0.045599099999999997, 0.045599099999999997, 0.045599099999999997, 0.045599099999999997, 0.045599099999999997, 0.045599099999999997,
0.046055100000000002, 0.046055100000000002, 0.046055100000000002, 0.046055100000000002, 0.046055100000000002, 0.046055100000000002, 0.046055100000000002, 0.046055100000000002,
0.0465157, 0.0465157, 0.0465157, 0.0465157, 0.0465157, 0.0465157, 0.0465157, 0.0465157,
0.046980800000000003, 0.046980800000000003, 0.046980800000000003, 0.046980800000000003, 0.046980800000000003, 0.046980800000000003, 0.046980800000000003, 0.046980800000000003,
0.047450600000000002, 0.047450600000000002, 0.047450600000000002, 0.047450600000000002, 0.047450600000000002, 0.047450600000000002, 0.047450600000000002, 0.047450600000000002,
0.047925200000000001, 0.047925200000000001, 0.047925200000000001, 0.047925200000000001, 0.047925200000000001, 0.047925200000000001, 0.047925200000000001, 0.047925200000000001,
0.0484044, 0.0484044, 0.0484044, 0.0484044, 0.0484044, 0.0484044, 0.0484044, 0.0484044,
0.048888399999999999, 0.048888399999999999, 0.048888399999999999, 0.048888399999999999, 0.048888399999999999, 0.048888399999999999, 0.048888399999999999, 0.048888399999999999,
0.049377299999999999, 0.049377299999999999, 0.049377299999999999, 0.049377299999999999, 0.049377299999999999, 0.049377299999999999, 0.049377299999999999, 0.049377299999999999,
0.049871100000000002, 0.049871100000000002, 0.049871100000000002, 0.049871100000000002, 0.049871100000000002, 0.049871100000000002, 0.049871100000000002, 0.049871100000000002,
0.050369799999999999, 0.050369799999999999, 0.050369799999999999, 0.050369799999999999, 0.050369799999999999, 0.050369799999999999, 0.050369799999999999, 0.050369799999999999,
0.050873500000000002, 0.050873500000000002, 0.050873500000000002, 0.050873500000000002, 0.050873500000000002, 0.050873500000000002, 0.050873500000000002, 0.050873500000000002,
0.051382299999999999, 0.051382299999999999, 0.051382299999999999, 0.051382299999999999, 0.051382299999999999, 0.051382299999999999, 0.051382299999999999, 0.051382299999999999,
0.051896100000000001, 0.051896100000000001, 0.051896100000000001, 0.051896100000000001, 0.051896100000000001, 0.051896100000000001, 0.051896100000000001, 0.051896100000000001,
0.052415000000000003, 0.052415000000000003, 0.052415000000000003, 0.052415000000000003, 0.052415000000000003, 0.052415000000000003, 0.052415000000000003, 0.052415000000000003,
0.052939199999999999, 0.052939199999999999, 0.052939199999999999, 0.052939199999999999, 0.052939199999999999, 0.052939199999999999, 0.052939199999999999, 0.052939199999999999,
0.053468599999999998, 0.053468599999999998, 0.053468599999999998, 0.053468599999999998, 0.053468599999999998, 0.053468599999999998, 0.053468599999999998, 0.053468599999999998,
0.054003299999999997, 0.054003299999999997, 0.054003299999999997, 0.054003299999999997, 0.054003299999999997, 0.054003299999999997, 0.054003299999999997, 0.054003299999999997,
0.054543300000000003, 0.054543300000000003, 0.054543300000000003, 0.054543300000000003, 0.054543300000000003, 0.054543300000000003, 0.054543300000000003, 0.054543300000000003,
0.055088699999999997, 0.055088699999999997, 0.055088699999999997, 0.055088699999999997, 0.055088699999999997, 0.055088699999999997, 0.055088699999999997, 0.055088699999999997,
0.055639599999999997, 0.055639599999999997, 0.055639599999999997, 0.055639599999999997, 0.055639599999999997, 0.055639599999999997, 0.055639599999999997, 0.055639599999999997,
0.056196000000000003, 0.056196000000000003, 0.056196000000000003, 0.056196000000000003, 0.056196000000000003, 0.056196000000000003, 0.056196000000000003, 0.056196000000000003,
0.056758000000000003, 0.056758000000000003, 0.056758000000000003, 0.056758000000000003, 0.056758000000000003, 0.056758000000000003, 0.056758000000000003, 0.056758000000000003,
0.057325599999999997, 0.057325599999999997, 0.057325599999999997, 0.057325599999999997, 0.057325599999999997, 0.057325599999999997, 0.057325599999999997, 0.057325599999999997,
0.0578988, 0.0578988, 0.0578988, 0.0578988, 0.0578988, 0.0578988, 0.0578988, 0.0578988,
0.058477800000000003, 0.058477800000000003, 0.058477800000000003, 0.058477800000000003, 0.058477800000000003, 0.058477800000000003, 0.058477800000000003, 0.058477800000000003,
0.0590626, 0.0590626, 0.0590626, 0.0590626, 0.0590626, 0.0590626, 0.0590626, 0.0590626,
0.059653200000000003, 0.059653200000000003, 0.059653200000000003, 0.059653200000000003, 0.059653200000000003, 0.059653200000000003, 0.059653200000000003, 0.059653200000000003,
0.060249700000000003, 0.060249700000000003, 0.060249700000000003, 0.060249700000000003, 0.060249700000000003, 0.060249700000000003, 0.060249700000000003, 0.060249700000000003,
0.060852200000000002, 0.060852200000000002, 0.060852200000000002, 0.060852200000000002, 0.060852200000000002, 0.060852200000000002, 0.060852200000000002, 0.060852200000000002,
0.0614607, 0.0614607, 0.0614607, 0.0614607, 0.0614607, 0.0614607, 0.0614607, 0.0614607,
0.062075400000000003, 0.062075400000000003, 0.062075400000000003, 0.062075400000000003, 0.062075400000000003, 0.062075400000000003, 0.062075400000000003, 0.062075400000000003,
0.062696100000000005, 0.062696100000000005, 0.062696100000000005, 0.062696100000000005, 0.062696100000000005, 0.062696100000000005, 0.062696100000000005, 0.062696100000000005,
0.063323099999999993, 0.063323099999999993, 0.063323099999999993, 0.063323099999999993, 0.063323099999999993, 0.063323099999999993, 0.063323099999999993, 0.063323099999999993,
0.063956299999999994, 0.063956299999999994, 0.063956299999999994, 0.063956299999999994, 0.063956299999999994, 0.063956299999999994, 0.063956299999999994, 0.063956299999999994,
0.064595899999999998, 0.064595899999999998, 0.064595899999999998, 0.064595899999999998, 0.064595899999999998, 0.064595899999999998, 0.064595899999999998, 0.064595899999999998,
0.065241800000000003, 0.065241800000000003, 0.065241800000000003, 0.065241800000000003, 0.065241800000000003, 0.065241800000000003, 0.065241800000000003, 0.065241800000000003,
0.0658942, 0.0658942, 0.0658942, 0.0658942, 0.0658942, 0.0658942, 0.0658942, 0.0658942,
0.066553200000000007, 0.066553200000000007, 0.066553200000000007, 0.066553200000000007, 0.066553200000000007, 0.066553200000000007, 0.066553200000000007, 0.066553200000000007,
0.067218700000000006, 0.067218700000000006, 0.067218700000000006, 0.067218700000000006, 0.067218700000000006, 0.067218700000000006, 0.067218700000000006, 0.067218700000000006,
0.067890900000000004, 0.067890900000000004, 0.067890900000000004, 0.067890900000000004, 0.067890900000000004, 0.067890900000000004, 0.067890900000000004, 0.067890900000000004,
0.0685698, 0.0685698, 0.0685698, 0.0685698, 0.0685698, 0.0685698, 0.0685698, 0.0685698,
0.069255499999999998, 0.069255499999999998, 0.069255499999999998, 0.069255499999999998, 0.069255499999999998, 0.069255499999999998, 0.069255499999999998, 0.069255499999999998,
0.069948099999999999, 0.069948099999999999, 0.069948099999999999, 0.069948099999999999, 0.069948099999999999, 0.069948099999999999, 0.069948099999999999, 0.069948099999999999,
0.070647500000000002, 0.070647500000000002, 0.070647500000000002, 0.070647500000000002, 0.070647500000000002, 0.070647500000000002, 0.070647500000000002, 0.070647500000000002,
0.071354000000000001, 0.071354000000000001, 0.071354000000000001, 0.071354000000000001, 0.071354000000000001, 0.071354000000000001, 0.071354000000000001, 0.071354000000000001, 0.071354000000000001,
0.072067599999999996, 0.072067599999999996, 0.072067599999999996, 0.072067599999999996, 0.072067599999999996, 0.072067599999999996, 0.072067599999999996, 0.072067599999999996, 0.072067599999999996,
0.072788199999999997, 0.072788199999999997, 0.072788199999999997, 0.072788199999999997, 0.072788199999999997, 0.072788199999999997, 0.072788199999999997, 0.072788199999999997, 0.072788199999999997,
0.073516100000000001, 0.073516100000000001, 0.073516100000000001, 0.073516100000000001, 0.073516100000000001, 0.073516100000000001, 0.073516100000000001, 0.073516100000000001, 0.073516100000000001,
0.074251300000000006, 0.074251300000000006, 0.074251300000000006, 0.074251300000000006, 0.074251300000000006, 0.074251300000000006, 0.074251300000000006, 0.074251300000000006, 0.074251300000000006,
0.074993799999999999, 0.074993799999999999, 0.074993799999999999, 0.074993799999999999, 0.074993799999999999, 0.074993799999999999, 0.074993799999999999, 0.074993799999999999, 0.074993799999999999,
0.075743699999999997, 0.075743699999999997, 0.075743699999999997, 0.075743699999999997, 0.075743699999999997, 0.075743699999999997, 0.075743699999999997, 0.075743699999999997, 0.075743699999999997,
0.076501200000000005, 0.076501200000000005, 0.076501200000000005, 0.076501200000000005, 0.076501200000000005, 0.076501200000000005, 0.076501200000000005, 0.076501200000000005, 0.076501200000000005,
0.077266199999999993, 0.077266199999999993, 0.077266199999999993, 0.077266199999999993, 0.077266199999999993, 0.077266199999999993, 0.077266199999999993, 0.077266199999999993, 0.077266199999999993,
0.078038800000000005, 0.078038800000000005, 0.078038800000000005, 0.078038800000000005, 0.078038800000000005, 0.078038800000000005, 0.078038800000000005, 0.078038800000000005, 0.078038800000000005,
0.078819200000000006, 0.078819200000000006, 0.078819200000000006, 0.078819200000000006, 0.078819200000000006, 0.078819200000000006, 0.078819200000000006, 0.078819200000000006, 0.078819200000000006,
0.079607399999999995, 0.079607399999999995, 0.079607399999999995, 0.079607399999999995, 0.079607399999999995, 0.079607399999999995, 0.079607399999999995, 0.079607399999999995, 0.079607399999999995,
0.080403500000000003, 0.080403500000000003, 0.080403500000000003, 0.080403500000000003, 0.080403500000000003, 0.080403500000000003, 0.080403500000000003, 0.080403500000000003, 0.080403500000000003,
0.081207500000000002, 0.081207500000000002, 0.081207500000000002, 0.081207500000000002, 0.081207500000000002, 0.081207500000000002, 0.081207500000000002, 0.081207500000000002, 0.081207500000000002,
0.082019599999999998, 0.082019599999999998, 0.082019599999999998, 0.082019599999999998, 0.082019599999999998, 0.082019599999999998, 0.082019599999999998, 0.082019599999999998, 0.082019599999999998,
0.082839800000000005, 0.082839800000000005, 0.082839800000000005, 0.082839800000000005, 0.082839800000000005, 0.082839800000000005, 0.082839800000000005, 0.082839800000000005, 0.082839800000000005,
0.083668199999999998, 0.083668199999999998, 0.083668199999999998, 0.083668199999999998, 0.083668199999999998, 0.083668199999999998, 0.083668199999999998, 0.083668199999999998, 0.083668199999999998,
0.084504899999999994, 0.084504899999999994, 0.084504899999999994, 0.084504899999999994, 0.084504899999999994, 0.084504899999999994, 0.084504899999999994, 0.084504899999999994, 0.084504899999999994,
0.085349900000000006, 0.085349900000000006, 0.085349900000000006, 0.085349900000000006, 0.085349900000000006, 0.085349900000000006, 0.085349900000000006, 0.085349900000000006, 0.085349900000000006,
0.086203399999999999, 0.086203399999999999, 0.086203399999999999, 0.086203399999999999, 0.086203399999999999, 0.086203399999999999, 0.086203399999999999, 0.086203399999999999, 0.086203399999999999,
0.087065500000000004, 0.087065500000000004, 0.087065500000000004, 0.087065500000000004, 0.087065500000000004, 0.087065500000000004, 0.087065500000000004, 0.087065500000000004, 0.087065500000000004,
0.087936100000000003, 0.087936100000000003, 0.087936100000000003, 0.087936100000000003, 0.087936100000000003, 0.087936100000000003, 0.087936100000000003, 0.087936100000000003, 0.087936100000000003,
0.088815500000000006, 0.088815500000000006, 0.088815500000000006, 0.088815500000000006, 0.088815500000000006, 0.088815500000000006, 0.088815500000000006, 0.088815500000000006, 0.088815500000000006,
0.089703599999999994, 0.089703599999999994, 0.089703599999999994, 0.089703599999999994, 0.089703599999999994, 0.089703599999999994, 0.089703599999999994, 0.089703599999999994,
0.090600700000000006, 0.090600700000000006, 0.090600700000000006, 0.090600700000000006, 0.090600700000000006, 0.090600700000000006, 0.090600700000000006, 0.090600700000000006,
0.091506699999999996, 0.091506699999999996, 0.091506699999999996, 0.091506699999999996, 0.091506699999999996, 0.091506699999999996, 0.091506699999999996, 0.091506699999999996,
0.092421699999999996, 0.092421699999999996, 0.092421699999999996, 0.092421699999999996, 0.092421699999999996, 0.092421699999999996, 0.092421699999999996, 0.092421699999999996,
0.093345999999999998, 0.093345999999999998, 0.093345999999999998, 0.093345999999999998, 0.093345999999999998, 0.093345999999999998, 0.093345999999999998, 0.093345999999999998,
0.094279399999999999, 0.094279399999999999, 0.094279399999999999, 0.094279399999999999, 0.094279399999999999, 0.094279399999999999, 0.094279399999999999, 0.094279399999999999,
0.095222200000000007, 0.095222200000000007, 0.095222200000000007, 0.095222200000000007, 0.095222200000000007, 0.095222200000000007, 0.095222200000000007, 0.095222200000000007,
0.096174399999999993, 0.096174399999999993, 0.096174399999999993, 0.096174399999999993, 0.096174399999999993, 0.096174399999999993, 0.096174399999999993, 0.096174399999999993,
0.097136200000000006, 0.097136200000000006, 0.097136200000000006, 0.097136200000000006, 0.097136200000000006, 0.097136200000000006, 0.097136200000000006, 0.097136200000000006,
0.0981075, 0.0981075, 0.0981075, 0.0981075, 0.0981075, 0.0981075, 0.0981075, 0.0981075,
0.099088599999999999, 0.099088599999999999, 0.099088599999999999, 0.099088599999999999, 0.099088599999999999, 0.099088599999999999, 0.099088599999999999, 0.099088599999999999,
0.1000795, 0.1000795, 0.1000795, 0.1000795, 0.1000795, 0.1000795, 0.1000795, 0.1000795,
0.1010803, 0.1010803, 0.1010803, 0.1010803, 0.1010803, 0.1010803, 0.1010803, 0.1010803,
0.1020911, 0.1020911, 0.1020911, 0.1020911, 0.1020911, 0.1020911, 0.1020911, 0.1020911,
0.103112, 0.103112, 0.103112, 0.103112, 0.103112, 0.103112, 0.103112, 0.103112,
0.1041431, 0.1041431, 0.1041431, 0.1041431, 0.1041431, 0.1041431, 0.1041431, 0.1041431,
0.1051846, 0.1051846, 0.1051846, 0.1051846, 0.1051846, 0.1051846, 0.1051846, 0.1051846,
0.10623639999999999, 0.10623639999999999, 0.10623639999999999, 0.10623639999999999, 0.10623639999999999, 0.10623639999999999, 0.10623639999999999, 0.10623639999999999,
0.1072988, 0.1072988, 0.1072988, 0.1072988, 0.1072988, 0.1072988, 0.1072988, 0.1072988,
0.1083718, 0.1083718, 0.1083718, 0.1083718, 0.1083718, 0.1083718, 0.1083718, 0.1083718,
0.1094555, 0.1094555, 0.1094555, 0.1094555, 0.1094555, 0.1094555, 0.1094555, 0.1094555,
0.11055, 0.11055, 0.11055, 0.11055, 0.11055, 0.11055, 0.11055, 0.11055,
0.1116555, 0.1116555, 0.1116555, 0.1116555, 0.1116555, 0.1116555, 0.1116555, 0.1116555,
0.1127721, 0.1127721, 0.1127721, 0.1127721, 0.1127721, 0.1127721, 0.1127721, 0.1127721,
0.1138998, 0.1138998, 0.1138998, 0.1138998, 0.1138998, 0.1138998, 0.1138998, 0.1138998,
0.1150388, 0.1150388, 0.1150388, 0.1150388, 0.1150388, 0.1150388, 0.1150388, 0.1150388,
0.11618920000000001, 0.11618920000000001, 0.11618920000000001, 0.11618920000000001, 0.11618920000000001, 0.11618920000000001, 0.11618920000000001, 0.11618920000000001,
0.1173511, 0.1173511, 0.1173511, 0.1173511, 0.1173511, 0.1173511, 0.1173511, 0.1173511,
0.11852459999999999, 0.11852459999999999, 0.11852459999999999, 0.11852459999999999, 0.11852459999999999, 0.11852459999999999, 0.11852459999999999, 0.11852459999999999,
0.11970989999999999, 0.11970989999999999, 0.11970989999999999, 0.11970989999999999, 0.11970989999999999, 0.11970989999999999, 0.11970989999999999, 0.11970989999999999, 0.11970989999999999,
0.120907, 0.120907, 0.120907, 0.120907, 0.120907, 0.120907, 0.120907, 0.120907, 0.120907,
0.122116, 0.122116, 0.122116, 0.122116, 0.122116, 0.122116, 0.122116, 0.122116, 0.122116,
0.12333719999999999, 0.12333719999999999, 0.12333719999999999, 0.12333719999999999, 0.12333719999999999, 0.12333719999999999, 0.12333719999999999, 0.12333719999999999, 0.12333719999999999,
0.1245706, 0.1245706, 0.1245706, 0.1245706, 0.1245706, 0.1245706, 0.1245706, 0.1245706, 0.1245706,
0.12581629999999999, 0.12581629999999999, 0.12581629999999999, 0.12581629999999999, 0.12581629999999999, 0.12581629999999999, 0.12581629999999999, 0.12581629999999999, 0.12581629999999999,
0.1270744, 0.1270744, 0.1270744, 0.1270744, 0.1270744, 0.1270744, 0.1270744, 0.1270744, 0.1270744,
0.12834519999999999, 0.12834519999999999, 0.12834519999999999, 0.12834519999999999, 0.12834519999999999, 0.12834519999999999, 0.12834519999999999, 0.12834519999999999, 0.12834519999999999,
]
| 78.664835 | 201 | 0.714465 |
4a5aa207ff9ea605da1f2298c14cd166f3a7d32b | 1,225 | //
// GSLineChartViewController.swift
// GSAnalysis
//
// Created by 胡秋实 on 25/12/2015.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import UIKit
import GSAnalysis
class GSLineChartViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let lineView = GSLineView(frame: CGRect(x: 50,y: 200,width: 280,height: 200))
lineView.points = [4, 1, 6, 10, 5, 8, 3]
lineView.startColor = UIColor(red: 250/255.0, green: 233/255.0, blue: 222/255.0, alpha: 1.0)
lineView.endColor = UIColor(red: 252/255.0, green: 79/255.0, blue: 8/255.0, alpha: 1.0)
self.view.addSubview(lineView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 29.166667 | 106 | 0.657959 |
ffa342f979910ce7f80b2af90d24fef6d094cb34 | 402 | //
// Optional.swift
// DJBExtensionKit
//
// Created by Douwe Bos on 03/02/2020.
//
import Foundation
public extension Optional {
// Mimics Kotlin's .also behavior
// Makes sharing code between my Kotlin and Swift projects a lot easier
func also(handler: ((Wrapped) -> Swift.Void)) {
if case let Optional.some(value) = self {
handler(value)
}
}
}
| 20.1 | 75 | 0.619403 |
fe9a838a94cbdc39628f4468bed93e8bfa8a7d08 | 14,862 | //
// ComponentsTests.swift
//
//
// Created by Mathew Polzin on 12/29/19.
//
import XCTest
import OpenAPIKit
final class ComponentsTests: XCTestCase {
func test_referenceLookup() throws {
let components = OpenAPI.Components(
schemas: [
"hello": .string,
"world": .integer(required: false)
]
)
let ref1 = JSONReference<JSONSchema>.component(named: "world")
let ref2 = JSONReference<JSONSchema>.component(named: "missing")
let ref3 = JSONReference<OpenAPI.Parameter>.component(named: "param")
XCTAssertEqual(components[ref1], .integer(required: false))
XCTAssertEqual(components.dereference(ref1), components[ref1])
XCTAssertNil(components[ref2])
XCTAssertNil(components[ref3])
let ref4 = JSONReference<JSONSchema>.InternalReference.component(name: "world")
let ref5 = JSONReference<JSONSchema>.InternalReference.component(name: "missing")
let ref6 = JSONReference<OpenAPI.Parameter>.InternalReference.component(name: "param")
XCTAssertEqual(components[ref4], .integer(required: false))
XCTAssertNil(components[ref5])
XCTAssertNil(components[ref6])
let ref7 = JSONReference<JSONSchema>.external(URL(string: "hello.json")!)
XCTAssertNil(components[ref7])
XCTAssertThrowsError(try components.contains(ref7))
}
func test_failedExternalReferenceLookup() {
let components = OpenAPI.Components.noComponents
let ref = JSONReference<JSONSchema>.external(URL(string: "hi.json#/hello")!)
XCTAssertThrowsError(try components.contains(ref)) { error in
XCTAssertEqual(String(describing: error), "You cannot look up remote JSON references in the Components Object local to this file.")
}
}
func test_referenceCreation() throws {
let components = OpenAPI.Components(
schemas: [
"hello": .string,
"world": .integer(required: false)
]
)
let ref1 = try components.reference(named: "hello", ofType: JSONSchema.self)
let ref2 = try components.reference(named: "world", ofType: JSONSchema.self)
XCTAssertEqual(ref1, .component(named: "hello"))
XCTAssertEqual(ref2, .component(named: "world"))
XCTAssertThrowsError(try components.reference(named: "missing", ofType: JSONSchema.self))
XCTAssertThrowsError(try components.reference(named: "hello", ofType: OpenAPI.Parameter.self))
}
func test_failedReferenceCreation() {
let components = OpenAPI.Components.noComponents
XCTAssertThrowsError(try components.reference(named: "hello", ofType: JSONSchema.self)) { error in
XCTAssertEqual(String(describing: error), "You cannot create references to components that do not exist in the Components Object this way. You can construct a `JSONReference` directly if you need to circumvent this protection. 'hello' was not found in schemas.")
}
}
func test_lookupEachType() throws {
let components = OpenAPI.Components(
schemas: [
"one": .string
],
responses: [
"two": .init(description: "hello", content: [:])
],
parameters: [
"three": .init(name: "hello", context: .query, schema: .string)
],
examples: [
"four": .init(value: .init(URL(string: "hello.com/hello")!))
],
requestBodies: [
"five": .init(content: [:])
],
headers: [
"six": .init(schema: .string)
],
securitySchemes: [
"seven": .apiKey(name: "hello", location: .cookie)
]
)
let ref1 = try components.reference(named: "one", ofType: JSONSchema.self)
let ref2 = try components.reference(named: "two", ofType: OpenAPI.Response.self)
let ref3 = try components.reference(named: "three", ofType: OpenAPI.Parameter.self)
let ref4 = try components.reference(named: "four", ofType: OpenAPI.Example.self)
let ref5 = try components.reference(named: "five", ofType: OpenAPI.Request.self)
let ref6 = try components.reference(named: "six", ofType: OpenAPI.Header.self)
let ref7 = try components.reference(named: "seven", ofType: OpenAPI.SecurityScheme.self)
XCTAssertEqual(components[ref1], .string)
XCTAssertEqual(components[ref2], .init(description: "hello", content: [:]))
XCTAssertEqual(components[ref3], .init(name: "hello", context: .query, schema: .string))
XCTAssertEqual(components[ref4], .init(value: .init(URL(string: "hello.com/hello")!)))
XCTAssertEqual(components[ref5], .init(content: [:]))
XCTAssertEqual(components[ref6], .init(schema: .string))
XCTAssertEqual(components[ref7], .apiKey(name: "hello", location: .cookie))
}
func test_dereference() {
let components = OpenAPI.Components(
schemas: [
"hello": .boolean
]
)
let schemas: [Either<JSONReference<JSONSchema>, JSONSchema>] = [
.schema(.string),
.reference(.component(named: "hello")),
.reference(.component(named: "not_there"))
]
let resolvedSchemas = schemas.map(components.dereference)
XCTAssertEqual(resolvedSchemas, [.string, .boolean, nil])
}
func test_forceDereference() throws {
let components = OpenAPI.Components(
schemas: [
"hello": .boolean
]
)
let schema1: Either<JSONReference<JSONSchema>, JSONSchema> = .reference(.component(named: "hello"))
let resolvedSchema = try components.forceDereference(schema1)
XCTAssertEqual(resolvedSchema, .boolean)
let schema2: Either<JSONReference<JSONSchema>, JSONSchema> = .reference(.component(named: "not_there"))
XCTAssertThrowsError(try components.forceDereference(schema2)) { error in
XCTAssertEqual(error as? OpenAPI.Components.MissingReferenceError, .referenceMissingOnLookup(name: "not_there", key: "schemas"))
XCTAssertEqual((error as? OpenAPI.Components.MissingReferenceError)?.description, "Failed to look up a JSON Reference. 'not_there' was not found in schemas.")
}
let schema3: Either<JSONReference<JSONSchema>, JSONSchema> = .reference(.external(URL(string: "https://hi.com/hi.json#/hello/world")!))
XCTAssertThrowsError(try components.forceDereference(schema3)) { error in
XCTAssertEqual(error as? OpenAPI.Components.ReferenceError, .cannotLookupRemoteReference)
}
let reference1: JSONReference<JSONSchema> = .component(named: "hello")
let resolvedSchema2 = try components.forceDereference(reference1)
XCTAssertEqual(resolvedSchema2, .boolean)
let reference2: JSONReference<JSONSchema> = .component(named: "not_there")
XCTAssertThrowsError(try components.forceDereference(reference2)) { error in
XCTAssertEqual(error as? OpenAPI.Components.MissingReferenceError, .referenceMissingOnLookup(name: "not_there", key: "schemas"))
}
let reference3: JSONReference<JSONSchema> = .external(URL(string: "https://hi.com/hi.json#/hello/world")!)
XCTAssertThrowsError(try components.forceDereference(reference3)) { error in
XCTAssertEqual(error as? OpenAPI.Components.ReferenceError, .cannotLookupRemoteReference)
}
}
func test_goodKeysNoProblems() {
XCTAssertNil(OpenAPI.ComponentKey.problem(with: "hello"))
XCTAssertNil(OpenAPI.ComponentKey.problem(with: "_hell.o-"))
XCTAssertNil(OpenAPI.ComponentKey.problem(with: "HELLO"))
}
func test_badKeysHaveProblems() {
XCTAssertEqual(OpenAPI.ComponentKey.problem(with: "#hello"), "Keys for components in the Components Object must conform to the regex `^[a-zA-Z0-9\\.\\-_]+$`. '#hello' does not..")
XCTAssertEqual(OpenAPI.ComponentKey.problem(with: ""), "Keys for components in the Components Object must conform to the regex `^[a-zA-Z0-9\\.\\-_]+$`. '' does not..")
}
}
// MARK: - Codable Tests
extension ComponentsTests {
func test_minimal_encode() throws {
let t1 = OpenAPI.Components()
let encoded = try orderUnstableTestStringFromEncoding(of: t1)
assertJSONEquivalent(
encoded,
"""
{
}
"""
)
}
func test_minimal_decode() throws {
let t1 =
"""
{
}
""".data(using: .utf8)!
let decoded = try orderUnstableDecode(OpenAPI.Components.self, from: t1)
XCTAssertEqual(decoded, OpenAPI.Components())
}
func test_maximal_encode() throws {
let t1 = OpenAPI.Components(
schemas: [
"one": .string
],
responses: [
"two": .init(description: "hello", content: [:])
],
parameters: [
"three": .init(name: "hi", context: .query, content: [:])
],
examples: [
"four": .init(value: .init(URL(string: "http://address.com")!))
],
requestBodies: [
"five": .init(content: [:])
],
headers: [
"six": .init(schema: .string)
],
securitySchemes: [
"seven": .http(scheme: "cool")
],
vendorExtensions: ["x-specialFeature": ["hello", "world"]]
)
let encoded = try orderUnstableTestStringFromEncoding(of: t1)
assertJSONEquivalent(
encoded,
"""
{
"examples" : {
"four" : {
"externalValue" : "http:\\/\\/address.com"
}
},
"headers" : {
"six" : {
"schema" : {
"type" : "string"
}
}
},
"parameters" : {
"three" : {
"content" : {
},
"in" : "query",
"name" : "hi"
}
},
"requestBodies" : {
"five" : {
"content" : {
}
}
},
"responses" : {
"two" : {
"description" : "hello"
}
},
"schemas" : {
"one" : {
"type" : "string"
}
},
"securitySchemes" : {
"seven" : {
"scheme" : "cool",
"type" : "http"
}
},
"x-specialFeature" : [
"hello",
"world"
]
}
"""
)
}
func test_maximal_decode() throws {
let t1 =
"""
{
"examples" : {
"four" : {
"externalValue" : "http:\\/\\/address.com"
}
},
"headers" : {
"six" : {
"schema" : {
"type" : "string"
}
}
},
"parameters" : {
"three" : {
"content" : {
},
"in" : "query",
"name" : "hi"
}
},
"requestBodies" : {
"five" : {
"content" : {
}
}
},
"responses" : {
"two" : {
"description" : "hello"
}
},
"schemas" : {
"one" : {
"type" : "string"
}
},
"securitySchemes" : {
"seven" : {
"scheme" : "cool",
"type" : "http"
}
},
"x-specialFeature" : [
"hello",
"world"
]
}
""".data(using: .utf8)!
let decoded = try orderUnstableDecode(OpenAPI.Components.self, from: t1)
XCTAssertEqual(
decoded,
OpenAPI.Components(
schemas: [
"one": .string(required: false)
],
responses: [
"two": .init(description: "hello", content: [:])
],
parameters: [
"three": .init(name: "hi", context: .query, content: [:])
],
examples: [
"four": .init(value: .init(URL(string: "http://address.com")!))
],
requestBodies: [
"five": .init(content: [:])
],
headers: [
"six": .init(schema: .string(required: false))
],
securitySchemes: [
"seven": .http(scheme: "cool")
],
vendorExtensions: ["x-specialFeature": ["hello", "world"]]
)
)
}
func test_doesNotFailDecodingLinks() {
let t1 = """
{
"links" : {
"link" : {
"operationId" : "test",
"parameters" : {
"userId" : "$response.body#/id",
"description" : "A link test"
}
}
}
}
""".data(using: .utf8)!
XCTAssertNoThrow(try orderUnstableDecode(OpenAPI.Components.self, from: t1))
}
func test_doesNotFailDecodingCallbacks() {
let t1 = """
{
"callbacks" : {
"callback" : {
"{$request.query.queryUrl}" : {
"post" : {
"responses" : {
"200" : {
"description" : "callback successfully processed"
}
}
}
}
}
}
}
""".data(using: .utf8)!
XCTAssertNoThrow(try orderUnstableDecode(OpenAPI.Components.self, from: t1))
}
}
// MARK: ComponentKey
extension ComponentsTests {
func test_acceptableKeys_encode() throws {
let t1 = ComponentKeyWrapper(key: "shell0")
let t2 = ComponentKeyWrapper(key: "hello_world1234-.")
let encoded1 = try orderUnstableTestStringFromEncoding(of: t1)
let encoded2 = try orderUnstableTestStringFromEncoding(of: t2)
assertJSONEquivalent(
encoded1,
"""
{
"key" : "shell0"
}
"""
)
assertJSONEquivalent(
encoded2,
"""
{
"key" : "hello_world1234-."
}
"""
)
}
func test_acceptableKeys_decode() throws {
let t1 =
"""
{
"key": "shell0"
}
""".data(using: .utf8)!
let t2 =
"""
{
"key": "1234-_."
}
""".data(using: .utf8)!
let decoded1 = try orderUnstableDecode(ComponentKeyWrapper.self, from: t1)
let decoded2 = try orderUnstableDecode(ComponentKeyWrapper.self, from: t2)
XCTAssertEqual(decoded1.key, "shell0")
XCTAssertEqual(decoded2.key, "1234-_.")
}
func test_unacceptableKeys_encode() {
let t1 = ComponentKeyWrapper(key: "$hell0")
let t2 = ComponentKeyWrapper(key: "hello world")
XCTAssertThrowsError(try orderUnstableEncode(t1))
XCTAssertThrowsError(try orderUnstableEncode(t2))
}
func test_unacceptableKeys_decode() {
let t1 =
"""
{
"key": "$hell0"
}
""".data(using: .utf8)!
let t2 =
"""
{
"key": "hello world"
}
""".data(using: .utf8)!
XCTAssertThrowsError(try orderUnstableDecode(ComponentKeyWrapper.self, from: t1))
XCTAssertThrowsError(try orderUnstableDecode(ComponentKeyWrapper.self, from: t2))
}
}
fileprivate struct ComponentKeyWrapper: Codable {
let key: OpenAPI.ComponentKey
}
| 28.746615 | 274 | 0.572265 |
1ebbfe5856f14b89df499c3e135a96ad316841e7 | 3,012 | /// Copyright (c) 2019 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
struct Toy: Encodable {
var name: String
var label: String
enum CodingKeys: CodingKey {
case name, label
}
// MARK: 自定义编码
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
var labelContainer = container.nestedUnkeyedContainer(forKey: .label)
try labelContainer.encode(name.lowercased())
try labelContainer.encode(name.uppercased())
try labelContainer.encode(name)
}
}
extension Toy: Decodable {
// MARK: 自定义解码
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
var labelContainer = try container.nestedUnkeyedContainer(forKey: .label)
var labelName = ""
while !labelContainer.isAtEnd {
labelName = try labelContainer.decode(String.self)
}
label = labelName
}
}
let toy = Toy(name: "Teddy Bear", label: "Teddy Bear")
let encoder = JSONEncoder()
let decoder = JSONDecoder()
// MARK: Model -> JSON
let data = try encoder.encode(toy)
let string = String(data: data, encoding: .utf8)!
// MARK: JSON -> Model
let sameToy = try decoder.decode(Toy.self, from: data)
| 39.116883 | 83 | 0.714807 |
1cb5db4abbd55eda1c13b6a063447326e60955fb | 287 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
import Foundation
protocol IdentifiableType {
associatedtype Identity: Hashable
var identity: Identity { get }
}
| 22.076923 | 91 | 0.738676 |
d6ea631ad391c38b5e0943ad85b75b89e145c33b | 1,605 | //
// Gallery.swift
// NetworkingTestExample
//
// Created by Stoyan Stoyanov on 25/03/22.
// Copyright © 2022 Stoyan Stoyanov. All rights reserved.
//
import Foundation
import NetworkingKit
/// Fetch images from Imgur gallery.
///
/// Due to caching limitations of Imgur, it's not possible to change the result size of the gallery resources.
///
/// This container has all things regarding the `Gallery` call.
/// If you want to call the endpoint initialize this.
final class GalleryEndpoint: Endpoint.WithResponseTypeOnly<Basic<[Image]>> {
let section: Section
let sortedUsing: SortOption
let inTimeWindow: Window
let page: Int
let appClientId: String
override var host: String { "api.imgur.com" }
override var path: String { "/3/gallery/\(section.rawValue)/\(sortedUsing.rawValue)/\(inTimeWindow.rawValue)/\(page)" }
override var headers: [HTTP.Header] {
[.init(.authorization, value: "Client-ID \(appClientId)")]
}
@discardableResult public init(section: Section = .hot, sortedUsing: SortOption = .top, inTimeWindow: Window = .all, page: Int, appClientId: String, completion: @escaping (Basic<[Image]>?, Endpoint.Error?) -> ()) {
self.sortedUsing = sortedUsing
self.inTimeWindow = inTimeWindow
self.page = page
self.appClientId = appClientId
self.section = section
super.init(completion: completion)
}
@available(*, unavailable)
override init(completion: @escaping (Basic<[Image]>?, Endpoint.Error?) -> ()) {
fatalError("not implemented")
}
}
| 32.1 | 218 | 0.671028 |
61bf9d37fa6d37a1c5a408d87986abeb565b7b75 | 4,177 | //
// BubbleNode.swift
// BubblePond
//
// Created by Matt Blair on 4/19/19.
// Copyright © 2019 Elsewise. All rights reserved.
//
import SpriteKit
extension Notification.Name {
static let BubbleWillFade = NSNotification.Name("BubbleWillFade")
}
class BubbleNode: SKSpriteNode {
static let noteNameKey: String = "NoteNameKey"
// DEPRECATED?
//let noteName: String
let collision1NoteName: String
let collision2NoteName: String
// have this vary over time and determine alpha/amplitude?
var vitality: Float = 0.0
var isMortal: Bool = true
var lifeDuration: Int
var lastSounded: Date?
// Additional properties to consider:
// collisions left
// collision behavior...enum?
// duration before fade
init(note1: String, note2: String, imageName: String, diameter: CGFloat, duration: Int) {
print("Adding node which will last \(duration) seconds")
//noteName = note
collision1NoteName = note1
collision2NoteName = note2
lifeDuration = duration
// TODO: Read these from the score, or add as init parameter
//let imageName = "sk180313-dot-\(Int.random(in: 1...7))"
// make this initializer failable based on success of this?
let texture = SKTexture(imageNamed: imageName)
let dotSize = CGSize(width: diameter, height: diameter)
// have to call this b/c it's the designated init, but color isn't used.
super.init(texture: texture, color: .white, size: dotSize)
// TODO: Is this used for anything? Debugging?
name = "\(collision1NoteName)-\(collision2NoteName)"
alpha = 0.0
// TODO: separate method for configuring physics body? here? or in scene?
// Does the physicBody have to be added to a scene before config?
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented for BubbleNode")
}
// MARK: - Physics
func physicsRadius(multiplier: Float) -> CGFloat {
return max(frame.size.width / 2, frame.size.height / 2) * CGFloat(multiplier)
}
func configurePhysics(score: BubblePondScore) {
let radius = physicsRadius(multiplier: score.physicsRadiusMultiplier)
physicsBody = SKPhysicsBody(circleOfRadius: radius)
physicsBody?.velocity = score.randomInitialVelocity()
print("Bubble density: \(physicsBody?.density ?? 0.0)")
print("Bubble default mass: \(physicsBody?.mass ?? 0.0)")
physicsBody?.mass = 0.2
physicsBody?.linearDamping = 0.05
physicsBody?.categoryBitMask = PhysicsBodyTypes.bubble.rawValue
physicsBody?.categoryBitMask = PhysicsBodyTypes.bubble.rawValue | PhysicsBodyTypes.edge.rawValue
physicsBody?.contactTestBitMask = PhysicsBodyTypes.bubble.rawValue | PhysicsBodyTypes.edge.rawValue
}
// MARK: - Lifecycle
func arrive() {
// Have this call configurePhysics?
run(SKAction.fadeIn(withDuration: 2.0))
}
func age(by duration: Int = 1) {
guard isMortal else { return }
lifeDuration -= duration
if lifeDuration < 1 {
departTheScene()
}
}
private func departTheScene() {
// This may save a slight amount of energy...
physicsBody = nil
run(SKAction.sequence([SKAction.fadeOut(withDuration: 2.0),
SKAction.removeFromParent()]))
// Use this if orchestra should play this node's specific note:
/*
NotificationCenter.default.post(name: .BubbleWillFade,
object: self,
userInfo: [ BubbleNode.noteNameKey: noteName ])
*/
// Use this if the orchestra chooses the note
NotificationCenter.default.post(name: .BubbleWillFade,
object: self)
}
}
| 30.940741 | 107 | 0.5966 |
1ae230c73ed5b132779945af6549455d898dade7 | 3,221 | //
// CrowdinSupportedLanguages.swift
// CrowdinSDK
//
// Created by Serhii Londar on 3/26/19.
//
import Foundation
extension LanguagesResponseData: CrowdinLanguage { }
class CrowdinSupportedLanguages {
static let shared = CrowdinSupportedLanguages()
let api = LanguagesAPI()
fileprivate enum Strings: String {
case SupportedLanguages
case Crowdin
}
fileprivate enum Keys: String {
case lastUpdatedDate = "CrowdinSupportedLanguages.lastUpdatedDate"
}
fileprivate var filePath: String {
return CrowdinFolder.shared.path + String.pathDelimiter + Strings.Crowdin.rawValue + String.pathDelimiter + Strings.SupportedLanguages.rawValue + FileType.json.extension
}
fileprivate var lastUpdatedDate: Date? {
set {
UserDefaults.standard.set(newValue, forKey: Keys.lastUpdatedDate.rawValue)
UserDefaults.standard.synchronize()
}
get {
return UserDefaults.standard.value(forKey: Keys.lastUpdatedDate.rawValue) as? Date
}
}
var loaded: Bool { return supportedLanguages != nil }
var supportedLanguages: LanguagesResponse? {
didSet {
saveSupportedLanguages()
}
}
init() {
readSupportedLanguages()
updateSupportedLanguagesIfNeeded()
}
func updateSupportedLanguagesIfNeeded() {
guard self.supportedLanguages != nil else {
self.downloadSupportedLanguages()
return
}
guard let lastUpdatedDate = lastUpdatedDate else {
self.downloadSupportedLanguages()
return
}
if Date().timeIntervalSince(lastUpdatedDate) > 7 * 24 * 60 * 60 {
self.downloadSupportedLanguages()
}
}
func downloadSupportedLanguages(completion: (() -> Void)? = nil, error: ((Error) -> Void)? = nil) {
api.getLanguages(limit: 500, offset: 0) { (supportedLanguages, err) in
if let err = err {
error?(err)
return
}
guard let supportedLanguages = supportedLanguages else { return }
self.supportedLanguages = supportedLanguages
self.lastUpdatedDate = Date()
CrowdinLogsCollector.shared.add(log: CrowdinLog(type: .info, message: "Download supported languages success"))
completion?()
}
}
func downloadSupportedLanguagesSync() {
let semaphore = DispatchSemaphore(value: 0)
self.downloadSupportedLanguages(completion: {
semaphore.signal()
}, error: { _ in
semaphore.signal()
})
_ = semaphore.wait(timeout: .now() + 60)
}
fileprivate func saveSupportedLanguages() {
guard let data = try? JSONEncoder().encode(supportedLanguages) else { return }
try? data.write(to: URL(fileURLWithPath: filePath), options: Data.WritingOptions.atomic)
}
fileprivate func readSupportedLanguages() {
guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else { return }
self.supportedLanguages = try? JSONDecoder().decode(LanguagesResponse.self, from: data)
}
}
| 33.552083 | 177 | 0.63117 |
d929f9a2e73bc364b36b0066b939fe9eb1e2ee1f | 1,415 | // RUN: %target-swift-frontend -swift-version 5 -enable-implicit-dynamic -I %t -emit-silgen %s | %FileCheck %s
// Make sure that these functions are not implicitly marked dynamic.
public struct NotImplicitDynamic {
@inlinable
public var x : Int {
// CHECK: sil [serialized] [ossa] @$s16implicit_dynamic18NotImplicitDynamicV1xSivg
// CHECK: sil [serialized] [ossa] @$s16implicit_dynamic18NotImplicitDynamicV1xSivs
get {
return 1
}
set {
}
}
@inlinable
public var y : Int {
// CHECK: sil [serialized] [ossa] @$s16implicit_dynamic18NotImplicitDynamicV1ySivg
return 1
}
public var z : Int {
// CHECK: sil [serialized] [ossa] @$s16implicit_dynamic18NotImplicitDynamicV1zSivg
// CHECK: sil [ossa] @$s16implicit_dynamic18NotImplicitDynamicV1zSivs
@inlinable
get {
return 1
}
set {
}
}
@_transparent
public var x2 : Int {
// CHECK: sil [transparent] [serialized] [ossa] @$s16implicit_dynamic18NotImplicitDynamicV2x2Sivg
// CHECK: sil [transparent] [serialized] [ossa] @$s16implicit_dynamic18NotImplicitDynamicV2x2Sivs
get {
return 1
}
set {
}
}
public subscript() -> Int {
// CHECK: sil [transparent] [serialized] [ossa] @$s16implicit_dynamic18NotImplicitDynamicVSiycig
@_transparent
get{
return 1
}
}
}
// CHECK: sil [ossa] @foobar
@_silgen_name("foobar")
public func noImplicitDynamicFunc() {
}
| 24.396552 | 111 | 0.691166 |
506025b4a63478b93975aeeff4a4360da6f59647 | 10,170 | import UIKit
import AVFoundation
import Vision
// controlling the pace of the machine vision analysis
var lastAnalysis: TimeInterval = 0
var pace: TimeInterval = 0.33 // in seconds, classification will not repeat faster than this value
// performance tracking
let trackPerformance = false // use "true" for performance logging
var frameCount = 0
let framesPerSample = 10
var startDate = NSDate.timeIntervalSinceReferenceDate
class ViewController: UIViewController {
@IBOutlet weak var previewView: UIView!
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var lowerView: UIView!
var previewLayer: AVCaptureVideoPreviewLayer!
let bubbleLayer = BubbleLayer(string: "")
let queue = DispatchQueue(label: "videoQueue")
var captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice?
let videoOutput = AVCaptureVideoDataOutput()
var unknownCounter = 0 // used to track how many unclassified images in a row
let confidence: Float = 0.7
// MARK: Load the Model
let targetImageSize = CGSize(width: 227, height: 227) // must match model data input
lazy var classificationRequest: [VNRequest] = {
do {
// Load the Custom Vision model.
// To add a new model, drag it to the Xcode project browser making sure that the "Target Membership" is checked.
// Then update the following line with the name of your new model.
let model = try VNCoreMLModel(for: Duck().model)
let classificationRequest = VNCoreMLRequest(model: model, completionHandler: self.handleClassification)
return [ classificationRequest ]
} catch {
fatalError("Can't load Vision ML model: \(error)")
}
}()
// MARK: Handle image classification results
func handleClassification(request: VNRequest, error: Error?) {
guard let observations = request.results as? [VNClassificationObservation]
else { fatalError("unexpected result type from VNCoreMLRequest") }
guard let best = observations.first else {
fatalError("classification didn't return any results")
}
// Use results to update user interface (includes basic filtering)
print("\(best.identifier): \(best.confidence)")
if best.identifier.starts(with: "Unknown") || best.confidence < confidence {
if self.unknownCounter < 3 { // a bit of a low-pass filter to avoid flickering
self.unknownCounter += 1
} else {
self.unknownCounter = 0
DispatchQueue.main.async {
self.bubbleLayer.string = nil
}
}
} else {
self.unknownCounter = 0
DispatchQueue.main.async {
// Trimming labels because they sometimes have unexpected line endings which show up in the GUI
self.bubbleLayer.string = best.identifier.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewView.layer.addSublayer(previewLayer)
}
override func viewDidAppear(_ animated: Bool) {
bubbleLayer.opacity = 0.0
bubbleLayer.position.x = self.view.frame.width / 2.0
bubbleLayer.position.y = lowerView.frame.height / 2
lowerView.layer.addSublayer(bubbleLayer)
setupCamera()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer.frame = previewView.bounds;
}
// MARK: Camera handling
func setupCamera() {
let deviceDiscovery = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .back)
if let device = deviceDiscovery.devices.last {
captureDevice = device
beginSession()
}
}
func beginSession() {
do {
videoOutput.videoSettings = [((kCVPixelBufferPixelFormatTypeKey as NSString) as String) : (NSNumber(value: kCVPixelFormatType_32BGRA) as! UInt32)]
videoOutput.alwaysDiscardsLateVideoFrames = true
videoOutput.setSampleBufferDelegate(self, queue: queue)
captureSession.sessionPreset = .hd1920x1080
captureSession.addOutput(videoOutput)
let input = try AVCaptureDeviceInput(device: captureDevice!)
captureSession.addInput(input)
captureSession.startRunning()
} catch {
print("error connecting to capture device")
}
}
}
// MARK: Video Data Delegate
extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
// called for each frame of video
func captureOutput(_ captureOutput: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let currentDate = NSDate.timeIntervalSinceReferenceDate
// control the pace of the machine vision to protect battery life
if currentDate - lastAnalysis >= pace {
lastAnalysis = currentDate
} else {
return // don't run the classifier more often than we need
}
// keep track of performance and log the frame rate
if trackPerformance {
frameCount = frameCount + 1
if frameCount % framesPerSample == 0 {
let diff = currentDate - startDate
if (diff > 0) {
if pace > 0.0 {
print("WARNING: Frame rate of image classification is being limited by \"pace\" setting. Set to 0.0 for fastest possible rate.")
}
print("\(String.localizedStringWithFormat("%0.2f", (diff/Double(framesPerSample))))s per frame (average)")
}
startDate = currentDate
}
}
// Crop and resize the image data.
// Note, this uses a Core Image pipeline that could be appended with other pre-processing.
// If we don't want to do anything custom, we can remove this step and let the Vision framework handle
// crop and resize as long as we are careful to pass the orientation properly.
guard let croppedBuffer = croppedSampleBuffer(sampleBuffer, targetSize: targetImageSize) else {
return
}
do {
let classifierRequestHandler = VNImageRequestHandler(cvPixelBuffer: croppedBuffer, options: [:])
try classifierRequestHandler.perform(classificationRequest)
} catch {
print(error)
}
}
}
let context = CIContext()
var rotateTransform: CGAffineTransform?
var scaleTransform: CGAffineTransform?
var cropTransform: CGAffineTransform?
var resultBuffer: CVPixelBuffer?
func croppedSampleBuffer(_ sampleBuffer: CMSampleBuffer, targetSize: CGSize) -> CVPixelBuffer? {
guard let imageBuffer: CVImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
fatalError("Can't convert to CVImageBuffer.")
}
// Only doing these calculations once for efficiency.
// If the incoming images could change orientation or size during a session, this would need to be reset when that happens.
if rotateTransform == nil {
let imageSize = CVImageBufferGetEncodedSize(imageBuffer)
let rotatedSize = CGSize(width: imageSize.height, height: imageSize.width)
guard targetSize.width < rotatedSize.width, targetSize.height < rotatedSize.height else {
fatalError("Captured image is smaller than image size for model.")
}
let shorterSize = (rotatedSize.width < rotatedSize.height) ? rotatedSize.width : rotatedSize.height
rotateTransform = CGAffineTransform(translationX: imageSize.width / 2.0, y: imageSize.height / 2.0).rotated(by: -CGFloat.pi / 2.0).translatedBy(x: -imageSize.height / 2.0, y: -imageSize.width / 2.0)
let scale = targetSize.width / shorterSize
scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
// Crop input image to output size
let xDiff = rotatedSize.width * scale - targetSize.width
let yDiff = rotatedSize.height * scale - targetSize.height
cropTransform = CGAffineTransform(translationX: xDiff/2.0, y: yDiff/2.0)
}
// Convert to CIImage because it is easier to manipulate
let ciImage = CIImage(cvImageBuffer: imageBuffer)
let rotated = ciImage.transformed(by: rotateTransform!)
let scaled = rotated.transformed(by: scaleTransform!)
let cropped = scaled.transformed(by: cropTransform!)
// Note that the above pipeline could be easily appended with other image manipulations.
// For example, to change the image contrast. It would be most efficient to handle all of
// the image manipulation in a single Core Image pipeline because it can be hardware optimized.
// Only need to create this buffer one time and then we can reuse it for every frame
if resultBuffer == nil {
let result = CVPixelBufferCreate(kCFAllocatorDefault, Int(targetSize.width), Int(targetSize.height), kCVPixelFormatType_32BGRA, nil, &resultBuffer)
guard result == kCVReturnSuccess else {
fatalError("Can't allocate pixel buffer.")
}
}
// Render the Core Image pipeline to the buffer
context.render(cropped, to: resultBuffer!)
// For debugging
// let image = imageBufferToUIImage(resultBuffer!)
// print(image.size) // set breakpoint to see image being provided to CoreML
return resultBuffer
}
// Only used for debugging.
// Turns an image buffer into a UIImage that is easier to display in the UI or debugger.
func imageBufferToUIImage(_ imageBuffer: CVImageBuffer) -> UIImage {
CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
let quartzImage = context!.makeImage()
CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
let image = UIImage(cgImage: quartzImage!, scale: 1.0, orientation: .right)
return image
}
| 38.377358 | 202 | 0.720747 |
716ab6e995548eae85832e96dd1a03a841c01dd3 | 129 | import Foundation
public protocol NamedEntityContract: EntityContract {
var name: String { get }
var url: URL { get }
}
| 18.428571 | 53 | 0.705426 |
f7038f822e83feafba8d8ebfec3720953da8eb9f | 2,008 | //
// LSystemElementTransition.swift
//
//
// Created by Enzo Maruffa Moreira on 24/12/20.
//
import Foundation
/// A struct that defines how the parameters from an input element translate into the parameters for an output element
public struct LSystemParametersTransition {
/// The input element this transition applies to
public let input: String
/// The output element this transition applies to
public let output: String
/// A function that specify how the parameters are transformed for an input into an output
public let transition: ([String: Any]?) -> ([String: Any])
/// Creates a `LSystemParametersTransition`
/// - Parameters:
/// - input: The input element this transition applies to
/// - output: The output element this transition applies to
/// - transition: A function that specify how the parameters are transformed for an input into an output
public init(input: String,
output: String,
transition: @escaping ([String: Any]?) -> ([String: Any])) {
self.input = input
self.output = output
self.transition = transition
}
/// Checks if a transition is valid given an input and output
/// - Parameters:
/// - input: The input to compare to
/// - output: The output to compare to
/// - Returns: A `Bool` that if true means the transition is valid
public func isValid(forInput input: String, output: String) -> Bool {
return input == self.input
&& output == self.output
}
/// Performs a transition of an `inputElement` into an output
/// - Parameter inputElement: The `inputElement` to use in the transition
/// - Returns: The output generated by the transition
public func performTransition(inputElement: LSystemElement) -> LSystemElement {
let newParameters = transition(inputElement.parameters)
return LSystemElement(output, parameters: newParameters)
}
}
| 37.185185 | 118 | 0.661853 |
89a9380a33407dd79b75b0f42f51a210345c48d4 | 4,215 | //
// JCFNSDateExtension.swift
// Many Pages
//
// Created by Julio Cesar Fausto on 4/14/15.
// Copyright (c) 2015 Julio Cesar Fausto. All rights reserved.
//
// This is a NSDate extension compliant with Swift 1.2 that
// offers some helper functions for dealing with dates
//
// This piece of code is released under MIT licence.
// Check it here: http://jcfausto.mit-license.org
// You can find me at twitter @jcfausto | [email protected]
import Foundation
/**
A NSDate extension with helpers to easy your development life
*/
extension NSDate {
/**
Returns a NSDate representing the first day of the current week
*/
func beginningOfWeek() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate())
components.day = (components.day - (components.weekday - 1))
components.weekday = 1 //The first day of the week
return calendar.dateFromComponents(components)!
}
/**
Returns a NSDate representing the last day of the current week
*/
func endOfWeek() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate())
components.day = (components.day + (7 - components.weekday))
components.hour = 23
components.minute = 59
components.second = 59
return calendar.dateFromComponents(components)!
}
/**
Returns a NSDate representing the first day of the current month
*/
func beginningOfMonth() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate())
components.day = 1
components.hour = 0
components.minute = 0
components.second = 0
return calendar.dateFromComponents(components)!
}
/**
Returns a NSDate representing the last day of the current month
*/
func endOfMonth() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate())
let daysInMonth: NSRange = calendar.rangeOfUnit(NSCalendarUnit.CalendarUnitDay, inUnit: NSCalendarUnit.CalendarUnitMonth, forDate: NSDate())
components.day = daysInMonth.length
components.hour = 23
components.minute = 59
components.second = 59
return calendar.dateFromComponents(components)!
}
/**
Returns a NSDate representing the first day of the current year
*/
func beginningOfYear() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate())
components.day = 1
components.month = 1
components.hour = 0
components.minute = 0
components.second = 0
return calendar.dateFromComponents(components)!
}
/**
Returns a NSDate representing the last day of the current year
*/
func endOfYear() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate())
components.day = 31
components.month = 12
components.hour = 23
components.minute = 59
components.second = 59
return calendar.dateFromComponents(components)!
}
}
| 33.188976 | 202 | 0.65172 |
21edc464856deb7b21282fa29dd2480ea192a5a4 | 8,837 | //
// Picker+UIImageView.swift
// HXPHPicker
//
// Created by Slience on 2021/5/26.
//
import UIKit
import AVKit
#if canImport(Kingfisher)
import Kingfisher
#endif
extension UIImageView {
#if canImport(Kingfisher)
@discardableResult
func setImage(
for asset: PhotoAsset,
urlType: DonwloadURLType,
indicatorColor: UIColor? = nil,
progressBlock: DownloadProgressBlock? = nil,
downloadTask: ((Kingfisher.DownloadTask?) -> Void)? = nil,
completionHandler: ((UIImage?, KingfisherError?, PhotoAsset) -> Void)? = nil
) -> Any? {
#if HXPICKER_ENABLE_EDITOR
if let photoEdit = asset.photoEdit {
if urlType == .thumbnail {
image = photoEdit.editedImage
completionHandler?(photoEdit.editedImage, nil, asset)
}else {
do {
let imageData = try Data(contentsOf: photoEdit.editedImageURL)
let img = DefaultImageProcessor.default.process(item: .data(imageData), options: .init([]))!
let kfView = self as? AnimatedImageView
kfView?.image = img
}catch {
image = photoEdit.editedImage
}
completionHandler?(photoEdit.editedImage, nil, asset)
}
return nil
}else if let videoEdit = asset.videoEdit {
image = videoEdit.coverImage
completionHandler?(videoEdit.coverImage, nil, asset)
return nil
}
#endif
let isThumbnail = urlType == .thumbnail
if isThumbnail {
kf.indicatorType = .activity
if let color = indicatorColor {
(kf.indicator?.view as? UIActivityIndicatorView)?.color = color
}
}
var url = URL(string: "")
var placeholderImage: UIImage?
var options: KingfisherOptionsInfo = []
var loadVideoCover: Bool = false
if let imageAsset = asset.networkImageAsset {
url = isThumbnail ? imageAsset.thumbnailURL : imageAsset.originalURL
placeholderImage = UIImage.image(for: imageAsset.placeholder)
let processor = DownsamplingImageProcessor(size: imageAsset.thumbnailSize)
options = isThumbnail ?
[.onlyLoadFirstFrame, .processor(processor), .cacheOriginalImage] :
[]
}else if let videoAsset = asset.networkVideoAsset {
if let coverImage = videoAsset.coverImage {
image = coverImage
completionHandler?(coverImage, nil, asset)
return nil
}else if let coverImageURL = videoAsset.coverImageURL {
url = coverImageURL
options = []
}else {
let key = videoAsset.videoURL.absoluteString
var videoURL: URL
if PhotoTools.isCached(forVideo: key) {
videoURL = PhotoTools.getVideoCacheURL(for: key)
}else {
videoURL = videoAsset.videoURL
}
loadVideoCover = true
url = videoURL
}
}else if let videoAsset = asset.localVideoAsset {
if let coverImage = videoAsset.image {
image = coverImage
completionHandler?(coverImage, nil, asset)
return nil
}
loadVideoCover = true
url = videoAsset.videoURL
}
if let url = url, loadVideoCover {
let provider = AVAssetImageDataProvider(assetURL: url, seconds: 0.1)
provider.assetImageGenerator.appliesPreferredTrackTransform = true
let task = KF.dataProvider(provider)
.onSuccess { (result) in
let image = result.image
let videoSize: CGSize?
if asset.isNetworkAsset {
videoSize = asset.networkVideoAsset?.videoSize
}else {
videoSize = asset.localVideoAsset?.videoSize
}
if let videoSize = videoSize, videoSize.equalTo(.zero) {
asset.localVideoAsset?.videoSize = image.size
asset.networkVideoAsset?.videoSize = image.size
}
completionHandler?(image, nil, asset)
}
.onFailure { (error) in
completionHandler?(nil, error, asset)
}
.set(to: self)
return task
}
return kf.setImage(
with: url,
placeholder: placeholderImage,
options: options,
progressBlock: progressBlock
) { (result) in
switch result {
case .success(let value):
switch asset.mediaSubType {
case .networkImage(_):
if asset.localImageAsset == nil {
let localImageAsset = LocalImageAsset(image: value.image)
asset.localImageAsset = localImageAsset
}
asset.networkImageAsset?.imageSize = value.image.size
if asset.localImageType != .original && !isThumbnail {
if let imageData = value.image.kf.data(format: asset.mediaSubType.isGif ? .GIF : .unknown) {
asset.networkImageAsset?.fileSize = imageData.count
}
asset.localImageType = urlType
}
case .networkVideo:
asset.networkVideoAsset?.coverImage = value.image
default: break
}
completionHandler?(value.image, nil, asset)
case .failure(let error):
completionHandler?(nil, error, asset)
}
}
}
#else
@discardableResult
func setVideoCoverImage(
for asset: PhotoAsset,
imageGenerator: ((AVAssetImageGenerator) -> Void)? = nil,
completionHandler: ((UIImage?, PhotoAsset) -> Void)? = nil
) -> Any? {
#if HXPICKER_ENABLE_EDITOR
if let videoEdit = asset.videoEdit {
completionHandler?(videoEdit.coverImage, asset)
return nil
}
#endif
var videoURL: URL?
if let videoAsset = asset.networkVideoAsset {
if let coverImage = videoAsset.coverImage {
completionHandler?(coverImage, asset)
return nil
}else {
let key = videoAsset.videoURL.absoluteString
if PhotoTools.isCached(forVideo: key) {
videoURL = PhotoTools.getVideoCacheURL(for: key)
}else {
videoURL = videoAsset.videoURL
}
}
}else if let videoAsset = asset.localVideoAsset {
if let coverImage = videoAsset.image {
completionHandler?(coverImage, asset)
return nil
}
videoURL = videoAsset.videoURL
}else {
completionHandler?(nil, asset)
return nil
}
return PhotoTools.getVideoThumbnailImage(
url: videoURL!,
atTime: 0.1,
imageGenerator: imageGenerator
) { videoURL, image, result in
if result == .cancelled { return }
if asset.isNetworkAsset {
asset.networkVideoAsset?.coverImage = image
}else {
asset.localVideoAsset?.image = image
}
completionHandler?(image, asset)
}
}
#endif
}
extension ImageView {
#if canImport(Kingfisher)
@discardableResult
func setImage(
for asset: PhotoAsset,
urlType: DonwloadURLType,
progressBlock: DownloadProgressBlock? = nil,
downloadTask: ((Kingfisher.DownloadTask?) -> Void)? = nil,
completionHandler: ((UIImage?, KingfisherError?, PhotoAsset) -> Void)? = nil
) -> Any? {
imageView.setImage(
for: asset,
urlType: urlType,
progressBlock: progressBlock,
downloadTask: downloadTask,
completionHandler: completionHandler
)
}
#else
@discardableResult
func setVideoCoverImage(
for asset: PhotoAsset,
imageGenerator: ((AVAssetImageGenerator) -> Void)? = nil,
completionHandler: ((UIImage?, PhotoAsset) -> Void)? = nil
) -> Any? {
imageView.setVideoCoverImage(
for: asset,
imageGenerator: imageGenerator,
completionHandler: completionHandler
)
}
#endif
}
| 37.28692 | 116 | 0.536947 |
abb1cf0cee1c8ea2a8f77b8b63dc2c94952914e3 | 15,828 | //
// RequestTests.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
@testable import AlamofireImage
import Foundation
import XCTest
class DataRequestTestCase: BaseTestCase {
var acceptableImageContentTypes: Set<String>!
// MARK: - Setup and Teardown
override func setUp() {
super.setUp()
acceptableImageContentTypes = DataRequest.acceptableImageContentTypes
}
override func tearDown() {
super.tearDown()
DataRequest.acceptableImageContentTypes = acceptableImageContentTypes
}
// MARK: - Tests - Image Content Type
func testThatAddingAcceptableImageContentTypesInsertsThemIntoTheGlobalList() {
// Given
let contentTypes: Set<String> = ["image/jpg", "binary/octet-stream"]
// When
let beforeCount = DataRequest.acceptableImageContentTypes.count
DataRequest.addAcceptableImageContentTypes(contentTypes)
let afterCount = DataRequest.acceptableImageContentTypes.count
// Then
XCTAssertEqual(beforeCount, 11, "before count should be 11")
XCTAssertEqual(afterCount, 13, "after count should be 13")
}
// MARK: - Tests - Image Serialization
func testThatImageResponseSerializerCanDownloadPNGImage() {
// Given
let urlString = "https://httpbin.org/image/png"
let expectation = self.expectation(description: "Request should return PNG response image")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertTrue(response?.result.isSuccess ?? false, "result should be success")
if let image = response?.result.value {
#if os(iOS)
let screenScale = UIScreen.main.scale
let expectedSize = CGSize(width: CGFloat(100) / screenScale, height: CGFloat(100) / screenScale)
XCTAssertEqual(image.size, expectedSize, "image size does not match expected value")
XCTAssertEqual(image.scale, screenScale, "image scale does not match expected value")
#elseif os(macOS)
let expectedSize = CGSize(width: 100.0, height: 100.0)
XCTAssertEqual(image.size, expectedSize, "image size does not match expected value")
#endif
} else {
XCTFail("result image should not be nil")
}
}
func testThatImageResponseSerializerCanDownloadJPGImage() {
// Given
let urlString = "https://httpbin.org/image/jpeg"
let expectation = self.expectation(description: "Request should return JPG response image")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertTrue(response?.result.isSuccess ?? false, "result should be success")
if let image = response?.result.value {
#if os(iOS)
let screenScale = UIScreen.main.scale
let expectedSize = CGSize(width: CGFloat(239) / screenScale, height: CGFloat(178) / screenScale)
XCTAssertEqual(image.size, expectedSize, "image size does not match expected value")
XCTAssertEqual(image.scale, screenScale, "image scale does not match expected value")
#elseif os(macOS)
let expectedSize = CGSize(width: 239.0, height: 178.0)
XCTAssertEqual(image.size, expectedSize, "image size does not match expected value")
#endif
} else {
XCTFail("result image should not be nil")
}
}
func testThatImageResponseSerializerCanDownloadImageFromFileURL() {
// Given
let url = self.url(forResource: "apple", withExtension: "jpg")
let expectation = self.expectation(description: "Request should return JPG response image")
var response: DataResponse<Image>?
// When
sessionManager.request(url)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNil(response?.response, "response should be nil")
XCTAssertTrue(response?.result.isSuccess ?? false, "result should be success")
if let image = response?.result.value {
#if os(iOS)
let screenScale = UIScreen.main.scale
let expectedSize = CGSize(width: CGFloat(180) / screenScale, height: CGFloat(260) / screenScale)
XCTAssertEqual(image.size, expectedSize, "image size does not match expected value")
XCTAssertEqual(image.scale, screenScale, "image scale does not match expected value")
#elseif os(macOS)
let expectedSize = CGSize(width: 180.0, height: 260.0)
XCTAssertEqual(image.size, expectedSize, "image size does not match expected value")
#endif
} else {
XCTFail("result image should not be nil")
}
}
#if os(iOS) || os(tvOS)
// MARK: - Tests - Image Inflation
func testThatImageResponseSerializerCanDownloadAndInflatePNGImage() {
// Given
let urlString = "https://httpbin.org/image/png"
let expectation = self.expectation(description: "Request should return PNG response image")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertTrue(response?.result.isSuccess ?? false, "result should be success")
if let image = response?.result.value {
let screenScale = UIScreen.main.scale
let expectedSize = CGSize(width: CGFloat(100) / screenScale, height: CGFloat(100) / screenScale)
XCTAssertEqual(image.size, expectedSize, "image size does not match expected value")
XCTAssertEqual(image.scale, screenScale, "image scale does not match expected value")
} else {
XCTFail("result image should not be nil")
}
}
func testThatImageResponseSerializerCanDownloadAndInflateJPGImage() {
// Given
let urlString = "https://httpbin.org/image/jpeg"
let expectation = self.expectation(description: "Request should return JPG response image")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertTrue(response?.result.isSuccess ?? false, "result should be success")
if let image = response?.result.value {
let screenScale = UIScreen.main.scale
let expectedSize = CGSize(width: CGFloat(239) / screenScale, height: CGFloat(178) / screenScale)
XCTAssertEqual(image.size, expectedSize, "image size does not match expected value")
XCTAssertEqual(image.scale, screenScale, "image scale does not match expected value")
} else {
XCTFail("result image should not be nil")
}
}
#endif
// MARK: - Tests - Image Serialization Errors
func testThatAttemptingToDownloadImageFromBadURLReturnsFailureResult() {
// Given
let urlString = "https://invalid.for.sure"
let expectation = self.expectation(description: "Request should fail with bad URL")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNil(response?.response, "response should be nil")
XCTAssertTrue(response?.result.isFailure ?? false, "result should be failure")
XCTAssertNotNil(response?.result.error, "result error should not be nil")
}
func testThatAttemptingToDownloadUnsupportedImageTypeReturnsFailureResult() {
// Given
let urlString = "https://httpbin.org/image/webp"
let expectation = self.expectation(description: "Request should return webp response image")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertTrue(response?.result.isFailure ?? false, "result should be failure")
XCTAssertNotNil(response?.result.error, "result error should not be nil")
if let error = response?.result.error as? AFError {
XCTAssertTrue(error.isUnacceptableContentType)
} else {
XCTFail("error should not be nil")
}
}
func testThatAttemptingToSerializeEmptyDataReturnsFailureResult() {
// Given
let urlString = "https://httpbin.org/bytes/0"
let expectation = self.expectation(description: "Request should download no bytes")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertTrue(response?.result.isFailure ?? false, "result should be failure")
XCTAssertNotNil(response?.result.error, "result error should not be nil")
if let error = response?.result.error as? AFError {
XCTAssertTrue(error.isUnacceptableContentType)
} else {
XCTFail("error should not be nil")
}
}
func testThatAttemptingToSerializeRandomStreamDataReturnsFailureResult() {
// Given
let randomBytes = 4 * 1024 * 1024
let urlString = "https://httpbin.org/bytes/\(randomBytes)"
let expectation = self.expectation(description: "Request should download random bytes")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertTrue(response?.result.isFailure ?? false, "result should be failure")
XCTAssertNotNil(response?.result.error, "result error should not be nil")
if let error = response?.result.error as? AFError {
XCTAssertTrue(error.isUnacceptableContentType)
} else {
XCTFail("error should not be nil")
}
}
func testThatAttemptingToSerializeJSONResponseIntoImageReturnsFailureResult() {
// Given
let urlString = "https://httpbin.org/get"
let expectation = self.expectation(description: "Request should return JSON")
var response: DataResponse<Image>?
// When
sessionManager.request(urlString)
.responseImage { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertTrue(response?.result.isFailure ?? false, "result should be failure")
XCTAssertNotNil(response?.result.error, "result error should not be nil")
if let error = response?.result.error as? AFError {
XCTAssertTrue(error.isUnacceptableContentType)
} else {
XCTFail("error should not be nil")
}
}
// MARK: - Tests - Stream Images
func testThatImagesCanBeStreamedDynamicallyFromMJPEGStream() {
// Given
let urlString = "http://173.14.66.201/anony/mjpg.cgi" // Northgate Launder Land
let expectation = self.expectation(description: "Request should return images")
let expectedImageCount = 8
var imageCount = 0
// When
let request = sessionManager.request(urlString)
request.streamImage { image in
guard imageCount < expectedImageCount else { return }
imageCount += 1
if imageCount == expectedImageCount {
request.cancel()
expectation.fulfill()
}
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertEqual(imageCount, expectedImageCount)
}
}
| 38.324455 | 112 | 0.645691 |
ebe95d11a3f7ddc8bf743b07cfdc0d3a76bbebd0 | 1,238 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public
extension NoBindings where Self: SomeKey
{
static
var bindings: [AccessReportBinding] { [] }
}
| 37.515152 | 79 | 0.774637 |
18692cf3be1152c9afad6ea2e4633e802045c9cb | 742 | import Basic
import Foundation
import TuistSupport
/// Node specifying a product dependency on a swift package
class PackageProductNode: GraphNode {
let product: String
init(product: String, path: AbsolutePath) {
self.product = product
super.init(path: path, name: product)
}
}
/// Node specifying a swift package
class PackageNode: GraphNode {
let package: Package
init(package: Package, path: AbsolutePath) {
self.package = package
let name: String
switch package {
case let .local(path: path):
name = path.pathString
case let .remote(url: url, requirement: _):
name = url
}
super.init(path: path, name: name)
}
}
| 22.484848 | 59 | 0.62938 |
140cdbbe809a95b8035f059656de98f28081ecef | 1,973 | //
// MangaRealm.swift
// Yomu
//
// Created by Sendy Halim on 8/16/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import Foundation
import RealmSwift
/// Represents Manga object for `Realm` database
class MangaRealm: Object {
@objc dynamic var id: String = ""
@objc dynamic var slug: String = ""
@objc dynamic var title: String = ""
@objc dynamic var author: String = ""
@objc dynamic var imageEndpoint: String = ""
@objc dynamic var releasedYear: Int = 0
@objc dynamic var commaSeparatedCategories: String = ""
@objc dynamic var position: Int = MangaPosition.undefined.rawValue
override static func primaryKey() -> String? {
return "id"
}
/// Convert the given `Manga` struct to `MangaRealm` object
///
/// - parameter manga: `Manga`
///
/// - returns: `MangaRealm`
static func from(manga: Manga) -> MangaRealm {
let mangaRealm = MangaRealm()
mangaRealm.id = manga.id!
mangaRealm.slug = manga.slug
mangaRealm.title = manga.title
mangaRealm.author = manga.author
mangaRealm.imageEndpoint = manga.image.endpoint
mangaRealm.releasedYear = manga.releasedYear ?? 0
mangaRealm.commaSeparatedCategories = manga.categories.joined(separator: ",")
mangaRealm.position = manga.position
return mangaRealm
}
/// Convert the given `MangaRealm` object to `Manga` struct
///
/// - parameter mangaRealm: `MangaRealm`
///
/// - returns: `Manga`
static func from(mangaRealm: MangaRealm) -> Manga {
let categories = mangaRealm
.commaSeparatedCategories
.split {
$0 == ","
}
.map(String.init)
return Manga(
position: mangaRealm.position,
id: mangaRealm.id,
slug: mangaRealm.slug,
title: mangaRealm.title,
author: mangaRealm.author,
image: ImageUrl(endpoint: mangaRealm.imageEndpoint),
releasedYear: mangaRealm.releasedYear,
description: "",
categories: categories
)
}
}
| 27.027397 | 81 | 0.663457 |
2f5bfae22e0e2d135ce6ee2bcc6226d65f2475d7 | 4,063 | //
// Question.swift
// vaporWebAuth
//
// Created by SH on 05/12/2017.
//
import FluentProvider
// MARK: - Class: Question -
final class Question: Model, NodeConvertible {
let storage = Storage()
var Q1: String
var Q2: String
var Q3: String
var Q4: String
var Q5: String
var Q6: String
var Q7: String
var Q8: String
var Q9: String
var Q10: String
// MARK: - Initializer -
init(Q1: String,Q2: String,Q3: String,Q4: String,Q5: String,Q6: String,Q7: String,Q8: String,Q9: String,Q10: String) {
self.Q1 = Q1
self.Q2 = Q2
self.Q3 = Q3
self.Q4 = Q4
self.Q5 = Q5
self.Q6 = Q6
self.Q7 = Q7
self.Q8 = Q8
self.Q9 = Q9
self.Q10 = Q10
}
// MARK: - NodeConvertible -
init(node: Node) throws {
Q1 = try node.get("Q1")
Q2 = try node.get("Q2")
Q3 = try node.get("Q3")
Q4 = try node.get("Q4")
Q5 = try node.get("Q5")
Q6 = try node.get("Q6")
Q7 = try node.get("Q7")
Q8 = try node.get("Q8")
Q9 = try node.get("Q9")
Q10 = try node.get("Q10")
}
func makeNode(in context: Context?) throws -> Node {
var node = Node(context)
try node.set("Q1",Q1)
try node.set("Q2",Q2)
try node.set("Q3",Q3)
try node.set("Q4",Q4)
try node.set("Q5",Q5)
try node.set("Q6",Q6)
try node.set("Q7",Q7)
try node.set("Q8",Q8)
try node.set("Q9",Q9)
try node.set("Q10",Q10)
return node
}
// MARK: - DB: Parse & Serialize -
init(row: Row) throws {
Q1 = try row.get("Q1")
Q2 = try row.get("Q2")
Q3 = try row.get("Q3")
Q4 = try row.get("Q4")
Q5 = try row.get("Q5")
Q6 = try row.get("Q6")
Q7 = try row.get("Q7")
Q8 = try row.get("Q8")
Q9 = try row.get("Q9")
Q10 = try row.get("Q10")
}
func makeRow() throws -> Row {
var row = Row()
try row.set("Q1",Q1)
try row.set("Q2",Q2)
try row.set("Q3",Q3)
try row.set("Q4",Q4)
try row.set("Q5",Q5)
try row.set("Q6",Q6)
try row.set("Q7",Q7)
try row.set("Q8",Q8)
try row.set("Q9",Q9)
try row.set("Q10",Q10)
return row
}
}
// MARK: - JSONConvertible -
extension Question: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
Q1: json.get("Q1"),
Q2: json.get("Q2"),
Q3: json.get("Q3"),
Q4: json.get("Q4"),
Q5: json.get("Q5"),
Q6: json.get("Q6"),
Q7: json.get("Q7"),
Q8: json.get("Q8"),
Q9: json.get("Q9"),
Q10: json.get("Q10")
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("Q1",Q1)
try json.set("Q2",Q2)
try json.set("Q3",Q3)
try json.set("Q4",Q4)
try json.set("Q5",Q5)
try json.set("Q6",Q6)
try json.set("Q7",Q7)
try json.set("Q8",Q8)
try json.set("Q9",Q9)
try json.set("Q10",Q10)
return json
}
}
// MARK: - Database Preparation -
extension Question: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { questions in
questions.id()
questions.string("Q1")
questions.string("Q2")
questions.string("Q3")
questions.string("Q4")
questions.string("Q5")
questions.string("Q6")
questions.string("Q7")
questions.string("Q8")
questions.string("Q9")
questions.string("Q10")
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: - Timestampable -
extension Question: Timestampable { }
// MARK: - ResponseRepresentable -
extension Question: ResponseRepresentable { }
| 25.553459 | 122 | 0.498646 |
5638289fcb754195b3bb20a50413c5619c1ff41f | 6,889 | //
//
// Project Name: Thecircle
// Workspace: Loophole
// MacOS Version: 11.2
//
// File Name: VideoWriter.swift
// Creation: 4/19/21 3:56 PM
//
// Company: Thecircle LLC
// Contact: [email protected]
// Website: https://thecircle.xyz
// Author: Dragos-Costin Mandu
//
// Copyright © 2021 Thecircle LLC. All rights reserved.
//
//
import AVFoundation
import UIKit
class VideoWriter
{
private let renderSettings: RenderSettings
private var videoWriter: AVAssetWriter!
private var videoWriterInput: AVAssetWriterInput!
private var pixelBufferAdaptor: AVAssetWriterInputPixelBufferAdaptor!
var isReadyForData: Bool
{
return videoWriterInput?.isReadyForMoreMediaData ?? false
}
init(renderSettings: RenderSettings)
{
self.renderSettings = renderSettings
}
func pixelBufferFromImage(uiImage: UIImage, pixelBufferPool: CVPixelBufferPool, size: CGSize) -> CVPixelBuffer?
{
var pixelBufferOut: CVPixelBuffer?
let status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pixelBufferPool, &pixelBufferOut)
if status != kCVReturnSuccess
{
return nil
}
let pixelBuffer = pixelBufferOut!
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
guard let data = CVPixelBufferGetBaseAddress(pixelBuffer)
else
{
return nil
}
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(data: data, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
else
{
return nil
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.clear(rect)
let horizontalRatio = size.width / uiImage.size.width
let verticalRatio = size.height / uiImage.size.height
let aspectRatio = min(horizontalRatio, verticalRatio) // ScaleAspectFit.
let newSize = CGSize(width: uiImage.size.width * aspectRatio, height: uiImage.size.height * aspectRatio)
let x = newSize.width < size.width ? (size.width - newSize.width) / 2 : 0
let y = newSize.height < size.height ? (size.height - newSize.height) / 2 : 0
guard let cgImage = uiImage.cgImage
else
{
return nil
}
context.draw(cgImage, in: CGRect(x: x, y: y, width: newSize.width, height: newSize.height))
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
return pixelBuffer
}
func createPixelBufferAdaptor()
{
let sourcePixelBufferAttributesDictionary =
[
kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32ARGB),
kCVPixelBufferWidthKey as String: NSNumber(value: Float(renderSettings.size.width)),
kCVPixelBufferHeightKey as String: NSNumber(value: Float(renderSettings.size.height))
]
pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoWriterInput, sourcePixelBufferAttributes: sourcePixelBufferAttributesDictionary)
}
/// Creates a AVAssetWriter that writes in the output URL with given settings.
func createAssetWriter(avOutputSettings: [String : Any]) -> AVAssetWriter?
{
guard let assetWriter = try? AVAssetWriter(outputURL: renderSettings.outputURL!, fileType: .mp4)
else
{
return nil
}
guard assetWriter.canApply(outputSettings: avOutputSettings, forMediaType: .video) else
{
return nil
}
return assetWriter
}
func start(_ completion: @escaping (_ success: Bool) -> Void)
{
let avOutputSettings: [String : Any] =
[
AVVideoCodecKey: renderSettings.avCodecKey,
AVVideoWidthKey: NSNumber(value: Float(renderSettings.size.width)),
AVVideoHeightKey: NSNumber(value: Float(renderSettings.size.height))
]
videoWriter = createAssetWriter(avOutputSettings: avOutputSettings)
videoWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: avOutputSettings)
guard videoWriter != nil
else
{
completion(false)
return
}
if videoWriter.canAdd(videoWriterInput)
{
videoWriter.add(videoWriterInput)
}
else
{
completion(false)
return
}
createPixelBufferAdaptor()
if videoWriter.startWriting() == false
{
completion(false)
return
}
videoWriter.startSession(atSourceTime: .zero)
completion(true)
}
func render(appendPixelBuffers: ((VideoWriter) -> Bool)?, _ completion: @escaping (_ success: Bool) -> Void)
{
guard videoWriter != nil, videoWriterInput != nil
else
{
completion(false)
return
}
let queue = DispatchQueue(label: "_VideoWriterInputQueue")
videoWriterInput.requestMediaDataWhenReady(on: queue)
{
let finished = appendPixelBuffers?(self) ?? false
if finished
{
self.videoWriterInput.markAsFinished()
self.videoWriter.finishWriting()
{
if let error = self.videoWriter.error
{
debugPrint(error)
completion(false)
}
else
{
completion(true)
}
}
}
}
}
func addImageFrom(imageURL: URL, withPresentationTime presentationTime: CMTime) -> Bool
{
guard let data = try? Data(contentsOf: imageURL), let uiImage = UIImage(data: data)
else
{
return false
}
guard pixelBufferAdaptor != nil, pixelBufferAdaptor.pixelBufferPool != nil
else
{
return false
}
guard let pixelBuffer = pixelBufferFromImage(uiImage: uiImage, pixelBufferPool: pixelBufferAdaptor.pixelBufferPool!, size: renderSettings.size)
else
{
return false
}
return pixelBufferAdaptor.append(pixelBuffer, withPresentationTime: presentationTime)
}
}
| 31.313636 | 255 | 0.592829 |
67d0128b0b13b329c0bb14cda85d82d69606ad10 | 2,612 | //
// ResponseObjectSerializable.swift
// closest-beacon-demo
//
// Created by Pantira Naruphanthawart on 3/9/2559 BE.
// Copyright © 2559 Tevsi LLC. All rights reserved.
//
import Foundation
@objc public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}
extension Alamofire.Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self {
let serializer: Serializer = { (request, response, data) in
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
if response != nil && JSON != nil {
return (T(response: response!, representation: JSON!), nil)
} else {
return (nil, serializationError)
}
}
return response(serializer: serializer, completionHandler: { (request, response, object, error) in
completionHandler(request, response, object as? T, error)
})
}
}
public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}
extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
switch result {
case .Success(let value):
if let
response = response,
responseObject = T(response: response, representation: value)
{
return .Success(responseObject)
} else {
let failureReason = "JSON could not be serialized into response object: \(value)"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
} | 42.129032 | 148 | 0.627871 |
3348a6d5432f1c6fe46e7a52211230730974a6cd | 2,039 | //
// SideMenuViewModel.swift
// Monotone
//
// Created by Xueliang Chen on 2020/12/21.
//
import Foundation
import RxSwift
import RxRelay
import Action
class SideMenuViewModel: BaseViewModel, ViewModelStreamable{
// MARK: - Input
struct Input {
var pages: BehaviorRelay<[SideMenuPage]?> = BehaviorRelay<[SideMenuPage]?>(value: nil)
var currentUser: BehaviorRelay<User?> = BehaviorRelay<User?>(value: nil)
}
public var input: Input = Input()
// MARK: - Output
struct Output {
var collections: BehaviorRelay<[Collection]?> = BehaviorRelay<[Collection]?>(value: nil)
var likedPhotos: BehaviorRelay<[Photo]?> = BehaviorRelay<[Photo]?>(value: nil)
}
public var output: Output = Output()
// MARK: - Private
//
// MARK: - Inject
override func inject(args: [String : Any?]?) {
}
// MARK: - Bind
override func bind() {
// Service.
let userService = self.service(type: UserService.self)!
// Bindings.
// LikedPhotos.
self.input.currentUser
.unwrap()
.flatMap { (user) -> Observable<[Photo]> in
if let username = user.username{
return userService.listUserLikedPhotos(username: username, orderBy: "latest")
}
return Observable.empty()
}
.bind(to: self.output.likedPhotos)
.disposed(by: self.disposeBag)
// Collections.
self.input.currentUser
.unwrap()
.flatMap { (user) -> Observable<[Collection]> in
if let username = user.username{
return userService.listUserCollections(username: username)
}
return Observable.empty()
}
.bind(to: self.output.collections)
.disposed(by: self.disposeBag)
}
}
| 26.828947 | 97 | 0.535066 |
23d021886ffd39d1a7797a02b664061d403fefa8 | 3,449 | //
// PopoverAnimator.swift
// trifle
//
// Created by TOMY on 2019/3/26.
// Copyright © 2019年 tone. All rights reserved.
//
import UIKit
class PopoverAnimator: NSObject {
//控制弹出或者消失动画的属性
private var isPresented : Bool = false
//提供对外的设置frame的属性
var presentedViewFrame : CGRect = CGRect.zero
var callBack : ((_ present : Bool)->())?
init(callBack : @escaping (_ present : Bool)->()) {
self.callBack = callBack
}
override init() {
super.init()
}
}
extension PopoverAnimator : UIViewControllerTransitioningDelegate
{
///改变view的尺寸和添加朦板
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?{
let presenttationVC : TFEPresenttationController = TFEPresenttationController(presentedViewController: presented, presenting: presenting)
presenttationVC.presentedViewFrame = presentedViewFrame
return presenttationVC
}
///自定义弹出动画
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
//UIViewControllerAnimatedTransitioning是一个协议,需要返回一个d遵循这个协议的对象
isPresented = true
if callBack != nil {
self.callBack!(isPresented)
}
return self
}
///自定义消失动画
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
if callBack != nil {
self.callBack!(isPresented)
}
return self
}
}
///弹出和消失动画
extension PopoverAnimator : UIViewControllerAnimatedTransitioning
{
///动画执行时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
///转场上下文(包含弹出的View - to和消失的View - from)
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
isPresented ? animationforPresented(transitionContext: transitionContext) : animationforDismissed(transitionContext: transitionContext)
}
///弹出动画
private func animationforPresented(transitionContext: UIViewControllerContextTransitioning){
//获取弹出的View
let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
//将弹出view加入到containView(这里需要手动)
transitionContext.containerView.addSubview(presentedView)
//执行动画
presentedView.transform = CGAffineTransform(scaleX: 1.0, y: 0.0)
presentedView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration:transitionDuration(using: transitionContext), animations: {
presentedView.transform = CGAffineTransform.identity
}) { (_) in
transitionContext.completeTransition(true)
}
}
///消失动画
private func animationforDismissed(transitionContext: UIViewControllerContextTransitioning){
let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
dismissView.transform = CGAffineTransform(scaleX: 1.0, y: 0.000001)
}) { (_) in
dismissView.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
}
| 36.691489 | 169 | 0.702812 |
bb37ff11c6f914c2003a3b421a0deee5873d420c | 938 | //
// AnimatedView.swift
// Chapter06
//
// Created by Jayant Varma on 19/12/19.
// Copyright © 2019 Jayant Varma. All rights reserved.
//
import SwiftUI
struct AnimatedView: View {
@State private var flipFlop = false
let timer = Timer.publish(every: 1, on: .current, in: .common).autoconnect()
var body: some View {
ZStack {
Circle().fill(Color.green)
Circle().fill(Color.yellow).scaleEffect(0.8)
Circle().fill(Color.orange).scaleEffect(0.6)
Circle().fill(Color.red).scaleEffect(0.4)
}.scaleEffect(flipFlop ? 0.2 : 0.8)
.opacity(flipFlop ? 0.1 : 1.0)
.animation(Animation.spring().repeatForever(autoreverses: true))
.onReceive(timer){ _ in
self.flipFlop.toggle()
}
}
}
struct AnimatedView_Previews: PreviewProvider {
static var previews: some View {
AnimatedView()
}
}
| 26.8 | 80 | 0.598081 |
edf3a0b213314df9c2b2245e13638f6db1b6949b | 2,788 | //
//
// DayViewModel.swift
// Parylation
//
// Created by Vladislav Kondrashkov on 10.02.21.
// Copyright © 2021 Vladislav Kondrashkov. All rights reserved.
//
//
import RxCocoa
import RxSwift
import ParylationDomain
final class DayViewModelImpl: DayViewModel {
private let interactor: DayInteractor
private let router: DayRouter
let reloadTrigger: AnyObserver<Void>
let createTrigger: AnyObserver<Void>
let selectTrigger: AnyObserver<IndexPath>
let items: Driver<[DayTableItem]>
let selectedDay: Driver<String>
private let disposeBag = DisposeBag()
init(
interactor: DayInteractor,
router: DayRouter,
date: Date
) {
self.interactor = interactor
self.router = router
let reloadSubject = PublishSubject<Void>()
let tasks = reloadSubject
.flatMap { interactor.fetchTaks() }
let tasksSequence = tasks
.take(1)
.flatMap { Observable.from($0) }
let colors = tasksSequence
.flatMap { interactor.fetchColor(id: $0.colorId) }
let icons = tasksSequence
.flatMap { interactor.fetchIcon(id: $0.iconId) }
let taskItems = Observable.zip(tasksSequence, colors, icons)
.share()
.map { task, color, icon in
DayTableItem(
id: task.id,
icon: icon.image,
color: color.value,
title: task.title
)
}
.toArray()
let selectSubject = PublishSubject<IndexPath>()
selectSubject
.withLatestFrom(tasks) { ($0, $1) }
.compactMap { indexPath, items -> Task? in
guard items.count > indexPath.row else {
return nil
}
return items[indexPath.row]
}
.subscribe(onNext: { task in
router.showTask(taskId: task.id)
})
.disposed(by: disposeBag)
let createSubject = PublishSubject<Void>()
createSubject
.subscribe(onNext: {
let taskEditData = TaskEditData(date: date)
router.showTaskEdit(data: taskEditData)
})
.disposed(by: disposeBag)
let monthFormatter = DateFormatter()
monthFormatter.dateFormat = "dd MMMM y"
let day = Observable.just(monthFormatter.string(from: date))
reloadTrigger = reloadSubject.asObserver()
createTrigger = createSubject.asObserver()
selectTrigger = selectSubject.asObserver()
items = taskItems
.asDriver(onErrorJustReturn: [])
selectedDay = day
.asDriver(onErrorJustReturn: "")
}
}
| 28.161616 | 68 | 0.571019 |
8f27533f062b6a0ad051a1fc5d8bc61fffaf9bef | 584 | //
// GridGap.swift
// SwiftCss
//
// Created by Tibor Bodecs on 2021. 07. 10..
//
public func GridGap(_ value: String) -> Property {
Property(name: "grid-gap", value: value)
}
/// A shorthand property for the grid-row-gap and grid-column-gap properties
public func GridGap(_ row: GridRowGapValue, _ col: GridColumnGapValue) -> Property {
GridGap(row.rawValue + " " + col.rawValue)
}
/// A shorthand property for the grid-row-gap and grid-column-gap properties
public func GridGap(_ row: Unit, _ col: Unit) -> Property {
GridGap(row.rawValue + " " + col.rawValue)
}
| 27.809524 | 84 | 0.686644 |
e9e4627173e31ac3cb7271c5589dddc43f5e4eb1 | 3,095 | //
// PaginationController.swift
// DiffTableDirector_Example
//
// Created by Aleksandr Lavrinenko on 12.07.2020.
// Copyright © 2020 Aleksandr Lavrinenko. All rights reserved.
//
import UIKit
import DiffTableDirector
final class BottomPaginationController: UIViewController {
// MARK: - UI
private let _tableView: UITableView = {
let tableView = UITableView()
tableView.separatorStyle = .none
return tableView
}()
// MARK: - Properties
private lazy var _tableDirector: TableDirectorInput = {
return TableDirector(tableView: _tableView, reloadRule: .calculateReloadAsync(queue: .global()))
}()
var feedModels: [FeedModel] = []
var infoModels: [InfoModel] = []
private var _firstPageLoaded: Bool = false
// MARK: - Init
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nil, bundle: nil)
view.backgroundColor = .white
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(_tableView)
_tableView.translatesAutoresizingMaskIntoConstraints = false
[_tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
_tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
_tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
_tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
].forEach { $0.isActive = true }
_tableDirector = TableDirector(tableView: _tableView)
feedModels = _loadFeed()
let rows = self._createRows(feedModels: self.feedModels)
self._tableDirector.reload(with: rows)
let bottomPaginationController = PaginationController(
settings: .init(direction: .down, prefetch: .base(offsetFromLast: 0)),
loader: .deafult) { (handler) in
// Fake delay
DispatchQueue.global().asyncAfter(deadline: .now() + 5) {
handler.finished(isSuccessfull: !self._firstPageLoaded, canLoadNext: true)
if !self._firstPageLoaded {
self.feedModels = self.feedModels + self._loadFeed()
self._tableDirector.reload(with: self._createRows(feedModels: self.feedModels))
self._firstPageLoaded = true
}
}
}
_tableDirector.add(paginationController: bottomPaginationController)
}
// MARK: - Fetch data
private func _loadFeed() -> [FeedModel] {
return (0..<40).map { (index) in
let randomNumber = Double.random(in: Range(uncheckedBounds: (lower: 1, upper: 1000)))
return FeedModel(
id: "\(index) \(randomNumber)",
title: "Hi! I'm readonly cell №\(index)",
content: "Some description",
isMine: true)
}
}
// MARK: - Helpers
private func _createRows(feedModels: [FeedModel]) -> [CellConfigurator] {
let placeholderImage = UIImage(named: "placeholder")
let feedRows = feedModels.map { (feedModel: FeedModel) -> TableRow<FeedCell> in
return TableRow<FeedCell>(
viewModel: .init(
diffID: feedModel.id,
title: feedModel.title,
content: feedModel.content,
image: placeholderImage))
}
return feedRows
}
}
| 30.048544 | 98 | 0.721486 |
5b487752d15638d19c00b534a5e8c6030a524532 | 2,158 | //
// AppDelegate.swift
// BPM
//
// Created by Jurre Stender on 08/02/16.
// Copyright © 2016 jurre. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 49.045455 | 285 | 0.754402 |
bb2cf5997655b4395e278299c72e2c9310bb4f1b | 806 | //
// CLLocationExtensions.swift
// flutter_geolocator
//
// Created by Maurits Beusekom on 08/06/2018.
//
import Foundation
import CoreLocation
extension CLLocation {
public func toDictionary() -> NSDictionary {
return [
"latitude" : self.coordinate.latitude,
"longitude" : self.coordinate.longitude,
"timestamp" : CLLocation.currentTimeInMilliSeconds(dateToConvert: self.timestamp),
"altitude" : self.altitude,
"accuracy" : self.horizontalAccuracy,
"speed" : self.speed,
"speed_accuracy" : 0.0
]
}
private static func currentTimeInMilliSeconds(dateToConvert: Date)-> Int
{
let since1970 = dateToConvert.timeIntervalSince1970
return Int(since1970 * 1000)
}
}
| 26.866667 | 94 | 0.635236 |
e22b39ce5831b4456c31e57b36d9a7a3691cfdff | 1,239 | //
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]>
//
// SPDX-License-Identifier: MIT
//
extension TypedContentMetadataNamespace {
/// Defines a `ContentMetadataBlock` you can use to group your Relationship Metadata.
/// See `RelationshipsContentMetadataBlock`.
public typealias Relationships = RestrictedContentMetadataBlock<RelationshipsContentMetadataBlock>
}
/// The `RelationshipsContentMetadataBlock` can be used to structure your Relationship
/// Metadata declarations.
/// The Metadata is available under the `Relationships` name and can be used like the following:
/// ```swift
/// struct ExampleContent: Content {
/// // ...
/// static var metadata: Metadata {
/// Relationships {
/// // ...
/// }
/// }
/// }
/// ```
public class RelationshipsContentMetadataBlock: ContentMetadataDefinition {
public typealias Key = RelationshipSourceCandidateContextKey
public var value: [PartialRelationshipSourceCandidate] {
fatalError("value getter must be overwritten")
}
}
| 35.4 | 135 | 0.696529 |
5bebfa6c9ec8a1604ec8c3a20dda5ef93e188264 | 9,250 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Domain
import Platform
import MaterialComponents
final class SpeakerDetailsViewModel {
// MARK: - Dependencies
private let conferenceDataSource: ConferenceDataSource
private let bookmarkStore: WritableBookmarkStore
private let reservationStore: ReadonlyReservationStore
private let navigator: ScheduleNavigator
// MARK: - Input
let speaker: Speaker
// MARK: - Output
var speakerDetailsViewModel: ScheduleEventDetailsSpeakerViewModel?
var speakerDetailsMainInfoViewModel: SpeakerDetailsMainInfoViewModel?
var relatedSessions: [ConferenceEventViewModel]?
init(conferenceDataSource: ConferenceDataSource,
bookmarkStore: WritableBookmarkStore,
reservationStore: ReadonlyReservationStore,
navigator: ScheduleNavigator,
speaker: Speaker) {
self.conferenceDataSource = conferenceDataSource
self.bookmarkStore = bookmarkStore
self.reservationStore = reservationStore
self.navigator = navigator
self.speaker = speaker
registerForTimezoneUpdates()
registerForBookmarkUpdates()
registerForReservationsUpdates()
updateModel()
}
/// This method transform all inputs into the correct output
func transform() {
self.speakerDetailsViewModel = ScheduleEventDetailsSpeakerViewModel(speaker, navigator: navigator)
self.speakerDetailsMainInfoViewModel = SpeakerDetailsMainInfoViewModel(speaker, navigator: navigator)
self.relatedSessions = conferenceDataSource.allSessions
.filter { $0.speakerIds.contains(speaker.id) }
.map {
ConferenceEventViewModel(event: $0,
conferenceDataSource: self.conferenceDataSource,
bookmarkStore: self.bookmarkStore,
reservationStore: self.reservationStore)
}
}
func toggleBookmark(sessionId: String) {
DispatchQueue.global().async {
self.bookmarkStore.toggleBookmark(sessionId: sessionId)
}
}
// MARK: - View updates
var viewUpdateCallback: ((_ indexPath: IndexPath?) -> Void)?
func onUpdate(_ viewUpdateCallback: @escaping (_ indexPath: IndexPath?) -> Void) {
self.viewUpdateCallback = viewUpdateCallback
updateModel()
}
func indexPath(for sessionId: String) -> IndexPath? {
if let eventIndex = self.relatedSessions?.index(where: { $0.id == sessionId }) {
return IndexPath(row: eventIndex, section: 1)
}
return nil
}
// MARK: - Model updates
fileprivate var conferenceUpdatesObserver: NSObjectProtocol!
fileprivate var bookmarkUpdatesObserver: NSObjectProtocol!
private func registerForDataLayerUpdates() {
let center = NotificationCenter.default
conferenceUpdatesObserver = center.addObserver(forName: .conferenceUpdate,
object: nil,
queue: nil) { [weak self] _ in
// reload view
self?.updateView()
}
bookmarkUpdatesObserver = center.addObserver(forName: .bookmarkUpdate,
object: nil,
queue: nil) { [weak self] notification in
guard self != nil else { return }
// no need to update the model, as bookmarked sessions will be filtered later
if let sessionId = notification.userInfo?[BookmarkUpdates.sessionId] as? String {
let indexPath = self?.indexPath(for: sessionId)
self?.updateView(at: indexPath)
}
else {
self?.updateView()
}
}
}
deinit {
timezoneObserver = nil
NotificationCenter.default.removeObserver(conferenceUpdatesObserver)
NotificationCenter.default.removeObserver(bookmarkUpdatesObserver)
}
func updateModel() {
transform()
updateView()
}
func updateView(at indexPath: IndexPath? = nil) {
DispatchQueue.main.async { [weak self] in
self?.viewUpdateCallback?(indexPath)
}
}
// MARK: - Timezone observing
private func timeZoneUpdated() {
updateModel()
}
private var timezoneObserver: Any? {
willSet {
if let observer = timezoneObserver {
NotificationCenter.default.removeObserver(observer)
}
}
}
private func registerForTimezoneUpdates() {
timezoneObserver = NotificationCenter.default.addObserver(forName: .timezoneUpdate,
object: nil,
queue: nil) { [weak self] _ in
// update timezone
self?.timeZoneUpdated()
}
}
// MARK: - Data update observing
func bookmarksUpdated() {
updateModel()
}
private var bookmarkObserver: Any? {
willSet {
if let observer = bookmarkObserver {
NotificationCenter.default.removeObserver(observer)
}
}
}
private func registerForBookmarkUpdates() {
bookmarkObserver = NotificationCenter.default.addObserver(forName: .bookmarkUpdate,
object: nil,
queue: nil) { [weak self] _ in
guard self != nil else { return }
self?.bookmarksUpdated()
}
}
func reservationsUpdated() {
updateModel()
}
private var reservationsObserver: Any? {
willSet {
if let observer = reservationsObserver {
NotificationCenter.default.removeObserver(observer)
}
}
}
private func registerForReservationsUpdates() {
reservationsObserver = NotificationCenter.default.addObserver(forName: .reservationUpdate,
object: nil,
queue: nil) { [weak self] _ in
self?.reservationsUpdated()
}
}
func numberOfItemsInSection(_ section: Int) -> Int {
if let count = relatedSessions?.count {
return section == 0 ? 2 : count
}
return section == 0 ? 2 : 0
}
func numberOfSections() -> Int {
return relatedSessions?.count ?? 0 > 0 ? 2 : 1
}
func detailsViewController(for index: IndexPath) -> UIViewController? {
if index.section == 1,
let session = relatedSessionAtIndex(index.row) {
return navigator.detailsViewController(for: session.id)
}
return nil
}
func populateSupplementaryView(_ view: UICollectionReusableView, forItemAt indexPath: IndexPath) {
if let sectionHeader = view as? MDCCollectionViewTextCell {
sectionHeader.shouldHideSeparator = false
sectionHeader.textLabel?.text = NSLocalizedString("Related Sessions", comment: "Indicates that the list following has sessions given by the same speaker").localizedUppercase
}
}
func didSelectItemAt(indexPath index: IndexPath) {
if index.section == 1,
relatedSessions!.count > index.row,
let session = relatedSessions?[index.row] {
navigator.navigateToSessionDetails(sessionId: session.id, popToRoot: false)
}
}
func relatedSessionAtIndex(_ index: Int) -> ConferenceEventViewModel? {
return relatedSessions?[index]
}
private enum LayoutConstants {
static let cellheight: CGFloat = 112
static let sectionHeight: CGFloat = 50
static let headerSize = CGSize.zero
}
func sizeForHeader(inSection section: Int, inFrame frame: CGRect) -> CGSize {
switch section {
case 0:
return LayoutConstants.headerSize
case _:
return CGSize(width: frame.width, height: LayoutConstants.sectionHeight)
}
}
}
struct SpeakerDetailsMainInfoViewModel {
let bio: String
let plusOneUrl: URL?
let twitterUrl: URL?
private let navigator: ScheduleNavigator
init (_ speaker: Speaker, navigator: ScheduleNavigator) {
bio = speaker.bio
plusOneUrl = speaker.plusOneUrl
twitterUrl = speaker.twitterUrl
self.navigator = navigator
}
func twitterTapped() {
if let twitterUrl = twitterUrl {
self.navigator.navigateToURL(twitterUrl)
}
}
func plusTapped() {
if let plusOneUrl = plusOneUrl {
self.navigator.navigateToURL(plusOneUrl)
}
}
}
| 32.801418 | 179 | 0.623784 |
288c0ea04d0cad282f8c1ae06a7874e3fa894ad1 | 11,358 | import XCTest
@testable import Genetics
final class ReproductionTests: XCTestCase {
/// A very real test object...
struct Cryptid: Genetic {
var fitness: Double = 0.2
var chromosome: [Trait] = [Trait]()
static var genome: [Gene] = [
Gene(named: "Boolean", alleles: [Trait(true), Trait(false)]),
Gene(named: "Int", alleles: [Trait(0), Trait(1)]),
Gene(named: "String", alleles: [Trait("True"), Trait("False")]),
]
func reproduce(with other: Genetic) throws -> Cryptid {
// Reproduction will be controlled manually throughout the following tests.
return self
}
}
// MARK: - Single Point Crossover
// Ensure reproduction method creates children as expected.
func testSPCChildren() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1),Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),Trait(0),Trait(0),Trait(0),Trait(0)])
do {
let children = try first.standardSinglePointCrossover(point: first.chromosome.count / 2, with: second)
XCTAssertTrue("111000" == children.firstBorn.chromosomeToString())
XCTAssertTrue("000111" == children.secondBorn.chromosomeToString())
} catch {
XCTFail()
}
}
// Ensure standardSinglePointCrossover returns the correct error type and value.
func testSPCErrorBeyondIndex() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1),Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),Trait(0),Trait(0),Trait(0),Trait(0)])
do {
let _ = try first.standardSinglePointCrossover(point: 100, with: second)
} catch {
guard let error = error as? GeneticError else {
XCTFail("standardSinglePointCrossover did not return a GeneticError")
return
}
XCTAssertTrue(error.error == .unableToReproduce)
}
}
// Ensure standardSinglePointCrossover returns an error when trait lists do not match
// but the crossover point is valid for both.
func testSPCErrorMismatchingTraits() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),Trait(0),Trait(0),Trait(0),Trait(0)])
do {
let _ = try first.standardSinglePointCrossover(point: 2, with: second)
} catch {
guard let error = error as? GeneticError else {
XCTFail("standardSinglePointCrossover did not return a GeneticError")
return
}
XCTAssertTrue(error.error == .unableToReproduce)
}
}
// MARK: - Single Point Random Crossover
// Ensures singlePointRandomCrossover produces an error when standardSinglePointCrossover does.
func testSPRCFailure() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),Trait(0),Trait(0),Trait(0),Trait(0)])
do {
let _ = try first.singlePointRandomCrossover(with: second)
} catch {
guard let error = error as? GeneticError else {
XCTFail("standardSinglePointCrossover did not return a GeneticError")
return
}
XCTAssertTrue(error.error == .unableToReproduce)
}
}
// Ensures singlePointRandomCrossover produces vaild childen.
// A valid child is one of the same chromosome length as their parents.
// This method uses SPC, there is no need to determine trait value accuracy.
// It has already been done with another test.
func testSPRCVaildChildren() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1),Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),Trait(0),Trait(0),Trait(0),Trait(0)])
do {
// When dealing with random values,
// we should ensure the success of the test is not random itself.
for _ in 0..<12 {
let children = try first.singlePointRandomCrossover(with: second)
XCTAssertTrue(children.firstBorn.chromosome.count == children.secondBorn.chromosome.count)
XCTAssertTrue(children.secondBorn.chromosome.count == first.chromosome.count)
XCTAssertTrue(children.firstBorn.chromosome.count != 0)
}
} catch {
XCTFail("Error: \(error) occured")
}
}
// MARK: - Uniform Crossover
func testUCNotEnoughTraitsFailure() {
let first = Cryptid(chromosome: [])
let second = Cryptid(chromosome: [])
do {
let _ = try first.uniformCrossover(with: second)
} catch {
guard let error = error as? GeneticError else {
XCTFail("uniformCrossover did not return a GeneticError")
return
}
XCTAssertTrue(error.error == .insufficientTraits)
}
}
// Ensure the possibility of 100% rate transfer.
func testUCFullTransfer() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1),Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),Trait(0),Trait(0),Trait(0),Trait(0)])
do {
let children = try first.uniformCrossover(with:second, atRate: 1.0)
XCTAssertTrue(children.chromosome == first.chromosome)
} catch {
XCTFail("Rate Transfer was not 100%: \(error)")
}
}
// Ensure the possibility of 0% rate transfer.
func testUCFullExclusion() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1),Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),Trait(0),Trait(0),Trait(0),Trait(0)])
do {
let child = try first.uniformCrossover(with:second, atRate: 0.0)
XCTAssertTrue(child.chromosome == second.chromosome)
} catch {
XCTFail("Rate Transfer was not 0%: \(error)")
}
}
// Ensures the base rate of 50% gene transfer occurs within a large population.
func testUCNearBaseRate() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1),Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(-1),Trait(-1),Trait(-1),Trait(-1),Trait(-1),Trait(-1)])
var population = [Cryptid]()
var totalDifference: Int = 0
// as the population increases, the difference should decrease.
for _ in 0..<10000 {
do {
let child = try first.uniformCrossover(with:second)
population.append(child)
} catch {
XCTFail("An Error occured while running this test: \(error)")
}
}
// Sum the values to (hopefully) zero.
for member in population {
totalDifference += member.chromosome.compactMap({ ($0.value as! Int) }).reduce(0,+)
}
XCTAssert((totalDifference <= 10), "The total difference in traits exeeded the expected amount, run the test again or inspect for changes to random number generation in uniformCrossover(with:,atRate:)")
}
// Ensures results from set rates do not differ to expected values.
func testUCStaticRates() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),Trait(1),Trait(1),Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),Trait(0),Trait(0),Trait(0),Trait(0)])
do {
let child = try first.uniformCrossover(with:second, atRates: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
XCTAssertTrue(child.chromosome == first.chromosome)
let anotherChild = try first.uniformCrossover(with:second, atRates: [1.0, 1.0, 1.0, 0.0, 0.0, 0.0])
XCTAssertTrue(anotherChild.chromosome == [Trait(1),Trait(1),Trait(1),Trait(0),Trait(0),Trait(0)])
} catch {
XCTFail()
}
}
// MARK: - Revolving Random Crossover
// Ensures failure if chromosomes mismatch.
func testRRCMismatchFailure() {
let first = Cryptid(chromosome: [Trait(1)])
let second = Cryptid(chromosome: [])
// ... Checking chromosome count mismatch
do {
let _ = try first.revolvingRandomCrossover(with: second)
} catch {
guard let error = error as? GeneticError else {
XCTFail("revolvingRandomCrossover did not return a GeneticError")
return
}
XCTAssertTrue(error.error == .unableToReproduce)
}
}
// Ensures failure when the Proportion of genes cannot be met.
func testRRCProportionFailure() {
let first = Cryptid(chromosome: [Trait(1)])
let thrid = Cryptid(chromosome: [Trait(1)])
do {
let _ = try first.revolvingRandomCrossover(with: thrid)
} catch {
guard let error = error as? GeneticError else {
XCTFail("revolvingRandomCrossover did not return a GeneticError")
return
}
XCTAssertTrue(error.error == .unableToReproduce)
}
}
func testRRCFunctionallity() {
let first = Cryptid(chromosome: [Trait(1),Trait(1),
Trait(1),Trait(1),
Trait(1),Trait(1),
Trait(1),Trait(1),
Trait(1),Trait(1)])
let second = Cryptid(chromosome: [Trait(0),Trait(0),
Trait(0),Trait(0),
Trait(0),Trait(0),
Trait(0),Trait(0),
Trait(0),Trait(0)])
do {
let child = try first.revolvingRandomCrossover(with: second)
// check to see if 70% of traits from self (i.e. caller / first) are crossed over.
XCTAssertTrue((child.chromosome.filter({($0.value as? Int) == 1}).count == 7))
} catch {
XCTFail()
}
}
static var allTests = [
// - SPC
("testSPCChildren", testSPCChildren),
("testSPCErrorBeyondIndex", testSPCErrorBeyondIndex),
("testSPCErrorMismatchingTraits",testSPCErrorMismatchingTraits),
// - SPRC
("testSPRCFailure", testSPRCFailure),
("testSPRCVaildChildren", testSPRCVaildChildren),
// - UC
("testUCNotEnoughTraitsFailure",testUCNotEnoughTraitsFailure),
("testUCFullTransfer",testUCFullTransfer),
("testUCFullExclusion", testUCFullExclusion),
("testUCNearBaseRate", testUCNearBaseRate),
("testUCStaticRates", testUCStaticRates),
// - RRC
("testRRCMismatchFailure", testRRCMismatchFailure),
("testRRCProportionFailure", testRRCProportionFailure),
("testRRCFunctionallity", testRRCFunctionallity)
]
}
| 41.152174 | 210 | 0.575806 |
26fd9bfa084f26f733b977b578aecc34f3f418d9 | 3,984 | //
// CaptureViewController.swift
// Instagram
//
// Created by Cory Avra on 2/29/16.
// Copyright © 2016 coryavra. All rights reserved.
//
import UIKit
class CaptureViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// Outlets
@IBOutlet weak var currentImage: UIImageView!
@IBOutlet weak var captionTextField: UITextField!
// Variables
let imagePicker: UIImagePickerController! = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Delegates
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print("Got an image")
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
currentImage.contentMode = .ScaleAspectFit
currentImage.image = chosenImage
imagePicker.dismissViewControllerAnimated(true, completion: {
// Anything you want to happen when the user saves an image
print("Image Retrieved")
})
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
print("User canceled image")
dismissViewControllerAnimated(true, completion: {
// Anything you want to happen when the user selects cancel
print("Canceled")
})
}
func scaleImage(image: UIImage, newSize: CGSize) -> UIImage {
print("Resizing image...")
let resizeImageView = UIImageView(frame: CGRectMake(0, 0, newSize.width, newSize.height))
resizeImageView.contentMode = UIViewContentMode.ScaleAspectFill
resizeImageView.image = image
UIGraphicsBeginImageContext(resizeImageView.frame.size)
resizeImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print("Image resized")
return newImage
}
// Actions
@IBAction func onTakePictureButton(sender: AnyObject) {
if (UIImagePickerController.isSourceTypeAvailable(.Camera)) {
if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil {
imagePicker.allowsEditing = false
imagePicker.sourceType = .Camera
imagePicker.cameraCaptureMode = .Photo
presentViewController(imagePicker, animated: true, completion: {})
} else {
print("Rear camera doesn't exist")
}
} else {
print("Camera is inaccessable")
}
}
@IBAction func OnPhotoLibraryButton(sender: AnyObject) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func onUploadButton(sender: AnyObject) {
let desiredSize = CGSize(width: 320, height: 320)
if (currentImage.image != nil && captionTextField.text != "") {
let resizedImage = scaleImage(currentImage.image!, newSize: desiredSize)
UserMedia.postUserImage(resizedImage, withCaption: captionTextField.text) { (value: Bool, error: NSError?) -> Void in
if (value) {
print("Posted successfully!")
} else {
print(error?.localizedDescription)
}
}
} else {
print("Missing either the image or the caption!")
}
currentImage.image = nil
captionTextField.text = ""
}
}
| 32.655738 | 129 | 0.625 |
bf7dbac899d41c72a836d8c722fdfc6bc43c27bb | 510 | //
// Action.swift
// ReSwift
//
// Created by Benjamin Encz on 12/14/15.
// Copyright © 2015 Benjamin Encz. All rights reserved.
//
/// All actions that want to be able to be dispatched to a store need to conform to this protocol
/// Currently it is just a marker protocol with no requirements.
public protocol Action
{
}
/// Initial Action that is dispatched as soon as the store is created.
/// Reducers respond to this action by configuring their initial state.
public struct ReSwiftInit: Action
{
}
| 25.5 | 97 | 0.733333 |
7aca9e5e05cc82252977d4b2abbd6952c18d421c | 465 | //
// BaseView.swift
// Daimo
//
// Created by KIHYUN SO on 2021/01/20.
//
import UIKit
import RxSwift
class BaseView: UIView {
var disposeBag = DisposeBag()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupBinding()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc dynamic func setupUI() {
}
@objc dynamic func setupBinding() {
}
}
| 14.090909 | 55 | 0.612903 |
e982124d6685604285e88c6f13ff0de2ef270f76 | 2,795 | import UIKit
extension String {
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return String(self[Range(start ..< end)])
}
var containsAlphabets: Bool {
//Checks if all the characters inside the string are alphabets
let set = CharacterSet.letters
return self.utf16.contains {
guard let unicode = UnicodeScalar($0) else { return false }
return set.contains(unicode)
}
}
}
// MARK: - NSAttributedString extensions
public extension String {
/// Regular string.
public var regular: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.font: UIFont.systemFont(ofSize: UIFont.systemFontSize)])
}
/// Bold string.
public var bold: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
}
/// Underlined string
public var underline: NSAttributedString {
return NSAttributedString(string: self, attributes: [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])
}
/// Strikethrough string.
public var strikethrough: NSAttributedString {
return NSAttributedString(string: self, attributes: [.strikethroughStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)])
}
/// Italic string.
public var italic: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
/// Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: UIColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color])
}
}
extension Array where Element: NSAttributedString {
func joined(separator: NSAttributedString) -> NSAttributedString {
var isFirst = true
return self.reduce(NSMutableAttributedString()) {
(r, e) in
if isFirst {
isFirst = false
} else {
r.append(separator)
}
r.append(e)
return r
}
}
func joined(separator: String) -> NSAttributedString {
return joined(separator: NSAttributedString(string: separator))
}
}
| 32.882353 | 145 | 0.642576 |
6248101b3fe1f356a956647134f698eeb324522b | 6,406 | //
// TopIPAddressTableViewController.swift
// FirewallLogAnalyzer-iOS
//
// Created by Vadim Denisov on 10/05/2019.
// Copyright © 2019 Vadim Denisov. All rights reserved.
//
import UIKit
class TopIPAddressTableViewController: UITableViewController {
@IBOutlet weak var minDateButton: UIButton!
@IBOutlet weak var maxDateButton: UIButton!
var minDate = Date()
var maxDate = Date()
var toolBar = UIToolbar()
var datePicker = UIDatePicker()
var isMinDate = false
var isMaxDate = false
var formatter = DateFormatter()
var sourceLogs: [Log] = []
private var logs: [Log] = []
private var ipAddress: [String] = []
private var ipAddressCount: [Int] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
formatter.dateFormat = "dd.MM.yyyy"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale.current
minDate = formatter.date(from: "01.01.2000") ?? Date()
maxDate = formatter.date(from: formatter.string(from: Date())) ?? Date()
minDateButton.setTitle(self.formatter.string(from: minDate), for: .normal)
maxDateButton.setTitle(self.formatter.string(from: maxDate), for: .normal)
update()
}
@IBAction func setDateButton(_ sender: UIButton) {
toolBar.removeFromSuperview()
datePicker.removeFromSuperview()
datePicker = UIDatePicker()
if sender == minDateButton {
isMinDate = true
isMaxDate = false
datePicker.setDate(formatter.date(from: minDateButton.title(for: .normal) ?? "01.01.2000") ?? Date(), animated: true)
} else {
isMinDate = false
isMaxDate = true
datePicker.setDate(formatter.date(from: maxDateButton.title(for: .normal) ?? "01.01.2000") ?? Date(), animated: true)
}
datePicker.backgroundColor = UIColor.white
datePicker.autoresizingMask = .flexibleWidth
datePicker.datePickerMode = .date
datePicker.addTarget(self, action: #selector(self.dateChanged(_:)), for: .valueChanged)
datePicker.frame = CGRect(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300)
self.view.addSubview(datePicker)
toolBar = UIToolbar(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50))
toolBar.barStyle = .default
toolBar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.onDoneButtonClick))]
toolBar.sizeToFit()
view.addSubview(toolBar)
}
@objc func dateChanged(_ sender: UIDatePicker?) {
update()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row <= ipAddress.count {
return 44
} else {
return 0
}
}
func update() {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
if isMinDate {
minDate = datePicker.date
minDateButton.setTitle(formatter.string(from: datePicker.date), for: .normal)
} else if isMaxDate {
maxDate = datePicker.date
maxDate = calendar.date(bySettingHour: 23, minute: 59, second: 59, of: maxDate) ?? Date()
maxDateButton.setTitle(formatter.string(from: datePicker.date), for: .normal)
}
logs = sourceLogs.filter({ (log) -> Bool in
log.formatterDate <= maxDate && log.formatterDate >= minDate
})
setup()
}
@objc func onDoneButtonClick() {
update()
toolBar.removeFromSuperview()
datePicker.removeFromSuperview()
}
func setup() {
var values: [String : Int] = [:]
if logs.first?.firewallType == FirewallType.kaspersky {
let logs = self.logs as! [KasperskyLog]
logs.forEach {
if $0.ipAddress != "" {
values[$0.ipAddress] = (values[$0.ipAddress] ?? 0) + 1
}
}
title = "Top 10 IP Address (Kaspersky)"
}
if logs.first?.firewallType == FirewallType.tplink {
let logs = self.logs as! [TPLinkLog]
logs.forEach {
if $0.ipAddress != "" {
values[$0.ipAddress] = (values[$0.ipAddress] ?? 0) + 1
}
}
title = "Top 10 IP Address (TPLink)"
}
if logs.first?.firewallType == FirewallType.dlink {
let logs = self.logs as! [DLinkLog]
logs.forEach {
if $0.srcIP != "" {
values[$0.srcIP] = (values[$0.srcIP] ?? 0) + 1
}
}
title = "Top 10 IP Address (DLink)"
}
let sortedValues = values.sorted { $0.value > $1.value }
ipAddress = []
ipAddressCount = []
for (i, value) in sortedValues.enumerated() {
if i == 10 { break }
ipAddress.append(value.key)
ipAddressCount.append(value.value)
tableView.cellForRow(at: IndexPath(row: i + 1, column: 0))?.textLabel?.text = "IP: \(value.key) (\(value.value))"
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 { return }
let ip = ipAddress[indexPath.row - 1]
let alert = UIAlertController(title: "Show IP Geolocation?", message: ip, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Show", style: .default, handler: { _ in
self.tabBarController?.selectedIndex = 3
let ipGeolocationController = (self.tabBarController?.viewControllers?[3] as? UINavigationController)?.topViewController as? IPGeolocationTableViewController
ipGeolocationController?.search(ip: ip)
}))
self.present(alert, animated: true, completion: nil)
}
}
| 39.300613 | 207 | 0.593662 |
03c354b67938c47c0aaaa331557eb55c00afc122 | 1,401 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "LocaleSupport",
defaultLocalization: "en",
platforms: [
.macOS(.v10_15),
.iOS(.v12),
.tvOS(.v12),
.watchOS(.v6)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "LocaleSupport",
targets: ["LocaleSupport"]
),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "LocaleSupport",
dependencies: []
),
.target(
name: "TestResources",
dependencies: [],
resources: [.process("Resources")]
),
.testTarget(
name: "LocaleSupportTests",
dependencies: ["LocaleSupport", "TestResources"]
),
],
swiftLanguageVersions: [.v5]
)
| 31.133333 | 117 | 0.579586 |
f97b6cc9b216d25436f48a8af297bbd5d9758c3b | 2,208 | /// Copyright (c) 2020 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
import UIKit
enum ImageDownloader {
static func download(url: String, completion: @escaping (UIImage?) -> Void) {
let url = URL(string: url)!
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse,
httpURLResponse.statusCode == 200,
let data = data, error == nil,
let image = UIImage(data: data)
else {
completion(nil)
return
}
completion(image)
}.resume()
}
}
| 44.16 | 83 | 0.721014 |
e8fe6b371587de517244aec5d6c6dc13cb05ff15 | 1,343 | //
// TxManageDataOperationResponse.swift
// Lumenshine
//
// Created by Soneso GmbH on 12/12/2018.
// Munich, Germany
// web: https://soneso.com
// email: [email protected]
// Copyright © 2018 Soneso. All rights reserved.
//
import Foundation
class TxManageDataOperationResponse: TxOperationResponse {
/// Name from the (name/value pair) for an account.
public let name:String
/// Value from the (name/value pair) for an account.
public let value:String?
// Properties to encode and decode
private enum CodingKeys: String, CodingKey {
case name
case value
}
/**
Initializer - creates a new instance by decoding from the given decoder.
- Parameter decoder: The decoder containing the data
*/
public required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
value = try values.decodeIfPresent(String.self, forKey: .value)
try super.init(from: decoder)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(value, forKey: .value)
}
}
| 28.574468 | 77 | 0.656739 |
22aea5e56a1b55cc2531438ce350e006d6461f74 | 411 | //
// BitcoinWebSocketApp.swift
// BitcoinWebSocket
//
// Created by Terry Chen on 2021/11/30.
//
import SwiftUI
@main
struct BitcoinWebSocketApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
| 19.571429 | 97 | 0.666667 |
0e183d344cbf391efe5709d8d6fddc7ec31d536a | 2,023 | //
// PublishedValue+BroadcasterTests.swift
// MiniRexTests
//
// Created by Óscar Morales Vivó on 6/2/19.
// Copyright © 2019 Óscar Morales Vivó. All rights reserved.
//
import XCTest
import MiniRex
class PublishedValue_BroadcasterTests: XCTestCase {
func testPublishedValueWithBroadcaster() {
// We'll filter a published value into a broadcaster to get the right behavior.
let publishedInt = PublishedProperty<Int>(withInitialValue: -1)
// We're filtering out the first update as to erase the first update on subscription from the source.
var filteredOne = false
let filterOutExpectation = expectation(description: "Filtered one out")
let filterInExpectation = expectation(description: "Filtered one in")
let broadcastFilter = Broadcaster(
withSource: publishedInt.wrappedValue,
filterBlock: { (intValue) -> Bool in
if !filteredOne {
filterOutExpectation.fulfill()
filteredOne = true
return false
} else {
filterInExpectation.fulfill()
return true
}
}
)
let initialValue = 0
let publishedIntFromBroadcaster = broadcastFilter.publishedValue(withInitialValue: initialValue)
var receivedValue = -1000
var updateCount = 0
let subscriber = publishedIntFromBroadcaster.subscribe { (intValue) in
receivedValue = intValue
updateCount += 1
}
// Check that we have received the initial value back (NOT the value that publishedInt was initialized with).
XCTAssertEqual(receivedValue, initialValue)
let updatedValue = 7
publishedInt.value = updatedValue
// Check that the update went all the way to our subscriber.
XCTAssertEqual(receivedValue, updatedValue)
waitForExpectations(timeout: 1.0)
subscriber.invalidate()
}
}
| 33.163934 | 118 | 0.637173 |
1189450c23535efc24730ad9fa8db1decb7f8e30 | 230 | //
// Enharmonic.swift
// music-notation
//
// Created by Rob Hudson on 2016-09-16.
// Copyright © 2016 Kyle Sherman. All rights reserved.
//
public protocol Enharmonic: Equatable {
func isEnharmonic(with other: Self) -> Bool
}
| 19.166667 | 54 | 0.708696 |
4bcf58648987ebb2cb5c90f65414e394a0643f2a | 478 | //
// UIButtonExtension.swift
// CoCreate
//
// Created by Bartek Żabicki on 27.02.2018.
// Copyright © 2018 CoCreate. All rights reserved.
//
import UIKit
public protocol XIBLocalizable {
var localizableKey: String? { get set }
}
extension UIButton: XIBLocalizable {
///A key that is use to localize `title`
@IBInspectable public var localizableKey: String? {
get {
return nil
} set {
setTitle(newValue?.localized, for: .normal)
}
}
}
| 18.384615 | 53 | 0.665272 |
ef19be3e646bdc3d09d22086fafb3745520bcffc | 2,770 | //
// KeyValidatorTests.swift
// SplitTests
//
// Created by Javier L. Avrudsky on 10/01/2019.
// Copyright © 2019 Split. All rights reserved.
//
import XCTest
@testable import Split
class KeyValidatorTests: XCTestCase {
var validator: KeyValidator!
override func setUp() {
validator = DefaultKeyValidator()
}
override func tearDown() {
}
func testValidMatchingKey() {
XCTAssertNil(validator.validate(matchingKey: "key1", bucketingKey: nil))
}
func testValidMatchingAndBucketingKey() {
XCTAssertNil(validator.validate(matchingKey: "key1", bucketingKey: "bkey1"))
}
func testNullMatchingKey() {
let errorInfo = validator.validate(matchingKey: nil, bucketingKey: nil);
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed a null key, the key must be a non-empty string", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testInvalidEmptyMatchingKey() {
let errorInfo = validator.validate(matchingKey: "", bucketingKey: nil);
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed an empty string, matching key must a non-empty string", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testInvalidLongMatchingKey() {
let key = String(repeating: "p", count: 256)
let errorInfo = validator.validate(matchingKey: key, bucketingKey: nil);
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("matching key too long - must be \(ValidationConfig.default.maximumKeyLength) characters or less", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testInvalidEmptyBucketingKey() {
let errorInfo = validator.validate(matchingKey: "key1", bucketingKey: "");
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed an empty string, bucketing key must be null or a non-empty string", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testInvalidLongBucketingKey() {
let bkey = String(repeating: "p", count: 256)
let errorInfo = validator.validate(matchingKey: "key1", bucketingKey: bkey);
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("bucketing key too long - must be \(ValidationConfig.default.maximumKeyLength) characters or less", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
}
| 37.945205 | 147 | 0.683755 |
3aa94d70d7751ebadb735bdbd0ab71e62e2c4ee5 | 5,787 | //
// UIImageView+BlurEffect.swift
// SABlurImageView
//
// Created by 鈴木大貴 on 2015/03/27.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
import Foundation
import QuartzCore
open class SABlurImageView: UIImageView {
//MARK: - Static Properties
fileprivate struct Const {
static let fadeAnimationKey = "FadeAnimationKey"
static let maxImageCount: Int = 10
static let contentsAnimationKey = "contents"
}
//MARK: - Instance Properties
fileprivate var cgImages: [CGImage] = [CGImage]()
fileprivate var nextBlurLayer: CALayer?
fileprivate var previousImageIndex: Int = -1
fileprivate var previousPercentage: CGFloat = 0.0
open fileprivate(set) var isBlurAnimating: Bool = false
deinit {
clearMemory()
}
//MARK: - Life Cycle
open override func layoutSubviews() {
super.layoutSubviews()
nextBlurLayer?.frame = bounds
}
open func configrationForBlurAnimation(_ boxSize: CGFloat = 100) {
guard let image = image else { return }
let baseBoxSize = max(min(boxSize, 200), 0)
let baseNumber = sqrt(CGFloat(baseBoxSize)) / CGFloat(Const.maxImageCount)
let baseCGImages = [image].flatMap { $0.cgImage }
cgImages = bluredCGImages(baseCGImages, sourceImage: image, at: 0, to: Const.maxImageCount, baseNumber: baseNumber)
}
fileprivate func bluredCGImages(_ images: [CGImage], sourceImage: UIImage?, at index: Int, to limit: Int, baseNumber: CGFloat) -> [CGImage] {
guard index < limit else { return images }
let newImage = sourceImage?.blurEffect(pow(CGFloat(index) * baseNumber, 2))
let newImages = images + [newImage].flatMap { $0?.cgImage }
return bluredCGImages(newImages, sourceImage: newImage, at: index + 1, to: limit, baseNumber: baseNumber)
}
open func clearMemory() {
cgImages.removeAll(keepingCapacity: false)
nextBlurLayer?.removeFromSuperlayer()
nextBlurLayer = nil
previousImageIndex = -1
previousPercentage = 0.0
layer.removeAllAnimations()
}
//MARK: - Add single blur
open func addBlurEffect(_ boxSize: CGFloat, times: UInt = 1) {
guard let image = image else { return }
self.image = addBlurEffectTo(image, boxSize: boxSize, remainTimes: times)
}
fileprivate func addBlurEffectTo(_ image: UIImage, boxSize: CGFloat, remainTimes: UInt) -> UIImage {
guard let blurImage = image.blurEffect(boxSize) else { return image }
return remainTimes > 0 ? addBlurEffectTo(blurImage, boxSize: boxSize, remainTimes: remainTimes - 1) : image
}
//MARK: - Percentage blur
open func blur(_ percentage: CGFloat) {
let percentage = min(max(percentage, 0.0), 0.99)
if previousPercentage - percentage > 0 {
let index = Int(floor(percentage * 10)) + 1
if index > 0 {
setLayers(index, percentage: percentage, currentIndex: index - 1, nextIndex: index)
}
} else {
let index = Int(floor(percentage * 10))
if index < cgImages.count - 1 {
setLayers(index, percentage: percentage, currentIndex: index, nextIndex: index + 1)
}
}
previousPercentage = percentage
}
fileprivate func setLayers(_ index: Int, percentage: CGFloat, currentIndex: Int, nextIndex: Int) {
if index != previousImageIndex {
CATransaction.animationWithDuration(0) { layer.contents = self.cgImages[currentIndex] }
if nextBlurLayer == nil {
let nextBlurLayer = CALayer()
nextBlurLayer.frame = bounds
layer.addSublayer(nextBlurLayer)
self.nextBlurLayer = nextBlurLayer
}
CATransaction.animationWithDuration(0) {
self.nextBlurLayer?.contents = self.cgImages[nextIndex]
self.nextBlurLayer?.opacity = 1.0
}
}
previousImageIndex = index
let minPercentage = percentage * 100.0
let alpha = min(max((minPercentage - CGFloat(Int(minPercentage / 10.0) * 10)) / 10.0, 0.0), 1.0)
CATransaction.animationWithDuration(0) { self.nextBlurLayer?.opacity = Float(alpha) }
}
//MARK: - Animation blur
open func startBlurAnimation(_ duration: TimeInterval) {
if isBlurAnimating { return }
isBlurAnimating = true
let count = cgImages.count
let group = CAAnimationGroup()
group.animations = cgImages.enumerated().flatMap {
guard $0.offset < count - 1 else { return nil }
let anim = CABasicAnimation(keyPath: Const.contentsAnimationKey)
anim.fromValue = $0.element
anim.toValue = cgImages[$0.offset + 1]
anim.fillMode = kCAFillModeForwards
anim.isRemovedOnCompletion = false
anim.duration = duration / TimeInterval(count)
anim.beginTime = anim.duration * TimeInterval($0.offset)
return anim
}
group.duration = duration
group.delegate = self
group.isRemovedOnCompletion = false
group.fillMode = kCAFillModeForwards
layer.add(group, forKey: Const.fadeAnimationKey)
cgImages = cgImages.reversed()
}
}
extension SABlurImageView: CAAnimationDelegate {
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
guard let _ = anim as? CAAnimationGroup else { return }
layer.removeAnimation(forKey: Const.fadeAnimationKey)
isBlurAnimating = false
guard let cgImage = cgImages.first else { return }
image = UIImage(cgImage: cgImage)
}
}
| 39.101351 | 145 | 0.632625 |
e0c1719df9d9eee865cc3f5c941573a3cf2eb39e | 9,235 | //
// ColorSquarePicker.swift
// ColorPicker
//
// Created by Jimmy Tai on 2018/8/21.
// Copyright © 2018年 JimmyTai. All rights reserved.
//
import UIKit
import Foundation
protocol ColorPickerDelegate {
func colorSelected(selectedColor color: UIColor)
}
@IBDesignable
open class ColorPicker: UIControl {
private let contentInsetX: CGFloat = 0
private let contentInsetY: CGFloat = 0
private let indicatorSizeInactive: CGFloat = 45
private let indicatorSizeActive: CGFloat = 55
var delegate: ColorPickerDelegate?
private lazy var colorSquareView: ColorSquareView = {
return ColorSquareView()
}()
private lazy var aplphaSquareView: ColorSquareView = {
return ColorSquareView()
}()
open lazy var indicator: ColorIndicatorView = {
let size = CGSize(width: self.indicatorSizeInactive, height: self.indicatorSizeInactive)
let indicatorRect = CGRect(origin: .zero, size: size)
return ColorIndicatorView(frame: indicatorRect)
}()
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.clipsToBounds = true
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.clipsToBounds = true
}
public func setColor(red: Int, green: Int, blue: Int) {
let rgb = RGB(r: CGFloat(red) / 255.0, g: CGFloat(green) / 255, b: CGFloat(blue) / 255)
print("setColor (r, g, b) = (\(rgb.r), \(rgb.g), \(rgb.b))")
let hsv = rgb.toHSV(preserveHS: true)
print("set color hue: \(hsv.h * 360)")
let x = hsv.h * self.bounds.width
var saturation = hsv.s
if saturation > 1 {
saturation = 1
} else if saturation < 0.2 {
saturation = 0.2
}
let y = self.bounds.height - (saturation - 0.2) / 0.8 * self.bounds.height
indicator.center = CGPoint(x: x, y: y)
setIndicatorColor()
}
public func getColor() -> UIColor {
return indicator.color
}
private func setIndicatorColor() {
let color = colorSquareView.getPixelColorAtPoint(point: CGPoint(x: indicator.center.x, y: 5))
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
let sat = ((self.bounds.height - indicator.center.y) / self.bounds.height * 0.8 + 0.2)
let newColor = UIColor(hue: hue, saturation: sat, brightness: brightness, alpha: alpha)
indicator.color = newColor
}
// MARK - Drawing
open override func layoutSubviews() {
if colorSquareView.superview == nil {
print("colorSquareView width: \(bounds.width), height: \(bounds.height)")
let image = UIImage.gradientImageWithBounds(
bounds: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height),
colors: [
getColor(hexString: "#E6312E").cgColor,
getColor(hexString: "#E6842E").cgColor, getColor(hexString: "#E6D72E").cgColor,
getColor(hexString: "#98E62E").cgColor, getColor(hexString: "#2EE62F").cgColor,
getColor(hexString: "#2EE67C").cgColor, getColor(hexString: "#2ED5E6").cgColor,
getColor(hexString: "#2E79E6").cgColor, getColor(hexString: "#302EE6").cgColor,
getColor(hexString: "#7D2EE6").cgColor, getColor(hexString: "#E62EE3").cgColor,
getColor(hexString: "#E62EB5").cgColor,
getColor(hexString: "#E6312E").cgColor
],
startPoint: CGPoint(x: 0, y: 0.5),
endPoint: CGPoint(x: 1, y: 0.5))
colorSquareView.image = image
colorSquareView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(colorSquareView)
colorSquareView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: contentInsetX).isActive = true
colorSquareView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -contentInsetX).isActive = true
colorSquareView.topAnchor.constraint(equalTo: self.topAnchor, constant: contentInsetY).isActive = true
colorSquareView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -contentInsetY).isActive = true
}
if aplphaSquareView.superview == nil {
let alphaImage = UIImage.gradientImageWithBounds(
bounds: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height),
colors: [getColor(hexString: "#20FFFFFF").cgColor, getColor(hexString: "#C0FFFFFF").cgColor],
startPoint: CGPoint(x: 0.5, y: 0),
endPoint: CGPoint(x: 0.5, y: 1))
aplphaSquareView.image = alphaImage
aplphaSquareView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(aplphaSquareView)
aplphaSquareView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: contentInsetX).isActive = true
aplphaSquareView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -contentInsetX).isActive = true
aplphaSquareView.topAnchor.constraint(equalTo: self.topAnchor, constant: contentInsetY).isActive = true
aplphaSquareView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -contentInsetY).isActive = true
}
if indicator.superview == nil {
self.addSubview(indicator)
}
indicator.center = self.center
setIndicatorColor()
}
// MARK: - Tracking
private func trackIndicator(with touch: UITouch) {
var position = touch.location(in: self)
if position.x > self.bounds.width - 2 {
position.x = self.bounds.width - 2
} else if position.x < 2 {
position.x = 2
}
if position.y > self.bounds.height - 2 {
position.y = self.bounds.height - 2
} else if position.y < 2 {
position.y = 2
}
print("colorSquareView width: \(colorSquareView.bounds.width), height: \(colorSquareView.bounds.height)")
print("touch x: \(touch.location(in: self).x), y: \(touch.location(in: self).y)")
indicator.center = position
setIndicatorColor()
}
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
self.trackIndicator(with: touch)
growIndicator()
return true
}
open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
self.trackIndicator(with: touch)
return true
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
shrinkIndicator()
if let d = delegate {
d.colorSelected(selectedColor: indicator.color)
}
}
open override func cancelTracking(with event: UIEvent?) {
super.cancelTracking(with: event)
shrinkIndicator()
if let d = delegate {
d.colorSelected(selectedColor: indicator.color)
}
}
private func changeIndicatorSize(to size: CGFloat) {
let center = self.indicator.center
let size = CGSize(width: size, height: size)
let indicatorRect = CGRect(origin: .zero, size: size)
self.indicator.frame = indicatorRect
self.indicator.center = center
}
private func growIndicator() {
UIView.animate(withDuration: 0.15, delay: 0.0, options: [.curveEaseIn], animations: {
self.changeIndicatorSize(to: self.indicatorSizeActive)
}) { (finished) in
}
}
private func shrinkIndicator() {
UIView.animate(withDuration: 0.15, delay: 0.0, options: [.curveEaseOut], animations: {
self.changeIndicatorSize(to: self.indicatorSizeInactive)
self.indicator.setNeedsDisplay()
}) { (finished) in
self.indicator.setNeedsDisplay()
}
}
private func getColor(hexString: String) -> UIColor {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
| 39.131356 | 126 | 0.598376 |
1662e96aa9d3dfa16605492346f7ec507c6676e3 | 8,053 | //
// SpeechRecogitionManager.swift
// LectureBuddy
//
// Created by Arthur De Araujo on 1/5/18.
// Copyright © 2018 Arthur De Araujo. All rights reserved.
//
import Foundation
import Speech
protocol SpeechRecognitionManagerDelegate {
func recognizedSpeech(fullTranscription:String)
func didBeginCheckingForCancellation()
func checkedIfRecognitionFinishedCancelling(secondsWaiting:Int)
func restartedRecognition()
}
// Check out the link to understand this SFSpeechRecognizerDelegate code : https://medium.com/ios-os-x-development/speech-recognition-with-swift-in-ios-10-50d5f4e59c48
class SpeechRecognitionManager : NSObject, SFSpeechRecognizerDelegate {
private let audioEngine = AVAudioEngine()
private let speechRecognizer: SFSpeechRecognizer? = SFSpeechRecognizer()
private let request = SFSpeechAudioBufferRecognitionRequest()
private var recognitionTask: SFSpeechRecognitionTask?
private let applesAudioDurationLimit = 60.0
//private var isRecordingSpeech = false
private var resetSpeechRecognitionTimer: Timer = Timer()
var repeatRecognitionCounter = 0 // Incremented everytime the recognition gets restarted
private var repeatedRecognitionCancelledCheckCounter = 1 // Incremented every second the recognition is in the process of cancelling and restarting
var delegate: SpeechRecognitionManagerDelegate?
private var isDebugging:Bool = false
var volumeFloat:CGFloat = 0.0
var isCheckingForCancellation = false
var finishedTranscriptions:[String] = []
var currentBestTranscription:String = ""
init(isDebugging: Bool) {
self.isDebugging = isDebugging
}
func startRecognition(){
self.startSpeechRecognitionResetTimer()
self.recordAndRecognizeSpeech()
}
func stopRecognition(){
self.endRecording()
resetSpeechRecognitionTimer.invalidate()
}
func getFullTranscription() -> String {
var fullTranscription = ""
for transcription in finishedTranscriptions {
fullTranscription += transcription + ". "
}
return fullTranscription
}
private func startSpeechRecognitionResetTimer() {
resetSpeechRecognitionTimer.invalidate()
resetSpeechRecognitionTimer = Timer.scheduledTimer(timeInterval: applesAudioDurationLimit, target: self, selector: #selector(resetSpeechRecognitionTask), userInfo: nil, repeats: false)
}
// Check out this link to understand how this works: https://miguelsaldana.me/2017/03/18/how-to-create-a-volume-meter-in-swift-3/
func updateVolume(withBuffer:AVAudioPCMBuffer){
let buffer = withBuffer
let dataptrptr = buffer.floatChannelData! //Get buffer of floats
let dataptr = dataptrptr.pointee
let datum = dataptr[Int(buffer.frameLength) - 1] //Get a single float to read
//store the float on the variable
self.volumeFloat = CGFloat(fabs((datum)))
}
private func recordAndRecognizeSpeech(){
let node = audioEngine.inputNode
let recordingFormat = node.outputFormat(forBus: 0)
node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
self.updateVolume(withBuffer: buffer)
self.request.append(buffer)
}
audioEngine.prepare()
do {
try audioEngine.start()
} catch {
print("SpeechRecognitionManager: \(error)")
}
// TODO: - Handle these errors with a UIAlert view
guard let myRecognizer = SFSpeechRecognizer() else {
// A recognizer is not supported for the current locale
print("SpeechRecognitionManager: A recognizer is not supported for the current locale")
return
}
if !myRecognizer.isAvailable {
// A recogniszer is not avaliable right now
print("SpeechRecognitionManager: A recogniszer is not avaliable right now")
return
}
if isDebugging {
print("SpeechRecognitionManager: isCancelled: \(String(describing: recognitionTask?.isCancelled))")
print("SpeechRecognitionManager: isFinishing: \(String(describing: recognitionTask?.isFinishing))")
print("SpeechRecognitionManager: state: \(String(describing: recognitionTask?.state.rawValue))")
print("SpeechRecognitionManager: state when completed: \(String(describing: SFSpeechRecognitionTaskState.completed.rawValue))")
print("SpeechRecognitionManager: state when canceling: \(String(describing: SFSpeechRecognitionTaskState.canceling.rawValue))")
print("SpeechRecognitionManager: state when finishing: \(String(describing: SFSpeechRecognitionTaskState.finishing.rawValue))")
print("SpeechRecognitionManager: state when running: \(String(describing: SFSpeechRecognitionTaskState.running.rawValue))")
print("SpeechRecognitionManager: state when starting: \(String(describing: SFSpeechRecognitionTaskState.starting.rawValue))")
}
repeatRecognitionCounter+=1
recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
if result != nil {
if let result = result {
self.currentBestTranscription = result.bestTranscription.formattedString
let finishedTranscriptionsWithCurrent = self.getFullTranscription() + self.currentBestTranscription
self.delegate?.recognizedSpeech(fullTranscription: finishedTranscriptionsWithCurrent)
} else if let error = error {
print(error)
}
}
})
}
private func endRecording(){
request.endAudio()
audioEngine.stop()
let node = audioEngine.inputNode
node.removeTap(onBus: 0)
recognitionTask?.cancel()
}
func restartRecognition(){
finishedTranscriptions.append(currentBestTranscription)
startSpeechRecognitionResetTimer()
recordAndRecognizeSpeech()
repeatedRecognitionCancelledCheckCounter = 1
self.delegate?.restartedRecognition()
}
// Calls itself repeatedly until the recognition task is completed and then it begins a new recogition task
private func recordSpeechAfterTaskIsFinishedCompleting(){
if recognitionTask?.state == .completed {
restartRecognition()
isCheckingForCancellation = false
} else {
if isDebugging {
print("SpeechRecognitionManager: \(repeatedRecognitionCancelledCheckCounter)s waiting for cancellation to complete.")
print("SpeechRecognitionManager: taskState: \(String(describing: recognitionTask?.state.rawValue)).")
}
self.delegate?.checkedIfRecognitionFinishedCancelling(secondsWaiting: repeatedRecognitionCancelledCheckCounter)
if isCheckingForCancellation == false {
self.delegate?.didBeginCheckingForCancellation()
isCheckingForCancellation = true
}
repeatedRecognitionCancelledCheckCounter+=1
// Call this method again till the task has completed
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
self.recordSpeechAfterTaskIsFinishedCompleting()
})
}
}
// Called by the resetSpeechRecognitionTimer when apple's audio limit ( 1 min ) is exceeded it's time
@objc private func resetSpeechRecognitionTask() { // resetSpeechRecognitionTaskWithTimer ? Need to change the name of it maybe?
endRecording()
recordSpeechAfterTaskIsFinishedCompleting()
}
}
| 41.725389 | 192 | 0.665839 |
effa05c2b4b0b401940f66a4a26d90bd70b903b1 | 278 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
extension NSData {
enum b {
func a
{
class a {
protocol P {
struct d {
let NSObject {
class
case ,
| 17.375 | 87 | 0.733813 |
1a63ee837307d56d70fd494b4cb4752109cb3001 | 885 | //
// ZyncTests.swift
// ZyncTests
//
// Created by Pasi Heikkinen on 20.8.2021.
//
import XCTest
@testable import Zync
class ZyncTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.029412 | 111 | 0.658757 |
21b020b09af6ae05151c22b1f924c7cc86310518 | 337 | //
// Array.swift
// SwiftUITemplate
//
// Created by apple on 25/05/2021.
//
import Foundation
extension Array {
var description: String {
var output = "["
for i in 0 ..< count {
output += "\n{\n" + String(describing: self[i]) + "\n}\n"
}
output += "]"
return output
}
}
| 16.85 | 69 | 0.501484 |
76949fa22236c0dd879e805fc3d4b94e425fac60 | 550 | //
// MovieVM.swift
// MVVM-002
//
// Created by omrobbie on 05/08/20.
// Copyright © 2020 omrobbie. All rights reserved.
//
import Foundation
class MovieVM: NSObject {
var movies = [MovieEntry]()
var count: Int {
return movies.count
}
func fetchMovies(completion: @escaping () -> ()) {
NetworkManager.shared.fetchMovies { (data) in
self.movies = data
completion()
}
}
func labelAtRow(indexPath: IndexPath) -> String {
movies[indexPath.row].name.label
}
}
| 18.333333 | 54 | 0.589091 |
dbb3007d935cbd3b90d4637b57ae525b80e23cd1 | 1,956 | //
// SceneView.swift
// castleGISspb
//
// Created by Nikita Semenov on 10.03.2021.
//
import Foundation
import ArcGIS
final class SceneView {
private let DISTANCE_FROM_STARTING_POINT : Double = 35_000
private let CAMERA_HEADING : Double = 0
private let CAMERA_PITCH : Double = 45
private let CAMERA_ROLL : Double = 0
var scene : AGSSceneView
init(withBasemap: AGSBasemap = .topographic()) {
self.scene = AGSSceneView()
setup(basemap: withBasemap)
}
private var defaultLocation: Coordinates {
Coordinates(lon: 30.3609, lat: 59.9311)
}
private func setup(basemap: AGSBasemap) {
setupBasemapAndCamera(with: basemap)
setupSurface()
setupMeshLayer()
}
private func setupBasemapAndCamera(with basemap: AGSBasemap) {
let scene = AGSScene(basemap: basemap)
self.scene.scene = scene
self.scene.setViewpointCamera(setupDefaultLocation(coordinates: defaultLocation))
}
private func setupDefaultLocation(coordinates: Coordinates) -> AGSCamera {
let center = AGSPoint(clLocationCoordinate2D: Location2D(coordinates: coordinates))
let camera = AGSCamera(
lookAt: center,
distance: DISTANCE_FROM_STARTING_POINT,
heading: CAMERA_HEADING,
pitch: CAMERA_PITCH,
roll: CAMERA_ROLL
)
return camera
}
private func setupSurface() {
let surface = AGSSurface()
let worldElevationServiceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
let elevationSource = AGSArcGISTiledElevationSource(url: worldElevationServiceURL)
surface.elevationExaggeration = 1.8
surface.elevationSources.append(elevationSource)
scene.scene?.baseSurface = surface
}
private func setupMeshLayer() {
let url = URL(string: "https://tiles.arcgis.com/tiles/u0sSNqDXr7puKJrF/arcgis/rest/services/Frankfurt2017_v17/SceneServer/layers/0")!
let meshLayer = AGSIntegratedMeshLayer(url: url)
scene.scene?.operationalLayers.add(meshLayer)
}
}
| 27.549296 | 139 | 0.759202 |
481bdce9af2f52fb405358c151ca60e70b520aef | 222 | //
// UIView+addSubviews.swift
// TeslaApp
//
// Created by Кирилл Худяков on 23/09/2019.
//
import UIKit
extension UIView {
func addSubviews(_ views: [UIView]) {
views.forEach { addSubview($0) }
}
}
| 13.875 | 44 | 0.621622 |
e45abe42934b328002ad5ac13e0850c98b77377f | 2,214 | //
// DevicesDAO.swift
// SIMSmeCore
//
// Copyright © 2020 ginlo.net GmbH. All rights reserved.
//
typealias DeviceDictionary = [String: [String: Any]]
protocol DevicesDAOProtocol {
func extensionDeviceDictionary(withAccount account: DPAGAccount, guid: String, passToken: String, sharedSecret: String, publicKey: String?) throws -> DeviceDictionary?
func ownDeviceDictionary() throws -> DeviceDictionary?
}
class DevicesDAO: DevicesDAOProtocol {
func extensionDeviceDictionary(withAccount account: DPAGAccount, guid: String, passToken: String, sharedSecret: String, publicKey: String?) throws -> DeviceDictionary? {
var deviceDictionary: DeviceDictionary?
try DPAGApplicationFacade.persistance.loadWithError { localContext in
guard let device = SIMSDevice.mr_createEntity(in: localContext) else { return }
device.guid = guid
device.name = UIDevice.current.name
device.passToken = passToken
device.account_guid = account.guid
device.public_key = publicKey
device.sharedSecret = sharedSecret
device.publicRSAFingerprint = publicKey?.sha1()
device.ownDevice = 0
let signData = try DPAGCryptoHelper.newAccountCrypto()?.signData(data: device.publicRSAFingerprint ?? "")
device.signedPublicRSAFingerprint = signData
deviceDictionary = try device.deviceDictionary(type: "extension")
device.mr_deleteEntity(in: localContext)
localContext.reset()
}
return deviceDictionary
}
func ownDeviceDictionary() throws -> DeviceDictionary? {
var deviceDictionary: DeviceDictionary?
try DPAGApplicationFacade.persistance.loadWithError { localContext in
if let device = SIMSDevice.mr_findFirst(with: NSComparisonPredicate(leftExpression: NSExpression(forKeyPath: \SIMSDevice.ownDevice), rightExpression: NSExpression(forConstantValue: NSNumber(value: 1))), in: localContext) ?? SIMSDevice.mr_findFirst(in: localContext) {
deviceDictionary = try device.deviceDictionary(type: "permanent")
}
}
return deviceDictionary
}
}
| 38.172414 | 279 | 0.696929 |
08ec1ff605a7452cc21582788d665c748c3c73b3 | 2,172 | /*
332. Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
One must use all the tickets once and only once.
Example 1:
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
But it is larger in lexical order.
https://leetcode.com/problems/reconstruct-itinerary/
*/
class Solution {
var dict = [String: [String]]()
var result = [String]()
func findItinerary(_ tickets: [[String]]) -> [String] {
// init graph
for t in tickets {
let from = t[0]
let dest = t[1]
dict[from, default: [String]()].append(dest)
}
for k in dict.keys {
let dests = dict[k]!
// sort by lexical order
dict[k] = dests.sorted()
}
dfs("JFK")
return result
}
func dfs(_ from: String) {
/*
[["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
JFK: KUL, NRT
NRT: JFK
result:
["KUL"]
["JFK", "KUL"]
["NRT", "JFK", "KUL"]
["JFK", "NRT", "JFK", "KUL"]
*/
while var dests = dict[from], dests.count > 0 {
let next = dests.removeFirst()
dict[from] = dests
dfs(next)
}
result.insert(from, at:0)
}
} | 31.941176 | 233 | 0.552486 |
fb165d79ea12f4128f7f596c6fd952ba2c088c12 | 605 | //
// String+Validator.swift
// ProjectUpKit
//
// Created by Jonathan Jemson on 7/7/18.
// Copyright © 2018 Jonathan Jemson.
//
import Foundation
extension String {
func isValidIdentifier() -> Bool {
let identifier = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if let firstChar = identifier.first {
let s = String(firstChar).trimmingCharacters(in: CharacterSet.decimalDigits)
if s.isEmpty { return false }
}
if identifier.contains(" ") {
return false
}
return !identifier.isEmpty
}
}
| 25.208333 | 89 | 0.633058 |
d5a9e4acb0d3ccfc1b070418b69d64333c60c7fc | 16,696 | //: # Customized Decoding of Database Rows
//:
//: To run this playground:
//:
//: - Open GRDB.xcworkspace
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
//: - Build: menu Product > Build
//: - Select the playground in the Playgrounds Group
//: - Run the playground
import GRDB
//: This playground demonstrates how one can implement **customized decoding of
//: database rows**.
//:
//: Customized row decoding allows you to go beyong the built-in support for
//: requests of raw rows, values, or types that adopt the
//: FetchableRecord protocol.
//:
//: For example:
//:
//: - Your application needs polymorphic row decoding: it decodes some class or
//: another, depending on the values contained in a database row.
//:
//: - Your application needs to decode rows with a context: each decoded value
//: should be initialized with some extra value that does not come from
//: the database.
//:
//: - Your application needs a record type that supports untrusted databases,
//: and may fail at decoding database rows (throw an error when a row contains
//: invalid values).
//:
//: None of those use cases can be handled by the built-in `FetchableRecord`
//: protocol and its `init(row:)` initializer. They need *customized
//: row decoding*.
//:
//: ## An Example: Polymorphic Decoding
//:
//: In this playground, we will provide some sample code that performs
//: polymorphic row decoding. Given a base class, `Base`, and two subclasses
//: `Foo` and `Bar`, we'd like to fetch Foo or Bar instances, depending on the
//: value found in the `type` column of the `base` database table.
//:
//: From this sample code, we hope that you will be able to derive your own
//: customized decoding.
//:
//: Everything starts from our class hierarchy:
class Base {
var description: String { return "Base" }
init() { }
}
class Foo: Base {
var name: String
override var description: String { return "Foo: \(name)" }
init(name: String) {
self.name = name
super.init()
}
}
class Bar: Base {
var score: Int
override var description: String { return "Bar: \(score)" }
init(score: Int) {
self.score = score
super.init()
}
}
//: We need a database, a table, and a few values so that we can do a real demo:
// An in-memory database is good enough
let dbQueue = DatabaseQueue()
try dbQueue.write { db in
// Database table
try db.create(table: "base") { t in
t.column("type", .text).notNull() // Contains "Foo" or "Bar"
t.column("fooName", .text) // Contains a Foo's name
t.column("barScore", .integer) // Contains a Bar's score
}
// Demo values: two Foo and one Bar
try db.execute(
sql: """
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
""",
arguments: [
"Foo", "Arthur", nil,
"Bar", nil, 100,
"Foo", "Barbara", nil,
])
}
//: We also need a method that decodes database rows into `Foo` or `Bar`
//: instances: let's call it `Base.decode(row:)`:
extension Base {
static func decode(row: Row) -> Base {
switch row["type"] as String {
case "Foo":
return Foo(name: row["fooName"])
case "Bar":
return Bar(score: row["barScore"])
case let type:
fatalError("Unknown Base type: \(type)")
}
}
}
//: Now we are able to express the kind of request we'd like to write. For
//: example, we could fetch all Base values from the database:
//:
//: try dbQueue.read { db in
//: // An array [Base] that constains Foo and Bar instances
//: let bases = try Base.fetchAll(db)
//: }
//:
//: But so far, we have a compiler error:
// Compiler error: Type 'Base' has no member 'fetchAll'
//try dbQueue.read { db in
// let bases = try Base.fetchAll(db)
//}
//: We'll see that this goal can be achieved by declaring a protocol, writing a
//: few extensions that guarantee the most efficient use of GRDB, and have the
//: Base class adopt this protocol.
//:
//: ### Keep It Simple, Stupid!
//:
//: But first, let's see how polymorphic decoding can be done as simply as
//: possible. After all, it is useless to design a full-fledged protocol unless
//: we need to use this protocol several times, or write code that is as
//: streamlined as possible.
//:
//: Can we fetch Foo and Bar values from an SQL request? Sure:
try dbQueue.read { db in
print("> KISS: Fetch from SQL")
let rows = try Row.fetchAll(db, sql: "SELECT * FROM base") // Fetch database rows
let bases = rows.map { row in // Decode database rows
Base.decode(row: row)
}
for base in bases { // Use fetched values
print(base.description)
}
}
//: Can we have GRDB generate SQL for us? Sure, we just need to adopt the
//: `TableRecord` protocol:
extension Base: TableRecord {
static let databaseTableName = "base"
}
try dbQueue.read { db in
print("> KISS: Fetch from query interface request")
let request = Base.filter(Column("type") == "Foo") // Define a request
let rows = try Row.fetchAll(db, request) // Fetch database rows
let bases = rows.map { row in // Decode database rows
Base.decode(row: row)
}
for base in bases { // Use fetched values
print(base.description)
}
}
//: As seen above, we can perform polymorphic requests with the standard GRDB,
//: by fetching raw rows and mapping them through a decoding method.
//:
//: The resulting code is not as streamlined as usual GRDB code, but we could
//: already do what we needed without much effort.
//:
//: ### Custom Protocol: MyDatabaseDecoder
//:
//: In the rest of this playground, we will define a **new realm of requests**.
//:
//: GRDB ships with three built-in realms of requests: requests of raw rows,
//: requests of values, and requests of record types that adopt the
//: `FetchableRecord` protocol.
//:
//: We'll define requests of record types that adopt the custom
//: `MyDatabaseDecoder` protocol:
protocol MyDatabaseDecoder {
associatedtype DecodedType
static func decode(row: Row) -> DecodedType
}
//: Types that adopt the MyDatabaseDecoder protocol are able, among other
//: things, to perform polymorphic decoding. Our Base class, for example:
extension Base: MyDatabaseDecoder {
// Already declared above:
// static func decode(row: Row) -> Base { ... }
}
//: Now let's see how we can define a new realm of requests based on the
//: `MyDatabaseDecoder` protocol. Our goal is to make them just as powerful as
//: ready-made requests of rows, values and FetchableRecord.
//:
//: All we need is a set of *extensions* that define the classic GRDB fetching
//: methods: `fetchOne`, `fetchAll`, and `fetchCursor`. The most fundamental one
//: is `fetchCursor`, because from it we can derive the two others.
//:
//: The first extension is the most low-level one: fetching from SQLite
//: **prepared statement**:
//:
//: try dbQueue.read { db in
//: let statement = try db.makeSelectStatement(sql: "SELECT ...")
//: try Base.fetchCursor(statement) // Cursor of Base
//: try Base.fetchAll(statement) // [Base]
//: try Base.fetchOne(statement) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from SelectStatement
// SelectStatement, StatementArguments, and RowAdapter are the fundamental
// fetching parameters of GRDB. Make sure to accept them all:
static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
// Turn the cursor of raw rows into a cursor of decoded rows
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
self.decode(row: $0)
}
}
static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
// Turn the cursor into an Array
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
// Consume the first value of the cursor
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
}
}
try dbQueue.read { db in
print("> Fetch from prepared statement")
let statement = try db.makeSelectStatement(sql: "SELECT * FROM base")
let bases = try Base.fetchAll(statement)
for base in bases {
print(base.description)
}
}
//: Now that we can fetch from prepared statements, we can fetch when given a
//: **request**, as defined by the `FetchRequest` protocol. This is the
//: protocol for query interface requests such as `Base.all()`, or
//: `SQLRequest`, etc.
//:
//: try dbQueue.read { db in
//: let request = Base.all()
//: try Base.fetchCursor(db, request) // Cursor of Base
//: try Base.fetchAll(db, request) // [Base]
//: try Base.fetchOne(db, request) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from FetchRequest
static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> MapCursor<RowCursor, DecodedType> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [DecodedType] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> DecodedType? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
try dbQueue.read { db in
print("> Fetch given a request")
let request = Base.all()
let bases = try Base.fetchAll(db, request)
for base in bases {
print(base.description)
}
}
//: When it's fine to fetch given a request, it's even better when requests can
//: fetch, too:
//:
//: try dbQueue.read { db in
//: let request = Base.all()
//: try request.fetchCursor(db) // Cursor of Base
//: try request.fetchAll(db) // [Base]
//: try request.fetchOne(db) // Base?
//: }
extension FetchRequest where RowDecoder: MyDatabaseDecoder {
// MARK: - FetchRequest fetching methods
func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, RowDecoder.DecodedType> {
return try RowDecoder.fetchCursor(db, self)
}
func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] {
return try RowDecoder.fetchAll(db, self)
}
func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? {
return try RowDecoder.fetchOne(db, self)
}
}
try dbQueue.read { db in
print("> Fetch from request")
let request = Base.all()
let bases = try request.fetchAll(db)
for base in bases {
print(base.description)
}
}
//: Types that adopt both FetchableRecord and TableRecord are able to fetch
//: right from the base type. Let's allow this as well for MyDatabaseDecoder:
//:
//: try dbQueue.read { db in
//: try Base.fetchCursor(db) // Cursor of Base
//: try Base.fetchAll(db) // [Base]
//: try Base.fetchOne(db) // Base?
//: }
extension MyDatabaseDecoder where Self: TableRecord {
// MARK: - Static fetching methods
static func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, DecodedType> {
return try all().fetchCursor(db)
}
static func fetchAll(_ db: Database) throws -> [DecodedType] {
return try all().fetchAll(db)
}
static func fetchOne(_ db: Database) throws -> DecodedType? {
return try all().fetchOne(db)
}
}
try dbQueue.read { db in
print("> Fetch from base type")
let bases = try Base.fetchAll(db)
for base in bases {
print(base.description)
}
}
//: Finally, you can support raw SQL as well:
//:
//: try dbQueue.read { db in
//: try Base.fetchAll(db,
//: sql: "SELECT ... WHERE name = ?",
//: arguments: ["O'Brien"]) // [Base]
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from SQL
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
try dbQueue.read { db in
print("> Fetch from SQL")
let bases = try Base.fetchAll(db, sql: "SELECT * FROM base")
for base in bases {
print(base.description)
}
}
//: Voilà! Our `MyDatabaseDecoder` protocol is now as able as the built-in
//: `FetchableRecord` protocol.
//:
//: To sum up, you have learned:
//:
//: - how to keep things simple: as long as you can fetch rows, you can decode
//: them the way you want.
//: - how to define a whole new realm of requests based on a custom protocol.
//: This involves writing a few extensions that give your protocol the same
//: fluent interface that is ready-made for the built-in FetchableRecord
//: protocol. This is more work, but you are granted with the full
//: customization freedom.
//:
//: To end this tour, let's quickly look at two other possible customized
//: row decoding strategies.
//:
//: ## An Example: Contextualized Records
//:
//: Your application needs to decode rows with a context: each decoded value
//: should be initialized with some extra value that does not come from
//: the database.
//:
//: In this case, you may define a `ContextFetchableRecord` protocol, and
//: derive all other fetching methods from the most fundamental one, which
//: fetches a cursor from a prepared statement (as we did for the
//: MyDatabaseDecoder protocol, above):
protocol ContextFetchableRecord {
associatedtype Context
init(row: Row, context: Context)
}
extension ContextFetchableRecord {
static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
context: Context)
throws -> MapCursor<RowCursor, Self>
{
// Turn the cursor of raw rows into a cursor of decoded rows
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
self.init(row: $0, context: context)
}
}
// Define fetchAll, fetchOne, and other extensions...
}
//: ## An Example: Failable Records
//:
//: Your application needs a record type that supports untrusted databases,
//: and may fail at decoding database rows (throw an error when a row contains
//: invalid values).
//:
//: In this case, you may define a `FailableFetchableRecord` protocol, and
//: derive all other fetching methods from the most fundamental one, which
//: fetches a cursor from a prepared statement (as we did for the
//: MyDatabaseDecoder protocol, above):
protocol FailableFetchableRecord {
init(row: Row) throws
}
extension FailableFetchableRecord {
static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> MapCursor<RowCursor, Self>
{
// Turn the cursor of raw rows into a cursor of decoded rows
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
try self.init(row: $0)
}
}
// Define fetchAll, fetchOne, and other extensions...
}
| 35.675214 | 184 | 0.652192 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.