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
|
---|---|---|---|---|---|
d79665424a519e856e7e263e394179addf2d130e | 2,303 | ///
/// @Generated by Mockolo
///
import Foundation
public class NetworkingMock: Networking {
public init() { }
public private(set) var dataCallCount = 0
public var dataArgValues = [(URLRequest, URLSessionTaskDelegate?)]()
public var dataHandler: ((URLRequest, URLSessionTaskDelegate?) async throws -> (
Data, URLResponse
))?
public func data(for request: URLRequest, delegate: URLSessionTaskDelegate?) async throws -> (
Data, URLResponse
) {
dataCallCount += 1
dataArgValues.append((request, delegate))
if let dataHandler = dataHandler {
return try await dataHandler(request, delegate)
}
fatalError("dataHandler returns can't have a default value thus its handler must be set")
}
}
public class GitHubClientProtocolMock: GitHubClientProtocol {
public init() { }
public private(set) var searchCallCount = 0
public var searchArgValues = [(String, SortOrder, Int, String?)]()
public var searchHandler: ((String, SortOrder, Int, String?) async throws -> ([Repository]))?
public func search(query: String, sortOrder: SortOrder, page: Int, language: String?) async throws -> [Repository] {
searchCallCount += 1
searchArgValues.append((query, sortOrder, page, language))
if let searchHandler = searchHandler {
return try await searchHandler(query, sortOrder, page, language)
}
return [Repository]()
}
public private(set) var getSearchHistoryCallCount = 0
public var getSearchHistoryArgValues = [Int]()
public var getSearchHistoryHandler: ((Int) -> ([String]))?
public func getSearchHistory(maxCount: Int) -> [String] {
getSearchHistoryCallCount += 1
getSearchHistoryArgValues.append(maxCount)
if let getSearchHistoryHandler = getSearchHistoryHandler {
return getSearchHistoryHandler(maxCount)
}
return [String]()
}
public private(set) var clearSearchHistoryCallCount = 0
public var clearSearchHistoryHandler: (() -> ())?
public func clearSearchHistory() {
clearSearchHistoryCallCount += 1
if let clearSearchHistoryHandler = clearSearchHistoryHandler {
clearSearchHistoryHandler()
}
}
}
| 32.9 | 120 | 0.666088 |
33bc94b6daea699dda79d4105c094a0d517eb3ab | 1,563 |
import Foundation
extension Presenter {
private static var didImportPlugins = false
// MARK: Plugins
static func usePlugins() {
guard !didImportPlugins else { return }
didImportPlugins = true
use(plugin: DefaultPlugin())
}
public static func use<P: Plugin>(plugin: P) {
plugin.willAdd()
plugin.views.forEach { $0.use() }
plugin.viewModifiers.forEach { $0.use() }
plugin.actions.forEach { $0.use() }
plugin.plugins.forEach { $0.use() }
plugin.didAdd()
}
public static func remove<P: Plugin>(plugin: P) {
plugin.willRemove()
plugin.views.forEach { $0.remove() }
plugin.viewModifiers.forEach { $0.remove() }
plugin.actions.forEach { $0.remove() }
plugin.plugins.forEach { $0.remove() }
plugin.didRemove()
}
}
extension _View where Self: Codable {
static func use() {
Presenter.use(view: Self.self)
}
static func remove() {
Presenter.remove(view: Self.self)
}
}
extension AnyViewModifying {
static func use() {
Presenter.use(modifier: Self.self)
}
static func remove() {
Presenter.remove(modifier: Self.self)
}
}
extension Action {
static func use() {
Presenter.use(action: Self.self)
}
static func remove() {
Presenter.remove(action: Self.self)
}
}
extension Plugin {
func use() {
Presenter.use(plugin: self)
}
func remove() {
Presenter.remove(plugin: self)
}
}
| 18.831325 | 53 | 0.584133 |
dbcc0d0a2a5b379e66d11b8101529a9695cfc426 | 390 | //
// RouteComposer
// WindowProvider.swift
// https://github.com/ekazaev/route-composer
//
// Created by Eugene Kazaev in 2018-2021.
// Distributed under the MIT license.
//
#if os(iOS)
import Foundation
import UIKit
/// Provides `UIWindow`
public protocol WindowProvider {
// MARK: Properties to implement
/// `UIWindow` instance
var window: UIWindow? { get }
}
#endif
| 15 | 44 | 0.692308 |
38d777cbe781951d7d66dca17ce85a94d38ff40e | 1,141 | //
// UXKit
//
// Copyright © 2016-2021 ZeeZide GmbH. All rights reserved.
//
#if os(macOS)
import Cocoa
public typealias UXLayoutConstraint = NSLayoutConstraint
@available(OSX 10.11, *)
public typealias UXLayoutGuide = NSLayoutGuide
#if swift(>=4.0)
public extension NSStackView {
typealias Alignment = NSLayoutConstraint.Attribute
typealias UXAlignment = NSLayoutConstraint.Attribute
typealias Axis = NSUserInterfaceLayoutOrientation
}
#else // Swift 3.2
public extension NSLayoutConstraint {
public typealias Attribute = NSLayoutAttribute
public typealias Relation = NSLayoutRelation
#if false // crashes 3.2 in Xcode 9 9A235 - Because it exists? in 3.2? But not in 3.1?
public typealias Priority = NSLayoutPriority
#endif
}
public extension NSStackView {
public typealias Distribution = NSStackViewDistribution
public typealias Alignment = NSLayoutAttribute
public typealias UXAlignment = NSLayoutAttribute
}
#endif
public typealias UXStackViewAxis = NSUserInterfaceLayoutOrientation
#endif
| 31.694444 | 90 | 0.708151 |
5d8ac4120554bc5e628a26aef2a18d87079818df | 4,216 | import Foundation
import CocoaLumberjackSwift
open class DebugObserverFactory: ObserverFactory {
public override init() {}
override open func getObserverForTunnel(_ tunnel: Tunnel) -> Observer<TunnelEvent>? {
return DebugTunnelObserver()
}
override open func getObserverForProxyServer(_ server: ProxyServer) -> Observer<ProxyServerEvent>? {
return DebugProxyServerObserver()
}
override open func getObserverForProxySocket(_ socket: ProxySocket) -> Observer<ProxySocketEvent>? {
return DebugProxySocketObserver()
}
override open func getObserverForAdapterSocket(_ socket: AdapterSocket) -> Observer<AdapterSocketEvent>? {
return DebugAdapterSocketObserver()
}
open override func getObserverForRuleManager(_ manager: RuleManager) -> Observer<RuleMatchEvent>? {
return DebugRuleManagerObserver()
}
}
open class DebugTunnelObserver: Observer<TunnelEvent> {
override open func signal(_ event: TunnelEvent) {
switch event {
case .receivedRequest,
.closed:
DDLogInfo("\(event)")
case .opened,
.connectedToRemote,
.updatingAdapterSocket:
DDLogVerbose("\(event)")
case .closeCalled,
.forceCloseCalled,
.receivedReadySignal,
.proxySocketReadData,
.proxySocketWroteData,
.adapterSocketReadData,
.adapterSocketWroteData:
DDLogDebug("\(event)")
}
}
}
open class DebugProxySocketObserver: Observer<ProxySocketEvent> {
override open func signal(_ event: ProxySocketEvent) {
switch event {
case .errorOccured:
DDLogError("\(event)")
case .disconnected,
.receivedRequest:
DDLogInfo("\(event)")
case .socketOpened,
.askedToResponseTo,
.readyForForward:
DDLogVerbose("\(event)")
case .disconnectCalled,
.forceDisconnectCalled,
.readData,
.wroteData:
DDLogDebug("\(event)")
}
}
}
open class DebugAdapterSocketObserver: Observer<AdapterSocketEvent> {
override open func signal(_ event: AdapterSocketEvent) {
switch event {
case .errorOccured:
DDLogError("\(event)")
case .disconnected,
.connected:
DDLogInfo("\(event)")
case .socketOpened,
.readyForForward:
DDLogVerbose("\(event)")
case .disconnectCalled,
.forceDisconnectCalled,
.readData,
.wroteData:
DDLogDebug("\(event)")
}
}
}
open class DebugProxyServerObserver: Observer<ProxyServerEvent> {
override open func signal(_ event: ProxyServerEvent) {
switch event {
case .started,
.stopped:
DDLogInfo("\(event)")
case .newSocketAccepted,
.tunnelClosed:
DDLogVerbose("\(event)")
}
}
}
open class DebugRuleManagerObserver: Observer<RuleMatchEvent> {
open override func signal(_ event: RuleMatchEvent) {
switch event {
case .ruleDidNotMatch, .dnsRuleMatched:
DDLogVerbose("\(event)")
case .ruleMatched:
DDLogInfo("\(event)")
}
}
}
open class YanshiDebugTunnelObserver: Observer<TunnelEvent> {
static var count: Int = 0
override open func signal(_ event: TunnelEvent) {
switch event {
case .closed,
.forceCloseCalled:
YanshiDebugTunnelObserver.count-=1
//NSLog("NEKit YanshiDebugTunnel signal close, event: \(event)")
case .opened(let tunnel):
YanshiDebugTunnelObserver.count+=1
//NSLog("NEKit YanshiDebugTunnel signal open count: \(YanshiDebugTunnelObserver.count), event: \(event), Tunnel: \(tunnel)")
default:
_ = 0
}
}
}
open class YanshiDebugObserverFactory: DebugObserverFactory {
public override init() {}
override open func getObserverForTunnel(_ tunnel: Tunnel) -> Observer<TunnelEvent>? {
return YanshiDebugTunnelObserver()
}
}
| 30.114286 | 136 | 0.60982 |
71ab5da3195c56b5f98b2f2cef421f9b414181ae | 5,851 | //
// AppDelegate.swift
// OnTheRoadB
//
// Created by Cunqi.X on 14/10/24.
// Copyright (c) 2014年 CS9033. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.xiaocq203.OnTheRoadB" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("OnTheRoadB", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("OnTheRoadB.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| 52.241071 | 287 | 0.750128 |
033ebae09a9a079d7c0e83d4d7084758f643e946 | 221 | //
// Tags.swift
// ModelSynchro
//
// Created by Jonathan Samudio on 01/02/18.
// Copyright © 2018 Prolific Interactive. All rights reserved.
//
/*
Auto-Generated using ModelSynchro
*/
struct Tags: Codable {
} | 14.733333 | 63 | 0.674208 |
0abf6f6e93b8d53748176109847ba31e1e03c2ec | 1,039 | //
// SwiftFortuneWheelDemo_macOSTests.swift
// SwiftFortuneWheelDemo-macOSTests
//
// Created by Sherzod Khashimov on 7/13/20.
// Copyright © 2020 Sherzod Khashimov. All rights reserved.
//
import XCTest
@testable import SwiftFortuneWheelDemo_macOS
class SwiftFortuneWheelDemo_macOSTests: 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.
}
}
}
| 29.685714 | 111 | 0.693936 |
8f6513d452f55219e156badcdbaed3942c7ae650 | 6,370 | //
// BlockingObservable+Operators.swift
// Rx
//
// Created by Krunoslav Zaher on 10/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
extension BlockingObservable {
/**
Blocks current thread until sequence terminates.
If sequence terminates with error, terminating error will be thrown.
- returns: All elements of sequence.
*/
public func toArray() throws -> [E] {
var elements: [E] = Array<E>()
var error: Swift.Error?
let lock = RunLoopLock(timeout: timeout)
let d = SingleAssignmentDisposable()
defer {
d.dispose()
}
lock.dispatch {
let subscription = self.source.subscribe { e in
if d.isDisposed {
return
}
switch e {
case .next(let element):
elements.append(element)
case .error(let e):
error = e
d.dispose()
lock.stop()
case .completed:
d.dispose()
lock.stop()
}
}
d.setDisposable(subscription)
}
try lock.run()
if let error = error {
throw error
}
return elements
}
}
extension BlockingObservable {
/**
Blocks current thread until sequence produces first element.
If sequence terminates with error before producing first element, terminating error will be thrown.
- returns: First element of sequence. If sequence is empty `nil` is returned.
*/
public func first() throws -> E? {
var element: E?
var error: Swift.Error?
let d = SingleAssignmentDisposable()
defer {
d.dispose()
}
let lock = RunLoopLock(timeout: timeout)
lock.dispatch {
let subscription = self.source.subscribe { e in
if d.isDisposed {
return
}
switch e {
case .next(let e):
if element == nil {
element = e
}
break
case .error(let e):
error = e
default:
break
}
d.dispose()
lock.stop()
}
d.setDisposable(subscription)
}
try lock.run()
if let error = error {
throw error
}
return element
}
}
extension BlockingObservable {
/**
Blocks current thread until sequence terminates.
If sequence terminates with error, terminating error will be thrown.
- returns: Last element in the sequence. If sequence is empty `nil` is returned.
*/
public func last() throws -> E? {
var element: E?
var error: Swift.Error?
let d = SingleAssignmentDisposable()
defer {
d.dispose()
}
let lock = RunLoopLock(timeout: timeout)
lock.dispatch {
let subscription = self.source.subscribe { e in
if d.isDisposed {
return
}
switch e {
case .next(let e):
element = e
return
case .error(let e):
error = e
default:
break
}
d.dispose()
lock.stop()
}
d.setDisposable(subscription)
}
try lock.run()
if let error = error {
throw error
}
return element
}
}
extension BlockingObservable {
/**
Blocks current thread until sequence terminates.
If sequence terminates with error before producing first element, terminating error will be thrown.
- returns: Returns the only element of an sequence, and reports an error if there is not exactly one element in the observable sequence.
*/
public func single() throws -> E? {
return try single { _ in true }
}
/**
Blocks current thread until sequence terminates.
If sequence terminates with error before producing first element, terminating error will be thrown.
- parameter predicate: A function to test each source element for a condition.
- returns: Returns the only element of an sequence that satisfies the condition in the predicate, and reports an error if there is not exactly one element in the sequence.
*/
public func single(_ predicate: @escaping (E) throws -> Bool) throws -> E? {
var element: E?
var error: Swift.Error?
let d = SingleAssignmentDisposable()
defer {
d.dispose()
}
let lock = RunLoopLock(timeout: timeout)
lock.dispatch {
let subscription = self.source.subscribe { e in
if d.isDisposed {
return
}
switch e {
case .next(let e):
do {
if try !predicate(e) {
return
}
if element == nil {
element = e
} else {
throw RxError.moreThanOneElement
}
} catch (let err) {
error = err
d.dispose()
lock.stop()
}
return
case .error(let e):
error = e
case .completed:
if element == nil {
error = RxError.noElements
}
}
d.dispose()
lock.stop()
}
d.setDisposable(subscription)
}
try lock.run()
if let error = error {
throw error
}
return element
}
}
| 25.07874 | 176 | 0.465463 |
fe43fdaf15e47b8749649ee7d86b3c155075118f | 1,350 | //
// Superhero.swift
// MarvelApp
//
// Created by Marcelo Vazquez on 28/02/2019.
// Copyright © 2019 Marcelo Vazquez. All rights reserved.
//
import Foundation
import RealmSwift
class Superhero: Object {
@objc dynamic var id = 0
@objc dynamic var name = ""
@objc dynamic var biography = ""
@objc dynamic var detailUrl = ""
@objc dynamic var lastModified = Date.distantPast
@objc dynamic var thumbnail = ""
@objc dynamic var comicsCount = 0
@objc dynamic var seriesCount = 0
@objc dynamic var storiesCount = 0
@objc dynamic var eventsCount = 0
convenience init(_ character: CharacterDto) {
self.init()
id = character.id
name = character.name
biography = character.description
let modifiedYear = Calendar.current.dateComponents([.year], from: character.modified).year!
if (modifiedYear > 1970) {
lastModified = character.modified
}
thumbnail = character.thumbnail
comicsCount = character.comics.available
seriesCount = character.series.available
storiesCount = character.stories.available
eventsCount = character.events.available
detailUrl = (character.urls.first{ $0.type == "wiki" }
?? character.urls.first{ $0.type == "detail" })?.url
?? ""
}
}
| 27 | 99 | 0.639259 |
de805ca78f233b4617b5b1ad77efe26294e0b958 | 2,809 | //
// HomeViewController.swift
// Instagram
//
// Created by Ulric Ye on 3/13/17.
// Copyright © 2017 uye. All rights reserved.
//
import UIKit
import Parse
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var posts: [PFObject]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 120
tableView.rowHeight = UITableViewAutomaticDimension
// Do any additional setup after loading the view.
let query = PFQuery(className: "Post")
query.order(byDescending: "createdAt")
query.includeKey("author")
query.limit = 20
query.findObjectsInBackground { (posts: [PFObject]?, error: Error?) -> Void in
if let posts = posts {
// do something with the data fetched
self.posts = posts
self.tableView.reloadData()
} else {
// handle error
print(error!.localizedDescription)
}
}
}
override func viewWillAppear(_ animated: Bool) {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let posts = posts {
return posts.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
let post = posts?[indexPath.row]
cell.captionLabel.text = post?["caption"] as? String
let imagePost = post?["media"] as? PFFile
imagePost?.getDataInBackground(block: { (data: Data?, error: Error?) in
if error == nil {
if let data = data {
print("image load success")
cell.imagePost.image = UIImage(data: data)
}
} else {
print(error?.localizedDescription)
}
})
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 30.532609 | 106 | 0.592026 |
7931e31ad6dcb0c66a1f80171e000e3a0e82fb58 | 2,062 | //
// CGImage+Accelerate.swift
// DynamicBlurView
//
// Created by Kyohei Ito on 2017/08/17.
// Copyright © 2017年 kyohei_ito. All rights reserved.
//
import Accelerate
import UIKit
extension CGImage {
var area: Int {
return width * height
}
private var size: CGSize {
return CGSize(width: width, height: height)
}
private var bytes: Int {
return bytesPerRow * height
}
private func imageBuffer(from data: UnsafeMutableRawPointer!) -> vImage_Buffer {
return vImage_Buffer(data: data, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: bytesPerRow)
}
func blurred(with boxSize: UInt32, iterations: Int, blendColor: UIColor?, blendMode: CGBlendMode) -> CGImage? {
guard let providerData = dataProvider?.data else {
return nil
}
let inData = malloc(bytes)
var inBuffer = imageBuffer(from: inData)
let outData = malloc(bytes)
var outBuffer = imageBuffer(from: outData)
let tempSize = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, boxSize, boxSize, nil, vImage_Flags(kvImageEdgeExtend + kvImageGetTempBufferSize))
let tempData = malloc(tempSize)
defer {
free(inData)
free(outData)
free(tempData)
}
let source = CFDataGetBytePtr(providerData)
memcpy(inBuffer.data, source, bytes)
for _ in 0..<iterations {
vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, tempData, 0, 0, boxSize, boxSize, nil, vImage_Flags(kvImageEdgeExtend))
let temp = inBuffer.data
inBuffer.data = outBuffer.data
outBuffer.data = temp
}
let context = colorSpace.flatMap {
CGContext(data: inBuffer.data, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: $0, bitmapInfo: bitmapInfo.rawValue)
}
return context?.makeImage(with: blendColor, blendMode: blendMode, size: size)
}
}
| 30.776119 | 178 | 0.6484 |
7a79b564d8b6b11ef68c00f64fd975ba630772e3 | 1,563 | //
// SearchDecodableMockTests.swift
// CleanSwiftTests
//
// Created by Mustafa on 12/19/19.
// Copyright © 2019 Andela. All rights reserved.
//
import XCTest
@testable import CleanSwift
class SearchDecodableMockTests: XCTestCase {
// sut: mean system under test
var sut: SearchResponsableMock!
override func setUp() {
super.setUp()
// should init after super.setup()
sut = SearchResponsableMock()
}
override func tearDown() {
// should deinit before super.tearDown()
sut = nil
super.tearDown()
}
func testSearchDecodableMock_ResultCount() {
guard let data = SearchConstants.sampleData.data(using: .utf8) else {
XCTAssert(false)
return
}
self.sut.map(data) { result in
switch(result) {
case .success(let response):
XCTAssertEqual(response.resultCount, 50)
case .failure(let error):
XCTAssert(false, error.localizedDescription)
}
}
}
func testSeachDecodableMock_First_ArtistName() {
guard let data = SearchConstants.sampleData.data(using: .utf8) else {
XCTAssert(false)
return
}
self.sut.map(data) { result in
switch(result) {
case .success(let response):
XCTAssertEqual(response.results?[0].artistName, "Adele")
case .failure(let error):
XCTAssert(false, error.localizedDescription)
}
}
}
}
| 28.418182 | 77 | 0.583493 |
225d50d2504784b28c650df31b0eb8152d94f9eb | 653 | //
// Autogenerated by Scrooge
//
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
//
import Foundation
import TwitterApacheThrift
public struct CollectiontThriftStruct: Hashable {
public var arrays: [Double]?
public var maps: [String:String]?
public var sets: Set<Int32>?
enum CodingKeys: Int, CodingKey {
case arrays = 1
case maps = 2
case sets = 3
}
public init(arrays: [Double]? = nil, maps: [String:String]? = nil, sets: Set<Int32>? = nil) {
self.arrays = arrays
self.maps = maps
self.sets = sets
}
}
extension CollectiontThriftStruct: ThriftCodable {}
| 27.208333 | 97 | 0.647779 |
e0739829e2551dd80c3d910af581ac7fd5fc318b | 1,787 | //
// Post.swift
// PhotoSnap
//
// Created by Fernanda on 3/19/16.
// Copyright © 2016 Maria C. All rights reserved.
//
import UIKit
import Parse
class Post: NSObject {
class func postUserImage(image: UIImage?, withCaption caption: String?, withCompletion completion: PFBooleanResultBlock?){
let post = PFObject(className: "Post")
// Add relevant fields to the object
post["media"] = getPFFileFromImage(image) // PFFile column type
post["author"] = PFUser.currentUser() // Pointer column type that points to PFUser
post["caption"] = caption
post["likesCount"] = 0
post["commentsCount"] = 0
// Save object (following function will save the object in Parse asynchronously)
post.saveInBackgroundWithBlock(completion)
}
func resize(image: UIImage, newSize: CGSize) -> UIImage {
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()
return newImage
}
class func getPFFileFromImage(image: UIImage?) -> PFFile? {
// check if image is not nil
if let image = image {
// get image data and check if that is not nil
if let imageData = UIImagePNGRepresentation(image) {
return PFFile(name: "image.png", data: imageData)
}
}
return nil
}
}
| 32.490909 | 126 | 0.639619 |
4a1fbdb0c9fbfb3d30ebc29b5f7eebab85769a47 | 2,570 | //
// Friendship.swift
// Swiftagram
//
// Created by Stefano Bertagno on 31/07/20.
//
import Foundation
/// A `struct` representing a `Friendship`.
public struct Friendship: Wrapped {
/// The underlying `Response`.
public var wrapper: () -> Wrapper
/// Whether they're followed by the logged in user or not.
public var isFollowedByYou: Bool? { self["following"].bool() }
/// Whether they follow the logged in user or not.
public var isFollowingYou: Bool? { self["followedBy"].bool() }
/// Whether they're blocked by the logged in user or not.
public var isBlockedByYou: Bool? { self["blocking"].bool() }
/// Whether they're in the logged in user's close firends list or not.
public var isCloseFriend: Bool? { self["isBestie"].bool() }
/// Whether they've requested to follow the logged in user or not.
public var didRequestToFollowYou: Bool? { self["incomingRequest"].bool() }
/// Whether the logged in user have requested to follow them or not.
public var didRequestToFollow: Bool? { self["outgoingRequest"].bool() }
/// Whether the logged in user is muting their stories.
public var isMutingStories: Bool? { self["isMutingReel"].bool() }
/// Whether the logged in user is muting their posts.
public var isMutingPosts: Bool? { self["muting"].bool() }
/// Init.
/// - parameter wrapper: A valid `Wrapper`.
public init(wrapper: @escaping () -> Wrapper) {
self.wrapper = wrapper
}
}
public extension Friendship {
/// A `struct` representing a `Friendship` collection.
struct Dictionary: Specialized {
/// The underlying `Response`.
public var wrapper: () -> Wrapper
/// The friendships.
public var friendships: [String: Friendship]! {
self["friendshipStatuses"].dictionary()?.mapValues { Friendship(wrapper: $0) }
}
/// Init.
/// - parameter wrapper: A valid `Wrapper`.
public init(wrapper: @escaping () -> Wrapper) {
self.wrapper = wrapper
}
}
/// A `struct` representing a single `Friendship` value.
struct Unit: Specialized {
/// The underlying `Response`.
public var wrapper: () -> Wrapper
/// The friendship.
public var friendship: Friendship? {
self["friendshipStatus"].optional().flatMap(Friendship.init)
}
/// Init.
/// - parameter wrapper: A valid `Wrapper`.
public init(wrapper: @escaping () -> Wrapper) {
self.wrapper = wrapper
}
}
}
| 34.266667 | 90 | 0.622179 |
fe079a7d587b9d8f3a15c0413bf782cab665f7c8 | 6,906 | //
// TTSManagerTest.swift
// SpokestackTests
//
// Created by Noel Weichbrodt on 11/15/19.
// Copyright © 2020 Spokestack, Inc. All rights reserved.
//
import Foundation
import XCTest
import Spokestack
@available(iOS 13, *)
class TextToSpeechTest: XCTestCase {
/// MARK: Synthesize
func testSynthesize() {
let delegate = TestTextToSpeechDelegate()
let input = TextToSpeechInput()
// bad config results in a failed request that calls failure
let badConfig = SpeechConfiguration()
let didFailConfigExpectation = expectation(description: "bad config results in a failed request that calls TestTextToSpeechDelegate.failure")
badConfig.apiId = "BADBADNOTGOOD"
let badTTS = TextToSpeech([delegate], configuration: badConfig)
delegate.asyncExpectation = didFailConfigExpectation
badTTS.synthesize(input)
wait(for: [didFailConfigExpectation], timeout: 5)
XCTAssert(delegate.didFail)
XCTAssertFalse(delegate.didSucceed)
let config = SpeechConfiguration()
let tts = TextToSpeech([delegate], configuration: config)
// bad input results in a failed request that calls failure
delegate.reset()
let didFailInputExpectation = expectation(description: "bad input results in a failed request that calls failure")
delegate.asyncExpectation = didFailInputExpectation
let badInput = TextToSpeechInput()
badInput.voice = "tracy-throne"
tts.synthesize(badInput)
wait(for: [didFailInputExpectation], timeout: 5)
XCTAssert(delegate.didFail)
XCTAssertFalse(delegate.didSucceed)
// successful request calls success
delegate.reset()
let didSucceedExpectation = expectation(description: "successful request calls TestTextToSpeechDelegate.success")
delegate.asyncExpectation = didSucceedExpectation
tts.synthesize(input)
wait(for: [didSucceedExpectation], timeout: 5)
XCTAssert(delegate.didSucceed)
XCTAssertFalse(delegate.didFail)
}
func testSynthesizeSSML() {
let delegate = TestTextToSpeechDelegate()
let config = SpeechConfiguration()
let tts = TextToSpeech([delegate], configuration: config)
// successful request with ssml formatting
let didSucceedExpectation2 = expectation(description: "successful request calls TestTextToSpeechDelegate.success")
delegate.asyncExpectation = didSucceedExpectation2
let ssmlInput = TextToSpeechInput("<speak>Yet right now the average age of this 52nd Parliament is 49 years old, <break time='500ms'/> OK Boomer.</speak>", voice: "demo-male", inputFormat: .ssml)
tts.synthesize(ssmlInput)
wait(for: [didSucceedExpectation2], timeout: 5)
XCTAssert(delegate.didSucceed)
XCTAssertFalse(delegate.didFail)
}
func testSynthesizeMarkdown() {
let delegate = TestTextToSpeechDelegate()
let config = SpeechConfiguration()
let tts = TextToSpeech([delegate], configuration: config)
// successful request with markdown formatting
delegate.reset()
let didSucceedExpectation3 = expectation(description: "successful request calls TestTextToSpeechDelegate.success")
delegate.asyncExpectation = didSucceedExpectation3
let markdownInput = TextToSpeechInput("Yet right now the average age of this (50)[number] second Parliament is (49)[number] years old, [1s] OK Boomer.", voice: "demo-male", inputFormat: .markdown)
tts.synthesize(markdownInput)
wait(for: [didSucceedExpectation3], timeout: 5)
XCTAssert(delegate.didSucceed)
XCTAssertFalse(delegate.didFail)
}
func testSynthesizePublisher() {
let config = SpeechConfiguration()
guard let tts = try? TextToSpeech(configuration: config) else {
XCTFail("could not initialize TextToSpeech class")
return
}
let input = TextToSpeechInput()
// successful request
let didCompleteExpectation = expectation(description: "successful request publishes completion")
let publisher = tts.synthesize([input])
.sink(
receiveCompletion: {completion in
switch completion {
case .failure(let error):
XCTFail(error.localizedDescription)
break
case .finished:
didCompleteExpectation.fulfill()
break
}
},
receiveValue: {result in
XCTAssertTrue(result.count > 0)
XCTAssertNotNil(result.first?.url)
})
XCTAssertNotNil(publisher)
wait(for: [didCompleteExpectation], timeout: 5)
}
}
class TextToSpeechSynthesizeTest: XCTestCase {
func testSpeak() {
// speak() calls didBeginSpeaking and didFinishSpeaking
let didBeginExpectation = expectation(description: "successful request calls TestTextToSpeechDelegate.didBeginSpeaking")
let didFinishExpectation = expectation(description: "successful request calls TestTextToSpeechDelegate.didFinishSpeaking")
let delegate = TestTextToSpeechDelegate()
delegate.asyncExpectation = didBeginExpectation
delegate.didFinishExpectation = didFinishExpectation
let input = TextToSpeechInput()
let config = SpeechConfiguration()
let tts = TextToSpeech([delegate], configuration: config)
tts.speak(input)
wait(for: [didBeginExpectation, didFinishExpectation], timeout: 10)
XCTAssert(delegate.didBegin)
XCTAssert(delegate.didFinish)
}
}
class TestTextToSpeechDelegate: SpokestackDelegate {
/// Spy pattern for the system under test.
/// asyncExpectation lets the caller's test know when the delegate has been called.
var didSucceed: Bool = false
var didFail: Bool = false
var didBegin: Bool = false
var didFinish: Bool = false
var asyncExpectation: XCTestExpectation?
var didFinishExpectation: XCTestExpectation?
func reset() {
didSucceed = false
didFail = false
didBegin = false
didFinish = false
asyncExpectation = .none
}
func success(result: TextToSpeechResult) {
asyncExpectation?.fulfill()
didSucceed = true
}
func failure(error: Error) {
asyncExpectation?.fulfill()
didFail = true
}
func didBeginSpeaking() {
asyncExpectation?.fulfill()
didBegin = true
}
func didFinishSpeaking() {
didFinishExpectation?.fulfill()
didFinish = true
}
func didTrace(_ trace: String) -> Void {
print(trace)
}
}
| 38.797753 | 204 | 0.659427 |
e5ca07f4bfdde881a72a872faa73be01738042fa | 578 | //
// Photo.swift
// FlickrUpdates
//
// Created by Leonardo Vinicius Kaminski Ferreira on 25/08/17.
// Copyright © 2017 Leonardo Ferreira. All rights reserved.
//
import Foundation
struct Photo {
let urlMedium: String
let ownerName: String
init(urlMedium: String, ownerName: String) {
self.urlMedium = urlMedium
self.ownerName = ownerName
}
init(dict: [String: AnyObject]) {
self.urlMedium = JSONParserHelper.parseString(dict["url_m"])
self.ownerName = JSONParserHelper.parseString(dict["ownername"])
}
}
| 23.12 | 72 | 0.66436 |
e2dba2e8e6dfdeda77f64707b2c8bdfc29c6aaaf | 2,873 | import CloudKit.CKDatabase
#if !COCOAPODS
import PromiseKit
#endif
/**
To import the `CKDatabase` category:
use_frameworks!
pod "PromiseKit/CloudKit"
And then in your sources:
#import <PromiseKit/PromiseKit.h>
*/
extension CKDatabase {
public func fetchRecordWithID(recordID: CKRecordID) -> Promise<CKRecord> {
return Promise { fetchRecordWithID(recordID, completionHandler: $0) }
}
public func fetchRecordZoneWithID(recordZoneID: CKRecordZoneID) -> Promise<CKRecordZone> {
return Promise { fetchRecordZoneWithID(recordZoneID, completionHandler: $0) }
}
public func fetchSubscriptionWithID(subscriptionID: String) -> Promise<CKSubscription> {
return Promise { fetchSubscriptionWithID(subscriptionID, completionHandler: $0) }
}
public func fetchAllRecordZones() -> Promise<[CKRecordZone]> {
return Promise { fetchAllRecordZonesWithCompletionHandler($0) }
}
public func fetchAllSubscriptions() -> Promise<[CKSubscription]> {
return Promise { fetchAllSubscriptionsWithCompletionHandler($0) }
}
public func save(record: CKRecord) -> Promise<CKRecord> {
return Promise { saveRecord(record, completionHandler: $0) }
}
public func save(recordZone: CKRecordZone) -> Promise<CKRecordZone> {
return Promise { saveRecordZone(recordZone, completionHandler: $0) }
}
public func save(subscription: CKSubscription) -> Promise<CKSubscription> {
return Promise { saveSubscription(subscription, completionHandler: $0) }
}
public func deleteRecordWithID(recordID: CKRecordID) -> Promise<CKRecordID> {
return Promise { deleteRecordWithID(recordID, completionHandler: $0) }
}
public func deleteRecordZoneWithID(zoneID: CKRecordZoneID) -> Promise<CKRecordZoneID> {
return Promise { deleteRecordZoneWithID(zoneID, completionHandler: $0) }
}
public func deleteSubscriptionWithID(subscriptionID: String) -> Promise<String> {
return Promise { deleteSubscriptionWithID(subscriptionID, completionHandler: $0) }
}
public func performQuery(query: CKQuery, inZoneWithID zoneID: CKRecordZoneID? = nil) -> Promise<[CKRecord]> {
return Promise { performQuery(query, inZoneWithID: zoneID, completionHandler: $0) }
}
public func performQuery(query: CKQuery, inZoneWithID zoneID: CKRecordZoneID? = nil) -> Promise<CKRecord?> {
return Promise { resolve in
performQuery(query, inZoneWithID: zoneID) { records, error in
resolve(records?.first, error)
}
}
}
public func fetchUserRecord(container: CKContainer = CKContainer.defaultContainer()) -> Promise<CKRecord> {
return container.fetchUserRecordID().then(on: zalgo) { uid -> Promise<CKRecord> in
return self.fetchRecordWithID(uid)
}
}
}
| 36.367089 | 113 | 0.699965 |
79aae80ac319635a1f4cfd537356ce212ddd8de0 | 14,562 | //
// StageExpandTableViewController.swift
// Chula Expo 2017
//
// Created by NOT on 2/1/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
import CoreData
class StageExpandTableViewController: StageExpandableCoreDataTableViewController {
@IBOutlet weak var topTab: UIView!
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBOutlet weak var button4: UIButton!
@IBOutlet weak var button5: UIButton!
var dateForDefault: Int = 1
let dateComp = NSDateComponents()
let nowDate = Date()
var selectionIndicatorView: UIView = UIView()
var selectedDate: Int = 1{
didSet{
selectSection = nil
switch selectedDate {
case 1:
startDate = Date.day1
endDate = Date.day2
case 2:
startDate = Date.day2
endDate = Date.day3
case 3:
startDate = Date.day3
endDate = Date.day4
case 4:
startDate = Date.day4
endDate = Date.day5
case 5:
startDate = Date.day5
endDate = Date.day6
default:
startDate = Date.day1
endDate = Date.day2
}
updateUI()
tableView.reloadData()
// tableView.beginUpdates()
// tableView.endUpdates()
}
}
var startDate = Date.day1
var endDate = Date.day2
var stageNo: Int? {
didSet {
// updateUI()
}
}
var managedObjectContext: NSManagedObjectContext? {
didSet {
updateUI()
}
}
var selectSection: Int?{
willSet{
if selectSection != nil{
let indexPath = IndexPath(row: 0, section: selectSection!)
if let selectCell = tableView.cellForRow(at: indexPath) as? StageExpandableCell{
selectCell.closeTitle()
}
}
}
didSet{
if selectSection != nil{
let indexPath = IndexPath(row: 0, section: selectSection!)
if let selectCell = tableView.cellForRow(at: indexPath) as? StageExpandableCell{
selectCell.expandTitle()
}
}
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
}
func setupTopTab(){
moveToptabIndicator()
let shadowPath = UIBezierPath(rect: topTab.bounds)
topTab.layer.shadowColor = UIColor.darkGray.cgColor
topTab.layer.shadowOffset = CGSize(width: 0, height: 0)
topTab.layer.shadowRadius = 1
topTab.layer.shadowOpacity = 0.5
topTab.layer.shadowPath = shadowPath.cgPath
updateButton(no: selectedDate, toBlack: false)
}
@IBAction func selectDate(_ sender: Any) {
if let button = sender as? UIButton{
updateButton(no: selectedDate, toBlack: true)
selectedDate = button.tag
updateButton(no: selectedDate, toBlack: false)
}
moveToptabIndicator()
}
func changeButtonAttributeColor(_ color: UIColor,for button: UIButton){
let attribute = NSMutableAttributedString(attributedString: button.currentAttributedTitle!)
attribute.addAttribute(NSForegroundColorAttributeName , value: color, range: NSRange(location: 0,length: 6))
button.setAttributedTitle(attribute, for: .normal)
button.setAttributedTitle(attribute, for: .highlighted)
}
func moveToptabIndicator(){
UIView.animate(withDuration: 0.15, animations: { () -> Void in
let sectionWidth = self.topTab.frame.width / 5
let sectionX = (sectionWidth * (CGFloat)(self.selectedDate - 1) ) + 2
self.selectionIndicatorView.frame = CGRect(x: sectionX, y: self.topTab.bounds.height-2, width: sectionWidth-4, height: 2)
})
}
func updateButton(no: Int,toBlack: Bool){
var color: UIColor
var button: UIButton
if toBlack{
color = UIColor.black
} else {
color = UIColor(red:1.00, green:0.43, blue:0.60, alpha:1.0)
}
switch no {
case 1:
button = button1
case 2:
button = button2
case 3:
button = button3
case 4:
button = button4
case 5:
button = button5
default:
button = button1
}
changeButtonAttributeColor(color, for: button)
}
fileprivate func updateUI(){
if let context = managedObjectContext{
if let stageNo = stageNo{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
request.predicate = NSPredicate(format: "toActivity.end >= %@ AND toActivity.start <= %@ AND stage == %i", startDate as NSDate, endDate as NSDate, stageNo)
request.sortDescriptors = [NSSortDescriptor(
key: "toActivity.start",
ascending: true,
selector: #selector(NSDate.compare(_:))
)]
fetchedResultsController = NSFetchedResultsController(
fetchRequest: request,
managedObjectContext: context,
sectionNameKeyPath: "activityId",
cacheName: nil
)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
print("\(startDate.toThaiText()) - \(endDate.toThaiText())")
selectedDate = dateForDefault
self.navigationController?.navigationBar.isTranslucent = false
var selectionIndicatorFrame : CGRect = CGRect()
let sectionWidth = topTab.frame.width / 5
selectionIndicatorFrame = CGRect(x: (sectionWidth * (CGFloat)(selectedDate - 1) ) + 2 , y: topTab.bounds.height-2, width: sectionWidth - 4, height: 2)
selectionIndicatorView = UIView(frame: selectionIndicatorFrame)
selectionIndicatorView.backgroundColor = UIColor(red:1.00, green:0.43, blue:0.60, alpha:1.0)
setupTopTab()
topTab.addSubview(selectionIndicatorView)
tableView.estimatedRowHeight = 140
tableView.reloadData()
// tableView.contentInset = UIEdgeInsetsMake(((self.navigationController?.navigationBar.frame)?.height)! + (self.navigationController?.navigationBar.frame)!.origin.y, 0.0, ((self.tabBarController?.tabBar.frame)?.height)!, 0);
// Uncomment the following line to preserve selection between presentations
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
// self.tableView.backgroundColor = UIColor.blue
print("loadedStage")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print("layoutStage")
setupTopTab()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell
if indexPath.row == 0{
cell = tableView.dequeueReusableCell(withIdentifier: "StageEventCell", for: indexPath)
if let fetchData = fetchedResultsController?.object(at: IndexPath(row: 0, section: indexPath.section)) as? StageActivity{
var name: String?
var startTime: String?
var endTime: String?
var dotOption: Int = 0
fetchData.managedObjectContext?.performAndWait {
name = fetchData.toActivity?.name
if let sTime = fetchData.toActivity?.start{
print("sTime \(sTime.toThaiText())")
startTime = sTime.toTimeText()
if let eTime = fetchData.toActivity?.end{
print("eTime \(eTime.toThaiText())")
endTime = eTime.toTimeText()
if self.nowDate.isInRangeOf(start: sTime, end: eTime){
dotOption = 1
}
else if self.nowDate.isLessThanDate(sTime){
dotOption = 2
}
else if self.nowDate.isGreaterThanDate(eTime){
dotOption = 0
}
}
}
}
if let stageExpandableCell = cell as? StageExpandableCell{
if indexPath.section == selectSection{
stageExpandableCell.expandTitle()
} else {
stageExpandableCell.closeTitle()
}
stageExpandableCell.name = name
stageExpandableCell.time = startTime
stageExpandableCell.endTime = ("-\(endTime ?? "")")
switch dotOption {
case 0:
stageExpandableCell.runningDot.image = #imageLiteral(resourceName: "passedDot")
case 1:
stageExpandableCell.runningDot.image = #imageLiteral(resourceName: "runningDot")
case 2:
stageExpandableCell.runningDot.image = #imageLiteral(resourceName: "nextComingDot")
default:
stageExpandableCell.runningDot.image = #imageLiteral(resourceName: "passedDot")
}
}
}
}
else{
cell = tableView.dequeueReusableCell(withIdentifier: "stageDetail", for: indexPath)
if let fetchData = fetchedResultsController?.object(at: IndexPath(row: 0, section: indexPath.section)) as? StageActivity{
var desc: String?
var id: String?
fetchData.managedObjectContext?.performAndWait {
desc = fetchData.toActivity?.desc
id = fetchData.toActivity?.activityId
}
if let stageDetailCell = cell as? StageDetailCell{
stageDetailCell.desc = desc
stageDetailCell.button.actID = id
}
}
}
// Configure the cell...
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectSection == indexPath.section && indexPath.row == 0 {
selectSection = nil
}
else {
selectSection = indexPath.section
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == selectSection {
if indexPath.row == 0{
// if UITableViewAutomaticDimension < 0{
//
// return 50
// }
return UITableViewAutomaticDimension
}else{
return UITableViewAutomaticDimension
}
}
else if indexPath.row == 0 {
return UITableViewAutomaticDimension
}
return 0;
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetailFromStage"{
if let destination = segue.destination as? EventDetailTableViewController {
if let button = sender as? DetailButton{
if let id = button.actID{
ActivityData.fetchActivityData(activityId: id, inManageobjectcontext: managedObjectContext!, completion: { (activityData) in
if let activityData = activityData {
destination.activityId = activityData.activityId
destination.bannerUrl = activityData.bannerUrl
destination.topic = activityData.name
destination.locationDesc = ""
destination.toRounds = activityData.toRound
destination.desc = activityData.desc
destination.room = activityData.room
destination.place = activityData.place
destination.zoneId = activityData.faculty
destination.latitude = activityData.latitude
destination.longitude = activityData.longitude
destination.pdf = activityData.pdf
destination.video = activityData.video
destination.toImages = activityData.toImages
destination.toTags = activityData.toTags
destination.start = activityData.start
destination.end = activityData.end
destination.managedObjectContext = self.managedObjectContext
}
})
}
}
}
}
}
}
| 36.133995 | 233 | 0.508309 |
9cc0af2c448e7cfbe805230440acc71704189231 | 435 | //
// ViewController.swift
// SwiftGitTrans
//
// Created by Takanori.H on 2017/05/08.
// Copyright © 2017年 Takanori.H. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 13.59375 | 54 | 0.570115 |
eb08bee3e230b3033591b945aa2683911e645c2c | 7,608 | /* The MIT License
*
* Copyright © 2020 NBCO YooMoney 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
extension UIColor {
static let black12 = UIColor(white: 0, alpha: 0.12)
static let black50 = UIColor(white: 0, alpha: 0.5)
static let black65 = UIColor(white: 0, alpha: 0.65)
static let black90 = UIColor(white: 0, alpha: 0.9)
static let geyser = UIColor(red: 221 / 255, green: 227 / 255, blue: 229 / 255, alpha: 1)
static let greenHaze = UIColor(red: 0, green: 152 / 255, blue: 95 / 255, alpha: 1)
static let white90 = UIColor(white: 1, alpha: 0.9)
static let codGray = UIColor(white: 26 / 255, alpha: 1)
static let mineShaft = UIColor(white: 34 / 255, alpha: 1)
static let warmGray = UIColor(white: 153 / 255, alpha: 1)
static let alto = UIColor(white: 219 / 255, alpha: 1)
static let mousegrey = UIColor(white: 224 / 255, alpha: 1)
static let mercury = UIColor(white: 225 / 255, alpha: 1)
static let gallery = UIColor(white: 236 / 255, alpha: 1)
static let darkSkyBlue = UIColor(red: 70 / 255, green: 142 / 255, blue: 229 / 255, alpha: 1)
static let lightGold = UIColor(red: 254 / 255, green: 221 / 255, blue: 97 / 255, alpha: 1)
static let brightSun = UIColor(red: 254 / 255, green: 217 / 255, blue: 68 / 255, alpha: 1)
static let redOrange = UIColor(red: 1, green: 51 / 255, blue: 51 / 255, alpha: 1)
static let redOrange70 = UIColor(red: 1, green: 51 / 255, blue: 51 / 255, alpha: 0.7)
static let dandelion = UIColor(red: 254 / 255, green: 216 / 255, blue: 93 / 255, alpha: 1)
static let dandelion80 = UIColor(red: 1, green: 221 / 255, blue: 96 / 255, alpha: 0.8)
static let blueRibbon = UIColor(red: 0 / 255, green: 112 / 255, blue: 240 / 255, alpha: 1)
static let cerulean = UIColor(red: 6 / 255, green: 151 / 255, blue: 198 / 255, alpha: 1)
static let battleshipGrey = UIColor(red: 107 / 255, green: 117 / 255, blue: 136 / 255, alpha: 1)
static let dustyOrange = UIColor(red: 233 / 255, green: 107 / 255, blue: 76 / 255, alpha: 1)
static let emeraldGreen = UIColor(red: 0, green: 151 / 255, blue: 25 / 255, alpha: 1)
static let electricPurple = UIColor(red: 140 / 255, green: 63 / 255, blue: 1, alpha: 1)
static let brightBlue = UIColor(red: 0, green: 108 / 255, blue: 245 / 255, alpha: 1)
static let pine = UIColor(red: 61 / 255, green: 73 / 255, blue: 41 / 255.0, alpha: 1)
static let burntSienna = UIColor(red: 176 / 255, green: 60 / 255, blue: 22 / 255, alpha: 1)
static let darkIndigo = UIColor(red: 8 / 255, green: 38 / 255, blue: 59 / 255, alpha: 1)
static let darkSlateBlue = UIColor(red: 16 / 255, green: 58 / 255, blue: 74 / 255, alpha: 1)
static let dullBlue = UIColor(red: 76 / 255, green: 117 / 255, blue: 158 / 255, alpha: 1)
static let charcoalGrey = UIColor(red: 44 / 255, green: 42 / 255, blue: 45 / 255, alpha: 1)
static let marineBlue = UIColor(red: 0, green: 143 / 255, blue: 174 / 255, alpha: 1)
static let slateBlue = UIColor(red: 21 / 255, green: 42 / 255, blue: 96 / 255, alpha: 1)
static let uglyBlue = UIColor(red: 43 / 255, green: 136 / 255, blue: 146 / 255, alpha: 1)
// MARK: - Paired colors
static let black5 = UIColor(white: 0, alpha: 0.05)
static let cararra = UIColor(white: 247 / 255, alpha: 1)
static let mustard = UIColor(red: 1, green: 219 / 255, blue: 77 / 255, alpha: 1)
static let creamBrulee = UIColor(red: 1, green: 234 / 255, blue: 158 / 255, alpha: 1)
static let black60 = UIColor(white: 0, alpha: 0.6)
static let doveGray = UIColor(white: 102 / 255, alpha: 1)
static let black30 = UIColor(white: 0, alpha: 0.3)
static let nobel = UIColor(white: 179 / 255, alpha: 1)
static let blueRibbon50 = UIColor(red: 0 / 255, green: 112 / 255, blue: 240 / 255, alpha: 0.5)
static let jordyBlue = UIColor(red: 135 / 255, green: 184 / 255, blue: 245 / 255, alpha: 1)
static let success = UIColor(red: 0, green: 153 / 255, blue: 97 / 255, alpha: 1)
static let inverse = UIColor(white: 1, alpha: 1)
static let inverseTranslucent = UIColor(white: 1, alpha: 0.5)
static let inverse30 = UIColor(white: 1, alpha: 0.3)
static let link = UIColor(red: 0, green: 108 / 255, blue: 244 / 255, alpha: 1)
static func highlighted(from color: UIColor) -> UIColor {
return color.withAlphaComponent(0.5)
}
/// FadeTint from tint color
static func fadeTint(from color: UIColor) -> UIColor {
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
guard color.getHue(&hue,
saturation: &saturation,
brightness: &brightness,
alpha: &alpha) else { return color }
saturation *= 0.5
brightness *= 0.9
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
// MARK: - Adaptive colors
enum AdaptiveColors {
static var primary: UIColor = {
let color: UIColor
if #available(iOS 13.0, *) {
color = .init(dynamicProvider: { (trait) -> UIColor in
let dynamicProviderColor: UIColor
switch trait.userInterfaceStyle {
case .dark, .light:
dynamicProviderColor = .label
case .unspecified:
dynamicProviderColor = .black
@unknown default:
dynamicProviderColor = .black
}
return dynamicProviderColor
})
} else {
color = .black
}
return color
}()
static var secondary: UIColor = {
let color: UIColor
if #available(iOS 13.0, *) {
color = .init(dynamicProvider: { (trait) -> UIColor in
let dynamicProviderColor: UIColor
switch trait.userInterfaceStyle {
case .dark, .light:
dynamicProviderColor = .secondaryLabel
case .unspecified:
dynamicProviderColor = .doveGray
@unknown default:
dynamicProviderColor = .doveGray
}
return dynamicProviderColor
})
} else {
color = .doveGray
}
return color
}()
}
}
| 49.72549 | 100 | 0.606467 |
164dafac013e46ea7d9ffa88c03a282db494868a | 491 | //
// NewPasswordViewModel.swift
// Minning
//
// Created by denny on 2021/10/28.
// Copyright © 2021 Minning. All rights reserved.
//
import Foundation
final class NewPasswordViewModel {
private let coordinator: AuthCoordinator
public init(coordinator: AuthCoordinator) {
self.coordinator = coordinator
}
public func goToBack() {
coordinator.goToBack()
}
public func goToLogin() {
coordinator.start(asRoot: true)
}
}
| 18.884615 | 50 | 0.649695 |
16e7955f4565816501146bf8e04d99c9272c9115 | 200 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let twoThousand : UInt16 = 2000
let one : UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one) | 22.222222 | 52 | 0.73 |
ac0686819d246ae06c5963417e72be189dcee8df | 4,150 | //
// StorageUsageViewController.swift
// WeChatSwift
//
// Created by xu.shuifeng on 2019/8/16.
// Copyright © 2019 alexiscn. All rights reserved.
//
import AsyncDisplayKit
class StorageUsageViewController: ASViewController<ASDisplayNode> {
private let tableNode = ASTableNode(style: .grouped)
private let headBackgroundNode = ASDisplayNode()
private let summaryStorageNode: StorageUsageSummaryNode
private var dataSource: [StorageUsageDetail] = []
private let loadingView = StorageUsageLoadingView(frame: CGRect(x: 0, y: 0, width: Constants.screenWidth, height: 140))
private let scanner = StorageUsageScanner()
init() {
let summary = StorageUsageSummary(systemTotalSize: 100, systemFreeSize: 50, wechatSize: 30)
summaryStorageNode = StorageUsageSummaryNode(summary: summary)
let cacheStorageDetail = StorageUsageDetail(title: "缓存", desc: "缓存是使用微信过程中产生的临时数据,清理缓存不会影响微信的正常使用。", totalSize: 0, action: .clean)
let chatStorageDetail = StorageUsageDetail(title: "聊天记录", desc: "可清理聊天中的图片、视频、文件等数据,但不会删除消息。", totalSize: 0, action: .manage)
dataSource = [cacheStorageDetail, chatStorageDetail]
super.init(node: ASDisplayNode())
node.addSubnode(headBackgroundNode)
node.addSubnode(tableNode)
tableNode.dataSource = self
tableNode.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
headBackgroundNode.backgroundColor = Colors.white
headBackgroundNode.frame = CGRect(x: 0, y: Constants.topInset + Constants.statusBarHeight - Constants.screenHeight * 2.0, width: Constants.screenWidth, height: Constants.screenHeight * 2.0)
node.backgroundColor = Colors.DEFAULT_BACKGROUND_COLOR
tableNode.view.showsVerticalScrollIndicator = false
tableNode.view.showsHorizontalScrollIndicator = false
tableNode.frame = node.bounds
tableNode.view.separatorStyle = .none
tableNode.backgroundColor = .clear
tableNode.allowsSelection = false
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: Constants.screenWidth, height: 230))
headerView.addSubnode(summaryStorageNode)
summaryStorageNode.frame = headerView.bounds
tableNode.view.tableHeaderView = headerView
navigationItem.title = LocalizedString("Setting_StorageUsageVC_Title")
scanner.startScan { (summary, detail) in
}
}
override var wx_navigationBarBackgroundColor: UIColor? {
return .white
}
}
// MARK: - UIScrollViewDelegate
extension StorageUsageViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
headBackgroundNode.frame.origin.y = Constants.screenHeight * -2.0 - scrollView.contentOffset.y
}
}
extension StorageUsageViewController: ASTableDelegate, ASTableDataSource {
func numberOfSections(in tableNode: ASTableNode) -> Int {
return dataSource.count
}
func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableNode(_ tableNode: ASTableNode, nodeBlockForRowAt indexPath: IndexPath) -> ASCellNodeBlock {
let model = dataSource[indexPath.section]
let block: ASCellNodeBlock = {
return StorageUsageDetailNode(detail: model)
}
return block
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return nil
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 8.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
}
| 34.583333 | 197 | 0.679518 |
e0b890ee6ec74cb1f58cbef8cc08d38620cca75c | 5,650 | //
// AALegend.swift
// AAInfographicsDemo
//
// Created by AnAn on 2019/6/26.
// Copyright © 2019 An An. All rights reserved.
//*************** ...... SOURCE CODE ...... ***************
//***...................................................***
//*** https://github.com/AAChartModel/AAChartKit ***
//*** https://github.com/AAChartModel/AAChartKit-Swift ***
//***...................................................***
//*************** ...... SOURCE CODE ...... ***************
/*
* -------------------------------------------------------------------------------
*
* 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔
*
* Please contact me on GitHub,if there are any problems encountered in use.
* GitHub Issues : https://github.com/AAChartModel/AAChartKit-Swift/issues
* -------------------------------------------------------------------------------
* And if you want to contribute for this project, please contact me as well
* GitHub : https://github.com/AAChartModel
* StackOverflow : https://stackoverflow.com/users/12302132/codeforu
* JianShu : https://www.jianshu.com/u/f1e6753d4254
* SegmentFault : https://segmentfault.com/u/huanghunbieguan
*
* -------------------------------------------------------------------------------
*/
import Foundation
public class AALegend: AAObject {
public var layout: String? //The layout of the legend data items. Layout type: "horizontal" or "vertical" ie horizontal and vertical layout The default is: "horizontal".
public var align: String? //Set the horizontal alignment of the legend in the chart area. Legal values are "left", "center", and "right". The default is: "center".
public var verticalAlign: String? //Set the vertical alignment of the legend in the chart area. Legal values are "top", "middle", and "bottom". The vertical position can be further set by the y option.The default is: "bottom".
public var enabled: Bool?
public var borderColor: String?
public var borderWidth: Float?
public var itemMarginTop: Float? //The top margin of each item of the legend, in px. The default is: 0.
public var itemMarginBottom: Float?//The bottom margin of each item of the legend, in px. The default is: 0.
public var itemStyle: AAItemStyle?
public var symbolHeight: Float?
public var symbolPadding: Float?
public var symbolRadius: Float?
public var symbolWidth: Float?
public var x: Float?
public var y: Float?
public var floating: Bool?
@discardableResult
public func layout(_ prop: AAChartLayoutType?) -> AALegend {
layout = prop?.rawValue
return self
}
@discardableResult
public func align(_ prop: AAChartAlignType?) -> AALegend {
align = prop?.rawValue
return self
}
@discardableResult
public func verticalAlign(_ prop: AAChartVerticalAlignType?) -> AALegend {
verticalAlign = prop?.rawValue
return self
}
@discardableResult
public func enabled(_ prop: Bool?) -> AALegend {
enabled = prop
return self
}
@discardableResult
public func borderColor(_ prop: String?) -> AALegend {
borderColor = prop
return self
}
@discardableResult
public func borderWidth(_ prop: Float?) -> AALegend {
borderWidth = prop
return self
}
@discardableResult
public func itemMarginTop(_ prop: Float?) -> AALegend {
itemMarginTop = prop
return self
}
@discardableResult
public func itemStyle(_ prop: AAItemStyle?) -> AALegend {
itemStyle = prop
return self
}
@discardableResult
public func symbolHeight(_ prop: Float?) -> AALegend {
symbolHeight = prop
return self
}
@discardableResult
public func symbolPadding(_ prop: Float?) -> AALegend {
symbolPadding = prop
return self
}
@discardableResult
public func symbolRadius(_ prop: Float?) -> AALegend {
symbolRadius = prop
return self
}
@discardableResult
public func x(_ prop: Float?) -> AALegend {
x = prop
return self
}
@discardableResult
public func symbolWidth(_ prop: Float?) -> AALegend {
symbolWidth = prop
return self
}
@discardableResult
public func y(_ prop: Float?) -> AALegend {
y = prop
return self
}
@discardableResult
public func floating(_ prop: Bool?) -> AALegend {
floating = prop
return self
}
public override init () {
}
}
public class AAItemStyle: AAObject {
public var color: String?
public var cursor: String?
public var pointer: String?
public var fontSize: String?
public var fontWeight: AAChartFontWeightType?
@discardableResult
public func color(_ prop: String?) -> AAItemStyle {
color = prop
return self
}
@discardableResult
public func cursor(_ prop: String?) -> AAItemStyle {
cursor = prop
return self
}
@discardableResult
public func pointer(_ prop: String?) -> AAItemStyle {
pointer = prop
return self
}
@discardableResult
public func fontSize(_ prop: Float?) -> AAItemStyle {
if (prop != nil) {
fontSize = "\(prop!)px"
}
return self
}
@discardableResult
public func fontWeight(_ prop: AAChartFontWeightType?) -> AAItemStyle {
fontWeight = prop
return self
}
public override init() {
}
}
| 29.427083 | 230 | 0.575221 |
6aec281d99982e6fd39896ec5605f687938a6884 | 424 | #if MIXBOX_ENABLE_IN_APP_SERVICES
import MixboxIpc
public final class IpcMethodHandlerRegistrationDependencies {
public let ipcRouter: IpcRouter
public let ipcClient: IpcClient? // TODO: Make it not optional after removing SBTUITestTunnel
public init(
ipcRouter: IpcRouter,
ipcClient: IpcClient?)
{
self.ipcRouter = ipcRouter
self.ipcClient = ipcClient
}
}
#endif
| 22.315789 | 97 | 0.707547 |
1619d1f65b5dff11201680bfe5df311a9b1aabeb | 889 | //
// TYPEPersistenceStrategy.swift
//
import AmberBase
import Foundation
public class Dictionary_C_Date_FormatStyleCapitalizationContext_D_PersistenceStrategy: PersistenceStrategy
{
public var types: Types
{
return Types.generic("Dictionary", [Types.type("Date"), Types.type("FormatStyleCapitalizationContext")])
}
public func save(_ object: Any) throws -> Data
{
guard let typedObject = object as? Dictionary<Date, FormatStyleCapitalizationContext> else
{
throw AmberError.wrongTypes(self.types, AmberBase.types(of: object))
}
let encoder = JSONEncoder()
return try encoder.encode(typedObject)
}
public func load(_ data: Data) throws -> Any
{
let decoder = JSONDecoder()
return try decoder.decode(Dictionary<Date, FormatStyleCapitalizationContext>.self, from: data)
}
} | 28.677419 | 112 | 0.692913 |
fc72efc6ab66547ff848c39ffadded8a47e8b85b | 3,175 | //
// MZWorkerConfigViewController.swift
// Muzzley-iOS
//
// Created by Cristina Lopes on 19/12/15.
// Copyright © 2015 Muzzley. All rights reserved.
//
class MZWorkerConfigViewController: UIViewController, MZHTMLViewControllerDelegate {
@IBOutlet weak var webViewPlaceholder: UIView!
var deviceVMs: [MZDeviceViewModel]!
var workerVM: MZWorkerViewModel!
var type:String!
var isEdit:Bool = false
var isUpdate:Bool = false
var isShortcut:Bool = false
fileprivate enum ThingInteractionUIState: Int {
case initial = 0,
unableToLoad,
loading,
loaded
}
fileprivate var wireframe: MZRootWireframe!
fileprivate var interactor: MZWorkersInteractor!
fileprivate var htmlViewController: MZHTMLViewController!
convenience init(withWireframe wireframe: MZRootWireframe, andInteractor interactor: MZWorkersInteractor) {
self.init(nibName: "MZWorkerConfigViewController", bundle: Bundle.main)
self.wireframe = wireframe
self.interactor = interactor
}
override func viewDidLoad() {
super.viewDidLoad()
let barButton: UIBarButtonItem = UIBarButtonItem()
barButton.title = ""
self.navigationController?.navigationBar.topItem?.backBarButtonItem = barButton
self.htmlViewController = MZHTMLViewController()
self.htmlViewController.delegate = self
self.addChildViewController(self.htmlViewController)
self.htmlViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.htmlViewController.view.frame = self.webViewPlaceholder.bounds
self.webViewPlaceholder.addSubview(self.htmlViewController.view)
self.htmlViewController.enableActivityIndicator(true)
self.htmlViewController.load(with:URLRequest(url: self.interactor.getWorkerURL()), withOptions: self.interactor.getOptionsPayload(self.deviceVMs, type: self.type!) as! [AnyHashable: Any])
//.loadWithURLRequest(NSURLRequest(URL: self.interactor.getWorkerURL() as URL), withOptions: self.interactor.getOptionsPayload(self.deviceVMs, type: self.type!) as! [AnyHashable: Any])
}
// MARK: - MZHTMLViewController Delegate
func htmlViewController(_ htmlViewController: MZHTMLViewController!, didFailLoadWithError error: NSError!) {
if error.code != NSURLErrorCancelled {
}
}
func htmlViewController(_ htmlViewController: MZHTMLViewController!, onMessage message: [AnyHashable: Any]?)
{
if message != nil
{
workerVM = self.interactor.updateWorkerViewModel(workerVM!, message: message!, isUpdate: self.isUpdate, isEdit: self.isEdit, isShortcut: self.isShortcut)
if self.navigationController != nil
{
for vc in self.navigationController!.viewControllers
{
if vc is MZCreateWorkerViewController {
self.navigationController!.popToViewController(vc, animated: true)
break
}
}
}
}
}
}
| 36.079545 | 195 | 0.674961 |
035df4e1a2d7fafaac1c709ed0b585847018cab0 | 6,414 | //
// MenuItem.swift
// Menus
//
// Created by Simeon on 6/6/18.
// Copyright © 2018 Two Lives Left. All rights reserved.
//
import UIKit
import SnapKit
public protocol MenuItemView {
var highlighted: Bool { get set }
var highlightPosition: CGPoint { get set }
var initialFocusedRect: CGRect? { get }
var updateLayout: () -> Void { get set }
func startSelectionAnimation(completion: @escaping () -> Void)
}
extension MenuItemView {
public func startSelectionAnimation(completion: @escaping () -> Void) {}
public var initialFocusedRect: CGRect? { return nil }
}
//MARK: - Separator
class SeparatorMenuItemView: UIView, MenuItemView, MenuThemeable {
private let separatorLine = UIView()
init() {
super.init(frame: .zero)
addSubview(separatorLine)
separatorLine.snp.makeConstraints {
make in
make.left.right.equalToSuperview()
make.height.equalTo(1)
make.top.bottom.equalToSuperview().inset(2)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Menu Item View
var highlighted: Bool = false
var highlightPosition: CGPoint = .zero
var updateLayout: () -> Void = {}
//MARK: - Themeable
func applyTheme(_ theme: MenuTheme) {
separatorLine.backgroundColor = theme.separatorColor
}
}
//MARK: - Standard Menu Item
extension String {
var renderedShortcut: String {
switch self {
case " ":
return "Space"
case "\u{8}":
return "⌫"
default:
return self
}
}
}
extension ShortcutMenuItem.Shortcut {
var labels: [UILabel] {
let symbols = modifiers.symbols + [key]
return symbols.map {
let label = UILabel()
label.text = $0.renderedShortcut
label.textAlignment = .right
if $0 == key {
label.textAlignment = .left
label.snp.makeConstraints {
make in
make.width.greaterThanOrEqualTo(label.snp.height)
}
}
return label
}
}
}
public class ShortcutMenuItemView: UIView, MenuItemView, MenuThemeable {
private let nameLabel = UILabel()
private let shortcutStack = UIView()
private var shortcutLabels: [UILabel] {
return shortcutStack.subviews.compactMap { $0 as? UILabel }
}
public init(item: ShortcutMenuItem) {
super.init(frame: .zero)
nameLabel.text = item.name
addSubview(nameLabel)
nameLabel.textColor = .black
nameLabel.snp.makeConstraints {
make in
make.top.bottom.equalToSuperview().inset(4)
make.left.equalToSuperview().offset(10)
make.right.lessThanOrEqualToSuperview().offset(-10)
}
if let shortcut = item.shortcut, ShortcutMenuItem.displayShortcuts {
addSubview(shortcutStack)
nameLabel.snp.makeConstraints {
make in
make.right.lessThanOrEqualTo(shortcutStack.snp.left).offset(-12)
}
shortcutStack.snp.makeConstraints {
make in
make.top.bottom.equalToSuperview().inset(2)
make.right.equalToSuperview().inset(6)
}
shortcutStack.setContentHuggingPriority(.required, for: .horizontal)
let labels = shortcut.labels
for (index, label) in labels.enumerated() {
shortcutStack.addSubview(label)
label.snp.makeConstraints {
make in
make.top.bottom.equalToSuperview()
if index == 0 {
make.left.equalToSuperview()
} else if index < labels.count - 1 {
make.left.equalTo(labels[index - 1].snp.right).offset(1.0 / UIScreen.main.scale)
}
if index == labels.count - 1 {
if index > 0 {
make.left.equalTo(labels[index - 1].snp.right).offset(2)
}
make.right.equalToSuperview()
}
}
}
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func startSelectionAnimation(completion: @escaping () -> Void) {
updateHighlightState(false)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
[weak self] in
self?.updateHighlightState(true)
completion()
}
}
//MARK: - Menu Item View
public var highlighted: Bool = false {
didSet {
updateHighlightState(highlighted)
}
}
public var highlightPosition: CGPoint = .zero
public var updateLayout: () -> Void = {}
//MARK: - Themeable Helpers
private var highlightedBackgroundColor: UIColor = .clear
private func updateHighlightState(_ highlighted: Bool) {
nameLabel.isHighlighted = highlighted
shortcutLabels.forEach { $0.isHighlighted = highlighted }
backgroundColor = highlighted ? highlightedBackgroundColor : .clear
}
//MARK: - Themeable
public func applyTheme(_ theme: MenuTheme) {
nameLabel.font = theme.font
nameLabel.textColor = theme.textColor
nameLabel.highlightedTextColor = theme.highlightedTextColor
highlightedBackgroundColor = theme.highlightedBackgroundColor
shortcutLabels.forEach {
label in
label.font = theme.font
label.textColor = theme.textColor
label.highlightedTextColor = theme.highlightedTextColor
}
updateHighlightState(highlighted)
}
}
| 27.063291 | 104 | 0.536639 |
de5d73f686a786f28d9c1b0b68bcfe1e6fb480a3 | 482 | class Solution {
func buildArray(_ target: [Int], _ n: Int) -> [String] {
var result: [String] = []
var idx = 0
for elem in 1...n {
if elem == target[idx] {
result.append("Push")
idx += 1
} else {
result.append("Push")
result.append("Pop")
}
if elem == target.last {
break
}
}
return result
}
} | 25.368421 | 60 | 0.381743 |
387dc2ac942dac5eaec78c4a44d0c22f0043ac12 | 837 | //
// NavigationAnimating.swift
// LMAnimatedTransition
//
// Created by 刘明 on 2019/3/16.
// Copyright © 2019 com.ming. All rights reserved.
//
import UIKit
// MARK: Transitioning Animation Only
public protocol NavigationTransitionControlType {
// 生成Transition动画,使用协定定义,便于替换和扩展
var aniTransitionProducer: AniTransitionProducerType { get}
}
extension NavigationTransitionControlType where Self: UINavigationControllerDelegate {
public func noobj_naviController(
_ naviController: UINavigationController,
_ operation: UINavigationController.Operation,
_ fromVC: UIViewController,
_ toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return aniTransitionProducer.animation(from: fromVC, to: toVC, For: AniTransitionOperation(operation))
}
}
| 28.862069 | 110 | 0.740741 |
758d524202c9a1d5b0f3516b39215895bff6d972 | 676 | //
// FileDownloadDestination.swift
// CoronaContact
//
import Alamofire
import Foundation
import Moya
struct FileDownloadDestination {
static let defaultDestination: DownloadDestination = DownloadRequest.suggestedDownloadDestination(
for: .documentDirectory,
in: .userDomainMask,
options: [.removePreviousFile, .createIntermediateDirectories]
)
static func makeDestination(for url: URL) -> DownloadDestination {
// swiftformat:disable:next redundantReturn
return { temporaryURL, response in
let (_, options) = defaultDestination(temporaryURL, response)
return (url, options)
}
}
}
| 26 | 102 | 0.699704 |
1812ade37489907adae06d107378ef26db4daafc | 202 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{{{>{}}}}protocol c{typealias B:B | 40.4 | 87 | 0.747525 |
d950c0f3d1a9cd6341136666ab17b55cdd24986c | 444 | //
// Data+HBAdditions.swift
// Ride
//
// Created by William Henderson on 3/14/17.
// Copyright © 2017 Knock Softwae, Inc. All rights reserved.
//
import Foundation
extension Data {
public func hexadecimalString() -> String {
var string = ""
string.reserveCapacity(count * 2)
for byte in self {
string.append(String(format: "%02X", byte))
}
return string
}
}
| 19.304348 | 61 | 0.574324 |
2fc53083b5ca19069e458b6e6f889b6ea5f7d893 | 2,829 | /**
* (C) Copyright IBM Corp. 2016, 2020.
*
* 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
/**
Information about a classifier.
*/
public struct Classifier: Codable, Equatable {
/**
Training status of classifier.
*/
public enum Status: String {
case ready = "ready"
case training = "training"
case retraining = "retraining"
case failed = "failed"
}
/**
ID of a classifier identified in the image.
*/
public var classifierID: String
/**
Name of the classifier.
*/
public var name: String
/**
Unique ID of the account who owns the classifier. Might not be returned by some requests.
*/
public var owner: String?
/**
Training status of classifier.
*/
public var status: String?
/**
Whether the classifier can be downloaded as a Core ML model after the training status is `ready`.
*/
public var coreMLEnabled: Bool?
/**
If classifier training has failed, this field might explain why.
*/
public var explanation: String?
/**
Date and time in Coordinated Universal Time (UTC) that the classifier was created.
*/
public var created: Date?
/**
Classes that define a classifier.
*/
public var classes: [Class]?
/**
Date and time in Coordinated Universal Time (UTC) that the classifier was updated. Might not be returned by some
requests. Identical to `updated` and retained for backward compatibility.
*/
public var retrained: Date?
/**
Date and time in Coordinated Universal Time (UTC) that the classifier was most recently updated. The field matches
either `retrained` or `created`. Might not be returned by some requests.
*/
public var updated: Date?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case classifierID = "classifier_id"
case name = "name"
case owner = "owner"
case status = "status"
case coreMLEnabled = "core_ml_enabled"
case explanation = "explanation"
case created = "created"
case classes = "classes"
case retrained = "retrained"
case updated = "updated"
}
}
| 28.009901 | 119 | 0.653234 |
6ad115cf680184bba2b8cdcb4d33861f11a8bc5c | 263 | #if MIXBOX_ENABLE_IN_APP_SERVICES
public final class RandomBoolGenerator: Generator<Bool> {
public init(randomNumberProvider: RandomNumberProvider) {
super.init {
randomNumberProvider.nextRandomNumber() % 2 == 1
}
}
}
#endif
| 21.916667 | 61 | 0.688213 |
3ad9fc70f25f6f0495372ad7e3a3d10f5c48ef26 | 11,246 | //
// 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
//
import Apodini
import ApodiniOpenAPISecurity
import OpenAPIKit
/// Utility to convert `_PathComponent`s to `OpenAPI.Path` format.
struct OpenAPIPathBuilder: PathBuilderWithResult {
var components: [String] = []
mutating func append(_ string: String) {
components.append(string)
}
mutating func append<Type: Codable>(_ parameter: EndpointPathParameter<Type>) {
components.append("{\(parameter.name)}")
}
func result() -> OpenAPIKit.OpenAPI.Path {
OpenAPIKit.OpenAPI.Path(stringLiteral: self.components.joined(separator: "/"))
}
}
/// Corresponds to `paths` section in OpenAPI document.
/// See: https://swagger.io/specification/#paths-object
struct OpenAPIPathsObjectBuilder {
var pathsObject: OpenAPIKit.OpenAPI.PathItem.Map = [:]
let componentsObjectBuilder: OpenAPIComponentsObjectBuilder
init(componentsObjectBuilder: OpenAPIComponentsObjectBuilder) {
self.componentsObjectBuilder = componentsObjectBuilder
}
/// https://swagger.io/specification/#path-item-object
mutating func addPathItem<H: Handler>(from endpoint: Endpoint<H>) {
// Get OpenAPI-compliant path representation.
let absolutePath = endpoint.absoluteRESTPath
let path = absolutePath.build(with: OpenAPIPathBuilder.self)
// Get or create `PathItem`.
var pathItem = pathsObject[path] ?? OpenAPIKit.OpenAPI.PathItem()
// Get `OpenAPI.HttpMethod` and `OpenAPI.Operation` from endpoint.
let httpMethod = OpenAPIKit.OpenAPI.HttpMethod(endpoint[Operation.self])
let operation = buildPathItemOperationObject(from: endpoint)
pathItem.set(operation: operation, for: httpMethod)
// Add (or override) `PathItem` to map of paths.
pathsObject[path] = pathItem
}
}
private extension OpenAPIPathsObjectBuilder {
/// https://swagger.io/specification/#operation-object
mutating func buildPathItemOperationObject<H: Handler>(from endpoint: Endpoint<H>) -> OpenAPIKit.OpenAPI.Operation {
let handlerContext = endpoint[Context.self]
var defaultTag: String
let absolutePath = endpoint.absoluteRESTPath
// If parameter in path, get string component directly before first parameter component in path.
if let index = absolutePath.firstIndex(where: { $0.isParameter() }), index > 0 {
let stringComponent = absolutePath[index - 1].description
defaultTag = stringComponent.isEmpty ? "default" : stringComponent
// If not, get string component that was appended last to the path.
} else {
defaultTag = absolutePath.last { ($0.isString()) }?.description ?? "default"
}
// Get tags if some have been set explicitly passed via TagModifier.
let tags: [String] = handlerContext.get(valueFor: TagContextKey.self) ?? [defaultTag]
// Get customDescription if it has been set explicitly passed via DescriptionModifier.
let customDescription = handlerContext.get(valueFor: HandlerDescriptionMetadata.self)
// Set endpointDescription to customDescription or `endpoint.description` holding the `Handler`s type name.
let endpointDescription = customDescription ?? endpoint.description
// Get `Parameter.Array` from existing `query` or `path` parameters.
let parameters: OpenAPIKit.OpenAPI.Parameter.Array = buildParametersArray(from: endpoint.parameters, with: handlerContext)
// Get `OpenAPI.Request` body object containing HTTP body types.
let requestBody: OpenAPIKit.OpenAPI.Request? = buildRequestBodyObject(from: endpoint.parameters)
// Get `OpenAPI.Response.Map` containing all possible HTTP responses mapped to their status code.
let responses: OpenAPIKit.OpenAPI.Response.Map = buildResponsesObject(from: endpoint[ResponseType.self].type)
let securitySchemes = handlerContext
.get(valueFor: SecurityMetadata.self)
.map(to: EndpointSecurityDescription.self, on: endpoint)
var securityArray: [OpenAPIKit.OpenAPI.SecurityRequirement] = []
var requiredSecurityRequirementIndex: Int?
var requiresAuthentication = false
// see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object
// all required security is placed in the **same** `SecurityRequirement` object
// the list of `SecurityRequirement` it encodes that only one of those is required.
for (key, description) in securitySchemes {
guard let componentKey = OpenAPIKit.OpenAPI.ComponentKey(rawValue: key) else {
fatalError("""
Security Metadata Key must match pattern '^[a-zA-Z0-9\\.\\-_]+$'. \
Key '\(key)' for \(description) didn't match.
""")
}
componentsObjectBuilder.addSecurityScheme(key: componentKey, scheme: description.scheme)
requiresAuthentication = requiresAuthentication || description.required
if !description.required {
securityArray.append([.component(named: componentKey.rawValue): description.scopes])
continue
}
if let requiredIndex = requiredSecurityRequirementIndex {
securityArray[requiredIndex][.component(named: componentKey.rawValue)] = description.scopes
} else {
requiredSecurityRequirementIndex = securityArray.count
securityArray.append([.component(named: componentKey.rawValue): description.scopes])
}
}
if !securityArray.isEmpty && !requiresAuthentication {
// OpenAPI represents optional authentication with an empty SecurityRequirement
// see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object
securityArray.append([:])
}
return OpenAPIKit.OpenAPI.Operation(
tags: tags,
summary: handlerContext.get(valueFor: HandlerSummaryMetadata.self),
description: endpointDescription,
operationId: endpoint[AnyHandlerIdentifier.self].rawValue,
parameters: parameters,
requestBody: requestBody,
responses: responses,
security: securityArray.isEmpty ? nil : securityArray,
vendorExtensions: [
"x-apodiniHandlerId": AnyCodable(endpoint[AnyHandlerIdentifier.self].rawValue)
]
)
}
/// https://swagger.io/specification/#parameter-object
mutating func buildParametersArray(from parameters: [AnyEndpointParameter], with handlerContext: Context) -> OpenAPIKit.OpenAPI.Parameter.Array {
let parameterDescription = handlerContext.get(valueFor: ParameterDescriptionContextKey.self)
return parameters.compactMap {
guard let context = OpenAPIKit.OpenAPI.Parameter.Context($0) else {
return nil // filter out content parameters
}
return Either.parameter(
name: $0.name,
context: context,
schema: .from($0.propertyType),
description: parameterDescription[$0.id] ?? $0.description
)
}
}
/// https://swagger.io/specification/#request-body-object
mutating func buildRequestBodyObject(from parameters: [AnyEndpointParameter]) -> OpenAPIKit.OpenAPI.Request? {
var requestBody: OpenAPIKit.OpenAPI.Request?
let contentParameters = parameters.filter {
$0.parameterType == .content
}
var requestJSONSchema: JSONSchema?
do {
if contentParameters.count == 1 {
requestJSONSchema = try componentsObjectBuilder.buildSchema(for: contentParameters[0].propertyType)
} else if !contentParameters.isEmpty {
requestJSONSchema = try componentsObjectBuilder.buildWrapperSchema(for: contentParameters.map {
$0.propertyType
}, with: contentParameters.map {
$0.necessity
})
}
} catch {
fatalError("Could not build schema for request body wrapped by parameters \(contentParameters).")
}
if let requestJSONSchema = requestJSONSchema {
requestBody = OpenAPIKit.OpenAPI.Request(description: contentParameters
.map {
$0.description
}
.joined(separator: "\n"),
content: [
requestJSONSchema.openAPIContentType: .init(schema: requestJSONSchema)
]
)
}
return requestBody
}
/// https://swagger.io/specification/#responses-object
mutating func buildResponsesObject(from responseType: Encodable.Type) -> OpenAPIKit.OpenAPI.Response.Map {
var responseContent: OpenAPIKit.OpenAPI.Content.Map = [:]
let responseJSONSchema: JSONSchema
do {
responseJSONSchema = try componentsObjectBuilder.buildResponse(for: responseType)
} catch {
fatalError("Could not build schema for response body for type \(responseType): \(error)")
}
responseContent[responseJSONSchema.openAPIContentType] = .init(schema: responseJSONSchema)
var responses: OpenAPIKit.OpenAPI.Response.Map = [:]
responses[.status(code: 200)] = .init(OpenAPIKit.OpenAPI.Response(
description: "OK",
headers: nil,
content: responseContent,
vendorExtensions: [:])
)
responses[.status(code: 401)] = .init(
OpenAPIKit.OpenAPI.Response(description: "Unauthorized")
)
responses[.status(code: 403)] = .init(
OpenAPIKit.OpenAPI.Response(description: "Forbidden")
)
responses[.status(code: 404)] = .init(
OpenAPIKit.OpenAPI.Response(description: "Not Found")
)
responses[.status(code: 500)] = .init(
OpenAPIKit.OpenAPI.Response(description: "Internal Server Error")
)
return responses
}
}
extension AnyEndpoint {
/// RESTInterfaceExporter exports `@Parameter(.http(.path))`, which are not listed on the
/// path-elements on the `Component`-tree as additional path elements at the end of the path.
var absoluteRESTPath: [EndpointPath] {
self[EndpointPathComponentsHTTP.self].value
}
}
| 45.715447 | 149 | 0.629379 |
ef6bd87c1f2862fe07be66d79ec6d47d73378602 | 2,784 | //
// ViewController.swift
// WordMatching
//
// Created by Arvin Quiliza on 7/25/18.
// Copyright © 2018 arvnq. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//MARK:- IBOUTLETS
@IBOutlet weak var fruitsScoreLabel: UILabel!
@IBOutlet weak var animalsScoreLabel: UILabel!
@IBOutlet weak var vehiclesScoreLabel: UILabel!
@IBOutlet var mainMenuButtons: [UIButton]!
//MARK:- VARIABLES
var fruitScore = 0
var animalScore = 0
var vehicleScore = 0
//MARK:- LIFECYCLE
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isTranslucent = false
//navigation bar background color
navigationController?.navigationBar.barTintColor = .black
//navigation bar buttons color
navigationController?.navigationBar.tintColor = .white
//navigation bar title color
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
//navigationController?.navigationBar.prefersLargeTitles = true
updateHighScore()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
for button in mainMenuButtons {
button.imageView?.contentMode = .scaleAspectFill
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- SEGUE METHOD
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationViewController = segue.destination as! GamePageViewController
guard let segueIdentifier = segue.identifier else {
return
}
destinationViewController.gameType = segueIdentifier
switch segueIdentifier {
case "fruit" : destinationViewController.currentHighScore = fruitScore
case "animal": destinationViewController.currentHighScore = animalScore
case "vehicle": destinationViewController.currentHighScore = vehicleScore
default: destinationViewController.currentHighScore = 0
}
}
//MARK:- IBACTION
@IBAction func unwindToMenu (sender: UIStoryboardSegue) {
updateHighScore()
}
//MARK:- FUNCTION
/**
This function updates the high score for each of the game type.
*/
func updateHighScore() {
fruitsScoreLabel.text = "Fruits: \(fruitScore)"
animalsScoreLabel.text = "Animals: \(animalScore)"
vehiclesScoreLabel.text = "Vehicles: \(vehicleScore)"
}
}
| 30.593407 | 120 | 0.658405 |
e54371979bf98ef60ffa4f4218299749c7802924 | 103 |
(int r) f (string x) {
r = 1;
trace(x);
}
main {
string x = "hello world\n";
f(x);
}
| 9.363636 | 31 | 0.427184 |
f4e07f53f13cd16743fe4c5d619cc02938da8e1c | 6,322 | import Foundation
import UIKit
import CascableCore
import CascableCoreSwift
import Combine
@objc(LiveViewAndShootingViewController) class LiveViewAndShootingViewController: UIViewController, CameraViewController {
deinit {
// Make sure we remove our shot preview observer so it doesn't get fired after we're deallocated!
if let observer = shotPreviewObserver { camera?.removeShotPreviewObserver(with: observer) }
// Turn off live view if it's running.
stopLiveView()
}
// MARK: - Setup
var camera: (NSObject & Camera)?
func setupUI(for camera: (NSObject & Camera)?) {
self.camera = camera
guard let camera = camera else { return }
// Shot previews let us preview shots with a reasonably high quality as they're taken.
shotPreviewObserver = camera.addShotPreviewObserver({ [weak self] delivery in
self?.handleShotPreview(delivery)
})
startLiveView(on: camera)
}
// MARK: - Shooting Images
@IBAction func shootImage(_ sender: Any?) {
// If you need fine-grained control when invoking the focus and shutter, see the engageAutoFocus: et. al. methods.
// IMPORTANT: The error parameter given in the callback only indicates whether the request was sent without error.
// Whether or not the shutter was actually fired is a complex decision tree made by the camera, depending on
// various camera settings and whether or not autofocus was successful etc etc. The result of this decision is not returned.
camera?.invokeOneShotShutterExplicitlyEngagingAutoFocus(true, completionCallback: { error in
if let error = error {
print("\(CurrentFileName()): Shot trigger failed with error: \(error.localizedDescription)")
} else {
print("\(CurrentFileName()): Shot trigger succeeded")
}
})
}
// MARK: - Shot Preview
var shotPreviewObserver: String?
var lastShotPreviewImage: UIImage?
func handleShotPreview(_ previewDelivery: ShotPreviewDelivery) {
// Shot previews get delivered (on supported cameras) when a new preview is available. Previews will become invalid
// after an amount of time, so it's important to check they're still valid before fetching.
// Since fetching a preview can delay other commands, they're only fetched if you ask for them, which
// we do here 100% of the time.
guard previewDelivery.isValid else {
print("\(CurrentFileName()): Shot preview received, but it's invalid!")
return
}
print("\(CurrentFileName()): Fetching shot preview…")
previewDelivery.fetchShotPreview { [weak self] sourceData, previewImage, error in
guard let self = self else { return }
// sourceData is the raw image data as received from the camera, before any rotation etc. is applied.
// This can be useful if you want to apply your own tranformations to the image.
guard error == nil, let preview = previewImage else {
print("\(CurrentFileName()): Shot preview fetch failed with error: \(error?.localizedDescription ?? "unknown")")
return
}
print("Shot preview fetch succeeded")
self.lastShotPreviewImage = preview
self.performSegue(withIdentifier: "shotPreview", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let shotPreview = segue.destination as? ShotPreviewViewController {
shotPreview.loadViewIfNeeded()
shotPreview.imageView.image = lastShotPreviewImage
}
}
// MARK: - Live View
@IBOutlet var liveViewImageView: UIImageView!
// We store our Combine subscribers in here.
private var liveViewSubscribers: Set<AnyCancellable> = []
func startLiveView(on camera: Camera) {
// Make sure we're not subscribing more than once.
liveViewSubscribers.removeAll()
// In this example, we're using the Combine publisher provided to us by CascableCoreSwift. To use the "plain"
// API, which doesn't use Combine, see the LiveViewAndShootingViewController.m file in the Objective-C
// example — the APIs used there translate directly into Swift.
// The Combine publisher manages starting and stopping live view, etc. All we need to do is to subscribe to it.
camera.liveViewPublisher(options: [.maximumFramesPerSecond: FrameRate(fps: 30.0)])
.receive(on: DispatchQueue.main)
.sinkWithReadyHandler { [weak self] terminationReason in
// The termination reason lets us know why live view finished.
// We might want to display an error to the user if it finished abnormally.
switch terminationReason {
case .finished: print("\(CurrentFileName()): Live view terminated normally.")
case .failure(let error): print("\(CurrentFileName()): Live view failed with error: \(error.localizedDescription)")
}
self?.stopLiveView()
} receiveValue: { [weak self] frame, readyForNextFrame in
// CascableCoreSwift provides .sinkWithReadyHandler, which works like .sink except it can manage
// demand for live view frames nicely. It'll wait to issue demand for more live view frames until
// we're ready for more. Here we call it immediately, but if we wanted to implement a background
// image processing pipeline, this will help prevent buffer backfill.
self?.liveViewImageView.image = frame.image
// We must call the ready handler once we're ready for more live view frames. Since we want a nice,
// smooth image, we'll call the completion handler without delay.
readyForNextFrame()
}
.store(in: &liveViewSubscribers)
}
func stopLiveView() {
// The camera's live view frame publisher will automatically shut off live view when there's no subscribers
// left, so all we need to do is remove our observers.
liveViewSubscribers.removeAll()
}
}
| 43.30137 | 132 | 0.657703 |
e9eb01ad4a7f7bd76522de2580adf3da7e06be97 | 526 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct Q<T {
enum A : I) {
}
func a() -> {
struct c : P {
class func f<H : P {
protocol c = b.e = {
protocol A {
}
}
self.init(
| 26.3 | 79 | 0.69962 |
f48a796dabc2d21374a4cc9f7ea9673cd06cfc2e | 431 | //
// ViewController.swift
// CoreDuck
//
// Created by Maksym Skliarov on 05/09/2016.
// Copyright (c) 2016 Maksym Skliarov. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 9.0, *) {
Entity.batchDeleteAll()
} else {
// Fallback on earlier versions
Entity.deleteAllObjects()
}
}
}
| 17.958333 | 60 | 0.642691 |
e2b4c50daf2003bc8fc901f7e3465ea14a7cbcc9 | 162 | import XCTest
@testable import littleStore
class ProductListTests: XCTestCase {
func testPath() {
XCTAssertEqual(ProductList.path, "products.json")
}
}
| 16.2 | 53 | 0.746914 |
46ed4cb8b1a279d74ccee639088f3e3844e695ee | 1,357 | //
// OnboardingContentViewController.swift
// Supplements
//
// Created by Tomasz Iwaszek on 4/11/19.
// Copyright © 2019 matchusolutions. All rights reserved.
//
import UIKit
class OnboardingContentViewController: UIViewController {
var presenter: OnboardingPresenterProtocol!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var contentImageView: UIImageView!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var progressStackView: UIStackView!
var backgroundColor: UIColor = .red
var index = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = backgroundColor
presenter.getTitleImageAndDescOfContentView(index: index)
for (index, view) in progressStackView.subviews.enumerated() {
if index == self.index {
view.backgroundColor = backgroundColor == .onboardingLightRed ? .onboardingRed : .onboardingLightRed
break
}
}
}
func setTitleImageAndDescOfContentView(title: String, desc: String, image: UIImage) {
titleLabel.text = title
descriptionLabel.text = desc
contentImageView.image = image
}
@IBAction func closeTapped(_ sender: Any) {
presenter.closeOnboarding()
}
}
| 27.14 | 116 | 0.655122 |
09c5bcf831848488f2ae2ba741f3029b9c2c0140 | 919 | //
// NASA_ProbesTests.swift
// NASA ProbesTests
//
// Created by Matheus Cardoso kuhn on 19/04/19.
// Copyright © 2019 MDT. All rights reserved.
//
import XCTest
@testable import NASA_Probes
class NASA_ProbesTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.257143 | 111 | 0.658324 |
d50f39457f79fc27ccefca682b51261fbfcad538 | 1,249 | //
// DHArchiveDemoUITests.swift
// DHArchiveDemoUITests
//
// Created by aiden on 2018/2/3.
// Copyright © 2018年 aiden. All rights reserved.
//
import XCTest
class DHArchiveDemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.756757 | 182 | 0.665332 |
bbc6c0523d12427be1943a3ea74e2c9b9873189b | 3,745 | public protocol Stateable: AnyState {
associatedtype Value
var wrappedValue: Value { get set }
func beginTrigger(_ trigger: @escaping () -> Void)
func endTrigger(_ trigger: @escaping () -> Void)
func listen(_ listener: @escaping (_ old: Value, _ new: Value) -> Void)
func listen(_ listener: @escaping (_ value: Value) -> Void)
func listen(_ listener: @escaping () -> Void)
}
//public typealias UState = State
@propertyWrapper
open class UState<Value>: Stateable {
private var _originalValue: Value
private var _wrappedValue: Value
public var wrappedValue: Value {
get { _wrappedValue }
set {
let oldValue = _wrappedValue
_wrappedValue = newValue
beginTriggers.forEach { $0() }
listeners.forEach { $0(oldValue, newValue) }
endTriggers.forEach { $0() }
}
}
public var projectedValue: UState<Value> { self }
public init(wrappedValue value: Value) {
_originalValue = value
_wrappedValue = value
}
public func reset() {
let oldValue = _wrappedValue
_wrappedValue = _originalValue
beginTriggers.forEach { $0() }
listeners.forEach { $0(oldValue, _wrappedValue) }
endTriggers.forEach { $0() }
}
public func removeAllListeners() {
beginTriggers.removeAll()
endTriggers.removeAll()
listeners.removeAll()
}
public typealias Trigger = () -> Void
public typealias Listener = (_ old: Value, _ new: Value) -> Void
public typealias SimpleListener = (_ value: Value) -> Void
private var beginTriggers: [Trigger] = []
private var endTriggers: [Trigger] = []
private var listeners: [Listener] = []
public func beginTrigger(_ trigger: @escaping Trigger) {
beginTriggers.append(trigger)
}
public func endTrigger(_ trigger: @escaping Trigger) {
endTriggers.append(trigger)
}
public func listen(_ listener: @escaping Listener) {
listeners.append(listener)
}
public func listen(_ listener: @escaping SimpleListener) {
listeners.append({ _, new in listener(new) })
}
public func listen(_ listener: @escaping () -> Void) {
listeners.append({ _,_ in listener() })
}
public func merge(with state: UState<Value>) {
self.wrappedValue = state.wrappedValue
var justSetExternal = false
var justSetInternal = false
state.listen { new in
guard !justSetInternal else { return }
justSetExternal = true
self.wrappedValue = new
justSetExternal = false
}
self.listen { new in
guard !justSetExternal else { return }
justSetInternal = true
state.wrappedValue = new
justSetInternal = false
}
}
// MARK: Experimental part
public struct CombinedStateResult<A, B> {
public let left: A
public let right: B
}
/// Merging two states into one combined state which could be used as expressable state
public func and<V>(_ state: UState<V>) -> UState<CombinedStateResult<Value, V>> {
let stateA = self
let stateB = state
let combinedValue = {
return CombinedStateResult(left: stateA.wrappedValue, right: stateB.wrappedValue)
}
let resultState = UState<CombinedStateResult<Value, V>>(wrappedValue: combinedValue())
stateA.listen {
resultState.wrappedValue = combinedValue()
}
stateB.listen {
resultState.wrappedValue = combinedValue()
}
return resultState
}
}
| 30.950413 | 94 | 0.606142 |
f711ce50c6307ff579b23a4570f0d55a80ce289a | 1,035 | //
// Base58CheckTests.swift
// BitCoreTests
//
// Created by SPARK-Daniel on 2021/12/24.
//
import XCTest
@testable import BitCore
class Base58CheckTests: 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 testBase58CheckDecode() throws {
let addr = "mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf"
let h160 = Base58Check.decode(addr)?.dropFirst().hex
let want = "507b27411ccf7f16f10297de6cef3f291623eddf"
XCTAssertEqual(h160, want)
}
func testBase58CheckEncode() {
let hex = "507b27411ccf7f16f10297de6cef3f291623eddf"
let got = Base58Check.encode(Data(hex: "6f") + Data(hex: hex))
let addr = "mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf"
XCTAssertEqual(addr, got)
}
}
| 28.75 | 111 | 0.68599 |
fee3898f4bca39d65346e375a5f552c023fa9909 | 1,128 | /// 163. Missing Ranges
/// Given a sorted integer array nums, where the range of elements are in the inclusive range
/// [lower, upper], return its missing ranges.
///
/// Example:
/// Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,
/// Output: ["2", "4->49", "51->74", "76->99"]
import XCTest
/// Approach: Iteration
func findMissingRanges(_ nums: [Int], _ lower: Int, _ upper: Int) -> [String] {
var result: [String] = []
for i in -1..<nums.count {
let current = i == -1 ? lower - 1 : nums[i]
let next = i + 1 < nums.count ? nums[i + 1] : upper + 1
let difference = next - current
guard difference > 1 else { continue }
if difference == 2 {
result.append(String(current + 1))
} else {
result.append(String(current + 1) + "->" + String(next - 1))
}
}
return result
}
class Tests: XCTestCase {
func testExample() {
let nums = [0, 1, 3, 50, 75]
let expected = ["2", "4->49", "51->74", "76->99"]
XCTAssertEqual(findMissingRanges(nums, 0, 99), expected)
}
}
Tests.defaultTestSuite.run()
| 30.486486 | 93 | 0.558511 |
cc5551c460abfa26424184b9d94b9e4f7239d9ec | 353 | //
// DimSumReview.swift
// DimSumApp
//
// Created by Jian Ting Li on 7/11/19.
// Copyright © 2019 Jian Ting Li. All rights reserved.
//
import Foundation
struct DimSumReview: Codable {
let dimSumFoodEng: String
let userID: String?
let reviewID: String?
let rating: Double
let description: String
let location: String?
}
| 17.65 | 55 | 0.677054 |
d9bc6b38eca2221795096589a590335672b5d8c1 | 265 | // 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 {
case c,
{
class c : j { func a
struct B<T: A? {
var e: A? {
class
case c,
enum S<D> V
| 18.928571 | 87 | 0.698113 |
8a95d7a91490340a19a2f96a6efb9404c8d999fa | 1,103 | //
// TodoListingRouter.swift
// SocialAppCleanSwift
//
// Created by Christian Slanzi on 04.12.20.
// Copyright (c) 2020 Christian Slanzi. All rights reserved.
import UIKit
protocol ITodoListingRouter {
// do someting...
//func navigateToPhotos(for albumId: Int)
}
class TodoListingRouter: ITodoListingRouter {
var appRouter: IAppRouter
init(appRouter: IAppRouter) {
self.appRouter = appRouter
}
func presentView(parameters: [String: Any]) {
appRouter.presentView(view: create(parameters: parameters))
}
func create(parameters: [String: Any]) -> TodoListingViewController {
let bundle = Bundle(for: type(of: self))
let view = TodoListingViewController(nibName: "TodoListingViewController", bundle: bundle)
view.title = "todolisting_view_title".localized
let presenter = TodoListingPresenter(view: view)
let interactor = TodoListingInteractor(presenter: presenter)
view.interactor = interactor
view.router = self
interactor.parameters = parameters
return view
}
}
| 29.026316 | 98 | 0.687217 |
f946f7f2b57bc160d7fd0933c19c919b194a504e | 181 | //
// LoginViewController.swift
// OAuthProvider_Example
//
// Created by Grigor Hakobyan on 23.06.21.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import Foundation
| 18.1 | 52 | 0.723757 |
56a4b35de65b527d32f22ff51b5f543438d62e8b | 1,424 | //
// HomeScreenNavigationController.swift
// AgileLife
//
// Created by Zachary Gover on 4/16/16.
// Copyright © 2016 Full Sail University. All rights reserved.
//
import UIKit
class HomeScreenNavigationController: UINavigationController {
/* ==========================================
*
* MARK: Global Variables
*
* =========================================== */
var directToCreateBoard = false
/* ==========================================
*
* MARK: Default Methods
*
* =========================================== */
override func viewDidLoad() {
super.viewDidLoad()
// Set default values
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
if directToCreateBoard == true {
self.visibleViewController?.performSegue(withIdentifier: "createBoardSegue", sender: nil)
}
}
/* ==========================================
*
* MARK: Segue Methods
*
* =========================================== */
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? HomeScreenViewController {
destination.directToCreateBoard = true
}
}
}
| 24.982456 | 101 | 0.497893 |
7a78f8f8c105efe95e20e932a3b16b417d7af86f | 8,950 | // MIT License
//
// Copyright (c) 2018 Veldspar Team
//
// 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
// defines
public enum CryptoHashType {
case short10
case sha224
case sha256
case sha512
case md5
}
public var debug_on = false
public func debug(_ output: String) {
if debug_on {
print("[DEBUG] \(Date()) : \(output)")
}
}
public func consensusTime() -> UInt64 {
return UInt64(Date().timeIntervalSince1970 * 1000)
}
public extension Array where Element == UInt8 {
public func toHexSegmentString() -> String {
var values: [String] = []
for b in self as! [UInt8] {
values.append(b.toHex())
}
return values.joined(separator: "-")
}
}
extension String {
public func CryptoHash() -> String {
switch Config.DefaultHashType {
case .sha224:
return self.sha224()
case .sha256:
return self.sha256()
case .sha512:
return self.sha512()
case .md5:
return self.md5()
case .short10:
return self.sha224().prefix(10).lowercased()
}
}
}
extension UInt64 {
private func rawBytes() -> [UInt8] {
let totalBytes = MemoryLayout<UInt64>.size
var value = self
return withUnsafePointer(to: &value) { valuePtr in
return valuePtr.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { reboundPtr in
return Array(UnsafeBufferPointer(start: reboundPtr, count: totalBytes))
}
}
}
func toHex() -> String {
let byteArray = self.rawBytes().reversed()
return byteArray.map{String(format: "%02X", $0)}.joined()
}
}
extension UInt32 {
private func rawBytes() -> [UInt8] {
let totalBytes = MemoryLayout<UInt32>.size
var value = self
return withUnsafePointer(to: &value) { valuePtr in
return valuePtr.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { reboundPtr in
return Array(UnsafeBufferPointer(start: reboundPtr, count: totalBytes))
}
}
}
func toHex() -> String {
let byteArray = self.rawBytes().reversed()
return byteArray.map{String(format: "%02X", $0)}.joined()
}
}
extension UInt16 {
private func rawBytes() -> [UInt8] {
let totalBytes = MemoryLayout<UInt16>.size
var value = self
return withUnsafePointer(to: &value) { valuePtr in
return valuePtr.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { reboundPtr in
return Array(UnsafeBufferPointer(start: reboundPtr, count: totalBytes))
}
}
}
func toHex() -> String {
let byteArray = self.rawBytes().reversed()
return byteArray.map{String(format: "%02X", $0)}.joined()
}
}
extension UInt8 {
private func rawBytes() -> [UInt8] {
let totalBytes = MemoryLayout<UInt8>.size
var value = self
return withUnsafePointer(to: &value) { valuePtr in
return valuePtr.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { reboundPtr in
return Array(UnsafeBufferPointer(start: reboundPtr, count: totalBytes))
}
}
}
func toHex() -> String {
let byteArray = self.rawBytes().reversed()
return byteArray.map{String(format: "%02X", $0)}.joined()
}
}
struct Base58 {
static let base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
// Encode
static func base58FromBytes(_ bytes: [UInt8]) -> String {
var bytes = bytes
var zerosCount = 0
var length = 0
for b in bytes {
if b != 0 { break }
zerosCount += 1
}
bytes.removeFirst(zerosCount)
let size = bytes.count * 138 / 100 + 1
var base58: [UInt8] = Array(repeating: 0, count: size)
for b in bytes {
var carry = Int(b)
var i = 0
for j in 0...base58.count-1 where carry != 0 || i < length {
carry += 256 * Int(base58[base58.count - j - 1])
base58[base58.count - j - 1] = UInt8(carry % 58)
carry /= 58
i += 1
}
assert(carry == 0)
length = i
}
// skip leading zeros
var zerosToRemove = 0
var str = ""
for b in base58 {
if b != 0 { break }
zerosToRemove += 1
}
base58.removeFirst(zerosToRemove)
while 0 < zerosCount {
str = "\(str)1"
zerosCount -= 1
}
for b in base58 {
str = "\(str)\(base58Alphabet[String.Index(encodedOffset: Int(b))])"
}
return str
}
// Decode
static func bytesFromBase58(_ base58: String) -> [UInt8] {
// remove leading and trailing whitespaces
let string = base58.trimmingCharacters(in: CharacterSet.whitespaces)
guard !string.isEmpty else { return [] }
var zerosCount = 0
var length = 0
for c in string {
if c != "1" { break }
zerosCount += 1
}
let size = string.lengthOfBytes(using: String.Encoding.utf8) * 733 / 1000 + 1 - zerosCount
var base58: [UInt8] = Array(repeating: 0, count: size)
for c in string where c != " " {
// search for base58 character
guard let base58Index = base58Alphabet.index(of: c) else { return [] }
var carry = base58Index.encodedOffset
var i = 0
for j in 0...base58.count where carry != 0 || i < length {
carry += 58 * Int(base58[base58.count - j - 1])
base58[base58.count - j - 1] = UInt8(carry % 256)
carry /= 256
i += 1
}
assert(carry == 0)
length = i
}
// skip leading zeros
var zerosToRemove = 0
for b in base58 {
if b != 0 { break }
zerosToRemove += 1
}
base58.removeFirst(zerosToRemove)
var result: [UInt8] = Array(repeating: 0, count: zerosCount)
for b in base58 {
result.append(b)
}
return result
}
}
extension Array where Element == UInt8 {
public var base58EncodedString: String {
guard !self.isEmpty else { return "" }
return Base58.base58FromBytes(self)
}
public var base58CheckEncodedString: String {
var bytes = self
let checksum = [UInt8](bytes.sha256().sha256()[0..<4])
bytes.append(contentsOf: checksum)
return Base58.base58FromBytes(bytes)
}
}
extension String {
public var base58EncodedString: String {
return [UInt8](utf8).base58EncodedString
}
public var base58DecodedData: Data? {
let bytes = Base58.bytesFromBase58(self)
return Data(bytes)
}
public var base58CheckDecodedData: Data? {
guard let bytes = self.base58CheckDecodedBytes else { return nil }
return Data(bytes)
}
public var base58CheckDecodedBytes: [UInt8]? {
var bytes = Base58.bytesFromBase58(self)
guard 4 <= bytes.count else { return nil }
let checksum = [UInt8](bytes[bytes.count-4..<bytes.count])
bytes = [UInt8](bytes[0..<bytes.count-4])
let calculatedChecksum = [UInt8](bytes.sha256().sha256()[0...3])
if checksum != calculatedChecksum { return nil }
return bytes
}
}
| 30.033557 | 99 | 0.565587 |
147efcaf16ab347a1e4e2b88a79256546ad8e4ab | 193 | //
// MapHeaderData.swift
// Social-Reality
//
// Created by Nick Crews on 3/4/21.
//
import Foundation
import CoreLocation
struct MapHeaderData: Hashable {
let location: CLLocation
}
| 13.785714 | 36 | 0.709845 |
092af214ab368b14e40f50bc3810b160905490b3 | 1,412 | //
// TransformType.swift
// ObjectMapper
//
// Created by Syo Ikeda on 2/4/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// 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.
protocol TransformType {
associatedtype Object
associatedtype JSON
func transformFromJSON(_ value: Any?) -> Object?
func transformToJSON(_ value: Object?) -> JSON?
}
| 39.222222 | 81 | 0.742918 |
ddd3e18b4d461689506926b700936cce93c4c79f | 14,864 | //
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import SwiftDate
import XCTest
class TestDateInRegion_Components: XCTestCase {
func testDateInRegion_Components() {
let regionLondon = Region(calendar: Calendars.gregorian, zone: Zones.europeLondon, locale: Locales.italian)
let dateFormat = "yyyy-MM-dd HH:mm:ss"
// TEST #1: Date In Italian
let dateA = DateInRegion("2018-02-05 23:14:45", format: dateFormat, region: regionLondon)!
XCTValidateDateComponents(date: dateA, expec: ExpectedDateComponents {
$0.year = 2018
$0.month = 2
$0.day = 5
$0.hour = 23
$0.minute = 14
$0.second = 45
$0.monthNameDefault = "febbraio"
$0.monthNameDefaultStd = "febbraio"
$0.monthNameShort = "feb"
$0.monthNameStandaloneShort = "feb"
$0.msInDay = 83_686_000
$0.weekday = 2
$0.weekdayNameShort = "lun"
$0.weekdayNameVeryShort = "L"
$0.weekOfMonth = 2
$0.eraNameShort = "a.C."
$0.weekdayOrdinal = 1
$0.nearestHour = 23
$0.yearForWeekOfYear = 2018
$0.quarter = 1
})
// TEST #1: Date In French
let regionParis = Region(calendar: Calendars.gregorian, zone: Zones.europeParis, locale: Locales.french)
let dateB = DateInRegion("2018-02-05 23:14:45", format: dateFormat, region: regionParis)!
XCTValidateDateComponents(date: dateB, expec: ExpectedDateComponents {
$0.monthNameDefault = "février"
$0.monthNameShort = "févr."
$0.eraNameShort = "av. J.-C."
$0.weekdayNameDefault = "lundi"
})
// TEST #3: Other components
XCTAssert( (dateB.region == regionParis), "Failed to assign correct region to date")
XCTAssert( (dateB.calendar.identifier == regionParis.calendar.identifier), "Failed to assign correct region's calendar to date")
XCTAssert( (dateB.quarterName(.default) == "1er trimestre"), "Failed to get quarterName in default")
XCTAssert( (dateB.quarterName(.short) == "T1"), "Failed to get quarterName in short")
XCTAssert( (dateB.quarterName(.default, locale: Locales.italian) == "1º trimestre"), "Failed to get quarterName with overwrite of locale")
}
func testDateInRegion_isLeapMonth() {
let regionRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateA = DateInRegion("2018-02-05 00:00:00", format: dateFormat, region: regionRome)!
let dateB = DateInRegion("2016-02-22 00:00:00", format: dateFormat, region: regionRome)!
let dateC = DateInRegion("2017-12-10 00:00:00", format: dateFormat, region: regionRome)!
XCTAssert( dateA.isLeapMonth == false, "Failed to evaluate is date isLeapMonth == false")
XCTAssert( dateC.isLeapMonth == false, "Failed to evaluate is date isLeapMonth == false")
XCTAssert( dateB.isLeapMonth, "Failed to evaluate is date isLeapMonth")
}
func testDateInRegion_dateBySet() {
let originalDate = "2018-10-10T12:02:16.024".toISODate()
let newDate = originalDate?.dateBySet(hour: nil, min: nil, secs: nil, ms: 7)
XCTAssert( newDate?.toISO([.withInternetDateTimeExtended]) == "2018-10-10T12:02:16.007Z", "Failed to set milliseconds")
}
func testDateInRegion_isLeapYear() {
let regionRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateA = DateInRegion("2018-04-05 00:00:00", format: dateFormat, region: regionRome)!
let dateB = DateInRegion("2016-07-22 00:00:00", format: dateFormat, region: regionRome)!
let dateC = DateInRegion("2017-12-10 00:00:00", format: dateFormat, region: regionRome)!
XCTAssert( dateA.isLeapYear == false, "Failed to evaluate is date isLeapYear == false")
XCTAssert( dateC.isLeapYear == false, "Failed to evaluate is date isLeapYear == false")
XCTAssert( dateB.isLeapYear, "Failed to evaluate is date isLeapYear")
}
func testDateInRegion_julianDayAndModifiedJulianDay() {
// swiftlint:disable nesting
struct ExpectedJulian {
var dateISO: String
var julianDay: Double
var modifiedJulianDay: Double
}
let dates = [
ExpectedJulian(dateISO: "2017-12-22T00:06:18+01:00", julianDay: 2_458_109.462_708_333_5, modifiedJulianDay: 58108.962_708_333_51),
ExpectedJulian(dateISO: "2018-06-02T02:14:45+02:00", julianDay: 2_458_271.510_243_055_4, modifiedJulianDay: 58271.010_243_055_41),
ExpectedJulian(dateISO: "2018-04-04T13:31:12+02:00", julianDay: 2_458_212.98, modifiedJulianDay: 58212.479_999_999_98),
ExpectedJulian(dateISO: "2018-03-18T10:11:10+01:00", julianDay: 2_458_195.882_754_629_5, modifiedJulianDay: 58195.382_754_629_48),
ExpectedJulian(dateISO: "2018-03-10T18:03:22+01:00", julianDay: 2_458_188.210_671_296_3, modifiedJulianDay: 58187.710_671_296_34),
ExpectedJulian(dateISO: "2017-07-14T06:33:47+02:00", julianDay: 2_457_948.690_127_315, modifiedJulianDay: 57948.190_127_315),
ExpectedJulian(dateISO: "2018-02-14T16:51:14+01:00", julianDay: 2_458_164.160_578_703_5, modifiedJulianDay: 58163.660_578_703_51),
ExpectedJulian(dateISO: "2017-08-15T17:41:44+02:00", julianDay: 2_457_981.153_981_481_7, modifiedJulianDay: 57980.653_981_481_68),
ExpectedJulian(dateISO: "2018-03-04T09:54:54+01:00", julianDay: 2_458_181.871_458_333, modifiedJulianDay: 58181.371_458_332_986),
ExpectedJulian(dateISO: "2017-09-23T08:18:15+02:00", julianDay: 2_458_019.762_673_611, modifiedJulianDay: 58019.262_673_610_82),
ExpectedJulian(dateISO: "2017-12-10T10:29:42+01:00", julianDay: 2_458_097.895625, modifiedJulianDay: 58097.395_624_999_89),
ExpectedJulian(dateISO: "2017-11-11T02:49:41+01:00", julianDay: 2_458_068.576_168_981_4, modifiedJulianDay: 58068.076_168_981_38),
ExpectedJulian(dateISO: "2017-07-06T04:05:39+02:00", julianDay: 2_457_940.587_256_944_7, modifiedJulianDay: 57940.087_256_944_74),
ExpectedJulian(dateISO: "2017-12-02T00:23:52+01:00", julianDay: 2_458_089.474_907_407_5, modifiedJulianDay: 58088.974_907_407_54),
ExpectedJulian(dateISO: "2017-11-14T17:59:46+01:00", julianDay: 2_458_072.208_171_296_4, modifiedJulianDay: 58071.708_171_296_4),
ExpectedJulian(dateISO: "2018-03-02T10:53:52+01:00", julianDay: 2_458_179.912_407_407_5, modifiedJulianDay: 58179.412_407_407_54),
ExpectedJulian(dateISO: "2018-04-14T23:46:35+02:00", julianDay: 2_458_223.407_349_537, modifiedJulianDay: 58222.907_349_537_13),
ExpectedJulian(dateISO: "2018-04-28T07:25:22+02:00", julianDay: 2_458_236.725_949_074, modifiedJulianDay: 58236.225_949_074_14),
ExpectedJulian(dateISO: "2018-01-06T14:36:53+01:00", julianDay: 2_458_125.067_280_092_3, modifiedJulianDay: 58124.567_280_092_28),
ExpectedJulian(dateISO: "2017-09-24T19:58:19+02:00", julianDay: 2_458_021.248_831_019, modifiedJulianDay: 58020.748_831_018_806),
ExpectedJulian(dateISO: "2017-12-17T21:12:31+01:00", julianDay: 2_458_105.342_025_463, modifiedJulianDay: 58104.842_025_463_004),
ExpectedJulian(dateISO: "2018-05-04T02:28:42+02:00", julianDay: 2_458_242.519_930_555_5, modifiedJulianDay: 58242.019_930_555_485),
ExpectedJulian(dateISO: "2018-01-21T18:41:34+01:00", julianDay: 2_458_140.237_199_074, modifiedJulianDay: 58139.737_199_074_12),
ExpectedJulian(dateISO: "2018-04-05T02:36:54+02:00", julianDay: 2_458_213.525625, modifiedJulianDay: 58213.025_624_999_78),
ExpectedJulian(dateISO: "2018-02-07T13:35:16+01:00", julianDay: 2_458_157.024_490_741, modifiedJulianDay: 58156.524_490_741_08),
ExpectedJulian(dateISO: "2017-11-30T00:58:20+01:00", julianDay: 2_458_087.498_842_592_4, modifiedJulianDay: 58086.998_842_592_35),
ExpectedJulian(dateISO: "2018-04-10T07:10:34+02:00", julianDay: 2_458_218.715_671_296, modifiedJulianDay: 58218.215_671_296_23),
ExpectedJulian(dateISO: "2017-08-11T09:36:56+02:00", julianDay: 2_457_976.817_314_815, modifiedJulianDay: 57976.317_314_814_776),
ExpectedJulian(dateISO: "2018-04-28T12:30:18+02:00", julianDay: 2_458_236.937_708_333, modifiedJulianDay: 58236.437_708_333_135),
ExpectedJulian(dateISO: "2017-09-17T11:59:29+02:00", julianDay: 2_458_013.916_307_870_3, modifiedJulianDay: 58013.416_307_870_3)
]
dates.forEach {
let date = $0.dateISO.toISODate()!
guard date.julianDay == $0.julianDay else {
XCTFail("Failed to evaluate julianDay of '\($0.dateISO)'. Got '\(date.julianDay)', expected '\($0.julianDay)'")
return
}
guard date.modifiedJulianDay == $0.modifiedJulianDay else {
XCTFail("Failed to evaluate modifiedJulianDay of '\($0.dateISO)'. Got '\(date.modifiedJulianDay)', expected '\($0.modifiedJulianDay)'")
return
}
}
}
@available(iOS 9.0, macOS 10.11, *)
func test_ordinalDay() {
let newYork = Region(calendar: Calendars.gregorian, zone: Zones.americaNewYork, locale: Locales.englishUnitedStates)
let localDate = DateInRegion(components: {
$0.year = 2002
$0.month = 3
$0.day = 1
$0.hour = 5
$0.minute = 30
}, region: newYork)!
XCTAssert(localDate.ordinalDay == "1st", "Failed to get the correct value of the ordinalDay for a date")
let localDate2 = DateInRegion(components: {
$0.year = 2002
$0.month = 3
$0.day = 2
$0.hour = 5
$0.minute = 30
}, region: newYork)!
XCTAssert(localDate2.ordinalDay == "2nd", "Failed to get the correct value of the ordinalDay for a date")
let localDate3 = DateInRegion(components: {
$0.year = 2002
$0.month = 3
$0.day = 3
$0.hour = 5
$0.minute = 30
}, region: newYork)!
XCTAssert(localDate3.ordinalDay == "3rd", "Failed to get the correct value of the ordinalDay for a date")
let localDate4 = DateInRegion(components: {
$0.year = 2002
$0.month = 3
$0.day = 4
$0.hour = 5
$0.minute = 30
}, region: newYork)!
XCTAssert(localDate4.ordinalDay == "4th", "Failed to get the correct value of the ordinalDay for a date")
let regionRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let localDate5 = DateInRegion(components: {
$0.year = 2002
$0.month = 3
$0.day = 2
$0.hour = 5
$0.minute = 30
}, region: regionRome)!
XCTAssert(localDate5.ordinalDay == "2º", "Failed to get the correct value of the ordinalDay for a date")
}
func testDateInRegion_ISOFormatterAlt() {
let regionRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = DateInRegion("2017-07-22 00:00:00", format: dateFormat, region: regionRome)!
XCTAssert( date.toISO() == "2017-07-22T00:00:00+02:00", "Failed to format ISO")
XCTAssert( date.toISO([.withFullDate]) == "2017-07-22", "Failed to format ISO")
XCTAssert( date.toISO([.withFullDate, .withFullTime, .withDashSeparatorInDate, .withSpaceBetweenDateAndTime]) == "2017-07-22 00:00:00+02:00", "Failed to format ISO")
}
func testDateInRegion_getIntervalForComponentBetweenDates() {
let regionRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateA = DateInRegion("2017-07-22 00:00:00", format: dateFormat, region: regionRome)!
let dateB = DateInRegion("2017-07-23 12:00:00", format: dateFormat, region: regionRome)!
let dateC = DateInRegion("2017-09-23 12:00:00", format: dateFormat, region: regionRome)!
let dateD = DateInRegion("2017-09-23 12:54:00", format: dateFormat, region: regionRome)!
XCTAssert( (dateA.getInterval(toDate: dateB, component: .hour) == 36), "Failed to evaluate is hours interval")
XCTAssert( (dateA.getInterval(toDate: dateB, component: .day) == 2), "Failed to evaluate is days interval") // 1 days, 12 hours
XCTAssert( (dateB.getInterval(toDate: dateC, component: .month) == 2), "Failed to evaluate is months interval")
XCTAssert( (dateB.getInterval(toDate: dateC, component: .day) == 62), "Failed to evaluate is days interval")
XCTAssert( (dateB.getInterval(toDate: dateC, component: .year) == 0), "Failed to evaluate is years interval")
XCTAssert( (dateB.getInterval(toDate: dateC, component: .weekOfYear) == 9), "Failed to evaluate is weeksOfYear interval")
XCTAssert( (dateC.getInterval(toDate: dateD, component: .minute) == 54), "Failed to evaluate is minutes interval")
XCTAssert( (dateC.getInterval(toDate: dateD, component: .hour) == 0), "Failed to evaluate is hours interval")
XCTAssert( (dateA.getInterval(toDate: dateD, component: .minute) == 91494), "Failed to evaluate is minutes interval")
}
func testDateInRegion_timeIntervalSince() {
let regionRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let regionLondon = Region(calendar: Calendars.gregorian, zone: Zones.europeLondon, locale: Locales.english)
let dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateA = DateInRegion("2017-07-22 00:00:00", format: dateFormat, region: regionRome)!
let dateB = DateInRegion("2017-07-22 00:00:00", format: dateFormat, region: regionRome)!
let dateC = DateInRegion("2017-07-23 13:20:15", format: dateFormat, region: regionLondon)!
let dateD = DateInRegion("2017-07-23 13:20:20", format: dateFormat, region: regionLondon)!
XCTAssert( dateA.timeIntervalSince(dateC) == -138015.0, "Failed to evaluate is minutes interval")
XCTAssert( dateA.timeIntervalSince(dateB) == 0, "Failed to evaluate is minutes interval")
XCTAssert( dateC.timeIntervalSince(dateD) == -5, "Failed to evaluate is minutes interval")
}
func testQuarter() {
let regionLondon = Region(calendar: Calendars.gregorian, zone: Zones.europeLondon, locale: Locales.english)
let dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateA = DateInRegion("2018-02-05 23:14:45", format: dateFormat, region: regionLondon)!
let dateB = DateInRegion("2018-09-05 23:14:45", format: dateFormat, region: regionLondon)!
let dateC = DateInRegion("2018-12-05 23:14:45", format: dateFormat, region: regionLondon)!
XCTAssert( dateA.quarter == 1, "Failed to evaluate quarter property")
XCTAssert( dateB.quarter == 3, "Failed to evaluate quarter property")
XCTAssert( dateC.quarter == 4, "Failed to evaluate quarter property")
}
func testAbsoluteDateISOFormatting() {
let now = DateInRegion()
let iso8601_string = now.toISO([.withInternetDateTime])
let absoluteDate = now.date
let absoluteDate_iso8601_string = absoluteDate.toISO([.withInternetDateTime])
XCTAssert( absoluteDate_iso8601_string == iso8601_string, "Failed respect the absolute ISO date")
}
func testComparingTimeUnitsWithDateComponents() {
SwiftDate.defaultRegion = .local
let now = Date()
XCTAssert((now.addingTimeInterval(3600) - now).in(.hour) == 1, "Failed to compare date")
XCTAssert((now.addingTimeInterval(3600) - now) == 1.hours, "Failed to compare date")
}
}
| 53.66065 | 167 | 0.735468 |
4bfdabfeea67d583b9cae819479f4a81c2b7b4ac | 2,810 | //
// HMFindViewController.swift
// HMEmergency
//
// Created by 齐浩铭 on 2021/9/27.
//
import UIKit
import Reusable
import AEAlertView
class HMFindViewController: UIViewController {
lazy var CardsData:[UIImage?] = {
return [UIImage(named: "健康救助站"),UIImage(named: "救助者计划")]
}()
private let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
collectionView.register(cellType: HMFindCollectionViewCell.self)
collectionView.backgroundColor = UIColor.clear
return collectionView
}()
init() {
super.init(nibName: nil, bundle: nil)
view.backgroundColor = shareColor.greenWrite
self.title = "发现"
collectionView.delegate = self
collectionView.dataSource = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarItem.image = UIImage(named: "发现")
setUI()
}
func setUI() {
self.view.addSubview(collectionView)
collectionView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview()
}
}
}
extension HMFindViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return CardsData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: HMFindCollectionViewCell.self)
cell.load(image: CardsData[indexPath.row]!)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: HMwidth-20, height: 190)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
self.navigationController?.pushViewController(HMHealthStationVC(), animated: true)
AEAlertView.show(title: "提示", actions: ["确定"], message: "本界面由政府或民间组织提供服务", handler: nil)
case 1:
self.navigationController?.pushViewController(HMHelperPlanVC(), animated: true)
default:
print("index:\(indexPath.row)")
}
}
}
let HMwidth = UIScreen.main.bounds.width
let HMheight = UIScreen.main.bounds.height
| 34.268293 | 160 | 0.680783 |
5690b7b33f327c216320de90df19f9fccdbb58ed | 8,832 | //
// Data+Gzip.swift
//
/*
The MIT License (MIT)
© 2014-2017 1024jp <wolfrosch.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
import zlib
/**
Compression level whose rawValue is based on the zlib's constants.
*/
public struct CompressionLevel: RawRepresentable {
/// Compression level in the range of `0` (no compression) to `9` (maximum compression).
public let rawValue: Int32
public static let noCompression = CompressionLevel(Z_NO_COMPRESSION)
public static let bestSpeed = CompressionLevel(Z_BEST_SPEED)
public static let bestCompression = CompressionLevel(Z_BEST_COMPRESSION)
public static let defaultCompression = CompressionLevel(Z_DEFAULT_COMPRESSION)
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public init(_ rawValue: Int32) {
self.rawValue = rawValue
}
}
/**
Errors on gzipping/gunzipping based on the zlib error codes.
*/
public struct GzipError: Swift.Error {
// cf. http://www.zlib.net/manual.html
public enum Kind {
/**
The stream structure was inconsistent.
- underlying zlib error: `Z_STREAM_ERROR` (-2)
*/
case stream
/**
The input data was corrupted (input stream not conforming to the zlib format or incorrect check value).
- underlying zlib error: `Z_DATA_ERROR` (-3)
*/
case data
/**
There was not enough memory.
- underlying zlib error: `Z_MEM_ERROR` (-4)
*/
case memory
/**
No progress is possible or there was not enough room in the output buffer.
- underlying zlib error: `Z_BUF_ERROR` (-5)
*/
case buffer
/**
The zlib library version is incompatible with the version assumed by the caller.
- underlying zlib error: `Z_VERSION_ERROR` (-6)
*/
case version
/**
An unknown error occurred.
- parameter code: return error by zlib
*/
case unknown(code: Int)
}
/// Error kind.
public let kind: Kind
/// Returned message by zlib.
public let message: String
internal init(code: Int32, msg: UnsafePointer<CChar>?) {
self.message = {
guard let msg = msg, let message = String(validatingUTF8: msg) else {
return "Unknown gzip error"
}
return message
}()
self.kind = {
switch code {
case Z_STREAM_ERROR:
return .stream
case Z_DATA_ERROR:
return .data
case Z_MEM_ERROR:
return .memory
case Z_BUF_ERROR:
return .buffer
case Z_VERSION_ERROR:
return .version
default:
return .unknown(code: Int(code))
}
}()
}
public var localizedDescription: String {
return self.message
}
}
extension Data {
/**
Whether the data is compressed in gzip format.
*/
public var isGzipped: Bool {
return self.starts(with: [0x1f, 0x8b]) // check magic number
}
/**
Create a new `Data` object by compressing the receiver using zlib.
Throws an error if compression failed.
- parameters:
- level: Compression level.
- throws: `GzipError`
- returns: Gzip-compressed `Data` object.
*/
public func gzipped(level: CompressionLevel = .defaultCompression) throws -> Data {
guard !self.isEmpty else {
return Data()
}
var stream = self.createZStream()
var status: Int32
status = deflateInit2_(&stream, level.rawValue, Z_DEFLATED, MAX_WBITS + 16, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, Int32(DataSize.stream))
guard status == Z_OK else {
// deflateInit2 returns:
// Z_VERSION_ERROR The zlib library version is incompatible with the version assumed by the caller.
// Z_MEM_ERROR There was not enough memory.
// Z_STREAM_ERROR A parameter is invalid.
throw GzipError(code: status, msg: stream.msg)
}
var data = Data(capacity: DataSize.chunk)
while stream.avail_out == 0 {
if Int(stream.total_out) >= data.count {
data.count += DataSize.chunk
}
data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<Bytef>) in
stream.next_out = bytes.advanced(by: Int(stream.total_out))
}
stream.avail_out = uInt(data.count) - uInt(stream.total_out)
deflate(&stream, Z_FINISH)
}
deflateEnd(&stream)
data.count = Int(stream.total_out)
return data
}
/**
Create a new `Data` object by decompressing the receiver using zlib.
Throws an error if decompression failed.
- throws: `GzipError`
- returns: Gzip-decompressed `Data` object.
*/
public func gunzipped() throws -> Data {
guard !self.isEmpty else {
return Data()
}
var stream = self.createZStream()
var status: Int32
status = inflateInit2_(&stream, MAX_WBITS + 32, ZLIB_VERSION, Int32(DataSize.stream))
guard status == Z_OK else {
// inflateInit2 returns:
// Z_VERSION_ERROR The zlib library version is incompatible with the version assumed by the caller.
// Z_MEM_ERROR There was not enough memory.
// Z_STREAM_ERROR A parameters are invalid.
throw GzipError(code: status, msg: stream.msg)
}
var data = Data(capacity: self.count * 2)
repeat {
if Int(stream.total_out) >= data.count {
data.count += self.count / 2
}
data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<Bytef>) in
stream.next_out = bytes.advanced(by: Int(stream.total_out))
}
stream.avail_out = uInt(data.count) - uInt(stream.total_out)
status = inflate(&stream, Z_SYNC_FLUSH)
} while status == Z_OK
guard inflateEnd(&stream) == Z_OK && status == Z_STREAM_END else {
// inflate returns:
// Z_DATA_ERROR The input data was corrupted (input stream not conforming to the zlib format or incorrect check value).
// Z_STREAM_ERROR The stream structure was inconsistent (for example if next_in or next_out was NULL).
// Z_MEM_ERROR There was not enough memory.
// Z_BUF_ERROR No progress is possible or there was not enough room in the output buffer when Z_FINISH is used.
throw GzipError(code: status, msg: stream.msg)
}
data.count = Int(stream.total_out)
return data
}
private func createZStream() -> z_stream {
var stream = z_stream()
self.withUnsafeBytes { (bytes: UnsafePointer<Bytef>) in
stream.next_in = UnsafeMutablePointer<Bytef>(mutating: bytes)
}
stream.avail_in = uint(self.count)
return stream
}
}
private struct DataSize {
static let chunk = 2 ^ 14
static let stream = MemoryLayout<z_stream>.size
private init() { }
}
| 29.737374 | 156 | 0.583107 |
e4fccbda1a11d074712dc43f5c8e4d5ea48268dc | 3,784 | //
// File.swift
//
//
// Created by Daniel Eden on 26/03/2022.
//
import Foundation
extension Twift {
/// Allows you to get an authenticated user's 800 most recent bookmarked Tweets.
///
/// Equivalent to `GET /2/users/:id/bookmarks`
/// - Parameters:
/// - userId: User ID of an authenticated user to request bookmarked Tweets for.
/// - fields: Any additional fields to include on returned objects
/// - expansions: Objects and their corresponding fields that should be expanded in the `includes` property
/// - paginationToken: When iterating over pages of results, you can pass in the `nextToken` from the previously-returned value to get the next page of results
/// - maxResults: The maximum number of results to fetch.
/// - Returns: A Twitter API response object containing an array of ``Tweet`` structs representing the authenticated user's bookmarked Tweets
public func getBookmarks(for userId: User.ID,
fields: Set<Tweet.Field> = [],
expansions: [Tweet.Expansions] = [],
paginationToken: String? = nil,
maxResults: Int = 10
) async throws -> TwitterAPIDataIncludesAndMeta<[Tweet], Tweet.Includes, Meta> {
var queryItems = [URLQueryItem(name: "max_results", value: "\(maxResults)")]
if let paginationToken = paginationToken { queryItems.append(URLQueryItem(name: "pagination_token", value: paginationToken)) }
let fieldsAndExpansions = fieldsAndExpansions(for: Tweet.self, fields: fields, expansions: expansions)
return try await call(route: .bookmarks(userId),
queryItems: queryItems + fieldsAndExpansions,
expectedReturnType: TwitterAPIDataIncludesAndMeta.self)
}
/// Causes the user ID of an authenticated user identified in the path parameter to Bookmark the target Tweet
///
/// Equivalent to `POST /2/users/:id/bookmarks`
/// - Parameters:
/// - tweetId: The ID of the Tweet that you would like the `userId` to Bookmark.
/// - userId: The user ID who you are liking a Tweet on behalf of. It must match your own user ID or that of an authenticating user.
/// - Returns: A response object containing a ``BookmarkResponse``
public func addBookmark(_ tweetId: Tweet.ID, userId: User.ID) async throws -> TwitterAPIData<BookmarkResponse> {
let body = ["tweet_id": tweetId]
let encodedBody = try JSONSerialization.data(withJSONObject: body, options: [])
return try await call(route: .bookmarks(userId),
method: .POST,
body: encodedBody,
expectedReturnType: TwitterAPIData.self)
}
/// Allows a user or authenticated user ID to remove a Bookmark of a Tweet.
///
/// Equivalent to `DELETE /2/users/:user_id/bookmarks/:tweet_id`
/// - Parameters:
/// - tweetId: The ID of the Tweet that you would like the `userId` to unlike.
/// - userId: The user ID who you are removing Like of a Tweet on behalf of. It must match your own user ID or that of an authenticating user.
/// - Returns: A response object containing a ``BookmarkResponse``
public func deleteBookmark(_ tweetId: Tweet.ID, userId: User.ID) async throws -> TwitterAPIData<BookmarkResponse> {
return try await call(route: .deleteBookmark(userId: userId, tweetId: tweetId),
method: .DELETE,
expectedReturnType: TwitterAPIData.self)
}
}
/// A response object containing information relating to Bookmark-related API requests
public struct BookmarkResponse: Codable {
/// Indicates whether the user bookmarked the specified Tweet as a result of this request.
public let bookmarked: Bool
}
| 51.835616 | 163 | 0.671247 |
2f21b73678875f7ea386f65cb4c97b6d8aa427d9 | 1,479 | // JWT+Header.swift
//
// Copyright (c) 2020 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if WEB_AUTH_PLATFORM
import Foundation
import JWTDecode
extension JWT {
var algorithm: JWTAlgorithm? {
guard let alg = header["alg"] as? String, let algorithm = JWTAlgorithm(rawValue: alg) else { return nil }
return algorithm
}
var kid: String? {
return header["kid"] as? String
}
}
#endif
| 38.921053 | 113 | 0.735632 |
fedc2fbbca074c2a3ca0d5cbeb7b77841315ac5d | 9,550 | // Created by Ostap Marchenko on 7/30/21.
import UIKit
import EventKit
import EventKitUI
private extension EventModel {
init(_ event: EKEvent) {
self.init(start: event.startDate, end: event.endDate, title: event.title, id: event.eventIdentifier, description: event.notes, url: nil)
}
}
class NativeEventManager: NSObject {
private enum Constants {
enum Error {
static let unknownError: String = "\n\n=== unknown error === \n\n"
static let predicateError: String = "\n\n=== Events list predicate error === \n\n"
static let notValidEvent: String = "\n\n=== Event not valid... === \n\n"
static let eventAlredyExist: String = "\n\n=== Event already exist === \n\n"
}
}
// MARK: Completions
var onEditingEnd: EventsManagerEmptyCompletion?
private lazy var eventStore: EKEventStore = {
EKEventStore()
}()
private var authorizationStatus: EKAuthorizationStatus {
EKEventStore.authorizationStatus(for: EKEntityType.event)
}
// MARK: Public(Methods)
public func addEvent(
_ event: EventAddMethod,
onSuccess: @escaping EventsManagerEmptyCompletion,
onError: EventsManagerError?) {
requestAuthorization(onSuccess: { [weak self] in
switch event {
case .easy(let event):
self?.generateAndAddEvent(event, onSuccess: onSuccess, onError: onError)
case .fromModal(let event):
self?.presentEventCalendarDetailModal(event: event)
}
},
onError: { error in
onError?(error)
}
)
}
public func getAllEvents(
from startDate: Date,
to endDate: Date,
onSuccess: @escaping EventsManagerEventsCompletion,
onError: @escaping EventsManagerError
) {
requestAuthorization(onSuccess: { [weak self] in
guard let predicate = self?.eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: nil) else {
onError(.message(Constants.Error.predicateError))
return
}
let events = self?.eventStore.events(matching: predicate) ?? []
let mapped = events.map({ EventModel( $0 ) })
onSuccess(mapped)
},
onError: { error in
onError(error)
}
)
}
public func eventExists(
_ newEvent: EventModel,
statusCompletion: @escaping (Bool) -> Void,
onError: @escaping EventsManagerError
) {
requestAuthorization(onSuccess: { [weak self] in
self?.getAllEvents(
from: newEvent.startDate,
to: newEvent.endDate,
onSuccess: { events in
let eventContains = events.contains { event in
(event.title == newEvent.title
&& event.startDate == newEvent.startDate
&& event.endDate == newEvent.endDate)
/// event can be edited by user so need to check ID also
|| event.id == newEvent.id
}
statusCompletion(eventContains)
},
onError: onError
)
},
onError: { error in
onError(error)
}
)
}
//MARK: - Authorization
public func requestAuthorization(
onSuccess: @escaping EventsManagerEmptyCompletion,
onError: @escaping EventsManagerError
) {
switch authorizationStatus {
case .authorized:
onSuccess()
case .notDetermined:
//Request access to the calendar
requestAccess { (accessGranted, error) in
if let error = error {
onError(.error(error))
}
else {
if accessGranted {
onSuccess()
} else {
onError(.accessStatus(accessGranted))
}
}
}
case .denied,
.restricted:
onError(.authorizationStatus(authorizationStatus))
@unknown default:
onError(.message(Constants.Error.unknownError))
}
}
// MARK: Private(Methods)
private func removeEvent(
onSuccess: @escaping EventsManagerEmptyCompletion,
onError: @escaping EventsManagerError
) {
requestAuthorization(onSuccess: {
},
onError: { error in
onError(error)
}
)
}
private func requestAccess(completion: @escaping EKEventStoreRequestAccessCompletionHandler) {
DispatchQueue.main.async { [weak self] in
self?.eventStore.requestAccess(to: EKEntityType.event) { (accessGranted, error) in
completion(accessGranted, error)
}
}
}
// Generate an event which will be then added to the calendar
private func generateEvent(event: EventModel) -> EKEvent {
let eventTitle: String? = event.title.isHtml() ? event.title.attributedText()?.string : event.title
let eventDescription: String? = event.description?.isHtml() ?? false ? event.description?.attributedText()?.string : event.description
let newEvent = EKEvent(eventStore: eventStore)
var startDate = event.startDate
var endDate = event.endDate
/// check is timeZone in summer/winter period
let timeZone = NSTimeZone.local
let currentTimeIsSummer = timeZone.isDaylightSavingTime(for: Date())
let startInSummerTime = timeZone.isDaylightSavingTime(for: startDate)
let endInSummerTime = timeZone.isDaylightSavingTime(for: endDate)
/// without this validation, you will get issue in calendar when event startTime in summer time zone and endTime in winter
if !currentTimeIsSummer {
if startInSummerTime {
startDate = startDate.adding(minutes: -1 * 60)
}
if endInSummerTime {
endDate = endDate.adding(minutes: -1 * 60)
}
}
else {
if !startInSummerTime {
startDate = startDate.adding(minutes: 1 * 60)
}
if !endInSummerTime {
endDate = endDate.adding(minutes: 1 * 60)
}
}
newEvent.title = eventTitle
newEvent.notes = eventDescription ?? ""
newEvent.startDate = startDate
newEvent.endDate = endDate
newEvent.calendar = eventStore.defaultCalendarForNewEvents
return newEvent
}
// Try to save an event to the calendar
private func generateAndAddEvent(
_ event: EventModel?,
onSuccess: @escaping EventsManagerEmptyCompletion,
onError: EventsManagerError?) {
guard let event = event else {
onError?(.message(Constants.Error.notValidEvent))
return
}
eventExists(event, statusCompletion: { [weak self] status in
if status {
do {
guard let self = self else {
onError?(.message("\n\n self == nil \n\n"))
return
}
let eventToAdd = self.generateEvent(event: event)
try self.eventStore.save(eventToAdd, span: .thisEvent)
onSuccess()
} catch let error as NSError {
onError?(.error(error))
}
}
else {
onError?(.message(Constants.Error.eventAlredyExist))
}
},
onError: { error in
onError?(error)
}
)
}
// Present edit event calendar modal
private func presentEventCalendarDetailModal(event: EventModel?) {
let eventModalController = EKEventEditViewController()
eventModalController.editViewDelegate = self
eventModalController.eventStore = eventStore
if let event = event {
let event = generateEvent(event: event)
eventModalController.event = event
}
if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
rootVC.present(eventModalController, animated: true, completion: nil)
}
}
}
// EKEventEditViewDelegate
extension NativeEventManager: EKEventEditViewDelegate {
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
controller.dismiss(animated: true, completion: onEditingEnd)
}
}
// MARK: Private extensions
private extension String {
func isHtml() -> Bool {
let validateTest = NSPredicate(format:"SELF MATCHES %@", "<[a-z][\\s\\S]*>")
return validateTest.evaluate(with: self)
}
func attributedText() -> NSAttributedString? {
if self.isHtml() {
let data = Data(self.utf8)
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
return attributedString
}
}
return nil
}
}
private extension Date {
func adding(minutes: Int) -> Date {
return Calendar.current.date(byAdding: .minute, value: minutes, to: self) ?? self
}
}
| 30.906149 | 164 | 0.572984 |
67a29b59b2917988a38424c51b71455f5ffd5728 | 6,310 | //
// Lock.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 4/9/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin.C
#elseif os(Linux)
import Glibc
#endif
#if os(Linux) || XcodeLinux
public protocol Locking {
func lock()
func unlock()
}
public final class Lock: Locking {
private var mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
public init() {
pthread_mutex_init(mutex, nil)
}
deinit {
pthread_mutex_destroy(mutex)
mutex.deinitialize()
mutex.deallocate(capacity: 1)
}
public func lock() {
pthread_mutex_lock(mutex)
}
public func unlock() {
pthread_mutex_unlock(mutex)
}
public func tryLock() -> Bool {
return pthread_mutex_trylock(mutex) == 0
}
public var name: String?
}
extension Lock {
private func synchronized<T>(_ closure: () -> T) -> T {
self.lock()
defer { self.unlock() }
return closure()
}
}
public final class ConditionLock: Locking {
private var _cond = Condition()
private var _value: Int
private var _thread: pthread_t?
public init(condition: Int = 0) {
_value = condition
}
public func lock() {
let _ = lockBeforeDate(Date.distantFuture)
}
public func unlock() {
_cond.lock()
_thread = nil
_cond.broadcast()
_cond.unlock()
}
public var condition: Int {
return _value
}
public func lockWhenCondition(_ condition: Int) {
let _ = lockWhenCondition(condition, beforeDate: Date.distantFuture)
}
public func tryLock() -> Bool {
return lockBeforeDate(Date.distantPast)
}
public func tryLockWhenCondition(_ condition: Int) -> Bool {
return lockWhenCondition(condition, beforeDate: Date.distantPast)
}
public func unlockWithCondition(_ condition: Int) {
_cond.lock()
_thread = nil
_value = condition
_cond.broadcast()
_cond.unlock()
}
public func lockBeforeDate(_ limit: Date) -> Bool {
_cond.lock()
while _thread == nil {
if !_cond.waitUntilDate(limit) {
_cond.unlock()
return false
}
}
_thread = pthread_self()
_cond.unlock()
return true
}
public func lockWhenCondition(_ condition: Int, beforeDate limit: Date) -> Bool {
_cond.lock()
while _thread != nil || _value != condition {
if !_cond.waitUntilDate(limit) {
_cond.unlock()
return false
}
}
_thread = pthread_self()
_cond.unlock()
return true
}
public var name: String?
}
public final class RecursiveLock: Locking {
private var mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
public init() {
var attrib = pthread_mutexattr_t()
withUnsafeMutablePointer(to: &attrib) { attrs in
pthread_mutexattr_settype(attrs, Int32(PTHREAD_MUTEX_RECURSIVE))
pthread_mutex_init(mutex, attrs)
}
}
deinit {
pthread_mutex_destroy(mutex)
mutex.deinitialize()
mutex.deallocate(capacity: 1)
}
public func lock() {
pthread_mutex_lock(mutex)
}
public func unlock() {
pthread_mutex_unlock(mutex)
}
public func tryLock() -> Bool {
return pthread_mutex_trylock(mutex) == 0
}
public var name: String?
}
public final class Condition: Locking {
private var mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
private var cond = UnsafeMutablePointer<pthread_cond_t>.allocate(capacity: 1)
public init() {
pthread_mutex_init(mutex, nil)
pthread_cond_init(cond, nil)
}
deinit {
pthread_mutex_destroy(mutex)
pthread_cond_destroy(cond)
mutex.deinitialize()
cond.deinitialize()
mutex.deallocate(capacity: 1)
cond.deallocate(capacity: 1)
}
public func lock() {
pthread_mutex_lock(mutex)
}
public func unlock() {
pthread_mutex_unlock(mutex)
}
public func wait() {
pthread_cond_wait(cond, mutex)
}
public func waitUntilDate(_ limit: Date) -> Bool {
let lim = limit.timeIntervalSinceReferenceDate
let ti = lim - Date.timeIntervalSinceReferenceDate
if ti < 0.0 {
return false
}
var ts = timespec()
ts.tv_sec = Int(floor(ti))
ts.tv_nsec = Int((ti - Double(ts.tv_sec)) * 1000000000.0)
var tv = timeval()
withUnsafeMutablePointer(to: &tv) { t in
gettimeofday(t, nil)
ts.tv_sec += t.pointee.tv_sec
ts.tv_nsec += Int((t.pointee.tv_usec * 1000000) / 1000000000)
}
let retVal: Int32 = withUnsafePointer(to: &ts) { t in
return pthread_cond_timedwait(cond, mutex, t)
}
return retVal == 0
}
public func signal() {
pthread_cond_signal(cond)
}
public func broadcast() {
pthread_cond_broadcast(cond)
}
public var name: String?
}
#endif
| 27.434783 | 89 | 0.500634 |
f85ea96dbf038be303ec2e02e2b2a06ce3744be2 | 1,715 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
extension DispatchQueue {
/// Schedules a work item for immediate execution and immediately returns with an `EventLoopFuture` providing the
/// result. For example:
///
/// let futureResult = DispatchQueue.main.asyncWithFuture(eventLoop: myEventLoop) { () -> String in
/// callbackMayBlock()
/// }
/// try let value = futureResult.wait()
///
/// - parameters:
/// - eventLoop: the `EventLoop` on which to processes the IO / task specified by `callbackMayBlock`.
/// - callbackMayBlock: The scheduled callback for the IO / task.
/// - returns a new `EventLoopFuture<ReturnType>` with value returned by the `block` parameter.
@inlinable
public func asyncWithFuture<NewValue>(
eventLoop: EventLoop,
_ callbackMayBlock: @escaping () throws -> NewValue
) -> EventLoopFuture<NewValue> {
let promise = eventLoop.makePromise(of: NewValue.self)
self.async {
do {
let result = try callbackMayBlock()
promise.succeed(result)
} catch {
promise.fail(error)
}
}
return promise.futureResult
}
}
| 35.729167 | 117 | 0.573178 |
909323847a38a48259c1af6a7b73e0c56ab06e10 | 2,063 | /// 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 Combine
public class MainViewModel: SignedInResponder, NotSignedInResponder {
// MARK: - Properties
@Published public private(set) var view: MainView = .launching
// MARK: - Methods
public init() {}
public func notSignedIn() {
view = .onboarding
}
public func signedIn(to userSession: UserSession) {
view = .signedIn(userSession: userSession)
}
}
| 42.979167 | 83 | 0.748909 |
339ffb0e380b903d7f58bf7f935fdac4e6badeff | 2,899 | import Foundation
extension ReceiveAddress {
enum Configurator {
static func configure(
viewController: ViewController,
viewConfig: ReceiveAddress.Model.ViewConfig,
sceneModel: ReceiveAddress.Model.SceneModel,
addressManager: AddressManagerProtocol,
shareUtil: ShareUtilProtocol,
qrCodeGenerator: ReceiveAddressSceneQRCodeGeneratorProtocol,
invoiceFormatter: InvoiceFormatterProtocol,
routing: Routing?
) {
let presenterDispatch = PresenterDispatch(displayLogic: viewController)
let presenter = Presenter(
presenterDispatch: presenterDispatch,
qrCodeGenerator: qrCodeGenerator,
invoiceFormatter: invoiceFormatter
)
let interactor = Interactor(
presenter: presenter,
shareUtil: shareUtil,
addressManager: addressManager
)
let interactorDispatch = InteractorDispatch(businessLogic: interactor)
viewController.inject(interactorDispatch: interactorDispatch, routing: routing)
viewController.viewConfig = viewConfig
}
}
}
extension ReceiveAddress {
class InteractorDispatch {
private let queue: DispatchQueue = DispatchQueue(
label: "\(NSStringFromClass(InteractorDispatch.self))\(BusinessLogic.self)".queueLabel,
qos: .userInteractive
)
private let businessLogic: BusinessLogic
init(businessLogic: BusinessLogic) {
self.businessLogic = businessLogic
}
func sendRequest(requestBlock: @escaping (_ businessLogic: BusinessLogic) -> Void) {
self.queue.async {
requestBlock(self.businessLogic)
}
}
func sendSyncRequest<ReturnType: Any>(
requestBlock: @escaping (_ businessLogic: BusinessLogic) -> ReturnType
) -> ReturnType {
return requestBlock(self.businessLogic)
}
}
class PresenterDispatch {
private weak var displayLogic: DisplayLogic?
init(displayLogic: DisplayLogic) {
self.displayLogic = displayLogic
}
func display(displayBlock: @escaping (_ displayLogic: DisplayLogic) -> Void) {
guard let displayLogic = self.displayLogic else { return }
DispatchQueue.main.async {
displayBlock(displayLogic)
}
}
func displaySync(displayBlock: @escaping (_ displayLogic: DisplayLogic) -> Void) {
guard let displayLogic = self.displayLogic else { return }
displayBlock(displayLogic)
}
}
}
| 33.321839 | 99 | 0.587444 |
abf8825373a77ce7f53c64b41c3f3320f513fbfb | 2,688 | //
// ViewController.swift
// SwiftTipping
//
// Created by Will Johansson on 2015-04-13.
// Copyright (c) 2015 Will Johansson. All rights reserved.
//
import UIKit
class CalculatorViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var billAmount: UITextField!
@IBOutlet weak var tipAmount: UILabel!
@IBOutlet weak var totalAmount: UILabel!
@IBOutlet weak var tipPercentage: UILabel!
@IBOutlet weak var percentageSlider: UISlider!
var billAmt: Float = 100.0
var tipPct: Float = 20.0
var tip: Float = 20.0
var total: Float = 120.0
let defaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
billAmount.delegate = self
tipPct = defaults.floatForKey("default_percentage")
percentageSlider.value = tipPct
updateFields()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTipPercentageChanged(sender: UISlider) {
tipPct = round(sender.value)
updateFields()
}
@IBAction func onBillAmountChanged(sender: UITextField) {
let text = (sender.text as NSString)
billAmt = (text.substringFromIndex(1) as NSString).floatValue
updateFields()
}
func updateFields() {
tip = billAmt * (tipPct / 100)
total = billAmt + tip
tipAmount.text = String(format: "$%.2f", tip)
totalAmount.text = String(format: "$%.2f", total)
tipPercentage.text = String(format: "%.0f%%", tipPct)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text as NSString)
// don't delete the $
if (text.length == 1 && string == "") { return false }
// don't add another decimal
if (text.containsString(".") && string == ".") { return false }
// don't blow up
if (string != "" && text.length >= 1 && text.length <= 2) { return true }
// don't add more than 2 decimal places
if (string != "" && text.substringFromIndex(text.length - 3).hasPrefix(".")) { return false }
return true
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
@IBAction func onSwipe(sender: AnyObject) {
// go to settings
performSegueWithIdentifier("firstSegue", sender: self)
}
}
| 30.202247 | 132 | 0.620908 |
e612a1f5073823d44555027b099900f4b59ee508 | 2,300 | //
// CameraRollVC.swift
// Zimcher
//
// Created by Weiyu Huang on 1/9/16.
// Copyright © 2016 Zimcher. All rights reserved.
//
import UIKit
import Photos
class CameraRollVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, PHPhotoLibraryChangeObserver {
@IBOutlet weak var downButton: UIButton!
@IBOutlet weak var collectionView: UICollectionView!
private var cellSize:CGSize {
return (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize
}
var fetchResult: PHFetchResult!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: options)
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fetchResult.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("photoCell", forIndexPath: indexPath) as! PreviewCell
let asset = fetchResult.objectAtIndex(indexPath.row) as! PHAsset
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: cellSize, contentMode: .AspectFill, options: nil) { image, _ in
cell.previewImage.image = image
}
return cell
}
func photoLibraryDidChange(changeInstance: PHChange) {
let fetchResultArray = fetchResult.copy() as! [PHFetchResult]
let changes = fetchResultArray
.map(changeInstance.changeDetailsForFetchResult)
let x = zip(fetchResultArray, changes)
.map { $0.1 == nil ? $0.0 : $0.1!.fetchResultAfterChanges }
fetchResult = x as! PHFetchResult
collectionView.reloadData()
}
} | 33.333333 | 143 | 0.677391 |
d690aea5b7b1e019ce24b82280c5ecef389a948b | 6,601 | //
// CharacterImageController.swift
// Marvel Characters
//
// Created by Daniel Illescas Romero on 20/11/20.
//
import Foundation
import UIKit
import Combine
class CharacterImagesController {
private var imagesIndexPath: [IndexPath: UIImage] = [:]
private var cachedImageForThumbnailURL: [String: UIImage] = [:]
private let charactersRepository: MarvelCharactersRepository = MarvelCharactersRepositoryImplementation()
private var cancellables: [IndexPath: AnyCancellable] = [:]
private var otherCancellables: [AnyCancellable] = []
private var downloadedImagesIndexStream = PassthroughSubject<Int, Never>()
private var downloadedImagesIndexPathStream = PassthroughSubject<IndexPath, Never>()
private let queue = DispatchQueue(label: "Images controller")
private let locker = NSLock()
let imagesSize: CoreGraphics.CGFloat
init(imagesSize: CoreGraphics.CGFloat) {
self.imagesSize = imagesSize
}
func downloadImage(_ thumbnailURL: String, withCommonPath path: String, forIndexPath indexPath: IndexPath) {
queue.async {
if self.imagesIndexPath[indexPath] == self.defaultAssetImage {
self.cancellables.removeValue(forKey: indexPath)
}
if self.cancellables.keys.contains(indexPath) {
return
}
if let cachedImage = self.imageFor(thumbnailURL: thumbnailURL, path: path, indexPath: indexPath) {
self.imagesIndexPath[indexPath] = cachedImage
if cachedImage != self.defaultAssetImage {
self.cachedImageForThumbnailURL[thumbnailURL] = cachedImage
self.downloadedImagesIndexPathStream.send(indexPath)
}
return
}
let url = URL(string: thumbnailURL)!
self.cancellables[indexPath] = self.charactersRepository.downloadCharacterThumbnail(url).sink(receiveCompletion: { (completion) in
if case .failure = completion {
self.imagesIndexPath[indexPath] = self.defaultAssetImage
self.downloadedImagesIndexPathStream.send(indexPath)
}
}, receiveValue: { (data) in
guard let image = UIImage(data: data)?.resizeImage(self.imagesSize, opaque: true, contentMode: .scaleAspectFill) else { return }
self.imagesIndexPath[indexPath] = image
self.cachedImageForThumbnailURL[thumbnailURL] = image
if Constants.useAgressiveCaching {
CommonImagesPoolController.shared.save(image: image, forURLPath: path, withImageSize: self.imagesSize)
DiskImagesPoolController.shared.saveImageDataOnDisk(imageData: data, forURLPath: path, withImageSize: self.imagesSize)
}
self.downloadedImagesIndexPathStream.send(indexPath)
})
}
}
func downloadImage(_ thumbnailURL: String, withCommonPath path: String) -> AnyPublisher<UIImage, URLError> {
if let cachedImage = self.retrieveImageFor(thumbnailURL: thumbnailURL, path: path) {
self.cachedImageForThumbnailURL[thumbnailURL] = cachedImage
return Just(cachedImage).setFailureType(to: URLError.self).eraseToAnyPublisher()
}
let url = URL(string: thumbnailURL)!
return self.charactersRepository.downloadCharacterThumbnail(url).flatMap { (data) -> AnyPublisher<UIImage, URLError> in
guard let image = UIImage(data: data)?.resizeImage(self.imagesSize, opaque: true, contentMode: .scaleAspectFill) else {
return Fail(error: URLError(.cannotDecodeContentData)).eraseToAnyPublisher()
}
self.cachedImageForThumbnailURL[thumbnailURL] = image
if Constants.useAgressiveCaching {
CommonImagesPoolController.shared.save(image: image, forURLPath: path, withImageSize: self.imagesSize)
DiskImagesPoolController.shared.saveImageDataOnDisk(imageData: data, forURLPath: path, withImageSize: self.imagesSize)
}
return Just(image).setFailureType(to: URLError.self).eraseToAnyPublisher()
}.eraseToAnyPublisher()
}
func imageFor(indexPath: IndexPath) -> UIImage? {
return self.imagesIndexPath[indexPath]
}
func imageFor(thumbnailURL: String, path: String) -> UIImage? {
locker.lock()
defer { locker.unlock() }
if let cachedImage = self.cachedImageForThumbnailURL[thumbnailURL] {
return cachedImage
}
if Constants.useAgressiveCaching {
if let commonCachedImage = CommonImagesPoolController.shared.retrieveImage(forURLPath: path, forImageSize: self.imagesSize) {
return commonCachedImage
}
}
return nil
}
private func retrieveImageFor(thumbnailURL: String, path: String) -> UIImage? {
locker.lock()
defer { locker.unlock() }
if let cachedImage = self.cachedImageForThumbnailURL[thumbnailURL] {
return cachedImage
}
if Constants.useAgressiveCaching {
if let commonCachedImage = CommonImagesPoolController.shared.retrieveImage(forURLPath: path, forImageSize: self.imagesSize) {
return commonCachedImage
}
}
return nil
}
private func imageFor(thumbnailURL: String, path: String, indexPath: IndexPath) -> UIImage? {
locker.lock()
defer { locker.unlock() }
if let cachedImage = self.cachedImageForThumbnailURL[thumbnailURL] {
return cachedImage
}
if Constants.useAgressiveCaching {
if let commonCachedImage = CommonImagesPoolController.shared.retrieveImage(forURLPath: path, forImageSize: self.imagesSize) {
return commonCachedImage
}
let diskImageExists = DiskImagesPoolController.shared.retrieveSavedImageDataOnDiskAsync(forURLPath: path, withImageSize: self.imagesSize, completionHandler: { imageData in
if let recoveredImage = imageData.flatMap({ UIImage(data: $0) }) {
self.locker.lock()
defer { self.locker.unlock() }
print("Using image data from disk (async)")
let resizedImage = recoveredImage.resizeImage(self.imagesSize, opaque: true, contentMode: .scaleAspectFill)
self.cachedImageForThumbnailURL[thumbnailURL] = resizedImage
CommonImagesPoolController.shared.save(image: resizedImage, forURLPath: path, withImageSize: self.imagesSize)
self.downloadedImagesIndexPathStream.send(indexPath)
}
})
if diskImageExists {
return self.defaultAssetImage
}
}
return nil
}
var publisher: AnyPublisher<IndexPath, Never> {
self.downloadedImagesIndexPathStream.eraseToAnyPublisher()
}
lazy var defaultAssetImage: UIImage = {
self.imagesSize == Constants.characterInSearchResultRowImageSize ? Asset.smallPlaceholderImage : Asset.placeholderImage
}()
func cancelRequests() {
self.cancellables.values.forEach {
$0.cancel()
}
self.cancellables.removeAll(keepingCapacity: true)
self.otherCancellables.forEach {
$0.cancel()
}
self.otherCancellables.removeAll(keepingCapacity: true)
}
func cleanImagesByIndexPath() {
self.imagesIndexPath.removeAll(keepingCapacity: true)
}
deinit {
cancelRequests()
}
}
| 36.071038 | 174 | 0.758824 |
d9f6c615f32c95d96125a3a4612a4186375c916b | 2,280 | //
// BusinessCell.swift
// Yelp
//
// Created by Tran Khanh Trung on 10/21/16.
// Copyright © 2016 CoderSchool. All rights reserved.
//
import UIKit
class BusinessCell: UITableViewCell {
@IBOutlet weak var thumbImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ratingImageView: UIImageView!
@IBOutlet weak var reviewCountsLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var categoriesLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
var bussines: Business!{
didSet{
if let imageURL = bussines.imageURL {
thumbImageView.setImageWith(imageURL)
}
if let name = bussines.name {
nameLabel.text = name
}
if let ratingImageURL = bussines.ratingImageURL{
ratingImageView.setImageWith(ratingImageURL)
}
if let reviewCount = bussines.reviewCount {
reviewCountsLabel.text = "\(reviewCount) Reviews"
}
if let address = bussines.address {
addressLabel.text = address
}
if let categories = bussines.categories {
categoriesLabel.text = categories
}
if let distance = bussines.distance {
distanceLabel.text = distance
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
if thumbImageView != nil{
thumbImageView.layer.cornerRadius = 5
thumbImageView.clipsToBounds = true
}
if nameLabel != nil{
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width
}
}
override func layoutSubviews() {
super.layoutSubviews()
if nameLabel != nil{
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 28.5 | 74 | 0.564912 |
e836e01edaaf4eae95035d0a487645979bfa9780 | 4,283 | import ComposableArchitecture
import ReactiveSwift
import SwiftUI
private let readMe = """
This demonstrates how to trigger effects when a view appears, and cancel effects when a view \
disappears. This can be helpful for starting up a feature's long living effects, such as timers, \
location managers, etc. when that feature is first presented.
To accomplish this we define a higher-order reducer that enhances any reducer with two additional \
actions, `.onAppear` and `.onDisappear`, and a way to automate running effects when those actions \
are sent to the store.
"""
extension Reducer {
public func lifecycle(
onAppear: @escaping (Environment) -> Effect<Action, Never>,
onDisappear: @escaping (Environment) -> Effect<Never, Never>
) -> Reducer<State?, LifecycleAction<Action>, Environment> {
return .init { state, lifecycleAction, environment in
switch lifecycleAction {
case .onAppear:
return onAppear(environment).map(LifecycleAction.action)
case .onDisappear:
return onDisappear(environment).fireAndForget()
case let .action(action):
guard state != nil else { return .none }
return self.run(&state!, action, environment)
.map(LifecycleAction.action)
}
}
}
}
public enum LifecycleAction<Action> {
case onAppear
case onDisappear
case action(Action)
}
extension LifecycleAction: Equatable where Action: Equatable {}
struct LifecycleDemoState: Equatable {
var count: Int?
}
enum LifecycleDemoAction: Equatable {
case timer(LifecycleAction<TimerAction>)
case toggleTimerButtonTapped
}
struct LifecycleDemoEnvironment {
var mainQueue: DateScheduler
}
let lifecycleDemoReducer:
Reducer<LifecycleDemoState, LifecycleDemoAction, LifecycleDemoEnvironment> = .combine(
timerReducer.pullback(
state: \.count,
action: /LifecycleDemoAction.timer,
environment: { TimerEnvironment(mainQueue: $0.mainQueue) }
),
Reducer { state, action, environment in
switch action {
case .timer:
return .none
case .toggleTimerButtonTapped:
state.count = state.count == nil ? 0 : nil
return .none
}
}
)
struct LifecycleDemoView: View {
let store: Store<LifecycleDemoState, LifecycleDemoAction>
var body: some View {
WithViewStore(self.store) { viewStore in
VStack {
Button("Toggle Timer") { viewStore.send(.toggleTimerButtonTapped) }
IfLetStore(
self.store.scope(state: { $0.count }, action: LifecycleDemoAction.timer),
then: TimerView.init(store:)
)
Spacer()
}
.navigationBarTitle("Lifecycle")
}
}
}
private struct TimerId: Hashable {}
enum TimerAction {
case decrementButtonTapped
case incrementButtonTapped
case tick
}
struct TimerEnvironment {
var mainQueue: DateScheduler
}
private let timerReducer = Reducer<Int, TimerAction, TimerEnvironment> {
state, action, TimerEnvironment in
switch action {
case .decrementButtonTapped:
state -= 1
return .none
case .incrementButtonTapped:
state += 1
return .none
case .tick:
state += 1
return .none
}
}
.lifecycle(
onAppear: {
Effect.timer(id: TimerId(), every: .seconds(1), tolerance: .seconds(0), on: $0.mainQueue)
.map { _ in TimerAction.tick }
},
onDisappear: { _ in
.cancel(id: TimerId())
})
private struct TimerView: View {
let store: Store<Int, LifecycleAction<TimerAction>>
var body: some View {
WithViewStore(self.store) { viewStore in
Section {
Text("Count: \(viewStore.state)")
.onAppear { viewStore.send(.onAppear) }
.onDisappear { viewStore.send(.onDisappear) }
Button("Decrement") { viewStore.send(.action(.decrementButtonTapped)) }
Button("Increment") { viewStore.send(.action(.incrementButtonTapped)) }
}
}
}
}
struct Lifecycle_Previews: PreviewProvider {
static var previews: some View {
Group {
NavigationView {
LifecycleDemoView(
store: .init(
initialState: .init(),
reducer: lifecycleDemoReducer,
environment: .init(
mainQueue: QueueScheduler.main
)
)
)
}
}
}
}
| 25.194118 | 101 | 0.667756 |
e8d6bffcd004393d0fa42595116e910d5a24c1ce | 353 | //
// ViewController.swift
// StackView
//
// Created by Raju on 8/10/17.
// Copyright © 2017 rajubd49. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 16.045455 | 51 | 0.66289 |
f8a870198a7f5eb2f8a5dcb78a491deda0d9df9a | 12,553 | //
// LifeViewController.swift
// Live-zzu
//
// Created by 如是我闻 on 2017/4/27.
// Copyright © 2017年 如是我闻. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
let width:CGFloat = 375
//let height:CGFloat = 668
class Books : NSObject{
//var title = ""
//var subtitle = ""
var image = ""
// var rating = ""
//var name = ""
}
class LifeViewController: UIViewController ,UIScrollViewDelegate{
var pageControl:UIPageControl?//页面控制器
var tmpSV:UIScrollView?//滚动视图
var timer :Timer? //定时器
let URLString = "https://api.douban.com/v2/book/search?tag=Swift"//网络请求地址
var books = [Books]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setScrollView()
self.setPageControl()
//添加view使用网格
let view1 = UIView(frame: CGRect(x: 0, y: 260, width: self.view.frame.size.width, height: 200))
view1.backgroundColor = UIColor.lightGray
self.view.addSubview(view1)
//添加第1个网格button1
let button1 = UIButton(frame:CGRect(x:0, y:261, width:200, height:100))
button1.backgroundColor = UIColor.white
let label11 = UILabel(frame:CGRect(x:20, y:2, width:90, height:20))
label11.text = "淘鱼"
label11.font = UIFont(name:"Zapfino", size:15)
button1.addSubview(label11)
button1.addTarget(self, action:#selector(taoyu) , for: .touchUpInside)
let label12 = UILabel(frame:CGRect(x:20, y:20 ,width:90, height:20))
label12.text = "资源共享,二次利用"
label12.font = UIFont(name:"Zapfino", size:10)
label12.textColor = UIColor.gray //灰色
button1.addSubview(label12)
let imageView1 = UIImageView(image:UIImage(named:"life_taoyu"))
imageView1.frame = CGRect(x:150, y:50, width:40, height:40)
button1.addSubview(imageView1)
self.view.addSubview(button1)
//添加第2个网格button2
let button2 = UIButton(frame:CGRect(x:0, y:362, width:200, height:97))
button2.backgroundColor = UIColor.white
let label21 = UILabel(frame:CGRect(x:20, y:2, width:90, height:20))
label21.text = "一起玩"
label21.font = UIFont(name:"Zapfino", size:15)
button2.addSubview(label21)
button2.addTarget(self, action:#selector(yiqiwan) , for: .touchUpInside)
let label22 = UILabel(frame:CGRect(x:20, y:20 ,width:90, height:20))
label22.text = "从此不再孤单"
label22.font = UIFont(name:"Zapfino", size:10)
label22.textColor = UIColor.gray //灰色
button2.addSubview(label22)
let imageView2 = UIImageView(image:UIImage(named:"life_play"))
imageView2.frame = CGRect(x:150, y:50, width:40, height:40)
button2.addSubview(imageView2)
self.view.addSubview(button2)
//添加第3个网格button3
let button3 = UIButton(frame:CGRect(x:201, y:261, width:180, height:66))
button3.backgroundColor = UIColor.white
let label31 = UILabel(frame:CGRect(x:20, y:2, width:90, height:20))
label31.text = "话题圈"
label31.font = UIFont(name:"Zapfino", size:15)
button3.addSubview(label31)
button3.addTarget(self, action:#selector(huati) , for: .touchUpInside)
let label32 = UILabel(frame:CGRect(x:20, y:20 ,width:90, height:20))
label32.text = "大家一起说"
label32.font = UIFont(name:"Zapfino", size:10)
label32.textColor = UIColor.gray //灰色
button3.addSubview(label32)
let imageView3 = UIImageView(image:UIImage(named:"life_talk"))
imageView3.frame = CGRect(x:150, y:30, width:20, height:20)
button3.addSubview(imageView3)
self.view.addSubview(button3)
//添加第4个网格button4
let button4 = UIButton(frame:CGRect(x:201, y:328, width:180, height:66))
button4.backgroundColor = UIColor.white
let label41 = UILabel(frame:CGRect(x:20, y:2, width:90, height:20))
label41.text = "树洞"
label41.font = UIFont(name:"Zapfino", size:15)
button4.addSubview(label41)
button4.addTarget(self, action:#selector(shudong) , for: .touchUpInside)
let label42 = UILabel(frame:CGRect(x:20, y:20 ,width:90, height:20))
label42.text = "有情绪就表达"
label42.font = UIFont(name:"Zapfino", size:10)
label42.textColor = UIColor.gray //灰色
button4.addSubview(label42)
let imageView4 = UIImageView(image:UIImage(named:"life_tree"))
imageView4.frame = CGRect(x:150, y:30, width:20, height:20)
button4.addSubview(imageView4)
self.view.addSubview(button4)
//添加第5个网格button5
let button5 = UIButton(frame:CGRect(x:201, y:395, width:180, height:64))
button5.backgroundColor = UIColor.white
let label51 = UILabel(frame:CGRect(x:20, y:2, width:90, height:20))
label51.text = "兼职"
label51.font = UIFont(name:"Zapfino", size:15)
button5.addSubview(label51)
button5.addTarget(self, action:#selector(jianzhi) , for: .touchUpInside)
let label52 = UILabel(frame:CGRect(x:20, y:20 ,width:90, height:20))
label52.text = "课外时间不停赚"
label52.font = UIFont(name:"Zapfino", size:10)
label52.textColor = UIColor.gray //灰色
button5.addSubview(label52)
let imageView5 = UIImageView(image:UIImage(named:"life_offer"))
imageView5.frame = CGRect(x:150, y:30, width:20, height:20)
button5.addSubview(imageView5)
self.view.addSubview(button4)
self.view.addSubview(button5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setScrollView() {
let scrollView = UIScrollView()
scrollView.frame = CGRect(x: 0, y: 80, width: self.view.frame.size.width, height: 180)
//设置内容大小
scrollView.contentSize = CGSize(width: CGFloat(width * 7), height: 180)
//scrollView.backgroundColor = UIColor.red
//设置起始偏移量
scrollView.contentOffset = CGPoint(x: 0, y: 0)
//隐藏水平指示条
scrollView.showsHorizontalScrollIndicator = false
//隐藏竖直指示条
scrollView.showsVerticalScrollIndicator = false
//开启分页效果
scrollView.isPagingEnabled = true
//设置代理
scrollView.delegate = self
self.view.addSubview(scrollView)
//网络请求
Alamofire.request(URLString, method: .get, parameters: ["tag" : "Swift"]).validate().responseJSON { (resp) -> Void in
if let error = resp.result.error{
print(error)
}else if let value = resp.result.value,let jsonArray = JSON(value)["books"].array {
for json in jsonArray{
let book = Books()
book.image = json["image"].string ?? ""
//print(book.image)
self.books.append(book)
//print(self.books)
}
//print(self.books.count)
for i in 0..<6 {
let imageView : UIImageView = UIImageView(frame: CGRect(x: width * CGFloat(i), y: 0, width: width, height: 180))
let book = self.books[i]
let urimage = URL(string: book.image)
let data = NSData(contentsOf: urimage!)
let image = UIImage(data: data! as Data)
imageView.image = image
//imageView.backgroundColor = colors[i]
scrollView.addSubview(imageView)
}
}
}
tmpSV = scrollView
//let colors:[UIColor] = [UIColor.red,UIColor.orange,UIColor.yellow,UIColor.green,UIColor.blue,UIColor.purple]
}
func setPageControl() {
pageControl = UIPageControl(frame: CGRect(x: self.view.center.x - 60, y: 220, width: 150, height: 20))
//设置显示的页数
pageControl?.numberOfPages = 5
//设置显示的起始页的索引
pageControl?.currentPage = 0
//设置单页时隐藏
pageControl?.hidesForSinglePage = true
//设置显示颜色
pageControl?.currentPageIndicatorTintColor = UIColor.green
//设置页背景指示颜色
pageControl?.pageIndicatorTintColor = UIColor.lightGray
//添加事件
pageControl?.addTarget(self, action: #selector(pageControlChanged), for: UIControlEvents.valueChanged)
self.view.addSubview(pageControl!)
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.change), userInfo: nil, repeats: true)
}
//pageControl的触发事件
func pageControlChanged() {
let page = pageControl?.currentPage
print("当前显示的是第\(page!+1)页")
tmpSV!.contentOffset = CGPoint(x: width * CGFloat(page!), y: 0)
var frame = tmpSV!.frame
frame.origin.x = width * CGFloat(page!)
tmpSV!.scrollRectToVisible(frame, animated: true)
}
//循环滚动方法
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//如果图片在第一张的位置
if scrollView.contentOffset.x == 0 {
//就变到倒数第二张的位置上
scrollView.scrollRectToVisible(CGRect(x: scrollView.contentSize.width - self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: 180), animated: false)
//如果图片是倒数第一张的位置
} else if scrollView.contentOffset.x == scrollView.contentSize.width - self.view.frame.size.width{
//就变到第二张的位置
scrollView .scrollRectToVisible(CGRect(x: self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: 180), animated: false)
}
pageControl?.currentPage = Int(scrollView.contentOffset.x / self.view.frame.size.width) - 1
}
//定时器执行方法
func change(timer :Timer) {
if pageControl?.currentPage == ( pageControl?.numberOfPages)! - 1 {
pageControl?.currentPage = 0
} else if ( pageControl?.currentPage)! < ( pageControl?.numberOfPages)! - 1 {
pageControl?.currentPage = (pageControl?.currentPage)! + 1
}
// tmpSV?.setContentOffset(CGPointMake((CGFloat( pageControl!.currentPage + 1)) * self.view.frame.size.width, 0), animated: false)
tmpSV?.setContentOffset(CGPoint(x: (CGFloat( pageControl!.currentPage + 1)) * self.view.frame.size.width, y: 0), animated: false)
}
//开启定时器
func addTimer() {
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.change), userInfo: nil, repeats: true)
}
//关闭定时器
func removeTimer() {
timer?.invalidate()
}
//开始拖拽时调用
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
//关闭定时器
removeTimer()
}
//拖拽结束后调用
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//开启定时器
addTimer()
}
func taoyu(){
let normalRoomVa = TaoYuViewController()
navigationController?.pushViewController(normalRoomVa, animated: true)
}
func yiqiwan(){
print("yiqiwan")
}
func huati(){
let normalRoomVd = HuaTiQuanViewController()
// 2.以Push方式弹出
navigationController?.pushViewController(normalRoomVd, animated: true)
}
func shudong(){
let normalRoomVc = ShuDongViewController()
// 2.以Push方式弹出
navigationController?.pushViewController(normalRoomVc, animated: true)
}
func jianzhi(){
print("jianzhi")
}
}
| 32.861257 | 183 | 0.572771 |
e96e9772d363ecd1e370a02ea9832ae71e070f87 | 10,531 | //
// NotificationHelper.swift
// Big Arrow
//
// Created by Marco Filetti on 19/11/2017.
// Copyright © 2017 Marco Filetti. All rights reserved.
//
import Foundation
import UserNotifications
/// Contains code for the delivery of notifications
class NotificationHelper {
/// Identifiers
class Identifiers {
// category identifiers
static let autoStoppedNearbyNotification = "com.marcofiletti.autoStoppedNearbyNotification"
static let stoppableNearbyNotification = "com.marcofiletti.stoppableNearbyNotification"
static let stopTrackingAction = "com.marcofiletti.stoppableNearbyAction"
// action identifiers
static let etaNotification = "com.marcofiletti.etaNotification"
}
// MARK: - Internal properties
/// Returns the notification categories we support.
/// Two categories:
/// - autoStoppedNearbyTrigger: we reached a destination and stopped ourselves.
/// - stoppableNearbyTrigger: we reached a destination but didn't stop ourselves.
/// The notification includes a button to stop tracking.
/// - etaTrigger: eta is less than a given value.
static let categories: Set<UNNotificationCategory> = {
let hiddenPlaceholder = "destination_reached".localized
let autoStoppedCategory = createNotificationCategory(identifier: Identifiers.autoStoppedNearbyNotification, hiddenPlaceholder: hiddenPlaceholder)
let stopAction = UNNotificationAction(identifier: Identifiers.stopTrackingAction, title: "stop".localized, options: [])
let stoppableCategory = createNotificationCategory(identifier: Identifiers.stoppableNearbyNotification, actions: [stopAction], hiddenPlaceholder: hiddenPlaceholder)
let etaCategory = createNotificationCategory(identifier: Identifiers.etaNotification, hiddenPlaceholder: "approaching_destination".localized)
return [autoStoppedCategory, stoppableCategory, etaCategory]
}()
/// Stores whether we sent notification (we want to do it only once).
/// Set to false every time location master starts.
static var sentNearDistanceNotification = false { didSet {
if sentNearDistanceNotification == false {
nextNearbyIdString = UUID().uuidString
}
}}
/// Stores whether we sent an eta notification.
static var sentETANotification = false { didSet {
if sentETANotification == false {
nextETAIdString = UUID().uuidString
lastSentETANotification = Date.distantPast
} else {
lastSentETANotification = Date()
}
}}
// MARK: - Private propertied
/// Last time an eta notification was sent.
/// Reset by sentETANotification
static private(set) var lastSentETANotification = Date.distantPast
/// Stores uuid string for next notification (reset every time sentNearDistanceNotification is set to false)
private static var nextNearbyIdString = UUID().uuidString
/// Stores uuid string for next notification (reset every time sentETANotification is set to false)
private static var nextETAIdString = UUID().uuidString
// MARK: - Static functions
/// Registers supported notification categories.
/// Do this during app launch.
static func registerCategories() {
let center = UNUserNotificationCenter.current()
center.setNotificationCategories(categories)
}
/// Sends user notifications if appropriate, and sends an internal notification
/// indicating that this was done
static func sendNotificationsIfNeeded(_ indication: Indication, _ destination: Destination?) {
// first of all, check if notifications are on, otherwise leave
guard UserDefaults.standard.object(forKey: Constants.Defs.nearNotificationsOn) as! Bool else {
return
}
// if the eta notification was not sent and preference is set, send that
if !sentETANotification, let destination = destination {
let requestedEta = UserDefaults.standard.object(forKey: Constants.Defs.notificationsETA) as! Double
if requestedEta > 0, let actualETA = indication.eta, actualETA < requestedEta, actualETA > 0 {
self.sentETANotification = true
let title = "approaching".localized + " " + destination.name
let body = "ETA: \(Formatters.format(briefTime: actualETA))"
let content = makeNotificationContent(title: title, body: body, categoryIdentifier: Identifiers.etaNotification)
requestNotification(content: content, idString: nextETAIdString)
}
} else if sentETANotification {
// if a minute has passed since last time a eta notification was set,
// and current eta is > requested eta, reset sentETANotification
if lastSentETANotification.addingTimeInterval(60) < Date(),
let requestedEta = UserDefaults.standard.object(forKey: Constants.Defs.notificationsETA) as? Double,
let actualEta = indication.eta,
requestedEta < actualEta {
sentETANotification = false
}
}
// continue only if we didn't send nearby notification
guard !sentNearDistanceNotification else {
return
}
// do nothing if there's no destination
guard let destination = destination else {
return
}
// notification raduis
let radius = UserDefaults.standard.object(forKey: Constants.Defs.nearNotificationMeters) as! Double
/*
OLD WAY, DISABLED FOR NOW
// trigger notification if nearby, making sure that 1) accuracy is less than radius
// or that 2) distance is less than half accuracy and radius is bigger than half dist
guard indication.minimumDistance <= 0 &&
(indication.accuracy <= radius ||
indication.distance <= indication.accuracy / 2 && radius >= indication.distance / 2 ) else {
return
}
*/
guard indication.distance <= radius else {
return
}
sentNearDistanceNotification = true
let content: UNNotificationContent
let title = String(format: "reached_%@".localized, destination.name)
let body = "distance".localized + ": \(Formatters.format(distance: indication.distance))"
if UserDefaults.standard.object(forKey: Constants.Defs.notificationsStopTracking) as! Bool {
content = makeNotificationContent(title: title, body: body, categoryIdentifier: Identifiers.autoStoppedNearbyNotification)
} else {
content = makeNotificationContent(title: title, body: body, categoryIdentifier: Identifiers.stoppableNearbyNotification)
}
requestNotification(content: content, idString: nextNearbyIdString) {
error in
if error == nil && UserDefaults.standard.object(forKey: Constants.Defs.notificationsStopTracking) as! Bool {
NotificationCenter.default.post(name: Constants.Notifications.nearDistanceNotificationStopTracking, object: nil)
}
}
}
/// Clear all notifications (e.g. when opening arrow view)
static func clearAllNotifications() {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
/// Helper function to convert a notification received in foreground to an internal notification
static func dispatchNotificationInternally(categoryIdentifier: String) {
switch categoryIdentifier {
case Identifiers.etaNotification:
NotificationCenter.default.post(name: Constants.Notifications.etaNotificationTriggered, object: nil)
case Identifiers.stoppableNearbyNotification:
NotificationCenter.default.post(name: Constants.Notifications.nearbyNotificationTriggered, object: nil)
case Identifiers.autoStoppedNearbyNotification:
// sendNotificationsIfNeeded already does send an internal notification, and does so regardless of fore or back ground
return
default:
return
}
}
// MARK: - Private functions
/// Helper function to submit a notification
private static func requestNotification(content: UNNotificationContent, idString: String, completionHandler: ((Error?) -> Void)? = nil) {
let center = UNUserNotificationCenter.current()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)
let request = UNNotificationRequest(identifier: idString, content: content, trigger: trigger)
center.add(request, withCompletionHandler: completionHandler)
}
/// Helper function to convert an indication > destination pair into content for a notification
private static func makeNotificationContent(title: String, body: String, categoryIdentifier: String) -> UNNotificationContent {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
if categoryIdentifier == Identifiers.autoStoppedNearbyNotification {
content.subtitle = "stopped_automatically".localized
}
content.categoryIdentifier = categoryIdentifier
#if !WatchApp
content.sound = Options.NotificationSound.saved.unNotificationSound
#else
content.sound = UNNotificationSound.default
#endif
return content
}
/// Helper function to build a notification category
private static func createNotificationCategory(identifier: String, actions: [UNNotificationAction] = [], hiddenPlaceholder: String) -> UNNotificationCategory {
let category: UNNotificationCategory
#if !WatchApp
if #available(iOS 11.0, *) {
category = UNNotificationCategory(identifier: identifier, actions: actions, intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: hiddenPlaceholder)
} else {
category = UNNotificationCategory(identifier: identifier, actions: actions, intentIdentifiers: [], options: [])
}
#else
category = UNNotificationCategory(identifier: identifier, actions: actions, intentIdentifiers: [], options: [])
#endif
return category
}
}
| 46.597345 | 172 | 0.677524 |
dda5e3c0e3464a7956562aae4ba5ff4133bdd82f | 683 | //
// ObjectDisplayable.swift
// Pods
//
// Created by Brian Strobach on 9/12/16.
//
//
import Foundation
public protocol ObjectDisplayable: AnyObject {
associatedtype DisplayableObjectType
func display(object: DisplayableObjectType)
}
public protocol ContextualObjectDisplayable {
associatedtype DisplayableObjectContextType
associatedtype DisplayableObjectType
func display(object: DisplayableObjectType, context: DisplayableObjectContextType)
}
public extension Array where Element: ObjectDisplayable {
func display(object: Element.DisplayableObjectType) {
for element in self {
element.display(object: object)
}
}
}
| 23.551724 | 86 | 0.74817 |
1a7bb1c885d2e695620213f91930e19a438df2c1 | 469 | //
// ArchiveInfo.swift
// Symphony
//
// Created by Bradley Hilton on 11/18/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
import Foundation
public protocol ArchiveInfo {
static var bundle: Bundle { get }
static var archiveKey: String { get }
}
extension ArchiveInfo {
public static var bundle: Bundle {
return Bundle.main
}
public static var archiveKey: String {
return "\(self)Archive"
}
}
| 17.37037 | 54 | 0.635394 |
23b1b2323d72a112397c6b62a7b1e3d509d3808c | 1,714 | //
// CircleColorCollectionViewCell.swift
// Expense Tracker
//
// Created by isEmpty on 11.12.2020.
//
import UIKit
final class GradientCategoryCollectionViewCell: UICollectionViewCell {
//MARK: - Properties & Outlets
@IBOutlet private weak var circleGradient: UIView!
private var gradientLayer: CAGradientLayer?
private var shadowLayer: CALayer?
override var isSelected: Bool {
didSet{
shadowLayer?.removeFromSuperlayer()
if isSelected {
configureShadow()
circleGradient.layer.borderWidth = 2
circleGradient.layer.borderColor = UIColor.white.cgColor
} else {
circleGradient.layer.borderWidth = 0
}
}
}
//MARK: - View Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
circleGradient.layer.cornerRadius = circleGradient.frame.height / 2
}
}
//MARK: - Supporting Methods
extension GradientCategoryCollectionViewCell {
/// Creates and configure `shadowLayer`
private func configureShadow() {
shadowLayer = CALayer()
shadowLayer?.shadowColor = UIColor.black.cgColor
shadowLayer?.shadowOpacity = 0.25
shadowLayer?.shadowOffset = CGSize(width: 0, height: 2)
shadowLayer?.shadowRadius = 3
shadowLayer?.shadowPath = CGPath(ellipseIn: circleGradient.frame, transform: nil)
layer.insertSublayer(shadowLayer!, at: 0)
}
public func configure(colors: [UIColor]) {
gradientLayer?.removeFromSuperlayer()
gradientLayer = circleGradient?.applyGradient(colours: colors, startPoint: .bottomLeft, endPoint: .topRight)
}
}
| 31.163636 | 116 | 0.655193 |
33f41cd708224510979421651061ec3a10eca3de | 919 | /*
Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
#if !os(macOS)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(TTYASTDumpTests.allTests),
testCase(TTYASTPrintTests.allTests),
testCase(ShebangIntegrationTests.allTests),
testCase(SemaIntegrationTests.allTests),
]
}
#endif
| 31.689655 | 85 | 0.752992 |
4ac2c76bf7bfce779518fb147f47155be07923b8 | 3,843 | // AOC16.swift
// AdventOfCode
//
// Created by Dash on 12/15/20.
//
import Foundation
struct AOC16: Puzzle {
func solve1(input: String) -> Int {
var validIndices = IndexSet()
for line in input.lineGroups[0].lines {
for rangeText in line.components(separatedBy: ": ")[1].components(separatedBy: " or ") {
validIndices.insert(integersIn: rangeText.range)
}
}
let nearbyTickets = input.lineGroups[2].lines[1...]
let invalidValues = nearbyTickets.compactMap({ $0.integers.first(where: { !validIndices.contains($0) }) })
return invalidValues.reduce(0, +)
}
func solve2(input: String) -> Int {
solve2(input: input, prefix: "departure")
}
func solve2(input: String, prefix: String) -> Int {
var validIndices = IndexSet()
var validIndicesByField: [String: IndexSet] = [:]
for line in input.lineGroups[0].lines {
let components = line.components(separatedBy: ": ")
let field = components[0]
for rangeText in components[1].components(separatedBy: " or ") {
validIndices.insert(integersIn: rangeText.range)
var fieldIndices = validIndicesByField[field] ?? IndexSet()
fieldIndices.insert(integersIn: rangeText.range)
validIndicesByField[field] = fieldIndices
}
}
let yourTicket = input.lineGroups[1].lines[1].integers
let nearbyTickets = input.lineGroups[2].lines[1...]
.map { $0.integers }
.filter { $0.allSatisfy({ validIndices.contains($0) }) }
// Create a set of valid fields for every index based on the nearby tickets
let possibleFieldsByIndex: [Int: Set<String>] = yourTicket.indices.reduce(into: [:], { fieldsByIndex, index in
let possibleFields = validIndicesByField.keys.filter { field in
nearbyTickets.allSatisfy({ ticket in validIndicesByField[field]!.contains(ticket[index]) })
}
fieldsByIndex[index] = Set(possibleFields)
})
// Resolve the possible fields per index down to one assigned field for each index
let fieldsByIndex = findFieldsByIndex(possibleFieldsByIndex: possibleFieldsByIndex)!
// Return the product of all fields in your own ticket that start with a prefix
return fieldsByIndex
.filter { $0.value.starts(with: prefix) }
.reduce(1) { $0 * yourTicket[$1.key] }
}
func findFieldsByIndex(possibleFieldsByIndex: [Int: Set<String>], fieldsByIndex: [Int: String] = [:]) -> [Int: String]? {
// Base case: all fields are resolved
if possibleFieldsByIndex.count == 0 {
return fieldsByIndex
}
// Choose the unresolved index with the least possibilities
let (index, possibleFields) = possibleFieldsByIndex.min(by: { $1.value.count > $0.value.count })!
// Remove it from the unresolved dictionary and try every option to resolve it
var newPossible = possibleFieldsByIndex
newPossible.removeValue(forKey: index)
for field in possibleFields {
// Skip any fields that are already assigned to a resolved index
if fieldsByIndex.values.contains(field) { continue }
// Try assigning this field to this index and resolving recursively
var newFieldsByIndex = fieldsByIndex
newFieldsByIndex[index] = field
if let resolvedFieldsByIndex = findFieldsByIndex(possibleFieldsByIndex: newPossible, fieldsByIndex: newFieldsByIndex) {
return resolvedFieldsByIndex
}
}
// Return nil if the remaining possibleFields are not resolvable
return nil
}
}
| 44.686047 | 131 | 0.622951 |
56a7ae1bc0cd2f94751901990c330998916387e8 | 2,188 | //
// AppDelegate.swift
// TryProcedureKit iOS
//
// Created by Daniel Thorpe on 05/12/2016.
// Copyright © 2016 ProcedureKit. 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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.553191 | 285 | 0.756856 |
18672176d7214e670cbbb97e2b752bfccb865dce | 268 | //
// Constants.swift
// SberIOS_Lesson17
//
// Created by Svetlana Fomina on 06.06.2021.
//
enum Constants {
static let urlString = "https://api.nasa.gov/planetary/apod"
static let api_key = "mU08RsKfiVxUFaN2g3a90dGvAWHrYhS7R8C90FiN"
static let count = "20"
}
| 20.615385 | 64 | 0.723881 |
7613bce89d9e2419ef6c9e9e9a36185fe492f60e | 3,119 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for ManagedGrafana
public struct ManagedGrafanaErrorType: AWSErrorType {
enum Code: String {
case accessDeniedException = "AccessDeniedException"
case conflictException = "ConflictException"
case internalServerException = "InternalServerException"
case resourceNotFoundException = "ResourceNotFoundException"
case serviceQuotaExceededException = "ServiceQuotaExceededException"
case throttlingException = "ThrottlingException"
case validationException = "ValidationException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize ManagedGrafana
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// You do not have sufficient permissions to perform this action.
public static var accessDeniedException: Self { .init(.accessDeniedException) }
/// A resource was in an inconsistent state during an update or a deletion.
public static var conflictException: Self { .init(.conflictException) }
/// Unexpected error while processing the request. Retry the request.
public static var internalServerException: Self { .init(.internalServerException) }
/// The request references a resource that does not exist.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// The request would cause a service quota to be exceeded.
public static var serviceQuotaExceededException: Self { .init(.serviceQuotaExceededException) }
/// The request was denied because of request throttling. Retry the request.
public static var throttlingException: Self { .init(.throttlingException) }
/// The value of a parameter in the request caused an error.
public static var validationException: Self { .init(.validationException) }
}
extension ManagedGrafanaErrorType: Equatable {
public static func == (lhs: ManagedGrafanaErrorType, rhs: ManagedGrafanaErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ManagedGrafanaErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 41.039474 | 117 | 0.686759 |
ed31e53b41b78673e7fdf8d5ab6dab30de91efae | 747 | //
// Presenter.swift
// MVP_Demo
//
// Created by 洋蔥胖 on 2019/1/23.
// Copyright © 2019 ChrisYoung. All rights reserved.
//
import Foundation
// 給View使用
protocol GreetingView {
func setGreeting(greeting: String)
}
// 給Presenter使用
protocol GreetingViewPresenter {
init(view: GreetingView, person:Person)
func showGreeting()
}
class GreetingPresenter: GreetingViewPresenter {
let view : GreetingView
let person: Person
// GreetingViewPresenter 代理
required init(view: GreetingView, person: Person) {
self.view = view
self.person = person
}
func showGreeting() {
self.view.setGreeting(greeting: "Hi! \(self.person.firstName) \(self.person.lastName)")
}
}
| 18.219512 | 95 | 0.661312 |
69619e6e3907246dd33e8e641d12a106e79c6381 | 3,718 | //
// FileLinkTableCell.swift
// Study Saga
//
// Created by Trần Đình Tôn Hiếu on 4/7/21.
//
import Foundation
import UIKit
import Masonry
protocol FileLinkTableCellDelegate: NSObject {
func didSelectCell(_ cell: FileLinkTableCell)
}
class FileLinkTableCell: UITableViewCell {
static let reuseId = "FileLinkTableCellReuseID"
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.customInit()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
weak var delegate: FileLinkTableCellDelegate? = nil
var document: DocumentModel? {
didSet {
if let document = self.document {
if document.type == .docx {
iconImageView.image = UIImage(named: "docx")
} else if document.type == .pdf {
iconImageView.image = UIImage(named: "pdf")
} else {
iconImageView.image = UIImage(named: "")
}
let attributedText = NSMutableAttributedString(string: document.name)
let rangeToUnderline = NSRange(location: 0, length: document.name.lenght)
attributedText.addAttribute(
NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: rangeToUnderline
)
attributedText.addAttributes(
[NSAttributedString.Key.font: UIFont(name: "HelveticaNeue", size: 15)!],
range: rangeToUnderline
)
self.nameLabel.attributedText = attributedText
}
}
}
var container = UIButton()
var iconImageView = UIImageView()
var nameLabel: UILabel = {
var lbl = UILabel()
lbl.textAlignment = .left
lbl.textColor = UIColor.systemBlue
return lbl
}()
private func customInit() {
self.contentView.isUserInteractionEnabled = false
self.addSubview(container)
container.addSubview(iconImageView)
container.addSubview(nameLabel)
container.backgroundColor = .clear
container.layer.cornerRadius = 10
container.setBackgroundColor(color: .lightGray, forState: .highlighted )
container.mas_makeConstraints { make in
make?.leading.equalTo()(self.mas_leading)?.with()?.offset()(10)
make?.trailing.equalTo()(self.mas_trailing)?.with()?.offset()(-10)
make?.top.equalTo()(self.mas_top)?.with()?.offset()(5)
make?.bottom.equalTo()(self.mas_bottom)?.with()?.offset()(-5)
}
container.addTarget(self, action: #selector(didSelectCell), for: .touchUpInside)
iconImageView.mas_makeConstraints { make in
make?.leading.equalTo()(container.mas_leading)?.with()?.offset()(12)
make?.size.equalTo()(25)
make?.centerY.equalTo()(container.mas_centerY)
}
nameLabel.mas_makeConstraints { make in
make?.leading.equalTo()(iconImageView.mas_trailing)?.with()?.offset()(10)
make?.trailing.equalTo()(container.mas_trailing)?.with()?.offset()(-12)
make?.centerY.equalTo()(container.mas_centerY)
}
}
func setBackground(_ color: UIColor) {
self.container.backgroundColor = color
}
@objc func didSelectCell() {
self.delegate?.didSelectCell(self)
}
}
| 33.495495 | 92 | 0.589564 |
b9e9bb3b3d0d2e61a505edf44af07d59aafed28e | 5,943 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// CHECK-DAG: %swift.refcounted = type
// CHECK-DAG: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }>
// CHECK-DAG: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }>
// CHECK-DAG: [[INT:%TSi]] = type <{ i64 }>
// CHECK-DAG: [[DOUBLE:%TSd]] = type <{ double }>
// CHECK-DAG: [[NSRECT:%TSo6NSRectV]] = type <{ %TSo7NSPointV, %TSo6NSSizeV }>
// CHECK-DAG: [[NSPOINT:%TSo7NSPointV]] = type <{ %TSd, %TSd }>
// CHECK-DAG: [[NSSIZE:%TSo6NSSizeV]] = type <{ %TSd, %TSd }>
// CHECK-DAG: [[OBJC:%objc_object]] = type opaque
// CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class {
// CHECK: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK: %swift.opaque* @_objc_empty_cache,
// CHECK: %swift.opaque* null,
// CHECK: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64)
// CHECK: }
// CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00"
// CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
// CHECK: i32 129,
// CHECK: i32 40,
// CHECK: i32 40,
// CHECK: i32 0,
// CHECK: i8* null,
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK: @_CLASS_METHODS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: i8* null,
// CHECK: i8* null,
// CHECK: i8* null
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
// CHECK: i32 128,
// CHECK: i32 16,
// CHECK: i32 24,
// CHECK: i32 0,
// CHECK: i8* null,
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: @_IVARS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: _PROPERTIES__TtC17objc_class_export3Foo
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @"$s17objc_class_export3FooCMf" = internal global <{{.*i64}} }> <{
// CHECK: void ([[FOO]]*)* @"$s17objc_class_export3FooCfD",
// CHECK: i8** @"$sBOWV",
// CHECK: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64),
// CHECK: %objc_class* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK: %swift.opaque* @_objc_empty_cache,
// CHECK: %swift.opaque* null,
// CHECK: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 1),
// CHECK: [[FOO]]* (%swift.type*)* @"$s17objc_class_export3FooC6createACyFZ",
// CHECK: void (double, double, double, double, [[FOO]]*)* @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"
// CHECK: }>, section "__DATA,__objc_data, regular"
// -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of
// Foo.
// CHECK: @"$s17objc_class_export3FooCN" = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @"$s17objc_class_export3FooCMf", i32 0, i32 2) to %swift.type*)
// CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @"$s17objc_class_export3FooCN"
import gizmo
class Hoozit {}
struct BigStructWithNativeObjects {
var x, y, w : Double
var h : Hoozit
}
@objc class Foo {
@objc var x = 0
@objc class func create() -> Foo {
return Foo()
}
@objc func drawInRect(dirty dirty: NSRect) {
}
// CHECK: define internal void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]*
// CHECK: call swiftcc void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
// CHECK: }
@objc func bounds() -> NSRect {
return NSRect(origin: NSPoint(x: 0, y: 0),
size: NSSize(width: 0, height: 0))
}
// CHECK: define internal void @"$s17objc_class_export3FooC6boundsSo6NSRectVyFTo"([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]*
// CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC6boundsSo6NSRectVyF"([[FOO]]* swiftself [[CAST]])
@objc func convertRectToBacking(r r: NSRect) -> NSRect {
return r
}
// CHECK: define internal void @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]*
// CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
func doStuffToSwiftSlice(f f: [Int]) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @"$s17objc_class_export3FooC19doStuffToSwiftSlice1fySaySiG_tcAAFTo"
func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStruct1ffS_FTV17objc_class_export27BigStructWithNativeObjects_T_
@objc init() { }
}
| 50.364407 | 219 | 0.665657 |
336f50f87dff86e6a46e83e7d4d93b3d06e84fa8 | 29,772 | //
// StartViewController.swift
// nxcd-liveness-example
//
// Created by Spencer Müller Diniz on 04/04/21.
//
import UIKit
import NXCDLivenessSDK
class StartViewController: UIViewController {
//MARK: - Constants
private static let kInstructionTextSize: CGFloat = 18.0
private static let kInstructionNumberSize: CGFloat = 14.0
//MARK:- Views
private let containerView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let headerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let bodyView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let closeButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "xmark"), for: .normal)
button.tintColor = .black
return button
}()
private let titleLabel: UILabel = {
let label = UILabel()
label.text = "Instruções"
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 32.0, weight: .bold)
label.textAlignment = .natural
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionsStackView: UIStackView = {
let stackView = UIStackView()
stackView.spacing = 8.0
stackView.alignment = .fill
stackView.distribution = .fillEqually
stackView.axis = .vertical
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private let instructionOneView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionOneTitleLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: kInstructionTextSize, weight: .regular)
label.textAlignment = .natural
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionOneNumberView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.38)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionOneNumberLabel: UILabel = {
let label = UILabel()
label.text = "1"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: kInstructionNumberSize, weight: .regular)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionTwoView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionTwoTitleLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: kInstructionTextSize, weight: .regular)
label.textAlignment = .natural
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionTwoNumberView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.38)
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionTwoNumberLabel: UILabel = {
let label = UILabel()
label.text = "2"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: kInstructionNumberSize, weight: .regular)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionThreeView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionThreeTitleLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: kInstructionTextSize, weight: .regular)
label.textAlignment = .natural
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionThreeNumberView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.38)
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionThreeNumberLabel: UILabel = {
let label = UILabel()
label.text = "3"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: kInstructionNumberSize, weight: .regular)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionFourView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionFourTitleLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: kInstructionTextSize, weight: .regular)
label.textAlignment = .natural
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionFourNumberView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.38)
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionFourNumberLabel: UILabel = {
let label = UILabel()
label.text = "4"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: kInstructionNumberSize, weight: .regular)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionFiveView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionFiveTitleLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: kInstructionTextSize, weight: .regular)
label.textAlignment = .natural
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let instructionFiveNumberView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.38)
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let instructionFiveNumberLabel: UILabel = {
let label = UILabel()
label.text = "5"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: kInstructionNumberSize, weight: .regular)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let letsGoButton: UIButton = {
let button = UIButton()
button.backgroundColor = .black
button.setTitle("OK, VAMOS LÁ", for: .normal)
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 4.0
button.layer.shadowColor = UIColor.black.cgColor
button.layer.shadowOpacity = 0.3
button.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
button.layer.shadowPath = UIBezierPath(rect: button.bounds).cgPath
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
private let viewActivityOverlay: UIView = {
let viewActivityOverlay = UIView()
viewActivityOverlay.translatesAutoresizingMaskIntoConstraints = false
viewActivityOverlay.isHidden = true
viewActivityOverlay.backgroundColor = UIColor.black.withAlphaComponent(0.5)
return viewActivityOverlay
}()
private let activityIndicator: UIActivityIndicatorView = {
let activityIndicator: UIActivityIndicatorView = {
if #available(iOS 13.0, *) {
return UIActivityIndicatorView(style: .large)
} else {
return UIActivityIndicatorView(style: .whiteLarge)
}
}()
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.color = .white
return activityIndicator
}()
//MARK: - Variables
private let instructions: InstructionsModel
private var imageArray = [UIImage]()
private let service = Service(isTest: true, apiKey: "<put your api key here>")
var startCapture: (() -> Void)?
override var preferredStatusBarStyle: UIStatusBarStyle {
if #available(iOS 13.0, *) {
return .darkContent
} else {
return .default
}
}
//MARK: - Initialization
init(instructions: InstructionsModel) {
self.instructions = instructions
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupUX()
}
override func viewDidLayoutSubviews() {
instructionOneNumberView.layer.cornerRadius = instructionOneNumberView.frame.size.width / 2.0
instructionOneNumberView.clipsToBounds = true
instructionTwoNumberView.layer.cornerRadius = instructionTwoNumberView.frame.size.width / 2.0
instructionTwoNumberView.clipsToBounds = true
instructionThreeNumberView.layer.cornerRadius = instructionThreeNumberView.frame.size.width / 2.0
instructionThreeNumberView.clipsToBounds = true
instructionFourNumberView.layer.cornerRadius = instructionFourNumberView.frame.size.width / 2.0
instructionFourNumberView.clipsToBounds = true
instructionFiveNumberView.layer.cornerRadius = instructionFiveNumberView.frame.size.width / 2.0
instructionFiveNumberView.clipsToBounds = true
}
//MARK: - Setups
private func setupUI() {
setupContainerView()
setupHeaderView()
setupCloseButton()
setupBodyView()
setupTitleLabel()
setupInstructionsStackView()
setupInstructionOne()
setupInstructionTwo()
setupInstructionThree()
setupInstructionFour()
setupInstructionFive()
setupLetsGoButton()
setupActivityOverlayView()
}
private func setupContainerView() {
view.addSubview(containerView)
containerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
private func setupHeaderView() {
containerView.addSubview(headerView)
headerView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
headerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
headerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
headerView.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
}
private func setupCloseButton() {
headerView.addSubview(closeButton)
closeButton.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 21.2).isActive = true
closeButton.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: -21.2).isActive = true
closeButton.heightAnchor.constraint(equalToConstant: 56.0).isActive = true
closeButton.widthAnchor.constraint(equalToConstant: 56.0).isActive = true
}
private func setupBodyView() {
containerView.addSubview(bodyView)
bodyView.topAnchor.constraint(equalTo: closeButton.bottomAnchor).isActive = true
bodyView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
bodyView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
bodyView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
}
private func setupTitleLabel() {
bodyView.addSubview(titleLabel)
titleLabel.topAnchor.constraint(equalTo: bodyView.topAnchor).isActive = true
titleLabel.leadingAnchor.constraint(equalTo: bodyView.leadingAnchor, constant: 48.0).isActive = true
}
private func setupInstructionsStackView() {
bodyView.addSubview(instructionsStackView)
instructionsStackView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 50).isActive = true
instructionsStackView.leadingAnchor.constraint(equalTo: bodyView.leadingAnchor, constant: 48.0).isActive = true
instructionsStackView.trailingAnchor.constraint(equalTo: bodyView.trailingAnchor, constant: -48.0).isActive = true
}
private func setupInstructionOne() {
instructionsStackView.addArrangedSubview(instructionOneView)
instructionOneView.leadingAnchor.constraint(equalTo: instructionsStackView.leadingAnchor).isActive = true
instructionOneView.trailingAnchor.constraint(equalTo: instructionsStackView.trailingAnchor).isActive = true
instructionOneView.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
instructionOneView.addSubview(instructionOneNumberView)
instructionOneNumberView.centerYAnchor.constraint(equalTo: instructionOneView.centerYAnchor).isActive = true
instructionOneNumberView.leadingAnchor.constraint(equalTo: instructionOneView.leadingAnchor).isActive = true
instructionOneNumberView.heightAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionOneNumberView.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionOneNumberView.addSubview(instructionOneNumberLabel)
instructionOneNumberLabel.centerXAnchor.constraint(equalTo: instructionOneNumberView.centerXAnchor).isActive = true
instructionOneNumberLabel.centerYAnchor.constraint(equalTo: instructionOneNumberView.centerYAnchor).isActive = true
instructionOneView.addSubview(instructionOneTitleLabel)
instructionOneTitleLabel.centerYAnchor.constraint(equalTo: instructionOneView.centerYAnchor).isActive = true
instructionOneTitleLabel.leadingAnchor.constraint(equalTo: instructionOneNumberView.trailingAnchor, constant: 8.0).isActive = true
instructionOneTitleLabel.trailingAnchor.constraint(equalTo: instructionOneView.trailingAnchor).isActive = true
instructionOneTitleLabel.text = instructions.instructionOne
}
private func setupInstructionTwo() {
instructionsStackView.addArrangedSubview(instructionTwoView)
instructionTwoView.leadingAnchor.constraint(equalTo: instructionsStackView.leadingAnchor).isActive = true
instructionTwoView.trailingAnchor.constraint(equalTo: instructionsStackView.trailingAnchor).isActive = true
instructionTwoView.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
instructionTwoView.addSubview(instructionTwoNumberView)
instructionTwoNumberView.centerYAnchor.constraint(equalTo: instructionTwoView.centerYAnchor).isActive = true
instructionTwoNumberView.leadingAnchor.constraint(equalTo: instructionTwoView.leadingAnchor).isActive = true
instructionTwoNumberView.heightAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionTwoNumberView.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionTwoNumberView.addSubview(instructionTwoNumberLabel)
instructionTwoNumberLabel.centerXAnchor.constraint(equalTo: instructionTwoNumberView.centerXAnchor).isActive = true
instructionTwoNumberLabel.centerYAnchor.constraint(equalTo: instructionTwoNumberView.centerYAnchor).isActive = true
instructionTwoView.addSubview(instructionTwoTitleLabel)
instructionTwoTitleLabel.centerYAnchor.constraint(equalTo: instructionTwoView.centerYAnchor).isActive = true
instructionTwoTitleLabel.leadingAnchor.constraint(equalTo: instructionTwoNumberView.trailingAnchor, constant: 8.0).isActive = true
instructionTwoTitleLabel.trailingAnchor.constraint(equalTo: instructionTwoView.trailingAnchor).isActive = true
instructionTwoTitleLabel.text = instructions.instructionTwo
}
private func setupInstructionThree() {
instructionsStackView.addArrangedSubview(instructionThreeView)
instructionThreeView.leadingAnchor.constraint(equalTo: instructionsStackView.leadingAnchor).isActive = true
instructionThreeView.trailingAnchor.constraint(equalTo: instructionsStackView.trailingAnchor).isActive = true
instructionThreeView.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
instructionThreeView.addSubview(instructionThreeNumberView)
instructionThreeNumberView.centerYAnchor.constraint(equalTo: instructionThreeView.centerYAnchor).isActive = true
instructionThreeNumberView.leadingAnchor.constraint(equalTo: instructionThreeView.leadingAnchor).isActive = true
instructionThreeNumberView.heightAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionThreeNumberView.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionThreeNumberView.addSubview(instructionThreeNumberLabel)
instructionThreeNumberLabel.centerXAnchor.constraint(equalTo: instructionThreeNumberView.centerXAnchor).isActive = true
instructionThreeNumberLabel.centerYAnchor.constraint(equalTo: instructionThreeNumberView.centerYAnchor).isActive = true
instructionThreeView.addSubview(instructionThreeTitleLabel)
instructionThreeTitleLabel.centerYAnchor.constraint(equalTo: instructionThreeView.centerYAnchor).isActive = true
instructionThreeTitleLabel.leadingAnchor.constraint(equalTo: instructionThreeNumberView.trailingAnchor, constant: 8.0).isActive = true
instructionThreeTitleLabel.trailingAnchor.constraint(equalTo: instructionThreeView.trailingAnchor).isActive = true
instructionThreeTitleLabel.text = instructions.instructionThree
}
private func setupInstructionFour() {
instructionsStackView.addArrangedSubview(instructionFourView)
instructionFourView.leadingAnchor.constraint(equalTo: instructionsStackView.leadingAnchor).isActive = true
instructionFourView.trailingAnchor.constraint(equalTo: instructionsStackView.trailingAnchor).isActive = true
instructionFourView.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
instructionFourView.addSubview(instructionFourNumberView)
instructionFourNumberView.centerYAnchor.constraint(equalTo: instructionFourView.centerYAnchor).isActive = true
instructionFourNumberView.leadingAnchor.constraint(equalTo: instructionFourView.leadingAnchor).isActive = true
instructionFourNumberView.heightAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionFourNumberView.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionFourNumberView.addSubview(instructionFourNumberLabel)
instructionFourNumberLabel.centerXAnchor.constraint(equalTo: instructionFourNumberView.centerXAnchor).isActive = true
instructionFourNumberLabel.centerYAnchor.constraint(equalTo: instructionFourNumberView.centerYAnchor).isActive = true
instructionFourView.addSubview(instructionFourTitleLabel)
instructionFourTitleLabel.centerYAnchor.constraint(equalTo: instructionFourView.centerYAnchor).isActive = true
instructionFourTitleLabel.leadingAnchor.constraint(equalTo: instructionFourNumberView.trailingAnchor, constant: 8.0).isActive = true
instructionFourTitleLabel.trailingAnchor.constraint(equalTo: instructionFourView.trailingAnchor).isActive = true
instructionFourTitleLabel.text = instructions.instructionFour
}
private func setupInstructionFive() {
instructionsStackView.addArrangedSubview(instructionFiveView)
instructionFiveView.leadingAnchor.constraint(equalTo: instructionsStackView.leadingAnchor).isActive = true
instructionFiveView.trailingAnchor.constraint(equalTo: instructionsStackView.trailingAnchor).isActive = true
instructionFiveView.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
instructionFiveView.isHidden = instructions.instructionFiveIsHidden
instructionFiveView.addSubview(instructionFiveNumberView)
instructionFiveNumberView.centerYAnchor.constraint(equalTo: instructionFiveView.centerYAnchor).isActive = true
instructionFiveNumberView.leadingAnchor.constraint(equalTo: instructionFiveView.leadingAnchor).isActive = true
instructionFiveNumberView.heightAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionFiveNumberView.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
instructionFiveNumberView.addSubview(instructionFiveNumberLabel)
instructionFiveNumberLabel.centerXAnchor.constraint(equalTo: instructionFiveNumberView.centerXAnchor).isActive = true
instructionFiveNumberLabel.centerYAnchor.constraint(equalTo: instructionFiveNumberView.centerYAnchor).isActive = true
instructionFiveView.addSubview(instructionFiveTitleLabel)
instructionFiveTitleLabel.centerYAnchor.constraint(equalTo: instructionFiveView.centerYAnchor).isActive = true
instructionFiveTitleLabel.leadingAnchor.constraint(equalTo: instructionFiveNumberView.trailingAnchor, constant: 8.0).isActive = true
instructionFiveTitleLabel.trailingAnchor.constraint(equalTo: instructionFiveView.trailingAnchor).isActive = true
instructionFiveTitleLabel.text = instructions.instructionFive
}
private func setupLetsGoButton() {
bodyView.addSubview(letsGoButton)
letsGoButton.centerXAnchor.constraint(equalTo: bodyView.centerXAnchor).isActive = true
letsGoButton.bottomAnchor.constraint(equalTo: bodyView.bottomAnchor, constant: -72.0).isActive = true
letsGoButton.heightAnchor.constraint(equalToConstant: 42.0).isActive = true
letsGoButton.widthAnchor.constraint(equalToConstant: 150.0).isActive = true
}
private func setupActivityOverlayView() {
containerView.addSubview(viewActivityOverlay)
viewActivityOverlay.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
viewActivityOverlay.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
viewActivityOverlay.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
viewActivityOverlay.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
viewActivityOverlay.addSubview(activityIndicator)
activityIndicator.centerXAnchor.constraint(equalTo: viewActivityOverlay.centerXAnchor).isActive = true
activityIndicator.centerYAnchor.constraint(equalTo: viewActivityOverlay.centerYAnchor, constant: -60.0).isActive = true
}
private func setupUX() {
letsGoButton.addTarget(self, action: #selector(tappedLetsGoButton), for: .touchUpInside)
closeButton.addTarget(self, action: #selector(tappedCloseButton), for: .touchUpInside)
}
//MARK: - Functions
@objc private func tappedLetsGoButton() {
startDemo()
}
@objc private func tappedCloseButton() {
dismiss(animated: true)
}
private func startDemo() {
startCapture?()
}
private func showAlertError() {
let alertController = UIAlertController(title: "Ooops!", message: "Desculpe o transtorno, mas ocorreu um erro. Por favor, tente novamente.", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default) { (_) in
alertController.dismiss(animated: true)
}
alertController.addAction(alertAction)
present(alertController, animated: true)
}
private func getFullOCR() {
showHideActivityOverlay(show: true)
let dataArray = convertImageArrayToDataArray()
service.getFullOCR(dataArray: dataArray) { [weak self] result in
guard let self = self else { return }
self.showHideActivityOverlay(show: false)
guard let json = result else { return }
let successModel = SuccessOCRModel(isDocumentDetected: true, json: json)
DispatchQueue.main.async {
self.goToSuccessViewController(model: successModel)
}
}
}
private func goToSuccessViewController(model: SuccessOCRModel) {
let successViewController = SuccessViewController(model: model)
successViewController.delegate = self
present(successViewController, animated: true)
}
private func showHideActivityOverlay(show: Bool) {
DispatchQueue.main.async {
if show {
self.viewActivityOverlay.isHidden = false
self.activityIndicator.startAnimating()
} else {
self.viewActivityOverlay.isHidden = true
self.activityIndicator.stopAnimating()
}
}
}
private func convertImageArrayToDataArray() -> [Data] {
var dataArray = [Data]()
imageArray.forEach { image in
guard let imageData = image.jpegData(compressionQuality: 1.0) else { return }
dataArray.append(imageData)
}
return dataArray
}
}
//MARK: - LivenessCameraViewControllerDelegate
extension StartViewController: LivenessCameraViewControllerDelegate {
func completedLivenessProcessing(result: Result<[String: Any], SDKError>, image: UIImage?) {
self.dismiss(animated: true) {
switch result {
case .success(let livenessResult):
if let data = livenessResult["data"] as? [String: Any],
let isAlive = data["isAlive"] as? Bool {
if isAlive {
self.goToSuccessViewController(model: SuccessOCRModel(isDocumentDetected: false))
}
else {
let failureViewController = FailureViewController()
failureViewController.delegate = self
self.present(failureViewController, animated: true)
}
} else {
self.showAlertError()
}
case .failure(let error):
print(error)
self.showAlertError()
}
}
}
}
//MARK: - DocumentCameraViewControllerDelegate
extension StartViewController: DocumentCameraViewControllerDelegate {
func completedDocumentProcessing(documentResult: Result<[String: Any], SDKError>, image: UIImage?) {
dismiss(animated: true) {
switch documentResult {
case .success(let result):
if let data = result["data"] as? [[String: Any]] {
print(data)
}
guard let image = image else { return }
self.imageArray.append(image)
let otherSide = OtherSideDocumentViewController()
otherSide.delegate = self
self.present(otherSide, animated: true)
case .failure(let error):
print(error)
self.showAlertError()
}
}
}
}
// MARK: - SuccessViewControllerDelegate
extension StartViewController: SuccessViewControllerDelegate {
func successViewControllerMainAction() {
imageArray.removeAll()
dismiss(animated: true)
}
}
// MARK: - FailureViewControllerDelegate
extension StartViewController: FailureViewControllerDelegate {
func failureViewControllerMainAction() {
imageArray.removeAll()
dismiss(animated: true) {
self.startDemo()
}
}
}
// MARK: - OtherSideDocumentDelegate
extension StartViewController: OtherSideDocumentDelegate {
func captureOtherSideDocument() {
dismiss(animated: true) {
self.startDemo()
}
}
func noCaptureOtherSideDocument() {
dismiss(animated: true) {
self.getFullOCR()
}
}
}
| 44.106667 | 172 | 0.696594 |
8a8903980dba42af99d4192cadff411af9e94a0d | 3,095 | //
// ImageExtension.swift
// VideoGeneration
//
// Created by DevLabs BG on 25.10.17.
// Copyright © 2017 Devlabs. All rights reserved.
//
import UIKit
extension UIImage {
/// Method to scale an image to the given size while keeping the aspect ratio
///
/// - Parameter newSize: the new size for the image
/// - Returns: the resized image
func scaleImageToSize(newSize: CGSize) -> UIImage {
var scaledImageRect: CGRect = CGRect.zero
let aspectWidth: CGFloat = newSize.width / size.width
let aspectHeight: CGFloat = newSize.height / size.height
let aspectRatio: CGFloat = min(aspectWidth, aspectHeight)
scaledImageRect.size.width = size.width * aspectRatio
scaledImageRect.size.height = size.height * aspectRatio
scaledImageRect.origin.x = (newSize.width - scaledImageRect.size.width) / 2.0
scaledImageRect.origin.y = (newSize.height - scaledImageRect.size.height) / 2.0
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
draw(in: scaledImageRect)
let scaledImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return scaledImage
}
/// Method to get a size for the image appropriate for video (dividing by 16 without overlapping 1200)
///
/// - Returns: a size fit for video
func getSizeForVideo() -> CGSize {
let scale = UIScreen.main.scale
var imageWidth = 16 * ((size.width / scale) / 16).rounded(.awayFromZero)
var imageHeight = 16 * ((size.height / scale) / 16).rounded(.awayFromZero)
var ratio: CGFloat!
if imageWidth > 1400 {
ratio = 1400 / imageWidth
imageWidth = 16 * (imageWidth / 16).rounded(.towardZero) * ratio
imageHeight = 16 * (imageHeight / 16).rounded(.towardZero) * ratio
}
if imageWidth < 800 {
ratio = 800 / imageWidth
imageWidth = 16 * (imageWidth / 16).rounded(.awayFromZero) * ratio
imageHeight = 16 * (imageHeight / 16).rounded(.awayFromZero) * ratio
}
if imageHeight > 1200 {
ratio = 1200 / imageHeight
imageWidth = 16 * (imageWidth / 16).rounded(.towardZero) * ratio
imageHeight = 16 * (imageHeight / 16).rounded(.towardZero) * ratio
}
return CGSize(width: imageWidth, height: imageHeight)
}
/// Method to resize an image to an appropriate video size
///
/// - Returns: the resized image
func resizeImageToVideoSize() -> UIImage? {
let scale = UIScreen.main.scale
let videoImageSize = getSizeForVideo()
let imageRect = CGRect(x: 0, y: 0, width: videoImageSize.width * scale, height: videoImageSize.height * scale)
UIGraphicsBeginImageContextWithOptions(CGSize(width: imageRect.width, height: imageRect.height), false, scale)
if let _ = UIGraphicsGetCurrentContext() {
draw(in: imageRect, blendMode: .normal, alpha: 1)
if let resultImage = UIGraphicsGetImageFromCurrentImageContext() {
UIGraphicsEndImageContext()
return resultImage
} else {
return nil
}
} else {
return nil
}
}
}
| 33.27957 | 114 | 0.669144 |
71045c563418b17f641221da16312d6bbbd08fb1 | 3,114 | import Foundation
import Future
import BTKit
import RuuviOntology
/// https://docs.ruuvi.com/communication/ruuvi-network/backends/serverless/user-api
protocol RuuviCloudApi {
func register(
_ requestModel: RuuviCloudApiRegisterRequest
) -> Future<RuuviCloudApiRegisterResponse, RuuviCloudApiError>
func verify(
_ requestModel: RuuviCloudApiVerifyRequest
) -> Future<RuuviCloudApiVerifyResponse, RuuviCloudApiError>
func claim(
_ requestModel: RuuviCloudApiClaimRequest,
authorization: String
) -> Future<RuuviCloudApiClaimResponse, RuuviCloudApiError>
func unclaim(
_ requestModel: RuuviCloudApiClaimRequest,
authorization: String
) -> Future<RuuviCloudApiUnclaimResponse, RuuviCloudApiError>
func share(
_ requestModel: RuuviCloudApiShareRequest,
authorization: String
) -> Future<RuuviCloudApiShareResponse, RuuviCloudApiError>
func unshare(
_ requestModel: RuuviCloudApiShareRequest,
authorization: String
) -> Future<RuuviCloudApiUnshareResponse, RuuviCloudApiError>
func sensors(
_ requestModel: RuuviCloudApiGetSensorsRequest,
authorization: String
) -> Future<RuuviCloudApiGetSensorsResponse, RuuviCloudApiError>
func user(
authorization: String
) -> Future<RuuviCloudApiUserResponse, RuuviCloudApiError>
func getSensorData(
_ requestModel: RuuviCloudApiGetSensorRequest,
authorization: String
) -> Future<RuuviCloudApiGetSensorResponse, RuuviCloudApiError>
func update(
_ requestModel: RuuviCloudApiSensorUpdateRequest,
authorization: String
) -> Future<RuuviCloudApiSensorUpdateResponse, RuuviCloudApiError>
func uploadImage(
_ requestModel: RuuviCloudApiSensorImageUploadRequest,
imageData: Data,
authorization: String,
uploadProgress: ((Double) -> Void)?
) -> Future<RuuviCloudApiSensorImageUploadResponse, RuuviCloudApiError>
func resetImage(
_ requestModel: RuuviCloudApiSensorImageUploadRequest,
authorization: String
) -> Future<RuuviCloudApiSensorImageResetResponse, RuuviCloudApiError>
func getSettings(
_ requestModel: RuuviCloudApiGetSettingsRequest,
authorization: String
) -> Future<RuuviCloudApiGetSettingsResponse, RuuviCloudApiError>
func postSetting(
_ requestModel: RuuviCloudApiPostSettingRequest,
authorization: String
) -> Future<RuuviCloudApiPostSettingResponse, RuuviCloudApiError>
func postAlert(
_ requestModel: RuuviCloudApiPostAlertRequest,
authorization: String
) -> Future<RuuviCloudApiPostAlertResponse, RuuviCloudApiError>
func getAlerts(
_ requestModel: RuuviCloudApiGetAlertsRequest,
authorization: String
) -> Future<RuuviCloudApiGetAlertsResponse, RuuviCloudApiError>
}
protocol RuuviCloudApiFactory {
func create(baseUrl: URL) -> RuuviCloudApi
}
public enum MimeType: String, Encodable {
case png = "image/png"
case gif = "image/gif"
case jpg = "image/jpeg"
}
| 32.103093 | 83 | 0.73282 |
9b4eb885bc5bd57ab8f126206faeed0fdffbd3d4 | 31,046 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import _NIODataStructures
import NIOCore
private final class EmbeddedScheduledTask {
let task: () -> Void
let readyTime: NIODeadline
let insertOrder: UInt64
init(readyTime: NIODeadline, insertOrder: UInt64, task: @escaping () -> Void) {
self.readyTime = readyTime
self.insertOrder = insertOrder
self.task = task
}
}
extension EmbeddedScheduledTask: Comparable {
static func < (lhs: EmbeddedScheduledTask, rhs: EmbeddedScheduledTask) -> Bool {
if lhs.readyTime == rhs.readyTime {
return lhs.insertOrder < rhs.insertOrder
} else {
return lhs.readyTime < rhs.readyTime
}
}
static func == (lhs: EmbeddedScheduledTask, rhs: EmbeddedScheduledTask) -> Bool {
return lhs === rhs
}
}
/// An `EventLoop` that is embedded in the current running context with no external
/// control.
///
/// Unlike more complex `EventLoop`s, such as `SelectableEventLoop`, the `EmbeddedEventLoop`
/// has no proper eventing mechanism. Instead, reads and writes are fully controlled by the
/// entity that instantiates the `EmbeddedEventLoop`. This property makes `EmbeddedEventLoop`
/// of limited use for many application purposes, but highly valuable for testing and other
/// kinds of mocking.
///
/// Time is controllable on an `EmbeddedEventLoop`. It begins at `NIODeadline.uptimeNanoseconds(0)`
/// and may be advanced by a fixed amount by using `advanceTime(by:)`, or advanced to a point in
/// time with `advanceTime(to:)`.
///
/// - warning: Unlike `SelectableEventLoop`, `EmbeddedEventLoop` **is not thread-safe**. This
/// is because it is intended to be run in the thread that instantiated it. Users are
/// responsible for ensuring they never call into the `EmbeddedEventLoop` in an
/// unsynchronized fashion.
public final class EmbeddedEventLoop: EventLoop {
/// The current "time" for this event loop. This is an amount in nanoseconds.
/* private but tests */ internal var _now: NIODeadline = .uptimeNanoseconds(0)
private var scheduledTasks = PriorityQueue<EmbeddedScheduledTask>()
/// Keep track of where promises are allocated to ensure we can identify their source if they leak.
private var _promiseCreationStore: [_NIOEventLoopFutureIdentifier: (file: StaticString, line: UInt)] = [:]
// The number of the next task to be created. We track the order so that when we execute tasks
// scheduled at the same time, we may do so in the order in which they were submitted for
// execution.
private var taskNumber: UInt64 = 0
private func nextTaskNumber() -> UInt64 {
defer {
self.taskNumber += 1
}
return self.taskNumber
}
/// - see: `EventLoop.inEventLoop`
public var inEventLoop: Bool {
return true
}
/// Initialize a new `EmbeddedEventLoop`.
public init() { }
/// - see: `EventLoop.scheduleTask(deadline:_:)`
@discardableResult
public func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> {
let promise: EventLoopPromise<T> = makePromise()
let task = EmbeddedScheduledTask(readyTime: deadline, insertOrder: self.nextTaskNumber()) {
do {
promise.succeed(try task())
} catch let err {
promise.fail(err)
}
}
let scheduled = Scheduled(promise: promise, cancellationTask: {
self.scheduledTasks.remove(task)
})
scheduledTasks.push(task)
return scheduled
}
/// - see: `EventLoop.scheduleTask(in:_:)`
@discardableResult
public func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> {
return scheduleTask(deadline: self._now + `in`, task)
}
/// On an `EmbeddedEventLoop`, `execute` will simply use `scheduleTask` with a deadline of _now_. This means that
/// `task` will be run the next time you call `EmbeddedEventLoop.run`.
public func execute(_ task: @escaping () -> Void) {
self.scheduleTask(deadline: self._now, task)
}
/// Run all tasks that have previously been submitted to this `EmbeddedEventLoop`, either by calling `execute` or
/// events that have been enqueued using `scheduleTask`/`scheduleRepeatedTask`/`scheduleRepeatedAsyncTask` and whose
/// deadlines have expired.
///
/// - seealso: `EmbeddedEventLoop.advanceTime`.
public func run() {
// Execute all tasks that are currently enqueued to be executed *now*.
self.advanceTime(to: self._now)
}
/// Runs the event loop and moves "time" forward by the given amount, running any scheduled
/// tasks that need to be run.
public func advanceTime(by increment: TimeAmount) {
self.advanceTime(to: self._now + increment)
}
/// Runs the event loop and moves "time" forward to the given point in time, running any scheduled
/// tasks that need to be run.
///
/// - Note: If `deadline` is before the current time, the current time will not be advanced.
public func advanceTime(to deadline: NIODeadline) {
let newTime = max(deadline, self._now)
while let nextTask = self.scheduledTasks.peek() {
guard nextTask.readyTime <= newTime else {
break
}
// Now we want to grab all tasks that are ready to execute at the same
// time as the first.
var tasks = Array<EmbeddedScheduledTask>()
while let candidateTask = self.scheduledTasks.peek(), candidateTask.readyTime == nextTask.readyTime {
tasks.append(candidateTask)
self.scheduledTasks.pop()
}
// Set the time correctly before we call into user code, then
// call in for all tasks.
self._now = nextTask.readyTime
for task in tasks {
task.task()
}
}
// Finally ensure we got the time right.
self._now = newTime
}
internal func drainScheduledTasksByRunningAllCurrentlyScheduledTasks() {
var currentlyScheduledTasks = self.scheduledTasks
while let nextTask = currentlyScheduledTasks.pop() {
self._now = nextTask.readyTime
nextTask.task()
}
// Just drop all the remaining scheduled tasks. Despite having run all the tasks that were
// scheduled when we entered the method this may still contain tasks as running the tasks
// may have enqueued more tasks.
while self.scheduledTasks.pop() != nil {}
}
/// - see: `EventLoop.close`
func close() throws {
// Nothing to do here
}
/// - see: `EventLoop.shutdownGracefully`
public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) {
run()
queue.sync {
callback(nil)
}
}
public func _preconditionSafeToWait(file: StaticString, line: UInt) {
// EmbeddedEventLoop always allows a wait, as waiting will essentially always block
// wait()
return
}
public func _promiseCreated(futureIdentifier: _NIOEventLoopFutureIdentifier, file: StaticString, line: UInt) {
precondition(_isDebugAssertConfiguration())
self._promiseCreationStore[futureIdentifier] = (file: file, line: line)
}
public func _promiseCompleted(futureIdentifier: _NIOEventLoopFutureIdentifier) -> (file: StaticString, line: UInt)? {
precondition(_isDebugAssertConfiguration())
return self._promiseCreationStore.removeValue(forKey: futureIdentifier)
}
public func _preconditionSafeToSyncShutdown(file: StaticString, line: UInt) {
// EmbeddedEventLoop always allows a sync shutdown.
return
}
deinit {
precondition(scheduledTasks.isEmpty, "Embedded event loop freed with unexecuted scheduled tasks!")
}
}
@usableFromInline
class EmbeddedChannelCore: ChannelCore {
var isOpen: Bool = true
var isActive: Bool = false
var eventLoop: EventLoop
var closePromise: EventLoopPromise<Void>
var error: Optional<Error>
private let pipeline: ChannelPipeline
init(pipeline: ChannelPipeline, eventLoop: EventLoop) {
closePromise = eventLoop.makePromise()
self.pipeline = pipeline
self.eventLoop = eventLoop
self.error = nil
}
deinit {
assert(!self.isOpen && !self.isActive,
"leaked an open EmbeddedChannel, maybe forgot to call channel.finish()?")
isOpen = false
closePromise.succeed(())
}
/// Contains the flushed items that went into the `Channel` (and on a regular channel would have hit the network).
@usableFromInline
var outboundBuffer: CircularBuffer<NIOAny> = CircularBuffer()
/// Contains the unflushed items that went into the `Channel`
@usableFromInline
var pendingOutboundBuffer: MarkedCircularBuffer<(NIOAny, EventLoopPromise<Void>?)> = MarkedCircularBuffer(initialCapacity: 16)
/// Contains the items that travelled the `ChannelPipeline` all the way and hit the tail channel handler. On a
/// regular `Channel` these items would be lost.
@usableFromInline
var inboundBuffer: CircularBuffer<NIOAny> = CircularBuffer()
@usableFromInline
func localAddress0() throws -> SocketAddress {
throw ChannelError.operationUnsupported
}
@usableFromInline
func remoteAddress0() throws -> SocketAddress {
throw ChannelError.operationUnsupported
}
@usableFromInline
func close0(error: Error, mode: CloseMode, promise: EventLoopPromise<Void>?) {
guard self.isOpen else {
promise?.fail(ChannelError.alreadyClosed)
return
}
isOpen = false
isActive = false
promise?.succeed(())
// As we called register() in the constructor of EmbeddedChannel we also need to ensure we call unregistered here.
self.pipeline.syncOperations.fireChannelInactive()
self.pipeline.syncOperations.fireChannelUnregistered()
eventLoop.execute {
// ensure this is executed in a delayed fashion as the users code may still traverse the pipeline
self.removeHandlers(pipeline: self.pipeline)
self.closePromise.succeed(())
}
}
@usableFromInline
func bind0(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
promise?.succeed(())
}
@usableFromInline
func connect0(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
isActive = true
promise?.succeed(())
self.pipeline.syncOperations.fireChannelActive()
}
@usableFromInline
func register0(promise: EventLoopPromise<Void>?) {
promise?.succeed(())
self.pipeline.syncOperations.fireChannelRegistered()
}
@usableFromInline
func registerAlreadyConfigured0(promise: EventLoopPromise<Void>?) {
isActive = true
register0(promise: promise)
self.pipeline.syncOperations.fireChannelActive()
}
@usableFromInline
func write0(_ data: NIOAny, promise: EventLoopPromise<Void>?) {
self.pendingOutboundBuffer.append((data, promise))
}
@usableFromInline
func flush0() {
self.pendingOutboundBuffer.mark()
while self.pendingOutboundBuffer.hasMark, let dataAndPromise = self.pendingOutboundBuffer.popFirst() {
self.addToBuffer(buffer: &self.outboundBuffer, data: dataAndPromise.0)
dataAndPromise.1?.succeed(())
}
}
@usableFromInline
func read0() {
// NOOP
}
public final func triggerUserOutboundEvent0(_ event: Any, promise: EventLoopPromise<Void>?) {
promise?.fail(ChannelError.operationUnsupported)
}
@usableFromInline
func channelRead0(_ data: NIOAny) {
addToBuffer(buffer: &inboundBuffer, data: data)
}
public func errorCaught0(error: Error) {
if self.error == nil {
self.error = error
}
}
private func addToBuffer<T>(buffer: inout CircularBuffer<T>, data: T) {
buffer.append(data)
}
}
/// `EmbeddedChannel` is a `Channel` implementation that does neither any
/// actual IO nor has a proper eventing mechanism. The prime use-case for
/// `EmbeddedChannel` is in unit tests when you want to feed the inbound events
/// and check the outbound events manually.
///
/// Please remember to call `finish()` when you are no longer using this
/// `EmbeddedChannel`.
///
/// To feed events through an `EmbeddedChannel`'s `ChannelPipeline` use
/// `EmbeddedChannel.writeInbound` which accepts data of any type. It will then
/// forward that data through the `ChannelPipeline` and the subsequent
/// `ChannelInboundHandler` will receive it through the usual `channelRead`
/// event. The user is responsible for making sure the first
/// `ChannelInboundHandler` expects data of that type.
///
/// `EmbeddedChannel` automatically collects arriving outbound data and makes it
/// available one-by-one through `readOutbound`.
///
/// - note: `EmbeddedChannel` is currently only compatible with
/// `EmbeddedEventLoop`s and cannot be used with `SelectableEventLoop`s from
/// for example `MultiThreadedEventLoopGroup`.
/// - warning: Unlike other `Channel`s, `EmbeddedChannel` **is not thread-safe**. This
/// is because it is intended to be run in the thread that instantiated it. Users are
/// responsible for ensuring they never call into an `EmbeddedChannel` in an
/// unsynchronized fashion. `EmbeddedEventLoop`s notes also apply as
/// `EmbeddedChannel` uses an `EmbeddedEventLoop` as its `EventLoop`.
public final class EmbeddedChannel: Channel {
/// `LeftOverState` represents any left-over inbound, outbound, and pending outbound events that hit the
/// `EmbeddedChannel` and were not consumed when `finish` was called on the `EmbeddedChannel`.
///
/// `EmbeddedChannel` is most useful in testing and usually in unit tests, you want to consume all inbound and
/// outbound data to verify they are what you expect. Therefore, when you `finish` an `EmbeddedChannel` it will
/// return if it's either `.clean` (no left overs) or that it has `.leftOvers`.
public enum LeftOverState {
/// The `EmbeddedChannel` is clean, ie. no inbound, outbound, or pending outbound data left on `finish`.
case clean
/// The `EmbeddedChannel` has inbound, outbound, or pending outbound data left on `finish`.
case leftOvers(inbound: [NIOAny], outbound: [NIOAny], pendingOutbound: [NIOAny])
/// `true` if the `EmbeddedChannel` was `clean` on `finish`, ie. there is no unconsumed inbound, outbound, or
/// pending outbound data left on the `Channel`.
public var isClean: Bool {
if case .clean = self {
return true
} else {
return false
}
}
/// `true` if the `EmbeddedChannel` if there was unconsumed inbound, outbound, or pending outbound data left
/// on the `Channel` when it was `finish`ed.
public var hasLeftOvers: Bool {
return !self.isClean
}
}
/// `BufferState` represents the state of either the inbound, or the outbound `EmbeddedChannel` buffer. These
/// buffers contain data that travelled the `ChannelPipeline` all the way.
///
/// If the last `ChannelHandler` explicitly (by calling `fireChannelRead`) or implicitly (by not implementing
/// `channelRead`) sends inbound data into the end of the `EmbeddedChannel`, it will be held in the
/// `EmbeddedChannel`'s inbound buffer. Similarly for `write` on the outbound side. The state of the respective
/// buffer will be returned from `writeInbound`/`writeOutbound` as a `BufferState`.
public enum BufferState {
/// The buffer is empty.
case empty
/// The buffer is non-empty.
case full([NIOAny])
/// Returns `true` is the buffer was empty.
public var isEmpty: Bool {
if case .empty = self {
return true
} else {
return false
}
}
/// Returns `true` if the buffer was non-empty.
public var isFull: Bool {
return !self.isEmpty
}
}
/// `WrongTypeError` is throws if you use `readInbound` or `readOutbound` and request a certain type but the first
/// item in the respective buffer is of a different type.
public struct WrongTypeError: Error, Equatable {
/// The type you expected.
public let expected: Any.Type
/// The type of the actual first element.
public let actual: Any.Type
public init(expected: Any.Type, actual: Any.Type) {
self.expected = expected
self.actual = actual
}
public static func == (lhs: WrongTypeError, rhs: WrongTypeError) -> Bool {
return lhs.expected == rhs.expected && lhs.actual == rhs.actual
}
}
/// Returns `true` if the `EmbeddedChannel` is 'active'.
///
/// An active `EmbeddedChannel` can be closed by calling `close` or `finish` on the `EmbeddedChannel`.
///
/// - note: An `EmbeddedChannel` starts _inactive_ and can be activated, for example by calling `connect`.
public var isActive: Bool { return channelcore.isActive }
/// - see: `Channel.closeFuture`
public var closeFuture: EventLoopFuture<Void> { return channelcore.closePromise.futureResult }
@usableFromInline
/*private but usableFromInline */ lazy var channelcore: EmbeddedChannelCore = EmbeddedChannelCore(pipeline: self._pipeline, eventLoop: self.eventLoop)
/// - see: `Channel._channelCore`
public var _channelCore: ChannelCore {
return channelcore
}
/// - see: `Channel.pipeline`
public var pipeline: ChannelPipeline {
return _pipeline
}
/// - see: `Channel.isWritable`
public var isWritable: Bool = true
/// Synchronously closes the `EmbeddedChannel`.
///
/// Errors in the `EmbeddedChannel` can be consumed using `throwIfErrorCaught`.
///
/// - parameters:
/// - acceptAlreadyClosed: Whether `finish` should throw if the `EmbeddedChannel` has been previously `close`d.
/// - returns: The `LeftOverState` of the `EmbeddedChannel`. If all the inbound and outbound events have been
/// consumed (using `readInbound` / `readOutbound`) and there are no pending outbound events (unflushed
/// writes) this will be `.clean`. If there are any unconsumed inbound, outbound, or pending outbound
/// events, the `EmbeddedChannel` will returns those as `.leftOvers(inbound:outbound:pendingOutbound:)`.
public func finish(acceptAlreadyClosed: Bool) throws -> LeftOverState {
do {
try close().wait()
} catch let error as ChannelError {
guard error == .alreadyClosed && acceptAlreadyClosed else {
throw error
}
}
self.embeddedEventLoop.drainScheduledTasksByRunningAllCurrentlyScheduledTasks()
self.embeddedEventLoop.run()
try throwIfErrorCaught()
let c = self.channelcore
if c.outboundBuffer.isEmpty && c.inboundBuffer.isEmpty && c.pendingOutboundBuffer.isEmpty {
return .clean
} else {
return .leftOvers(inbound: Array(c.inboundBuffer),
outbound: Array(c.outboundBuffer),
pendingOutbound: c.pendingOutboundBuffer.map { $0.0 })
}
}
/// Synchronously closes the `EmbeddedChannel`.
///
/// This method will throw if the `Channel` hit any unconsumed errors or if the `close` fails. Errors in the
/// `EmbeddedChannel` can be consumed using `throwIfErrorCaught`.
///
/// - returns: The `LeftOverState` of the `EmbeddedChannel`. If all the inbound and outbound events have been
/// consumed (using `readInbound` / `readOutbound`) and there are no pending outbound events (unflushed
/// writes) this will be `.clean`. If there are any unconsumed inbound, outbound, or pending outbound
/// events, the `EmbeddedChannel` will returns those as `.leftOvers(inbound:outbound:pendingOutbound:)`.
public func finish() throws -> LeftOverState {
return try self.finish(acceptAlreadyClosed: false)
}
private var _pipeline: ChannelPipeline!
/// - see: `Channel.allocator`
public var allocator: ByteBufferAllocator = ByteBufferAllocator()
/// - see: `Channel.eventLoop`
public var eventLoop: EventLoop {
return self.embeddedEventLoop
}
/// Returns the `EmbeddedEventLoop` that this `EmbeddedChannel` uses. This will return the same instance as
/// `EmbeddedChannel.eventLoop` but as the concrete `EmbeddedEventLoop` rather than as `EventLoop` existential.
public var embeddedEventLoop: EmbeddedEventLoop = EmbeddedEventLoop()
/// - see: `Channel.localAddress`
public var localAddress: SocketAddress? = nil
/// - see: `Channel.remoteAddress`
public var remoteAddress: SocketAddress? = nil
/// `nil` because `EmbeddedChannel`s don't have parents.
public let parent: Channel? = nil
/// If available, this method reads one element of type `T` out of the `EmbeddedChannel`'s outbound buffer. If the
/// first element was of a different type than requested, `EmbeddedChannel.WrongTypeError` will be thrown, if there
/// are no elements in the outbound buffer, `nil` will be returned.
///
/// Data hits the `EmbeddedChannel`'s outbound buffer when data was written using `write`, then `flush`ed, and
/// then travelled the `ChannelPipeline` all the way too the front. For data to hit the outbound buffer, the very
/// first `ChannelHandler` must have written and flushed it either explicitly (by calling
/// `ChannelHandlerContext.write` and `flush`) or implicitly by not implementing `write`/`flush`.
///
/// - note: Outbound events travel the `ChannelPipeline` _back to front_.
/// - note: `EmbeddedChannel.writeOutbound` will `write` data through the `ChannelPipeline`, starting with last
/// `ChannelHandler`.
@inlinable
public func readOutbound<T>(as type: T.Type = T.self) throws -> T? {
return try _readFromBuffer(buffer: &channelcore.outboundBuffer)
}
/// If available, this method reads one element of type `T` out of the `EmbeddedChannel`'s inbound buffer. If the
/// first element was of a different type than requested, `EmbeddedChannel.WrongTypeError` will be thrown, if there
/// are no elements in the outbound buffer, `nil` will be returned.
///
/// Data hits the `EmbeddedChannel`'s inbound buffer when data was send through the pipeline using `fireChannelRead`
/// and then travelled the `ChannelPipeline` all the way too the back. For data to hit the inbound buffer, the
/// last `ChannelHandler` must have send the event either explicitly (by calling
/// `ChannelHandlerContext.fireChannelRead`) or implicitly by not implementing `channelRead`.
///
/// - note: `EmbeddedChannel.writeInbound` will fire data through the `ChannelPipeline` using `fireChannelRead`.
@inlinable
public func readInbound<T>(as type: T.Type = T.self) throws -> T? {
return try _readFromBuffer(buffer: &channelcore.inboundBuffer)
}
/// Sends an inbound `channelRead` event followed by a `channelReadComplete` event through the `ChannelPipeline`.
///
/// The immediate effect being that the first `ChannelInboundHandler` will get its `channelRead` method called
/// with the data you provide.
///
/// - parameters:
/// - data: The data to fire through the pipeline.
/// - returns: The state of the inbound buffer which contains all the events that travelled the `ChannelPipeline`
// all the way.
@inlinable
@discardableResult public func writeInbound<T>(_ data: T) throws -> BufferState {
pipeline.fireChannelRead(NIOAny(data))
pipeline.fireChannelReadComplete()
try throwIfErrorCaught()
return self.channelcore.inboundBuffer.isEmpty ? .empty : .full(Array(self.channelcore.inboundBuffer))
}
/// Sends an outbound `writeAndFlush` event through the `ChannelPipeline`.
///
/// The immediate effect being that the first `ChannelOutboundHandler` will get its `write` method called
/// with the data you provide. Note that the first `ChannelOutboundHandler` in the pipeline is the _last_ handler
/// because outbound events travel the pipeline from back to front.
///
/// - parameters:
/// - data: The data to fire through the pipeline.
/// - returns: The state of the outbound buffer which contains all the events that travelled the `ChannelPipeline`
// all the way.
@inlinable
@discardableResult public func writeOutbound<T>(_ data: T) throws -> BufferState {
try writeAndFlush(NIOAny(data)).wait()
return self.channelcore.outboundBuffer.isEmpty ? .empty : .full(Array(self.channelcore.outboundBuffer))
}
/// This method will throw the error that is stored in the `EmbeddedChannel` if any.
///
/// The `EmbeddedChannel` will store an error some error travels the `ChannelPipeline` all the way past its end.
public func throwIfErrorCaught() throws {
if let error = channelcore.error {
channelcore.error = nil
throw error
}
}
@inlinable
func _readFromBuffer<T>(buffer: inout CircularBuffer<NIOAny>) throws -> T? {
if buffer.isEmpty {
return nil
}
let elem = buffer.removeFirst()
guard let t = self._channelCore.tryUnwrapData(elem, as: T.self) else {
throw WrongTypeError(expected: T.self, actual: type(of: self._channelCore.tryUnwrapData(elem, as: Any.self)!))
}
return t
}
/// Create a new instance.
///
/// During creation it will automatically also register itself on the `EmbeddedEventLoop`.
///
/// - parameters:
/// - handler: The `ChannelHandler` to add to the `ChannelPipeline` before register or `nil` if none should be added.
/// - loop: The `EmbeddedEventLoop` to use.
public convenience init(handler: ChannelHandler? = nil, loop: EmbeddedEventLoop = EmbeddedEventLoop()) {
let handlers = handler.map { [$0] } ?? []
self.init(handlers: handlers, loop: loop)
}
/// Create a new instance.
///
/// During creation it will automatically also register itself on the `EmbeddedEventLoop`.
///
/// - parameters:
/// - handlers: The `ChannelHandler`s to add to the `ChannelPipeline` before register.
/// - loop: The `EmbeddedEventLoop` to use.
public init(handlers: [ChannelHandler], loop: EmbeddedEventLoop = EmbeddedEventLoop()) {
self.embeddedEventLoop = loop
self._pipeline = ChannelPipeline(channel: self)
try! self._pipeline.syncOperations.addHandlers(handlers)
// This will never throw...
try! register().wait()
}
/// - see: `Channel.setOption`
@inlinable
public func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> EventLoopFuture<Void> {
self.setOptionSync(option, value: value)
return self.eventLoop.makeSucceededVoidFuture()
}
@inlinable
internal func setOptionSync<Option: ChannelOption>(_ option: Option, value: Option.Value) {
// No options supported
fatalError("no options supported")
}
/// - see: `Channel.getOption`
@inlinable
public func getOption<Option: ChannelOption>(_ option: Option) -> EventLoopFuture<Option.Value> {
return self.eventLoop.makeSucceededFuture(self.getOptionSync(option))
}
@inlinable
internal func getOptionSync<Option: ChannelOption>(_ option: Option) -> Option.Value {
if option is ChannelOptions.Types.AutoReadOption {
return true as! Option.Value
}
fatalError("option \(option) not supported")
}
/// Fires the (outbound) `bind` event through the `ChannelPipeline`. If the event hits the `EmbeddedChannel` which
/// happens when it travels the `ChannelPipeline` all the way to the front, this will also set the
/// `EmbeddedChannel`'s `localAddress`.
///
/// - parameters:
/// - address: The address to fake-bind to.
/// - promise: The `EventLoopPromise` which will be fulfilled when the fake-bind operation has been done.
public func bind(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
promise?.futureResult.whenSuccess {
self.localAddress = address
}
pipeline.bind(to: address, promise: promise)
}
/// Fires the (outbound) `connect` event through the `ChannelPipeline`. If the event hits the `EmbeddedChannel`
/// which happens when it travels the `ChannelPipeline` all the way to the front, this will also set the
/// `EmbeddedChannel`'s `remoteAddress`.
///
/// - parameters:
/// - address: The address to fake-bind to.
/// - promise: The `EventLoopPromise` which will be fulfilled when the fake-bind operation has been done.
public func connect(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
promise?.futureResult.whenSuccess {
self.remoteAddress = address
}
pipeline.connect(to: address, promise: promise)
}
}
extension EmbeddedChannel {
public struct SynchronousOptions: NIOSynchronousChannelOptions {
@usableFromInline
internal let channel: EmbeddedChannel
fileprivate init(channel: EmbeddedChannel) {
self.channel = channel
}
@inlinable
public func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) throws {
self.channel.setOptionSync(option, value: value)
}
@inlinable
public func getOption<Option: ChannelOption>(_ option: Option) throws -> Option.Value {
return self.channel.getOptionSync(option)
}
}
public final var syncOptions: NIOSynchronousChannelOptions? {
return SynchronousOptions(channel: self)
}
}
| 41.394667 | 154 | 0.661728 |
76849b2f6323c205bc6227556fe92a091a6a955d | 2,081 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func c<T: E) -> [T.A
}
import Foundation
let
func c<T where T{
Void{
}
let b : A? = nil
func b(() -> [T.C<T where g: E) -> (t: Int = {
"\() {
class A {
}
}
print(0)
let b { func f<T where g: (
}
class A : B<T where g:A? = f<H : Array) -> [T: NSObject {
}
struct S{
func c
let a {
let b : B{
}
struct c(Int,Int,e<T:e: {
A {
}
let (e: Array) {
A : Array) {
class B : Int = nil
func f< where
a {
}
struct c{
class A : {
{
func c<H : {
}
func c:e) = A
func g: b<T: Array) {
a {
enum S<T where g: Array) {
Void{
typealias e: Int = {
var b { func c:a{
let
}
typealias e),.C
m: NSObject {
func a{
return nil
}
let a {
let (),.B : B{
let
A : d = nil
func f<T where k.C<T where T.B {class d
struct S<T where H.C<T where g:NSObject{class B{0,0,0){enum S<T where g<T where g: NSManagedObject {
println
func f((0,0.C
func f() {
d>:T? {
class c:BooleanType
println
}
struct B{
]? {
m: NSManagedObject {
class C<T : ()
} (T.C
func c<d
let (Int),e: B>:A
}
struct S<d
d
func U
protocol e :A, AnyObject) {
return nil
class B>() {
]? {struct B<H : Array) {
func f() = f(T>c<T where k.A:NSObject{
{enum S<T{
class B:NSObject{
func a{
let a
func c
"\(
}
struct B<T where g
return nil
class B<T where H:a
{
enum S{
func U
print((T:BooleanType
return nil
func g: B>(0)
a{
func a{
class c:T.A
extension A {
}
func h(Int,Int)
a {
func e) -> [T]
}
func a
}
let a
a{
}
class A
func b{
{
return nil
class d
}
typealias e: d = {
func c
} (),Int)
}
class B<H : E) {
func U
}
{
extension A {
]? {
a
enum B{
print(t,e<T: Array) = A:A
print(
class d
func f(),e<T where H:c:BooleanType
func e) -> (T? = nil
func
println
d
return (Int,0),e) {
class d>(t: E) {0,e(0.A? = f(() {
}
import Foundation
var b { func a{
let b { func a
{
extension A : E) = A? {
class A : B{struct c<T where k.C<H : B{struct S<T where g:BooleanType
extension A : b() -> [T.h() {
func a{
func f(t: {
"\(e: b{class d
}
{0.b<T where k.h
}
}
} (T.C
}
protocol e :NSObject{
}
| 12.845679 | 100 | 0.59779 |
6297226bd4b32a34cf37042e22934339daa901a3 | 1,450 | //
// ModalViewController.swift
// CustomPresentationsProject
//
// Created by Blake Macnair on 12/21/18.
// Copyright © 2018 Macnair. All rights reserved.
//
import UIKit
public class ModalViewController: UIViewController {
private lazy var button: UIButton = {
let button = UIButton(type: .roundedRect)
button.setTitle("Dismiss!", for: .normal)
button.backgroundColor = UIColor.orange
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
init() {
super.init(nibName: nil, bundle: nil)
button.addTarget(self, action: #selector(dismissView), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
configureLayout()
}
private func configureLayout() {
view.addSubview(button)
NSLayoutConstraint.activate([
button.heightAnchor.constraint(equalToConstant: 80),
button.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8),
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
@objc private func dismissView() {
dismiss(animated: true, completion: nil)
}
}
| 26.851852 | 86 | 0.655862 |
01a7a3be5e88f44d8b99aa2fe094523c53e78b40 | 1,163 | //
// UICollectionView + Extension.swift
// RxBasicInterface
//
// Created by 陈恩湖 on 02/10/2017.
// Copyright © 2017 Judson. All rights reserved.
//
import UIKit
extension UICollectionView {
func registerForCell<T: UICollectionReusableView>(_ cellClass: T.Type, identifier: String? = nil, isNib: Bool = true) {
let nibName = cellClass.className
let cellIdentifier = identifier ?? nibName
if isNib {
self.register(UINib(nibName: nibName, bundle: nil), forCellWithReuseIdentifier: cellIdentifier)
} else {
self.register(cellClass, forCellWithReuseIdentifier: cellIdentifier)
}
}
func dequeueCell<T: UICollectionReusableView>(_ cellClass: T.Type, indexPath: IndexPath) -> T {
let identifier = cellClass.className
// swiftlint:disable:next force_cast
return self.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! T
}
}
extension UICollectionReusableView {
static var className: String {
return "\(self)"
}
}
extension UITableViewCell {
static var className: String {
return "\(self)"
}
}
| 27.046512 | 123 | 0.66896 |
ddca6fc371b092a4675bae9f62f4b85ad55f6f05 | 367 | // 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 a{
var b{class a{
struct c{
enum S{class a{
func a{
func a{
class a{protocol c{
struct B{
struct S{
enum a{
struct S{
struct B{class
b{class
case,
| 18.35 | 87 | 0.73297 |
d66211b9255edd128880d6500463663a8c57d2ce | 408 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let end = e>
protocol P {
protocol A : e) -> Void{
let end = B<T, U, U, g = ")
protocol A : B
func b<T where T.e : e) { e>() { }
let end = g<T where T>(v: d = "\(v: d = c
class B<T where T: B
typealias e : A"\(v: A? {
class B<T: e
protoco
| 25.5 | 87 | 0.632353 |
1497a33ff995ca127c46f39071f7520518470bfb | 38,976 | /*Copyright (c) 2016, Andrew Walz.
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 HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import AVFoundation
// MARK: View Controller Declaration
/// A UIViewController Camera View Subclass
open class SwiftyCamViewController: UIViewController {
// MARK: Enumeration Declaration
/// Enumeration for Camera Selection
public enum CameraSelection: String {
/// Camera on the back of the device
case rear = "rear"
/// Camera on the front of the device
case front = "front"
}
public enum FlashMode{
//Return the equivalent AVCaptureDevice.FlashMode
var AVFlashMode: AVCaptureDevice.FlashMode {
switch self {
case .on:
return .on
case .off:
return .off
case .auto:
return .auto
}
}
//Flash mode is set to auto
case auto
//Flash mode is set to on
case on
//Flash mode is set to off
case off
}
/// Enumeration for video quality of the capture session. Corresponds to a AVCaptureSessionPreset
public enum VideoQuality {
/// AVCaptureSessionPresetHigh
case high
/// AVCaptureSessionPresetMedium
case medium
/// AVCaptureSessionPresetLow
case low
/// AVCaptureSessionPreset352x288
case resolution352x288
/// AVCaptureSessionPreset640x480
case resolution640x480
/// AVCaptureSessionPreset1280x720
case resolution1280x720
/// AVCaptureSessionPreset1920x1080
case resolution1920x1080
/// AVCaptureSessionPreset3840x2160
case resolution3840x2160
/// AVCaptureSessionPresetiFrame960x540
case iframe960x540
/// AVCaptureSessionPresetiFrame1280x720
case iframe1280x720
}
/**
Result from the AVCaptureSession Setup
- success: success
- notAuthorized: User denied access to Camera of Microphone
- configurationFailed: Unknown error
*/
fileprivate enum SessionSetupResult {
case success
case notAuthorized
case configurationFailed
}
// MARK: Public Variable Declarations
/// Public Camera Delegate for the Custom View Controller Subclass
public weak var cameraDelegate: SwiftyCamViewControllerDelegate?
/// Maxiumum video duration if SwiftyCamButton is used
public var maximumVideoDuration : Double = 0.0
/// Video capture quality
public var videoQuality : VideoQuality = .high
/// Sets whether flash is enabled for photo and video capture
@available(*, deprecated, message: "use flashMode .on or .off") //use flashMode
public var flashEnabled: Bool = false {
didSet{
self.flashMode = self.flashEnabled ? .on : .off
}
}
// Flash Mode
public var flashMode:FlashMode = .off
/// Sets whether Pinch to Zoom is enabled for the capture session
public var pinchToZoom = true
/// Sets the maximum zoom scale allowed during gestures gesture
public var maxZoomScale = CGFloat.greatestFiniteMagnitude
/// Sets whether Tap to Focus and Tap to Adjust Exposure is enabled for the capture session
public var tapToFocus = true
/// Sets whether the capture session should adjust to low light conditions automatically
///
/// Only supported on iPhone 5 and 5C
public var lowLightBoost = true
/// Set whether SwiftyCam should allow background audio from other applications
public var allowBackgroundAudio = true
/// Sets whether a double tap to switch cameras is supported
public var doubleTapCameraSwitch = true
/// Sets whether swipe vertically to zoom is supported
public var swipeToZoom = true
/// Sets whether swipe vertically gestures should be inverted
public var swipeToZoomInverted = false
/// Set default launch camera
public var defaultCamera = CameraSelection.rear
/// Sets wether the taken photo or video should be oriented according to the device orientation
public var shouldUseDeviceOrientation = false {
didSet {
orientation.shouldUseDeviceOrientation = shouldUseDeviceOrientation
}
}
/// Sets whether or not View Controller supports auto rotation
public var allowAutoRotate = false
/// Specifies the [videoGravity](https://developer.apple.com/reference/avfoundation/avcapturevideopreviewlayer/1386708-videogravity) for the preview layer.
public var videoGravity : SwiftyCamVideoGravity = .resizeAspect
/// Sets whether or not video recordings will record audio
/// Setting to true will prompt user for access to microphone on View Controller launch.
public var audioEnabled = true
/// Sets whether or not app should display prompt to app settings if audio/video permission is denied
/// If set to false, delegate function will be called to handle exception
public var shouldPrompToAppSettings = true
/// Video will be recorded to this folder
public var outputFolder: String = NSTemporaryDirectory()
/// Public access to Pinch Gesture
fileprivate(set) public var pinchGesture : UIPinchGestureRecognizer!
/// Public access to Pan Gesture
fileprivate(set) public var panGesture : UIPanGestureRecognizer!
// MARK: Public Get-only Variable Declarations
/// Returns true if video is currently being recorded
private(set) public var isVideoRecording = false
/// Returns true if the capture session is currently running
private(set) public var isSessionRunning = false
/// Returns the CameraSelection corresponding to the currently utilized camera
private(set) public var currentCamera = CameraSelection.rear
// MARK: Private Constant Declarations
/// Current Capture Session
public let session = AVCaptureSession()
/// Serial queue used for setting up session
fileprivate let sessionQueue = DispatchQueue(label: "session queue", attributes: [])
// MARK: Private Variable Declarations
/// Variable for storing current zoom scale
fileprivate var zoomScale = CGFloat(1.0)
/// Variable for storing initial zoom scale before Pinch to Zoom begins
fileprivate var beginZoomScale = CGFloat(1.0)
/// Returns true if the torch (flash) is currently enabled
fileprivate var isCameraTorchOn = false
/// Variable to store result of capture session setup
fileprivate var setupResult = SessionSetupResult.success
/// BackgroundID variable for video recording
fileprivate var backgroundRecordingID : UIBackgroundTaskIdentifier? = nil
/// Video Input variable
fileprivate var videoDeviceInput : AVCaptureDeviceInput!
/// Movie File Output variable
fileprivate var movieFileOutput : AVCaptureMovieFileOutput?
/// Photo File Output variable
fileprivate var photoFileOutput : AVCaptureStillImageOutput?
/// Video Device variable
fileprivate var videoDevice : AVCaptureDevice?
/// PreviewView for the capture session
fileprivate var previewLayer : PreviewView!
/// UIView for front facing flash
fileprivate var flashView : UIView?
/// Pan Translation
fileprivate var previousPanTranslation : CGFloat = 0.0
/// Last changed orientation
fileprivate var orientation : Orientation = Orientation()
/// Boolean to store when View Controller is notified session is running
fileprivate var sessionRunning = false
/// Disable view autorotation for forced portrait recorindg
override open var shouldAutorotate: Bool {
return allowAutoRotate
}
/// Sets output video codec
public var videoCodecType: AVVideoCodecType? = nil
// MARK: ViewDidLoad
/// ViewDidLoad Implementation
override open func viewDidLoad() {
super.viewDidLoad()
previewLayer = PreviewView(frame: view.frame, videoGravity: videoGravity)
previewLayer.center = view.center
view.addSubview(previewLayer)
view.sendSubviewToBack(previewLayer)
// Add Gesture Recognizers
addGestureRecognizers()
previewLayer.session = session
// Test authorization status for Camera and Micophone
switch AVCaptureDevice.authorizationStatus(for: AVMediaType.video) {
case .authorized:
// already authorized
break
case .notDetermined:
// not yet determined
sessionQueue.suspend()
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { [unowned self] granted in
if !granted {
self.setupResult = .notAuthorized
}
self.sessionQueue.resume()
})
default:
// already been asked. Denied access
setupResult = .notAuthorized
}
sessionQueue.async { [unowned self] in
self.configureSession()
}
}
// MARK: ViewDidLayoutSubviews
/// ViewDidLayoutSubviews() Implementation
private func updatePreviewLayer(layer: AVCaptureConnection, orientation: AVCaptureVideoOrientation) {
if(shouldAutorotate){
layer.videoOrientation = orientation
} else {
layer.videoOrientation = .portrait
}
previewLayer.frame = self.view.bounds
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let connection = self.previewLayer?.videoPreviewLayer.connection {
let currentDevice: UIDevice = UIDevice.current
let orientation: UIDeviceOrientation = currentDevice.orientation
let previewLayerConnection : AVCaptureConnection = connection
if previewLayerConnection.isVideoOrientationSupported {
switch (orientation) {
case .portrait: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)
break
case .landscapeRight: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeLeft)
break
case .landscapeLeft: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeRight)
break
case .portraitUpsideDown: updatePreviewLayer(layer: previewLayerConnection, orientation: .portraitUpsideDown)
break
default: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)
break
}
}
}
}
// MARK: ViewWillAppear
/// ViewWillAppear(_ animated:) Implementation
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(captureSessionDidStartRunning), name: .AVCaptureSessionDidStartRunning, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(captureSessionDidStopRunning), name: .AVCaptureSessionDidStopRunning, object: nil)
}
// MARK: ViewDidAppear
/// ViewDidAppear(_ animated:) Implementation
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Subscribe to device rotation notifications
if shouldUseDeviceOrientation {
orientation.start()
}
// Set background audio preference
setBackgroundAudioPreference()
sessionQueue.async {
switch self.setupResult {
case .success:
// Begin Session
self.session.startRunning()
self.isSessionRunning = self.session.isRunning
// Preview layer video orientation can be set only after the connection is created
DispatchQueue.main.async {
self.previewLayer.videoPreviewLayer.connection?.videoOrientation = self.orientation.getPreviewLayerOrientation()
}
case .notAuthorized:
if self.shouldPrompToAppSettings == true {
self.promptToAppSettings()
} else {
self.cameraDelegate?.swiftyCamNotAuthorized(self)
}
case .configurationFailed:
// Unknown Error
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCamDidFailToConfigure(self)
}
}
}
}
// MARK: ViewDidDisappear
/// ViewDidDisappear(_ animated:) Implementation
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
sessionRunning = false
// If session is running, stop the session
if self.isSessionRunning == true {
self.session.stopRunning()
self.isSessionRunning = false
}
//Disble flash if it is currently enabled
disableFlash()
// Unsubscribe from device rotation notifications
if shouldUseDeviceOrientation {
orientation.stop()
}
}
// MARK: Public Functions
/**
Capture photo from current session
UIImage will be returned with the SwiftyCamViewControllerDelegate function SwiftyCamDidTakePhoto(photo:)
*/
public func takePhoto() {
guard let device = videoDevice else {
return
}
if device.hasFlash == true && flashMode != .off /* TODO: Add Support for Retina Flash and add front flash */ {
changeFlashSettings(device: device, mode: flashMode)
capturePhotoAsyncronously(completionHandler: { (_) in })
}else{
if device.isFlashActive == true {
changeFlashSettings(device: device, mode: flashMode)
}
capturePhotoAsyncronously(completionHandler: { (_) in })
}
}
/**
Begin recording video of current session
SwiftyCamViewControllerDelegate function SwiftyCamDidBeginRecordingVideo() will be called
*/
public func startVideoRecording() {
guard sessionRunning == true else {
print("[SwiftyCam]: Cannot start video recoding. Capture session is not running")
return
}
guard let movieFileOutput = self.movieFileOutput else {
return
}
if currentCamera == .rear && flashMode == .on {
enableFlash()
}
if currentCamera == .front && flashMode == .on {
flashView = UIView(frame: view.frame)
flashView?.backgroundColor = UIColor.white
flashView?.alpha = 0.85
previewLayer.addSubview(flashView!)
}
//Must be fetched before on main thread
let previewOrientation = previewLayer.videoPreviewLayer.connection!.videoOrientation
sessionQueue.async { [unowned self] in
if !movieFileOutput.isRecording {
if UIDevice.current.isMultitaskingSupported {
self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
}
// Update the orientation on the movie file output video connection before starting recording.
let movieFileOutputConnection = self.movieFileOutput?.connection(with: AVMediaType.video)
//flip video output if front facing camera is selected
if self.currentCamera == .front {
movieFileOutputConnection?.isVideoMirrored = true
}
movieFileOutputConnection?.videoOrientation = self.orientation.getVideoOrientation() ?? previewOrientation
// Start recording to a temporary file.
let outputFileName = UUID().uuidString
let outputFilePath = (self.outputFolder as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)
movieFileOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)
self.isVideoRecording = true
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didBeginRecordingVideo: self.currentCamera)
}
}
else {
movieFileOutput.stopRecording()
}
}
}
/**
Stop video recording video of current session
SwiftyCamViewControllerDelegate function SwiftyCamDidFinishRecordingVideo() will be called
When video has finished processing, the URL to the video location will be returned by SwiftyCamDidFinishProcessingVideoAt(url:)
*/
public func stopVideoRecording() {
if self.isVideoRecording == true {
self.isVideoRecording = false
movieFileOutput!.stopRecording()
disableFlash()
if currentCamera == .front && flashMode == .on && flashView != nil {
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: {
self.flashView?.alpha = 0.0
}, completion: { (_) in
self.flashView?.removeFromSuperview()
})
}
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFinishRecordingVideo: self.currentCamera)
}
}
}
/**
Switch between front and rear camera
SwiftyCamViewControllerDelegate function SwiftyCamDidSwitchCameras(camera: will be return the current camera selection
*/
public func switchCamera() {
guard isVideoRecording != true else {
//TODO: Look into switching camera during video recording
print("[SwiftyCam]: Switching between cameras while recording video is not supported")
return
}
guard session.isRunning == true else {
return
}
switch currentCamera {
case .front:
currentCamera = .rear
case .rear:
currentCamera = .front
}
session.stopRunning()
sessionQueue.async { [unowned self] in
// remove and re-add inputs and outputs
for input in self.session.inputs {
self.session.removeInput(input )
}
self.addInputs()
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didSwitchCameras: self.currentCamera)
}
self.session.startRunning()
}
// If flash is enabled, disable it as the torch is needed for front facing camera
disableFlash()
}
// MARK: Private Functions
/// Configure session, add inputs and outputs
fileprivate func configureSession() {
guard setupResult == .success else {
return
}
// Set default camera
currentCamera = defaultCamera
// begin configuring session
session.beginConfiguration()
configureVideoPreset()
addVideoInput()
addAudioInput()
configureVideoOutput()
configurePhotoOutput()
session.commitConfiguration()
}
/// Add inputs after changing camera()
fileprivate func addInputs() {
session.beginConfiguration()
configureVideoPreset()
addVideoInput()
addAudioInput()
session.commitConfiguration()
}
// Front facing camera will always be set to VideoQuality.high
// If set video quality is not supported, videoQuality variable will be set to VideoQuality.high
/// Configure image quality preset
fileprivate func configureVideoPreset() {
if currentCamera == .front {
session.sessionPreset = AVCaptureSession.Preset(rawValue: videoInputPresetFromVideoQuality(quality: .high))
} else {
if session.canSetSessionPreset(AVCaptureSession.Preset(rawValue: videoInputPresetFromVideoQuality(quality: videoQuality))) {
session.sessionPreset = AVCaptureSession.Preset(rawValue: videoInputPresetFromVideoQuality(quality: videoQuality))
} else {
session.sessionPreset = AVCaptureSession.Preset(rawValue: videoInputPresetFromVideoQuality(quality: .high))
}
}
}
/// Add Video Inputs
fileprivate func addVideoInput() {
switch currentCamera {
case .front:
videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaType.video.rawValue, preferringPosition: .front)
case .rear:
videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaType.video.rawValue, preferringPosition: .back)
}
if let device = videoDevice {
do {
try device.lockForConfiguration()
if device.isFocusModeSupported(.continuousAutoFocus) {
device.focusMode = .continuousAutoFocus
if device.isSmoothAutoFocusSupported {
device.isSmoothAutoFocusEnabled = true
}
}
if device.isExposureModeSupported(.continuousAutoExposure) {
device.exposureMode = .continuousAutoExposure
}
if device.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) {
device.whiteBalanceMode = .continuousAutoWhiteBalance
}
if device.isLowLightBoostSupported && lowLightBoost == true {
device.automaticallyEnablesLowLightBoostWhenAvailable = true
}
device.unlockForConfiguration()
} catch {
print("[SwiftyCam]: Error locking configuration")
}
}
do {
if let videoDevice = videoDevice {
let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
if session.canAddInput(videoDeviceInput) {
session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
} else {
print("[SwiftyCam]: Could not add video device input to the session")
print(session.canSetSessionPreset(AVCaptureSession.Preset(rawValue: videoInputPresetFromVideoQuality(quality: videoQuality))))
setupResult = .configurationFailed
session.commitConfiguration()
return
}
}
} catch {
print("[SwiftyCam]: Could not create video device input: \(error)")
setupResult = .configurationFailed
return
}
}
/// Add Audio Inputs
fileprivate func addAudioInput() {
guard audioEnabled == true else {
return
}
do {
if let audioDevice = AVCaptureDevice.default(for: AVMediaType.audio){
let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice)
if session.canAddInput(audioDeviceInput) {
session.addInput(audioDeviceInput)
} else {
print("[SwiftyCam]: Could not add audio device input to the session")
}
} else {
print("[SwiftyCam]: Could not find an audio device")
}
} catch {
print("[SwiftyCam]: Could not create audio device input: \(error)")
}
}
/// Configure Movie Output
fileprivate func configureVideoOutput() {
let movieFileOutput = AVCaptureMovieFileOutput()
if self.session.canAddOutput(movieFileOutput) {
self.session.addOutput(movieFileOutput)
if let connection = movieFileOutput.connection(with: AVMediaType.video) {
if connection.isVideoStabilizationSupported {
connection.preferredVideoStabilizationMode = .auto
}
if #available(iOS 11.0, *) {
if let videoCodecType = videoCodecType {
if movieFileOutput.availableVideoCodecTypes.contains(videoCodecType) == true {
// Use the H.264 codec to encode the video.
movieFileOutput.setOutputSettings([AVVideoCodecKey: videoCodecType], for: connection)
}
}
}
}
self.movieFileOutput = movieFileOutput
}
}
/// Configure Photo Output
fileprivate func configurePhotoOutput() {
let photoFileOutput = AVCaptureStillImageOutput()
if self.session.canAddOutput(photoFileOutput) {
photoFileOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
self.session.addOutput(photoFileOutput)
self.photoFileOutput = photoFileOutput
}
}
/**
Returns a UIImage from Image Data.
- Parameter imageData: Image Data returned from capturing photo from the capture session.
- Returns: UIImage from the image data, adjusted for proper orientation.
*/
fileprivate func processPhoto(_ imageData: Data) -> UIImage {
let dataProvider = CGDataProvider(data: imageData as CFData)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
// Set proper orientation for photo
// If camera is currently set to front camera, flip image
let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: self.orientation.getImageOrientation(forCamera: self.currentCamera))
return image
}
fileprivate func capturePhotoAsyncronously(completionHandler: @escaping(Bool) -> ()) {
guard sessionRunning == true else {
print("[SwiftyCam]: Cannot take photo. Capture session is not running")
return
}
if let videoConnection = photoFileOutput?.connection(with: AVMediaType.video) {
photoFileOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in
if (sampleBuffer != nil) {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer!)
let image = self.processPhoto(imageData!)
// Call delegate and return new image
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didTake: image)
}
completionHandler(true)
} else {
completionHandler(false)
}
})
} else {
completionHandler(false)
}
}
/// Handle Denied App Privacy Settings
fileprivate func promptToAppSettings() {
// prompt User with UIAlertView
DispatchQueue.main.async(execute: { [unowned self] in
let message = NSLocalizedString("AVCam doesn't have permission to use the camera, please change privacy settings", comment: "Alert message when the user has denied access to the camera")
let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: NSLocalizedString("Settings", comment: "Alert button to open Settings"), style: .default, handler: { action in
if #available(iOS 10.0, *) {
UIApplication.shared.openURL(URL(string: UIApplication.openSettingsURLString)!)
} else {
if let appSettings = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(appSettings)
}
}
}))
self.present(alertController, animated: true, completion: nil)
})
}
/**
Returns an AVCapturePreset from VideoQuality Enumeration
- Parameter quality: ViewQuality enum
- Returns: String representing a AVCapturePreset
*/
fileprivate func videoInputPresetFromVideoQuality(quality: VideoQuality) -> String {
switch quality {
case .high: return AVCaptureSession.Preset.high.rawValue
case .medium: return AVCaptureSession.Preset.medium.rawValue
case .low: return AVCaptureSession.Preset.low.rawValue
case .resolution352x288: return AVCaptureSession.Preset.cif352x288.rawValue
case .resolution640x480: return AVCaptureSession.Preset.vga640x480.rawValue
case .resolution1280x720: return AVCaptureSession.Preset.hd1280x720.rawValue
case .resolution1920x1080: return AVCaptureSession.Preset.hd1920x1080.rawValue
case .iframe960x540: return AVCaptureSession.Preset.iFrame960x540.rawValue
case .iframe1280x720: return AVCaptureSession.Preset.iFrame1280x720.rawValue
case .resolution3840x2160:
if #available(iOS 9.0, *) {
return AVCaptureSession.Preset.hd4K3840x2160.rawValue
}
else {
print("[SwiftyCam]: Resolution 3840x2160 not supported")
return AVCaptureSession.Preset.high.rawValue
}
}
}
/// Get Devices
fileprivate class func deviceWithMediaType(_ mediaType: String, preferringPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? {
if #available(iOS 10.0, *) {
let avDevice = AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: AVMediaType(rawValue: mediaType), position: position)
return avDevice
} else {
// Fallback on earlier versions
let avDevice = AVCaptureDevice.devices(for: AVMediaType(rawValue: mediaType))
var avDeviceNum = 0
for device in avDevice {
print("deviceWithMediaType Position: \(device.position.rawValue)")
if device.position == position {
break
} else {
avDeviceNum += 1
}
}
return avDevice[avDeviceNum]
}
//return AVCaptureDevice.devices(for: AVMediaType(rawValue: mediaType), position: position).first
}
/// Enable or disable flash for photo
fileprivate func changeFlashSettings(device: AVCaptureDevice, mode: FlashMode) {
do {
try device.lockForConfiguration()
device.flashMode = mode.AVFlashMode
device.unlockForConfiguration()
} catch {
print("[SwiftyCam]: \(error)")
}
}
/// Enable flash
fileprivate func enableFlash() {
if self.isCameraTorchOn == false {
toggleFlash()
}
}
/// Disable flash
fileprivate func disableFlash() {
if self.isCameraTorchOn == true {
toggleFlash()
}
}
/// Toggles between enabling and disabling flash
fileprivate func toggleFlash() {
guard self.currentCamera == .rear else {
// Flash is not supported for front facing camera
return
}
let device = AVCaptureDevice.default(for: AVMediaType.video)
// Check if device has a flash
if (device?.hasTorch)! {
do {
try device?.lockForConfiguration()
if (device?.torchMode == AVCaptureDevice.TorchMode.on) {
device?.torchMode = AVCaptureDevice.TorchMode.off
self.isCameraTorchOn = false
} else {
do {
try device?.setTorchModeOn(level: 1.0)
self.isCameraTorchOn = true
} catch {
print("[SwiftyCam]: \(error)")
}
}
device?.unlockForConfiguration()
} catch {
print("[SwiftyCam]: \(error)")
}
}
}
/// Sets whether SwiftyCam should enable background audio from other applications or sources
fileprivate func setBackgroundAudioPreference() {
guard allowBackgroundAudio == true else {
return
}
guard audioEnabled == true else {
return
}
do{
if #available(iOS 10.0, *) {
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.mixWithOthers, .allowBluetooth, .allowAirPlay, .allowBluetoothA2DP])
} else {
let options: [AVAudioSession.CategoryOptions] = [.mixWithOthers, .allowBluetooth]
let category = AVAudioSession.Category.playAndRecord
let selector = NSSelectorFromString("setCategory:withOptions:error:")
AVAudioSession.sharedInstance().perform(selector, with: category, with: options)
}
try AVAudioSession.sharedInstance().setActive(true)
session.automaticallyConfiguresApplicationAudioSession = false
}
catch {
print("[SwiftyCam]: Failed to set background audio preference")
}
}
/// Called when Notification Center registers session starts running
@objc private func captureSessionDidStartRunning() {
sessionRunning = true
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCamSessionDidStartRunning(self)
}
}
/// Called when Notification Center registers session stops running
@objc private func captureSessionDidStopRunning() {
sessionRunning = false
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCamSessionDidStopRunning(self)
}
}
}
extension SwiftyCamViewController : SwiftyCamButtonDelegate {
/// Sets the maximum duration of the SwiftyCamButton
public func setMaxiumVideoDuration() -> Double {
return maximumVideoDuration
}
/// Set UITapGesture to take photo
public func buttonWasTapped() {
takePhoto()
}
/// Set UILongPressGesture start to begin video
public func buttonDidBeginLongPress() {
startVideoRecording()
}
/// Set UILongPressGesture begin to begin end video
public func buttonDidEndLongPress() {
stopVideoRecording()
}
/// Called if maximum duration is reached
public func longPressDidReachMaximumDuration() {
stopVideoRecording()
}
}
// MARK: AVCaptureFileOutputRecordingDelegate
extension SwiftyCamViewController : AVCaptureFileOutputRecordingDelegate {
/// Process newly captured video and write it to temporary directory
public func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
if let currentBackgroundRecordingID = backgroundRecordingID {
backgroundRecordingID = UIBackgroundTaskIdentifier.invalid
if currentBackgroundRecordingID != UIBackgroundTaskIdentifier.invalid {
UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)
}
}
if let currentError = error {
print("[SwiftyCam]: Movie file finishing error: \(currentError)")
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFailToRecordVideo: currentError)
}
} else {
//Call delegate function with the URL of the outputfile
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFinishProcessVideoAt: outputFileURL)
}
}
}
}
// Mark: UIGestureRecognizer Declarations
extension SwiftyCamViewController {
/// Handle pinch gesture
@objc fileprivate func zoomGesture(pinch: UIPinchGestureRecognizer) {
guard pinchToZoom == true && self.currentCamera == .rear else {
//ignore pinch
return
}
do {
let captureDevice = AVCaptureDevice.devices().first
try captureDevice?.lockForConfiguration()
zoomScale = min(maxZoomScale, max(1.0, min(beginZoomScale * pinch.scale, captureDevice!.activeFormat.videoMaxZoomFactor)))
captureDevice?.videoZoomFactor = zoomScale
// Call Delegate function with current zoom scale
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didChangeZoomLevel: self.zoomScale)
}
captureDevice?.unlockForConfiguration()
} catch {
print("[SwiftyCam]: Error locking configuration")
}
}
/// Handle single tap gesture
@objc fileprivate func singleTapGesture(tap: UITapGestureRecognizer) {
guard tapToFocus == true else {
// Ignore taps
return
}
let screenSize = previewLayer!.bounds.size
let tapPoint = tap.location(in: previewLayer!)
let x = tapPoint.y / screenSize.height
let y = 1.0 - tapPoint.x / screenSize.width
let focusPoint = CGPoint(x: x, y: y)
if let device = videoDevice {
do {
try device.lockForConfiguration()
if device.isFocusPointOfInterestSupported == true {
device.focusPointOfInterest = focusPoint
device.focusMode = .autoFocus
}
device.exposurePointOfInterest = focusPoint
device.exposureMode = AVCaptureDevice.ExposureMode.continuousAutoExposure
device.unlockForConfiguration()
//Call delegate function and pass in the location of the touch
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFocusAtPoint: tapPoint)
}
}
catch {
// just ignore
}
}
}
/// Handle double tap gesture
@objc fileprivate func doubleTapGesture(tap: UITapGestureRecognizer) {
guard doubleTapCameraSwitch == true else {
return
}
switchCamera()
}
@objc private func panGesture(pan: UIPanGestureRecognizer) {
guard swipeToZoom == true && self.currentCamera == .rear else {
//ignore pan
return
}
let currentTranslation = pan.translation(in: view).y
let translationDifference = currentTranslation - previousPanTranslation
do {
let captureDevice = AVCaptureDevice.devices().first
try captureDevice?.lockForConfiguration()
let currentZoom = captureDevice?.videoZoomFactor ?? 0.0
if swipeToZoomInverted == true {
zoomScale = min(maxZoomScale, max(1.0, min(currentZoom - (translationDifference / 75), captureDevice!.activeFormat.videoMaxZoomFactor)))
} else {
zoomScale = min(maxZoomScale, max(1.0, min(currentZoom + (translationDifference / 75), captureDevice!.activeFormat.videoMaxZoomFactor)))
}
captureDevice?.videoZoomFactor = zoomScale
// Call Delegate function with current zoom scale
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didChangeZoomLevel: self.zoomScale)
}
captureDevice?.unlockForConfiguration()
} catch {
print("[SwiftyCam]: Error locking configuration")
}
if pan.state == .ended || pan.state == .failed || pan.state == .cancelled {
previousPanTranslation = 0.0
} else {
previousPanTranslation = currentTranslation
}
}
/**
Add pinch gesture recognizer and double tap gesture recognizer to currentView
- Parameter view: View to add gesture recognzier
*/
fileprivate func addGestureRecognizers() {
pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(zoomGesture(pinch:)))
pinchGesture.delegate = self
previewLayer.addGestureRecognizer(pinchGesture)
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTapGesture(tap:)))
singleTapGesture.numberOfTapsRequired = 1
singleTapGesture.delegate = self
previewLayer.addGestureRecognizer(singleTapGesture)
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapGesture(tap:)))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.delegate = self
previewLayer.addGestureRecognizer(doubleTapGesture)
panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGesture(pan:)))
panGesture.delegate = self
previewLayer.addGestureRecognizer(panGesture)
}
}
// MARK: UIGestureRecognizerDelegate
extension SwiftyCamViewController : UIGestureRecognizerDelegate {
/// Set beginZoomScale when pinch begins
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isKind(of: UIPinchGestureRecognizer.self) {
beginZoomScale = zoomScale;
}
return true
}
}
| 30.569412 | 189 | 0.699738 |
336223f4fc2921d250c05d124f10d4bc6422eda4 | 867 | //
// AcquaintancesListViewModel.swift
// Acquaintances
//
// Created by Alexey Chuvagin on 21.09.2021.
//
import Combine
import Resolver
import SwiftUI
class AcquaintancesListViewModel: ObservableObject {
@Injected private var repository: AcquaintancesRepository
@Published private(set) var acquaintances: [Acquaintance] = []
@Published var showingImagePicker = false
@Published var showingCreateAcquaintance = false
private var cancelables = Set<AnyCancellable>()
var image: Image?
func refresh() {
repository.fetchAll()
.receive(on: DispatchQueue.main)
.replaceError(with: [])
.assign(to: \.acquaintances, on: self)
.store(in: &cancelables)
}
deinit {
for cancelable in cancelables {
cancelable.cancel()
}
}
}
| 23.432432 | 66 | 0.638985 |
d7085f7721fb44e6919783ebcfc619cc9d4b7f0b | 7,215 | import UIKit
@objc(HYPPagesControllerDelegate) public protocol PagesControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController,
setViewController viewController: UIViewController,
atPage page: Int)
}
@objc(HYPPagesController) open class PagesController: UIPageViewController {
private struct Dimensions {
static let bottomLineHeight: CGFloat = 1.0
static let bottomLineSideMargin: CGFloat = 40.0
static let bottomLineBottomMargin: CGFloat = 36.0
}
public let startPage = 0
@objc public var setNavigationTitle = true
public var enableSwipe = true {
didSet {
toggle()
}
}
public var showBottomLine = false {
didSet {
bottomLineView.isHidden = !showBottomLine
}
}
public var showPageControl = true
private lazy var pages = Array<UIViewController>()
public var pagesCount: Int {
return pages.count
}
@objc public private(set) var currentIndex = 0
public weak var pagesDelegate: PagesControllerDelegate?
public private(set) lazy var bottomLineView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.white
view.alpha = 0.4
view.isHidden = true
return view
}()
public private(set) var pageControl: UIPageControl?
public convenience init(_ pages: [UIViewController],
transitionStyle: UIPageViewControllerTransitionStyle = .scroll,
navigationOrientation: UIPageViewControllerNavigationOrientation = .horizontal,
options: [String : AnyObject]? = nil) {
self.init(
transitionStyle: transitionStyle,
navigationOrientation: navigationOrientation,
options: options
)
add(pages)
}
open override func viewDidLoad() {
super.viewDidLoad()
delegate = self
dataSource = self
view.addSubview(bottomLineView)
addConstraints()
view.bringSubview(toFront: bottomLineView)
goTo(startPage)
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
for subview in view.subviews {
if subview is UIPageControl {
pageControl = subview as? UIPageControl
}
}
}
// MARK: - Public methods
open func goTo(_ index: Int) {
if index >= 0 && index < pages.count {
let direction: UIPageViewControllerNavigationDirection = (index > currentIndex) ? .forward : .reverse
let viewController = pages[index]
currentIndex = index
setViewControllers(
[viewController],
direction: direction,
animated: true,
completion: { [unowned self] finished in
self.pagesDelegate?.pageViewController(
self,
setViewController: viewController,
atPage: self.currentIndex
)
})
if setNavigationTitle {
title = viewController.title
}
}
}
@objc open func moveForward() {
goTo(currentIndex + 1)
}
@objc open func moveBack() {
goTo(currentIndex - 1)
}
@objc dynamic open func add(_ viewControllers: [UIViewController]) {
for viewController in viewControllers {
addViewController(viewController)
}
}
}
// MARK: - UIPageViewControllerDataSource
extension PagesController: UIPageViewControllerDataSource {
@objc open func pageViewController(_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController? {
let index = prevIndex(viewControllerIndex(viewController))
return pages.at(index)
}
@objc open func pageViewController(_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController? {
let index: Int? = nextIndex(viewControllerIndex(viewController))
return pages.at(index)
}
@objc open func presentationCount(for pageViewController: UIPageViewController) -> Int {
return showPageControl ? pages.count : 0
}
@objc open func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return showPageControl ? currentIndex : 0
}
}
// MARK: - UIPageViewControllerDelegate
extension PagesController: UIPageViewControllerDelegate {
@objc open func pageViewController(_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
guard completed else {
return
}
guard let viewController = pageViewController.viewControllers?.last else {
return
}
guard let index = viewControllerIndex(viewController) else {
return
}
currentIndex = index
if setNavigationTitle {
title = viewController.title
}
if let pageControl = pageControl {
pageControl.currentPage = currentIndex
}
pagesDelegate?.pageViewController(self, setViewController: pages[currentIndex], atPage: currentIndex)
}
}
// MARK: - Private methods
private extension PagesController {
func viewControllerIndex(_ viewController: UIViewController) -> Int? {
return pages.index(of: viewController)
}
func toggle() {
for subview in view.subviews {
if let subview = subview as? UIScrollView {
subview.isScrollEnabled = enableSwipe
break
}
}
}
func addViewController(_ viewController: UIViewController) {
pages.append(viewController)
if pages.count == 1 {
setViewControllers([viewController],
direction: .forward,
animated: true,
completion: { [unowned self] finished in
self.pagesDelegate?.pageViewController(self,
setViewController: viewController,
atPage: self.currentIndex)
})
if setNavigationTitle {
title = viewController.title
}
}
}
func addConstraints() {
view.addConstraint(NSLayoutConstraint(item: bottomLineView, attribute: .bottom,
relatedBy: .equal, toItem: view, attribute: .bottom,
multiplier: 1, constant: -Dimensions.bottomLineBottomMargin))
view.addConstraint(NSLayoutConstraint(item: bottomLineView, attribute: .left,
relatedBy: .equal, toItem: view, attribute: .left,
multiplier: 1, constant: Dimensions.bottomLineSideMargin))
view.addConstraint(NSLayoutConstraint(item: bottomLineView, attribute: .right,
relatedBy: .equal, toItem: view, attribute: .right,
multiplier: 1, constant: -Dimensions.bottomLineSideMargin))
view.addConstraint(NSLayoutConstraint(item: bottomLineView, attribute: .height,
relatedBy: .equal, toItem: nil, attribute: .notAnAttribute,
multiplier: 1, constant: Dimensions.bottomLineHeight))
}
}
// MARK: - Storyboard
extension PagesController {
public convenience init(_ storyboardIds: [String], storyboard: UIStoryboard = .Main) {
let pages = storyboardIds.map(storyboard.instantiateViewController(withIdentifier:))
self.init(pages)
}
}
| 29.329268 | 114 | 0.679418 |
8a847c24178abb16746e1e6cb1e76a8c18416507 | 258 | // 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{
class A{
typealias f=B
func b
{
}
typealias f=b
func b<T:f.c{
{
}
}
protocol B:b | 16.125 | 87 | 0.728682 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.