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
f9405306c153f058544f868eeab0f556f7a26bab
2,148
// // AppDelegate.swift // ZoomTransition // // Created by Said Marouf on 8/12/15. // Copyright © 2015 Said Marouf. All rights reserved. // import UIKit @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:. } }
45.702128
285
0.75419
fc7b2dc83436d2a4d2d8777781008d3940bfc4d5
1,219
// // arUITests.swift // arUITests // // Created by 조성현 on 2018. 4. 17.. // Copyright © 2018년 gaulim. All rights reserved. // import XCTest class arUITests: 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. } }
32.945946
182
0.654635
679662e91a53565e82e2abd05d9c8cbe98e8ca24
794
//: [Previous](@previous) import Foundation var input = getInput().split(separator: "\n") // MARK:- Part 1 var cubesState = [Cube: Bool]() for (row, cubes) in input.enumerated() { for (column, cube) in cubes.enumerated() { if cube == "#" { let c = Cube(x: column, y: row, z: 0) cubesState[c] = true } } } Cube.enableForth = false var cubesIn3D = cubesState for _ in 1...6 { cubesIn3D = liveCycle(cubes: cubesIn3D) } let answer = cubesIn3D.values.filter{ $0 }.count print("The answer is \(answer)") // MARK:- Part 2 Cube.enableForth = true var cubesIn4D = cubesState for _ in 1...6 { cubesIn4D = liveCycle(cubes: cubesIn4D) } let newAnswer = cubesIn4D.values.filter{ $0 }.count print("The answer is \(newAnswer)") //: [Next](@next)
21.459459
51
0.623426
50553bfb1b5c9666f5fa419456d47ec700cb3400
726
// 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: %target-swift-frontend %s -emit-silgen // Issue found by https://github.com/fluidsonic (Marc Knaup) class A { private let a = [B<(AnyObject, AnyObject) -> Void>]() func call(object1 object1: AnyObject, object2: AnyObject) { for b in a { b.c(object1, object2) } } } private class B<C> { let c: C init(c: C) { } }
27.923077
79
0.65978
7ad17580ef8bcc9cc5320fd5018d01b10712286b
3,799
// // APIRequest.swift // resolution // // Created by Johnny Good on 8/19/20. // Copyright © 2020 Unstoppable Domains. All rights reserved. // import Foundation public enum APIError: Error { case responseError case decodingError case encodingError } public typealias JsonRpcResponseArray = [JsonRpcResponse] public protocol NetworkingLayer { func makeHttpPostRequest (url: URL, httpMethod: String, httpHeaderContentType: String, httpBody: Data, completion: @escaping(Result<JsonRpcResponseArray, Error>) -> Void) } struct APIRequest { let url: URL let networking: NetworkingLayer init(_ endpoint: String, networking: NetworkingLayer) { self.url = URL(string: endpoint)! self.networking = networking } func post(_ body: JsonRpcPayload, completion: @escaping(Result<JsonRpcResponseArray, Error>) -> Void ) throws { do { networking.makeHttpPostRequest(url: self.url, httpMethod: "POST", httpHeaderContentType: "application/json", httpBody: try JSONEncoder().encode(body), completion: completion) } catch { throw APIError.encodingError } } func post(_ bodyArray: [JsonRpcPayload], completion: @escaping(Result<JsonRpcResponseArray, Error>) -> Void ) throws { do { networking.makeHttpPostRequest(url: self.url, httpMethod: "POST", httpHeaderContentType: "application/json", httpBody: try JSONEncoder().encode(bodyArray), completion: completion) } catch { throw APIError.encodingError } } } public struct DefaultNetworkingLayer: NetworkingLayer { public init() { } public func makeHttpPostRequest(url: URL, httpMethod: String, httpHeaderContentType: String, httpBody: Data, completion: @escaping(Result<JsonRpcResponseArray, Error>) -> Void) { var urlRequest = URLRequest(url: url) urlRequest.httpMethod = httpMethod urlRequest.addValue(httpHeaderContentType, forHTTPHeaderField: "Content-Type") urlRequest.httpBody = httpBody let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, _ in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let jsonData = data else { completion(.failure(APIError.responseError)) return } do { let result = try JSONDecoder().decode(JsonRpcResponseArray.self, from: jsonData) completion(.success(result)) } catch { do { let result = try JSONDecoder().decode(JsonRpcResponse.self, from: jsonData) completion(.success([result])) } catch { if let errorResponse = try? JSONDecoder().decode(NetworkErrorResponse.self, from: jsonData), let errorExplained = ResolutionError.parse(errorResponse: errorResponse) { completion(.failure(errorExplained)) } else { completion(.failure(APIError.decodingError)) } } } } dataTask.resume() } }
38.765306
122
0.537247
de1b0da0ccd926ed79d22bca672584f5424e1a5f
956
// // ViewController.swift // Pods-SwiftyComponents_Example // // Created by Pavel on 9/25/19. // import Foundation import UIKit public protocol UIControllerLifeCycleProtocol: class { // called on start func attachView() -> UIView var title: String { get } func onUpdate() } public class UIController: UIViewController { public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public weak var lifeCycleProtocol: UIControllerLifeCycleProtocol? override public func loadView() { view = lifeCycleProtocol?.attachView() } override public func viewDidLoad() { super.viewDidLoad() title = lifeCycleProtocol?.title } }
21.727273
89
0.655858
c1b7a5247362ce2ae517ed56e28ea27cb03b5cb7
740
// Copyright © 2020 Andy Liang. All rights reserved. import UIKit enum ImageAssets { static let defaultAlbumArt = UIImage(named: "DefaultAlbumArt")! static let play = UIImage(systemName: "play.fill") static let pause = UIImage(systemName: "pause.fill") static let backward = UIImage(systemName: "backward.fill") static let forward = UIImage(systemName: "forward.fill") static let musicNote = UIImage(systemName: "music.note") static let icloud = UIImage(systemName: "icloud.fill") static let repeating = UIImage(systemName: "repeat") static let waveform = UIImage(systemName: "waveform") static let flag = UIImage(systemName: "flag.fill") static let P = UIImage(systemName: "p.circle.fill") }
41.111111
67
0.714865
2109704d7465318182a57f40db81e983d6b9913f
2,737
// autogenerated // swiftlint:disable all import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif extension V1.AppInfoLocalizations.ById { public struct PATCH: Endpoint { public typealias Parameters = AppInfoLocalizationUpdateRequest public typealias Response = AppInfoLocalizationResponse public var path: String { "/v1/appInfoLocalizations/\(id)" } /// the id of the requested resource public var id: String /// AppInfoLocalization representation public var parameters: Parameters public init( id: String, parameters: Parameters ) { self.id = id self.parameters = parameters } public func request(with baseURL: URL) throws -> URLRequest? { var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true) components?.path = path var urlRequest = components?.url.map { URLRequest(url: $0) } urlRequest?.httpMethod = "PATCH" var jsonEncoder: JSONEncoder { let encoder = JSONEncoder() return encoder } urlRequest?.httpBody = try jsonEncoder.encode(parameters) urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type") return urlRequest } /// - Returns: **200**, Single AppInfoLocalization as `AppInfoLocalizationResponse` /// - Throws: **400**, Parameter error(s) as `ErrorResponse` /// - Throws: **403**, Forbidden error as `ErrorResponse` /// - Throws: **404**, Not found error as `ErrorResponse` /// - Throws: **409**, Request entity error(s) as `ErrorResponse` public static func response(from data: Data, urlResponse: HTTPURLResponse) throws -> Response { var jsonDecoder: JSONDecoder { let decoder = JSONDecoder() return decoder } switch urlResponse.statusCode { case 200: return try jsonDecoder.decode(AppInfoLocalizationResponse.self, from: data) case 400: throw try jsonDecoder.decode(ErrorResponse.self, from: data) case 403: throw try jsonDecoder.decode(ErrorResponse.self, from: data) case 404: throw try jsonDecoder.decode(ErrorResponse.self, from: data) case 409: throw try jsonDecoder.decode(ErrorResponse.self, from: data) default: throw try jsonDecoder.decode(ErrorResponse.self, from: data) } } } } // swiftlint:enable all
32.583333
103
0.597369
cc423a1de624a377ceda7daced6cfc9ee3c31ec6
4,772
// // AMShape.swift // AMDrawingView // // Created by Steve Landey on 7/23/18. // Copyright © 2018 Asana. All rights reserved. // import CoreGraphics import UIKit /** Base protocol which all shapes must implement. Note: If you implement your own shapes, see `Drawing.shapeDecoder`! */ public protocol Shape: AnyObject, Codable { /// Globally unique identifier for this shape. Meant to be used for equality /// checks, especially for network-based updates. var id: String { get } /// String value of this shape, for serialization and debugging static var type: String { get } /// Draw this shape to the given Core Graphics context. Transforms for drawing /// position and scale are already applied. func render(in context: CGContext) /// Return true iff the given point meaningfully intersects with the pixels /// drawn by this shape. See `ShapeWithBoundingRect` for a shortcut. func hitTest(point: CGPoint) -> Bool /// Apply any relevant values in `userSettings` (colors, sizes, fonts...) to /// this shape func apply(userSettings: UserSettings) } /** Enhancement to `Shape` protocol that allows you to simply specify a `boundingRect` property and have `hitTest` implemented automatically. */ public protocol ShapeWithBoundingRect: Shape { var boundingRect: CGRect { get } } extension ShapeWithBoundingRect { public func hitTest(point: CGPoint) -> Bool { return boundingRect.contains(point) } } /** Enhancement to `Shape` protocol that has a `transform` property, meaning it can be translated, rotated, and scaled relative to its original characteristics. */ public protocol ShapeWithTransform: Shape { var transform: ShapeTransform { get set } } /** Enhancement to `Shape` protocol that enforces requirements necessary for a shape to be used with the selection tool. This includes `ShapeWithBoundingRect` to render the selection rect around the shape, and `ShapeWithTransform` to allow the shape to be moved from its original position */ public protocol ShapeSelectable: ShapeWithBoundingRect, ShapeWithTransform { } extension ShapeSelectable { public func hitTest(point: CGPoint) -> Bool { return boundingRect.applying(transform.affineTransform).contains(point) } } /** Enhancement to `Shape` adding properties to match all `UserSettings` properties. There is a convenience method `apply(userSettings:)` which updates the shape to match the given values. */ public protocol ShapeWithStandardState: AnyObject { var strokeColor: UIColor? { get set } var fillColor: UIColor? { get set } var strokeWidth: CGFloat { get set } } extension ShapeWithStandardState { public func apply(userSettings: UserSettings) { strokeColor = userSettings.strokeColor fillColor = userSettings.fillColor strokeWidth = userSettings.strokeWidth } } /** Like `ShapeWithStandardState`, but ignores `UserSettings.fillColor`. */ public protocol ShapeWithStrokeState: AnyObject { var strokeColor: UIColor { get set } var strokeWidth: CGFloat { get set } } extension ShapeWithStrokeState { public func apply(userSettings: UserSettings) { strokeColor = userSettings.strokeColor ?? .black strokeWidth = userSettings.strokeWidth } } /** Special case of `Shape` where the shape is defined by exactly two points. This case is used to share code between the line, ellipse, and rectangle shapes and tools. */ public protocol ShapeWithTwoPoints { var a: CGPoint { get set } var b: CGPoint { get set } var strokeWidth: CGFloat { get set } } extension ShapeWithTwoPoints { public var rect: CGRect { let x1 = min(a.x, b.x) let y1 = min(a.y, b.y) let x2 = max(a.x, b.x) let y2 = max(a.y, b.y) return CGRect(x: x1, y: y1, width: x2 - x1, height: y2 - y1) } public var squareRect: CGRect { let width = min(abs(b.x - a.x), abs(b.y - a.y)) let x = b.x < a.x ? a.x - width : a.x let y = b.y < a.y ? a.y - width : a.y return CGRect(x: x, y: y, width: width, height: width) } public var boundingRect: CGRect { return rect.insetBy(dx: -strokeWidth/2, dy: -strokeWidth/2) } } /** Special case of `Shape` where the shape is defined by exactly three points. */ public protocol ShapeWithThreePoints { var a: CGPoint { get set } var b: CGPoint { get set } var c: CGPoint { get set } var strokeWidth: CGFloat { get set } } extension ShapeWithThreePoints { public var rect: CGRect { let x1 = min(a.x, b.x, c.x) let y1 = min(a.y, b.y, c.y) let x2 = max(a.x, b.x, c.x) let y2 = max(a.y, b.y, c.y) return CGRect(x: x1, y: y1, width: x2 - x1, height: y2 - y1) } public var boundingRect: CGRect { return rect.insetBy(dx: -strokeWidth/2, dy: -strokeWidth/2) } }
28.404762
80
0.700754
087c5dfb32e87be6911c6592f2ee595cfdf22093
238
// // SignInUser.swift // HairCare // // Created by Tobi Kuyoro on 06/02/2020. // Copyright © 2020 Tobi Kuyoro. All rights reserved. // import Foundation struct SignInUser: Codable { let email: String let password: String }
15.866667
54
0.680672
3a0b14e656e9ba87831ce9fbd2a7487f9f6f54e6
326
// 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 { func a<T where g: b { func a<T where I.E == c, class B<T : b { func b let t: B<T where I.E == c, { let start = a { protocol c { class case c, case
20.375
87
0.684049
e8892cab2a5d89ade34cccc3fe2712a84d3ffaf2
382
// Copyright SIX DAY LLC. All rights reserved. import Moya protocol TrustNetworkProtocol { var provider: MoyaProvider<TrustService> { get } var balanceService: TokensBalanceService { get } var account: Wallet { get } var config: Config { get } init(provider: MoyaProvider<TrustService>, balanceService: TokensBalanceService, account: Wallet, config: Config) }
31.833333
117
0.740838
210ad113fc2d062745973c90d75379c05347ff05
4,344
// // StateMachineTests.swift // StateMachineTests // // Created by Alex Rupérez on 20/1/18. // Copyright © 2018 alexruperez. All rights reserved. // import XCTest @testable import StateMachine class StateA: State { var deltaTime: TimeInterval = 0 func update(_ deltaTime: TimeInterval) { self.deltaTime = deltaTime } func isValidNext<S>(state type: S.Type) -> Bool where S : State { return type is StateB.Type } } class StateB: State { func isValidNext<S>(state type: S.Type) -> Bool where S : State { switch type { case is StateA.Type, is StateC.Type: return true default: return false } } } class StateC: State { func isValidNext<S>(state type: S.Type) -> Bool where S : State { return type is StateA.Type } } class StateMachineTests: XCTestCase { var stateMachine: StateMachine! override func setUp() { super.setUp() stateMachine = StateMachine([StateA(), StateB(), StateC()]) } override func tearDown() { stateMachine = nil super.tearDown() } func testStartWithA() { XCTAssertNil(stateMachine.current) XCTAssert(stateMachine.enter(StateA.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateA) } func testStartWithB() { XCTAssertNil(stateMachine.current) XCTAssert(stateMachine.enter(StateB.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateB) } func testStartWithC() { XCTAssertNil(stateMachine.current) XCTAssert(stateMachine.enter(StateC.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateC) } func testAB() { XCTAssert(stateMachine.enter(StateA.self)) XCTAssert(stateMachine.enter(StateB.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateB) } func testBC() { XCTAssert(stateMachine.enter(StateB.self)) XCTAssert(stateMachine.enter(StateC.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateC) } func testCA() { XCTAssert(stateMachine.enter(StateC.self)) XCTAssert(stateMachine.enter(StateA.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateA) } func testABA() { XCTAssert(stateMachine.enter(StateA.self)) XCTAssert(stateMachine.enter(StateB.self)) XCTAssert(stateMachine.enter(StateA.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateA) } func testAC() { XCTAssert(stateMachine.enter(StateA.self)) XCTAssertFalse(stateMachine.enter(StateC.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateA) } func testCB() { XCTAssert(stateMachine.enter(StateC.self)) XCTAssertFalse(stateMachine.enter(StateB.self)) XCTAssertNotNil(stateMachine.current) XCTAssert(stateMachine.current is StateC) } func testUpdate() { XCTAssert(stateMachine.enter(StateA.self)) let deltaTime = TimeInterval(arc4random_uniform(10) + 1) stateMachine.update(deltaTime) XCTAssertEqual((stateMachine.current as? StateA)?.deltaTime, deltaTime) XCTAssert(stateMachine.enter(StateB.self)) stateMachine.update(deltaTime) } func testSubscribe() { stateMachine.subscribe { (previous, current) in XCTAssertNil(previous) XCTAssertNotNil(current) XCTAssert(current is StateA) } XCTAssert(stateMachine.enter(StateA.self)) } func testUnsubscribe() { let index = stateMachine.subscribe { _, _ in } XCTAssert(stateMachine.enter(StateA.self)) XCTAssert(stateMachine.unsubscribe(index)) XCTAssertFalse(stateMachine.unsubscribe(index)) } func testUnsubscribeAll() { let index = stateMachine.subscribe { _, _ in } XCTAssert(stateMachine.enter(StateA.self)) stateMachine.unsubscribeAll() XCTAssertFalse(stateMachine.unsubscribe(index)) } }
28.578947
79
0.654696
3a57419844ecb5f1a232c0868f034db134eb149e
2,146
// // AppDelegate.swift // LLAEasyButtonDemo // // Created by Daisuke T on 2019/01/28. // Copyright © 2019 LLAEasyButtonDemo. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.659574
281
0.771668
e8b6768e96e9557800ca443d24864f64e8761571
15,440
import Foundation extension Data { public func getField(_ index: Int, width bitsField: Int) -> Int64 { let type = UInt32.self let bitWidth = type.bitWidth let bitPos = index * bitsField let i = bitPos / bitWidth let j = bitPos % bitWidth if (j+bitsField) <= bitWidth { let d : UInt32 = self.withUnsafeBytes { $0[i] } return (Int64(d) << (bitWidth-j-bitsField)) >> (bitWidth-bitsField) } else { return self.withUnsafeBytes { (p : UnsafePointer<UInt32>) -> Int64 in let _r = p[i] let _d = p[i+1] let r = Int64(_r) >> j let d = Int64(_d) << ((bitWidth<<1) - j - bitsField) return r | (d >> (bitWidth-bitsField)) } } } public func getFieldsImmediate(width valueWidth: Int, count: Int) -> [Int64] { guard valueWidth > 0 else { return [Int64](repeating: 0, count: count) } let bitWidth64 = UInt64.self.bitWidth var values = [Int64](reserveCapacity: count) var index = 0 let baseMask64 = ((UInt64(1) << (valueWidth)) - 1) let splitShiftLeftBase = (bitWidth64<<1) - valueWidth let splitShiftRight = bitWidth64-valueWidth repeat { let bitPos = index * valueWidth index += 1 let (offset_u64, intraValueBitOffset64) = bitPos.quotientAndRemainder(dividingBy: bitWidth64) if (intraValueBitOffset64+valueWidth) <= bitWidth64 { let d : UInt64 = self.withUnsafeBytes { $0[offset_u64] } let mask = baseMask64 << intraValueBitOffset64 let v1 = (d & mask) >> intraValueBitOffset64 values.append(Int64(v1)) } else { let v1 = self.withUnsafeBytes { (p : UnsafePointer<UInt64>) -> Int64 in let r = p[offset_u64] >> intraValueBitOffset64 let d = p[offset_u64+1] << (splitShiftLeftBase - intraValueBitOffset64) let v = r | (d >> splitShiftRight) return Int64(v) } values.append(Int64(v1)) } } while index < count return values } public func getFields(width valueWidth: Int, count: Int) -> AnySequence<Int64> { guard valueWidth > 0 else { let values = [Int64](repeating: 0, count: count) return AnySequence(values) } let bitWidth64 = UInt64.self.bitWidth return AnySequence { () -> BlockIterator<Int64> in var index = 0 let baseMask64 = ((UInt64(1) << (valueWidth)) - 1) let splitShiftLeftBase = (bitWidth64<<1) - valueWidth let splitShiftRight = bitWidth64-valueWidth return BlockIterator { guard index < count else { return nil } let bitPos = index * valueWidth index += 1 let (offset_u64, intraValueBitOffset64) = bitPos.quotientAndRemainder(dividingBy: bitWidth64) if (intraValueBitOffset64+valueWidth) <= bitWidth64 { let d : UInt64 = self.withUnsafeBytes { $0[offset_u64] } let mask = baseMask64 << intraValueBitOffset64 let v1 = (d & mask) >> intraValueBitOffset64 return [Int64(v1)] } else { let v1 = self.withUnsafeBytes { (p : UnsafePointer<UInt64>) -> Int64 in let r = p[offset_u64] >> intraValueBitOffset64 let d = p[offset_u64+1] << (splitShiftLeftBase - intraValueBitOffset64) let v = r | (d >> splitShiftRight) return Int64(v) } return [v1] } } } } } struct StderrOutputStream: TextOutputStream { public static let stream = StderrOutputStream() public func write(_ string: String) {fputs(string, stderr)} } var errStream = StderrOutputStream.stream func warn(_ item: Any) { if true { print(item, to: &errStream) } } public enum FileState { case none case opened(CInt) } func readVByte(_ ptr : inout UnsafeMutableRawPointer) -> UInt { var p = ptr.assumingMemoryBound(to: UInt8.self) var value : UInt = 0 var cont = true var shift = 0 repeat { let b = p[0] let bvalue = UInt(b & 0x7f) cont = ((b & 0x80) == 0) p += 1 value += bvalue << shift; shift += 7 } while cont ptr = UnsafeMutableRawPointer(p) return value } func readData(from mmappedPtr: UnsafeMutableRawPointer, at offset: off_t, length: Int) throws -> Data { var readBuffer = mmappedPtr readBuffer += Int(offset) let data = Data(bytesNoCopy: readBuffer, count: length, deallocator: .none) return data } func readSequenceLazy(from mmappedPtr: UnsafeMutableRawPointer, at offset: off_t, assertType: UInt8? = nil) throws -> (AnySequence<Int64>, Int64) { var readBuffer = mmappedPtr readBuffer += Int(offset) let crcStart = readBuffer let p = readBuffer.assumingMemoryBound(to: UInt8.self) let typeLength: Int if let assertType = assertType { let type = p[0] typeLength = 1 guard type == assertType else { throw HDTError.error("Invalid dictionary LogSequence2 type (\(type)) at offset \(offset)") } } else { typeLength = 0 } let bits = Int(p[typeLength]) let bitsLength = 1 var ptr = readBuffer + typeLength + bitsLength let entriesCount = Int(readVByte(&ptr)) let crc = CRC8(crcStart, length: crcStart.distance(to: ptr)) let expectedCRC8 = ptr.assumingMemoryBound(to: UInt8.self).pointee ptr += 1 if crc.crc8 != expectedCRC8 { let d = Int(offset) + readBuffer.distance(to: ptr) - 1 let s = String(format: "CRC8 failure at %d: got %02x, expected %02x", d, Int(crc.crc8), Int(expectedCRC8)) throw HDTError.error(s) } let arraySize = (bits * entriesCount + 7) / 8 let sequenceDataOffset = off_t(readBuffer.distance(to: ptr)) let crc32Start = ptr let sequenceData = try readData(from: mmappedPtr, at: offset + sequenceDataOffset, length: arraySize) ptr += arraySize let values = sequenceData.getFields(width: bits, count: entriesCount) let crc32 = CRC32(crc32Start, length: Int(arraySize)) let expectedCRC32 = ptr.assumingMemoryBound(to: UInt32.self).pointee let crcLength = 4 ptr += crcLength if crc32.crc32 != expectedCRC32 { let d = Int(offset) + readBuffer.distance(to: ptr) - crcLength let s = String(format: "CRC32 failure at %d: got %08x, expected %08x", d, crc32.crc32, expectedCRC32) throw HDTError.error(s) } let length = Int64(readBuffer.distance(to: ptr)) let seq = AnySequence(values) return (seq, length) } func readSequenceImmediate(from mmappedPtr: UnsafeMutableRawPointer, at offset: off_t, assertType: UInt8? = nil) throws -> ([Int64], Int64) { var readBuffer = mmappedPtr readBuffer += Int(offset) let crcStart = readBuffer let p = readBuffer.assumingMemoryBound(to: UInt8.self) let typeLength: Int if let assertType = assertType { let type = p[0] typeLength = 1 guard type == assertType else { throw HDTError.error("Invalid dictionary LogSequence2 type (\(type)) at offset \(offset)") } } else { typeLength = 0 } let bits = Int(p[typeLength]) let bitsLength = 1 var ptr = readBuffer + typeLength + bitsLength let entriesCount = Int(readVByte(&ptr)) let crc = CRC8(crcStart, length: crcStart.distance(to: ptr)) let expectedCRC8 = ptr.assumingMemoryBound(to: UInt8.self).pointee ptr += 1 if crc.crc8 != expectedCRC8 { let d = Int(offset) + readBuffer.distance(to: ptr) - 1 let s = String(format: "CRC8 failure at %d: got %02x, expected %02x", d, Int(crc.crc8), Int(expectedCRC8)) throw HDTError.error(s) } let arraySize = (bits * entriesCount + 7) / 8 let sequenceDataOffset = off_t(readBuffer.distance(to: ptr)) let crc32Start = ptr let sequenceData = try readData(from: mmappedPtr, at: offset + sequenceDataOffset, length: arraySize) ptr += arraySize let values = sequenceData.getFieldsImmediate(width: bits, count: entriesCount) let crc32 = CRC32(crc32Start, length: Int(arraySize)) let expectedCRC32 = ptr.assumingMemoryBound(to: UInt32.self).pointee let crcLength = 4 ptr += crcLength if crc32.crc32 != expectedCRC32 { let d = Int(offset) + readBuffer.distance(to: ptr) - crcLength let s = String(format: "CRC32 failure at %d: got %08x, expected %08x", d, crc32.crc32, expectedCRC32) throw HDTError.error(s) } let length = Int64(readBuffer.distance(to: ptr)) return (values, length) } func readBitmap(from mmappedPtr: UnsafeMutableRawPointer, at offset: off_t) throws -> (BlockIterator<Int>, Int64, Int64) { var readBuffer = mmappedPtr readBuffer += Int(offset) let crcStart = readBuffer let p = readBuffer.assumingMemoryBound(to: UInt8.self) let type = p[0] let typeLength = 1 guard type == 1 else { throw HDTError.error("Invalid bitmap type (\(type)) at offset \(offset)") } var ptr = readBuffer + typeLength let bitCount = Int(readVByte(&ptr)) let bytes = (bitCount + 7)/8 let crc = CRC8(crcStart, length: crcStart.distance(to: ptr)) let expectedCRC8 = ptr.assumingMemoryBound(to: UInt8.self).pointee ptr += 1 if crc.crc8 != expectedCRC8 { let d = Int(offset) + readBuffer.distance(to: ptr) - 1 let s = String(format: "CRC8 failure at %d: got %02x, expected %02x", d, Int(crc.crc8), Int(expectedCRC8)) throw HDTError.error(s) } let crc32Start = ptr let data = Data(bytesNoCopy: ptr, count: bytes, deallocator: .none) // let data = Data(bytes: ptr, count: bytes) var shift = 0 let blockIterator = BlockIterator { () -> [Int]? in var block = [Int]() repeat { for _ in 0..<16 { guard shift < data.count else { if block.isEmpty { return nil } else { return block } } let b = data[shift] let add = shift*8 if (b & 0x01) > 0 { block.append(0 + add) } if (b & 0x02) > 0 { block.append(1 + add) } if (b & 0x04) > 0 { block.append(2 + add) } if (b & 0x08) > 0 { block.append(3 + add) } if (b & 0x10) > 0 { block.append(4 + add) } if (b & 0x20) > 0 { block.append(5 + add) } if (b & 0x40) > 0 { block.append(6 + add) } if (b & 0x80) > 0 { block.append(7 + add) } // print("\(offset): [\(shift)]: \(block)") shift += 1 } } while block.isEmpty return block } ptr += bytes let crc32 = CRC32(crc32Start, length: Int(bytes)) let expectedCRC32 = ptr.assumingMemoryBound(to: UInt32.self).pointee let crcLength = 4 ptr += crcLength if crc32.crc32 != expectedCRC32 { let d = Int(offset) + readBuffer.distance(to: ptr) - crcLength let s = String(format: "CRC32 failure at %d: got %08x, expected %08x", d, crc32.crc32, expectedCRC32) throw HDTError.error(s) } let length = Int64(readBuffer.distance(to: ptr)) return (blockIterator, Int64(bitCount), length) } func readArray(from mmappedPtr: UnsafeMutableRawPointer, at offset: off_t) throws -> (AnySequence<Int64>, Int64) { var readBuffer = mmappedPtr readBuffer += Int(offset) let p = readBuffer.assumingMemoryBound(to: UInt8.self) let type = p[0] switch type { case 1: let (blocks, blocksLength) = try readSequenceLazy(from: mmappedPtr, at: offset, assertType: 1) return (blocks, blocksLength) case 2: throw HDTError.error("Array read unimplemented: uint32") // TODO: implement case 3: throw HDTError.error("Array read unimplemented: uint64") // TODO: implement default: throw HDTError.error("Invalid array type (\(type)) at offset \(offset)") } } public struct ConcatenateIterator<I: IteratorProtocol> : IteratorProtocol { public typealias Element = I.Element var iterators: [I] var current: I? public init(_ iterators: I...) { self.iterators = iterators if let first = self.iterators.first { self.current = first self.iterators.remove(at: 0) } else { self.current = nil } } public mutating func next() -> I.Element? { repeat { guard current != nil else { return nil } if let item = current!.next() { return item } else if let i = iterators.first { current = i iterators.remove(at: 0) } else { current = nil } } while true } } public struct BlockIterator<K>: IteratorProtocol { var base: () -> [K]? var open: Bool var buffer: [K] var index: Int public init(_ base: @escaping () -> [K]?) { self.open = true self.base = base self.buffer = [] self.index = buffer.endIndex } public mutating func dropFirst(_ k: Int) { // OPTIMIZE: drop in blocks for _ in 0..<k { _ = next() } } public mutating func next() -> K? { guard self.open else { return nil } repeat { if index != buffer.endIndex { let item = buffer[index] index = buffer.index(after: index) return item } guard open, let newBuffer = base() else { open = false return nil } buffer = newBuffer index = buffer.startIndex } while true } } struct PeekableIterator<T: IteratorProtocol> : IteratorProtocol { public typealias Element = T.Element private var generator: T private var bufferedElement: Element? public init(generator: T) { self.generator = generator bufferedElement = self.generator.next() } public mutating func next() -> Element? { let r = bufferedElement bufferedElement = generator.next() return r } public func peek() -> Element? { return bufferedElement } mutating func dropWhile(filter: (Element) -> Bool) { while bufferedElement != nil { if !filter(bufferedElement!) { break } _ = next() } } mutating public func elements() -> [Element] { var elements = [Element]() while let e = next() { elements.append(e) } return elements } }
33.638344
147
0.565803
dec1048340c72afd43c263458734f99ac5f967d1
1,601
// // MVVMView.swift // iOS-MVX // // Created by simon on 2017/3/2. // Copyright © 2017年 simon. All rights reserved. // import UIKit class MVVMView: UIView { fileprivate lazy var nameLb: UILabel = { let nameLb = UILabel(frame: CGRect(x: 100, y: 100, width: 200, height: 100)) nameLb.textColor = .black nameLb.textAlignment = .center nameLb.font = UIFont.systemFont(ofSize: 20) nameLb.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(clickName)) nameLb.addGestureRecognizer(tap) return nameLb }() var mvvmVM: MVVMViewModel? { didSet { mvvmVM?.addObserver(self, forKeyPath: "name", options: [.new, .initial], context: nil) } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "name" { let name = change?[.newKey] as? String setName(name) } } override init(frame: CGRect) { super.init(frame: frame) addSubview(nameLb) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { mvvmVM?.removeObserver(self, forKeyPath: "name") } } extension MVVMView { @objc fileprivate func clickName() { mvvmVM?.clickName() } fileprivate func setName(_ name: String?) { nameLb.text = name } }
24.630769
151
0.589007
48356c7c6a42d58136d01e28dc95b88b11abfbc9
151
// // Owner.swift // iOSEngineerCodeCheck // // Created by TanakaHirokazu on 2021/10/30. // struct Owner: Decodable { let avatarUrl: String? }
13.727273
44
0.668874
fb2ba72cae5389b6fdfb0d984f84de34839d2ab0
1,165
// // UILabelExtension.swift // appStore // // Created by myslab on 2020/09/19. // Copyright © 2020 mys. All rights reserved. // import UIKit extension UILabel { func highlight(searchedText: String?..., color: UIColor = UIColor(named: "FindFocusColor") ?? .red) { guard let txtLabel = self.text else { return } let attributeTxt = NSMutableAttributedString(string: txtLabel) let range = NSRange(location: 0, length: txtLabel.count) attributeTxt.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.systemGray, range: range) self.attributedText = attributeTxt searchedText.forEach { if let searchedText = $0?.lowercased() { let range: NSRange = attributeTxt.mutableString.range(of: searchedText, options: .caseInsensitive) attributeTxt.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range) attributeTxt.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: self.font.pointSize), range: range) } } self.attributedText = attributeTxt } }
34.264706
143
0.672961
9c77c330fce6237e9077b994a51a4a168ebd3148
150
import XCTest import alerts_and_pickers_new_3Tests var tests = [XCTestCaseEntry]() tests += alerts_and_pickers_new_3Tests.allTests() XCTMain(tests)
18.75
49
0.826667
bb34cb77d6ade64834094555da1746de0346ade7
190
// // MainMainRouter.swift // Weather // // Created by Sergey V. Krupov on 28/01/2019. // Copyright © 2019 Home. All rights reserved. // final class MainRouter: MainRouterProtocol { }
15.833333
47
0.684211
bb9ded7a0a7e7bebb21209997695e016ede15a0a
1,596
// // BusinessCell.swift // Yelp // // Created by Ibukun on 2/18/18. // Copyright © 2018 Timothy Lee. All rights reserved. // import UIKit class BusinessCell: UITableViewCell { var business: Business! { didSet { nameLabel.text = business.name thumbImageView.setImageWith(business.imageURL!) categoriesLabel.text = business.categories addressLabel.text = business.address reviewCountLabel.text = "\(business.reviewCount!) Reviews" ratingImageView.setImageWith(business.ratingImageURL!) distanceLabel.text = business.distance } } @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var ratingImageView: UIImageView! @IBOutlet weak var reviewCountLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code imageView?.layer.cornerRadius = 3 thumbImageView.clipsToBounds = true nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func layoutSubviews() { super.layoutSubviews() 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 } }
29.555556
70
0.667293
08a7cae533ac63aa0178fa1b96386012b4d48a3c
1,363
// // CarInfoCheckInViewCell.swift // Traffic_sys_Swift // // Created by 易无解 on 17/10/2017. // Copyright © 2017 易无解. All rights reserved. // import UIKit class CarInfoCheckInViewCell: HomeViewCell { // MARK: - 系统回调函数 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) valueLabel.isHidden = true sexSelector.isHidden = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } // MARK: - 外部接口 extension CarInfoCheckInViewCell { static func checkInCellWithTableView(tableView: UITableView) -> UITableViewCell? { let kCarInfoCheckInViewCellIdentifier = "CarInfoCheckInViewCell" var cell = tableView.dequeueReusableCell(withIdentifier: kCarInfoCheckInViewCellIdentifier) if cell == nil { cell = CarInfoCheckInViewCell(style: .subtitle, reuseIdentifier: kCarInfoCheckInViewCellIdentifier) } return cell } }
26.211538
111
0.674248
fb96cdb09a169e354d6bbb6ad62facfc27a74f3c
4,687
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.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 UIKit /** The QRCodeViewControllerBuilder aims to create a simple configuration object for the QRCode view controller. */ public final class QRCodeReaderViewControllerBuilder { // MARK: - Configuring the QRCodeViewController Objects /** The builder block. The block gives a reference of builder you can configure. */ public typealias QRCodeReaderViewControllerBuilderBlock = (QRCodeReaderViewControllerBuilder) -> Void /** The title to use for the cancel button. */ public var cancelButtonTitle = "Cancel" /** The code reader object used to scan the bar code. */ public var reader = QRCodeReader() /** The reader container view used to display the video capture and the UI components. */ public var readerView = QRCodeReaderContainer(displayable: QRCodeReaderView()) /** Flag to know whether the view controller start scanning the codes when the view will appear. */ public var startScanningAtLoad = true /** Flag to display the cancel button. */ public var showCancelButton = true /** Flag to display the switch camera button. */ public var showSwitchCameraButton: Bool { get { return _showSwitchCameraButton && reader.hasFrontDevice } set { _showSwitchCameraButton = newValue } } private var _showSwitchCameraButton: Bool = true /** Flag to display the toggle torch button. If the value is true and there is no torch the button will not be displayed. */ public var showTorchButton: Bool { get { return _showTorchButton && reader.isTorchAvailable } set { _showTorchButton = newValue } } private var _showTorchButton = true /** Flag to display the guide view. */ public var showOverlayView = false /** Flag to display the guide view. */ public var handleOrientationChange = true /** A UIStatusBarStyle key indicating your preferred status bar style for the view controller. Nil by default. It means it'll use the current context status bar style. */ public var preferredStatusBarStyle: UIStatusBarStyle? = nil /** Specifies a rectangle of interest for limiting the search area for visual metadata. The value of this property is a CGRect that determines the receiver's rectangle of interest for each frame of video. The rectangle's origin is top left and is relative to the coordinate space of the device providing the metadata. Specifying a rectOfInterest may improve detection performance for certain types of metadata. The default value of this property is the value CGRectMake(0, 0, 1, 1). Metadata objects whose bounds do not intersect with the rectOfInterest will not be returned. */ public var rectOfInterest: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1) { didSet { reader.metadataOutput.rectOfInterest = CGRect( x: min(max(rectOfInterest.origin.x, 0), 1), y: min(max(rectOfInterest.origin.y, 0), 1), width: min(max(rectOfInterest.width, 0), 1), height: min(max(rectOfInterest.height, 0), 1) ) } } // MARK: - Initializing a Flap View /** Initialize a QRCodeViewController builder with default values. */ public init() {} /** Initialize a QRCodeReaderViewController builder with default values. - parameter buildBlock: A QRCodeReaderViewController builder block to configure itself. */ public init(buildBlock: QRCodeReaderViewControllerBuilderBlock) { buildBlock(self) } }
33.007042
490
0.726051
e88a5588197aafd2d0b1fb7263fe0d1e7965b7bd
3,265
// // ViewController.swift // Instagram // // Created by ARG Lab on 2/25/18. // Copyright © 2018 Odin. All rights reserved. // import UIKit import Parse class LoginViewController: UIViewController { @IBOutlet weak var usernameLabel: UITextField! @IBOutlet weak var passwordLabel: UITextField! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. activityIndicator.stopAnimating() } @IBAction func loginButton(_ sender: Any) { loginUser() } @IBAction func signupButton(_ sender: Any) { registerUser() } func loginUser() { activityIndicator.startAnimating() let username = usernameLabel.text ?? "" let password = passwordLabel.text ?? "" if (username.isEmpty || password.isEmpty){ let alert = UIAlertController(title: nil, message: "Username or Password is empty", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) activityIndicator.stopAnimating() } PFUser.logInWithUsername(inBackground: username, password: password) { (user: PFUser?, error: Error?) in if let error = error { print("User log in failed: \(error.localizedDescription)") let alert = UIAlertController(title: nil, message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) self.activityIndicator.stopAnimating() } else { print("User logged in successfully") // display view controller that needs to shown after successful login self.performSegue(withIdentifier: "loginSegue", sender: nil) } } } func registerUser() { // initialize a user object let newUser = PFUser() newUser.username = usernameLabel.text ?? "" newUser.password = passwordLabel.text ?? "" // call sign up function on the object newUser.signUpInBackground { (success: Bool, error: Error?) in if let error = error { print(error.localizedDescription) let alert = UIAlertController(title: nil, message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { print("User Registered successfully") // manually segue to logged in view //self.performSegue(withIdentifier: "pushSegue" , sender: self) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
35.107527
119
0.601225
117aa4c45a12dfabc5d764d461bb59502c035d38
3,001
// // Power.swift // Velik // // Created by Grigory Avdyushin on 20/06/2020. // Copyright © 2020 Grigory Avdyushin. All rights reserved. // import Foundation struct Parameters { enum Defaults { static let altitude = Measurement(value: 0, unit: UnitLength.meters) static let temperature = Measurement(value: 20, unit: UnitTemperature.celsius) static let wind = Measurement(value: 0, unit: UnitSpeed.metersPerSecond) static let mass = Measurement(value: 80, unit: UnitMass.kilograms) } let avgSpeed: Measurement<UnitSpeed> let altitude: Measurement<UnitLength> let temperature: Measurement<UnitTemperature> let wind: Measurement<UnitSpeed> let weight: Measurement<UnitMass> let segmentDistance: Measurement<UnitLength>? let segmentElevation: Measurement<UnitLength>? init(avgSpeed: Measurement<UnitSpeed>, altitude: Measurement<UnitLength> = Defaults.altitude, temperature: Measurement<UnitTemperature> = Defaults.temperature, wind: Measurement<UnitSpeed> = Defaults.wind, weight: Measurement<UnitMass> = Defaults.mass, segmentDistance: Measurement<UnitLength>? = nil, segmentElevation: Measurement<UnitLength>? = nil) { self.avgSpeed = avgSpeed self.altitude = altitude self.temperature = temperature self.wind = wind self.weight = weight self.segmentDistance = segmentDistance self.segmentElevation = segmentElevation } } struct Power { // swiftlint:disable identifier_name static func power(parameters: Parameters) -> Measurement<UnitPower> { // Input let v = parameters.avgSpeed.converted(to: .metersPerSecond).value let h = parameters.altitude.converted(to: .meters).value let t = parameters.temperature.converted(to: .kelvin).value let m = parameters.weight.converted(to: .kilograms).value let w = parameters.wind.converted(to: .metersPerSecond).value let H = parameters.segmentElevation?.converted(to: .meters).value ?? 0 let L = parameters.segmentDistance?.converted(to: .meters).value ?? 1 // Constants let p = 101325.0 // zero pressure let M = 0.0289654 // molar mass of dry air let R = 8.31447 // ideal gas constant let Hn = 10400.0 // height reference let g = 9.8 // gravitational acceleration let loss = 0.02 // 2% let CdA = [0.388, 0.445, 0.420, 0.300, 0.233, 0.200] // Cd * A let Crr = [0.005, 0.004, 0.012] // rolling resistance // Calculations let rho = p * M / (R * t) * exp(-h / Hn) let V = pow(v + w, 2) let theta = asin(H / L) let Fg = m * g * sin(theta) let Fr = m * g * Crr[0] * cos(theta) let Fd = 0.5 * CdA[0] * rho * V let power = (Fg + Fr + Fd) * v * (1 + loss) return Measurement(value: power, unit: .watts) } // swiftlint:enable identifier_name }
35.72619
86
0.636121
e632d4f5ebd27a4a7ef86bb75e2eccf7aa5c7155
1,023
// // UIColor+Hex.swift // MLCardDrawer // // Created by Vinicius De Andrade Silva on 25/03/21. // extension UIColor { class func fromHex(_ hexValue: String) -> UIColor { let hexAlphabet = "0123456789abcdefABCDEF" let hex = hexValue.trimmingCharacters(in: CharacterSet(charactersIn: hexAlphabet).inverted) var hexInt = UInt32() Scanner(string: hex).scanHexInt32(&hexInt) let alpha, red, green, blue: UInt32 switch hex.count { case 3: (alpha, red, green, blue) = (255, (hexInt >> 8) * 17, (hexInt >> 4 & 0xF) * 17, (hexInt & 0xF) * 17) // RGB case 6: (alpha, red, green, blue) = (255, hexInt >> 16, hexInt >> 8 & 0xFF, hexInt & 0xFF) // RRGGBB case 8: (alpha, red, green, blue) = (hexInt >> 24, hexInt >> 16 & 0xFF, hexInt >> 8 & 0xFF, hexInt & 0xFF) // AARRGGBB default: return UIColor.black } return UIColor(red: CGFloat(red)/255, green: CGFloat(green)/255, blue: CGFloat(blue)/255, alpha: CGFloat(alpha)/255) } }
42.625
126
0.610948
9b7d521b9a3a678399e18b3b752015be236b78d0
631
// // ListControlFlowMock.swift // TelephoneDirectoryTests // // Created by Daniele Salvioni on 24/11/2019. // Copyright © 2019 Daniele Salvioni. All rights reserved. // import Foundation class ListControlFlowMock: ListPresenterFlowProtocol { var flowAddContact: Bool = false var flowEditContact: Bool = false var contact: ContactModel? func requestFlowAddContact(presenter: ListPresenter) { self.flowAddContact = true } func requestFlowEditContact(presenter: ListPresenter, contact: ContactModel) { self.flowEditContact = true self.contact = contact } }
22.535714
80
0.70206
bb67086d761df3294e3fcd334d48c1d78e8a7a8c
1,139
// // SSGoAuthLoginError..swift // Okee // // Created by Son Nguyen on 12/5/20. // import Foundation import FirebaseAuth public enum SSGoAuthLoginError: Error { case unknown case invalidCredential case userDisabled case userNotFound case accountConflicted case networkError case noInternetError case tokenExpired static func convertedError(forErorr error: Error) -> SSGoAuthLoginError { switch AuthErrorCode(rawValue: error._code) { case .wrongPassword, .invalidEmail, .invalidCredential: return .invalidCredential case .userDisabled: return .userDisabled case .userNotFound: return .userNotFound case .accountExistsWithDifferentCredential: return .accountConflicted case .networkError: if (error._userInfo?["NSUnderlyingError"] as? Error)?.isNoInternetError ?? false { return .noInternetError } return .networkError case .userTokenExpired: return .tokenExpired default: return .unknown } } }
26.488372
94
0.638279
cc53c501851b1c5af8caa0ab99a676c3c375fa79
22,662
// // PhotoEditorViewController.swift // MetalFilters // // Created by xushuifeng on 2018/6/9. // Copyright © 2018 shuifeng.me. All rights reserved. // import UIKit import Photos import MetalPetal import TensorFlowLite class PhotoEditorViewController: UIViewController { @IBOutlet weak var previewView: UIView! @IBOutlet weak var filtersView: UIView! @IBOutlet weak var filterButton: UIButton! @IBOutlet weak var editButton: UIButton! fileprivate var filterCollectionView: UICollectionView! fileprivate var toolCollectionView: UICollectionView! fileprivate var filterControlView: FilterControlView? fileprivate var imageView: MTIImageView! public var croppedImage: UIImage! fileprivate var originInputImage: MTIImage? fileprivate var adjustFilter = MTBasicAdjustFilter() fileprivate var allFilters: [MTFilter.Type] = [] fileprivate var allTools: [FilterToolItem] = [] fileprivate var thumbnails: [String: UIImage] = [:] fileprivate var cachedFilters: [Int: MTFilter] = [:] /// TODO /// It seems that we should have a group to store all filter states /// Currently just simply restore to selected filters fileprivate var currentSelectFilterIndex: Int = 0 fileprivate var showUnEditedGesture: UILongPressGestureRecognizer? fileprivate var currentAdjustStrengthFilter: MTFilter? // MARK: Instance Variables // Holds the results at any time private var result: Result? private var initialBottomSpace: CGFloat = 0.0 private var previousInferenceTimeMs: TimeInterval = Date.distantPast.timeIntervalSince1970 * 1000 // Handles all data preprocessing and makes calls to run inference through the `Interpreter`. private var modelDataHandler: ModelDataHandler? = ModelDataHandler(modelFileInfo: RAPIDNet.modelInfo) override func viewDidLoad() { super.viewDidLoad() guard modelDataHandler != nil else { fatalError("Model set up failed") } setupNavigationBar() imageView = MTIImageView(frame: previewView.bounds) imageView.resizingMode = .aspectFill imageView.backgroundColor = .clear previewView.addSubview(imageView) allFilters = MTFilterManager.shard.allFilters setupFilterCollectionView() setupToolDataSource() setupToolCollectionView() let ciImage = CIImage(cgImage: croppedImage.cgImage!) let originImage = MTIImage(ciImage: ciImage, isOpaque: true) originInputImage = originImage imageView.image = originImage generateFilterThumbnails() setupNavigationButton() } private func setupNavigationBar() { let luxImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) luxImageView.image = UIImage(named: "edit-luxtool") navigationItem.titleView = luxImageView } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if showUnEditedGesture == nil { let gesture = UILongPressGestureRecognizer(target: self, action: #selector(showUnEditPhotoGesture(_:))) gesture.minimumPressDuration = 0.02 imageView.addGestureRecognizer(gesture) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated) } private func setupNavigationButton() { let leftBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelBarButtonTapped(_:))) let rightBarButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(saveBarButtonTapped(_:))) self.navigationItem.leftBarButtonItem = leftBarButton self.navigationItem.rightBarButtonItem = rightBarButton } private func clearNavigationButton() { self.navigationItem.leftBarButtonItem = nil self.navigationItem.hidesBackButton = true self.navigationItem.rightBarButtonItem = nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() filterCollectionView.frame.size = filtersView.bounds.size toolCollectionView.frame.size = filtersView.bounds.size } override var prefersStatusBarHidden: Bool { return true } fileprivate func getFilterAtIndex(_ index: Int) -> MTFilter { if let filter = cachedFilters[index] { return filter } let filter = allFilters[index].init() cachedFilters[index] = filter return filter } @objc func showUnEditPhotoGesture(_ gesture: UILongPressGestureRecognizer) { switch gesture.state { case .cancelled, .ended: let filter = getFilterAtIndex(currentSelectFilterIndex) filter.inputImage = originInputImage imageView.image = filter.outputImage break default: let filter = getFilterAtIndex(0) filter.inputImage = originInputImage imageView.image = filter.outputImage break } } @objc func cancelBarButtonTapped(_ sender: Any) { navigationController?.popViewController(animated: false) } @objc func saveBarButtonTapped(_ sender: Any) { guard let image = self.imageView.image, let uiImage = MTFilterManager.shard.generate(image: image) else { return } PHPhotoLibrary.shared().performChanges({ let _ = PHAssetCreationRequest.creationRequestForAsset(from: uiImage) }) { (success, error) in DispatchQueue.main.async { let alert = UIAlertController(title: nil, message: "Photo Saved!", preferredStyle: .alert) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { self.dismiss(animated: true, completion: nil) }) self.present(alert, animated: true, completion: nil) } } } fileprivate func setupFilterCollectionView() { let frame = CGRect(x: 0, y: 0, width: filtersView.bounds.width, height: filtersView.bounds.height - 44) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = .zero layout.itemSize = CGSize(width: 104, height: frame.height) layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) filterCollectionView = UICollectionView(frame: frame, collectionViewLayout: layout) filterCollectionView.backgroundColor = .clear filterCollectionView.showsHorizontalScrollIndicator = false filterCollectionView.showsVerticalScrollIndicator = false filtersView.addSubview(filterCollectionView) filterCollectionView.dataSource = self filterCollectionView.delegate = self filterCollectionView.register(FilterPickerCell.self, forCellWithReuseIdentifier: NSStringFromClass(FilterPickerCell.self)) filterCollectionView.reloadData() } fileprivate func setupToolCollectionView() { let frame = CGRect(x: 0, y: 0, width: filtersView.bounds.width, height: filtersView.bounds.height - 44) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = .zero layout.itemSize = CGSize(width: 98, height: frame.height) layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) toolCollectionView = UICollectionView(frame: frame, collectionViewLayout: layout) toolCollectionView.backgroundColor = .clear toolCollectionView.showsHorizontalScrollIndicator = false toolCollectionView.showsVerticalScrollIndicator = false toolCollectionView.dataSource = self toolCollectionView.delegate = self toolCollectionView.register(ToolPickerCell.self, forCellWithReuseIdentifier: NSStringFromClass(ToolPickerCell.self)) toolCollectionView.reloadData() } fileprivate func setupToolDataSource() { allTools.removeAll() allTools.append(FilterToolItem(type: .adjust, slider: .adjustStraighten)) allTools.append(FilterToolItem(type: .brightness, slider: .negHundredToHundred)) allTools.append(FilterToolItem(type: .contrast, slider: .negHundredToHundred)) allTools.append(FilterToolItem(type: .structure, slider: .zeroToHundred)) allTools.append(FilterToolItem(type: .warmth, slider: .negHundredToHundred)) allTools.append(FilterToolItem(type: .saturation, slider: .negHundredToHundred)) allTools.append(FilterToolItem(type: .color, slider: .negHundredToHundred)) allTools.append(FilterToolItem(type: .fade, slider: .zeroToHundred)) allTools.append(FilterToolItem(type: .highlights, slider: .negHundredToHundred)) allTools.append(FilterToolItem(type: .shadows, slider: .negHundredToHundred)) allTools.append(FilterToolItem(type: .vignette, slider: .zeroToHundred)) allTools.append(FilterToolItem(type: .tiltShift, slider: .tiltShift)) allTools.append(FilterToolItem(type: .sharpen, slider: .zeroToHundred)) } fileprivate func generateFilterThumbnails() { let group = DispatchGroup() group.enter() DispatchQueue.global().async { let size = CGSize(width: 200, height: 200) UIGraphicsBeginImageContextWithOptions(size, false, 0) self.croppedImage.draw(in: CGRect(origin: .zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if let image = scaledImage { for filter in self.allFilters { let image = MTFilterManager.shard.generateThumbnailsForImage(image, with: filter) self.thumbnails[filter.name] = image // DispatchQueue.main.async { // self.filterCollectionView.reloadData() // } } } group.leave() } group.wait() // TODO: predictImage predictImage(originImage:croppedImage) // for filter in self.allFilters { DispatchQueue.main.async { self.filterCollectionView.reloadData() } // } } @IBAction func filterButtonTapped(_ sender: Any) { addCollectionView(at: 0) } @IBAction func editButtonTapped(_ sender: Any) { addCollectionView(at: 1) } fileprivate func addCollectionView(at index: Int) { let isFilterTabSelected = index == 0 if isFilterTabSelected && filterButton.isSelected { return } if !isFilterTabSelected && editButton.isSelected { return } UIView.animate(withDuration: 0.5, animations: { if isFilterTabSelected { self.toolCollectionView.removeFromSuperview() self.filtersView.addSubview(self.filterCollectionView) } else { self.filterCollectionView.removeFromSuperview() self.filtersView.addSubview(self.toolCollectionView) } }) { (finish) in self.filterButton.isSelected = isFilterTabSelected self.editButton.isSelected = !isFilterTabSelected } } fileprivate func presentFilterControlView(for tool: FilterToolItem) { //adjustFilter.inputImage = imageView.image adjustFilter.inputImage = originInputImage let width = self.filtersView.bounds.width let height = self.filtersView.bounds.height + 44 + view.safeAreaInsets.bottom let frame = CGRect(x: 0, y: view.bounds.height - height + 44, width: width, height: height) let value = valueForFilterControlView(with: tool) let controlView = FilterControlView(frame: frame, filterTool: tool, value: value) controlView.delegate = self filterControlView = controlView UIView.animate(withDuration: 0.2, animations: { self.view.addSubview(controlView) controlView.setPosition(offScreen: false) }) { finish in self.title = tool.title self.clearNavigationButton() } } fileprivate func dismissFilterControlView() { UIView.animate(withDuration: 0.2, animations: { self.filterControlView?.setPosition(offScreen: true) }) { finish in self.filterControlView?.removeFromSuperview() self.title = "Editor" self.setupNavigationButton() } } fileprivate func valueForFilterControlView(with tool: FilterToolItem) -> Float { switch tool.type { case .adjustStrength: return 1.0 case .adjust: return 0 case .brightness: return adjustFilter.brightness case .contrast: return adjustFilter.contrast case .structure: return 0 case .warmth: return adjustFilter.temperature case .saturation: return adjustFilter.saturation case .color: return 0 case .fade: return adjustFilter.fade case .highlights: return adjustFilter.highlights case .shadows: return adjustFilter.shadows case .vignette: return adjustFilter.vignette case .tiltShift: return adjustFilter.tintShadowsIntensity case .sharpen: return adjustFilter.sharpen } } } extension PhotoEditorViewController: FilterControlViewDelegate { func filterControlViewDidPressCancel() { dismissFilterControlView() } func filterControlViewDidPressDone() { dismissFilterControlView() } func filterControlViewDidStartDragging() { } func filterControlView(_ controlView: FilterControlView, didChangeValue value: Float, filterTool: FilterToolItem) { if filterTool.type == .adjustStrength { currentAdjustStrengthFilter?.strength = value imageView.image = currentAdjustStrengthFilter?.outputImage return } switch filterTool.type { case .adjust: break case .brightness: adjustFilter.brightness = value break case .contrast: adjustFilter.contrast = value break case .structure: break case .warmth: adjustFilter.temperature = value break case .saturation: adjustFilter.saturation = value break case .color: adjustFilter.tintShadowsColor = .green adjustFilter.tintShadowsIntensity = 1 break case .fade: adjustFilter.fade = value break case .highlights: adjustFilter.highlights = value break case .shadows: adjustFilter.shadows = value break case .vignette: adjustFilter.vignette = value break case .tiltShift: adjustFilter.tintShadowsIntensity = value case .sharpen: adjustFilter.sharpen = value default: break } imageView.image = adjustFilter.outputImage } func filterControlViewDidEndDragging() { } func filterControlView(_ controlView: FilterControlView, borderSelectionChangeTo isSelected: Bool) { if isSelected { let blendFilter = MTIBlendFilter(blendMode: .overlay) let filter = getFilterAtIndex(currentSelectFilterIndex) blendFilter.inputBackgroundImage = filter.borderImage blendFilter.inputImage = imageView.image imageView.image = blendFilter.outputImage } else { // let filter = getFilterAtIndex(currentSelectFilterIndex) // filter.inputImage = originInputImage // imageView.image = filter.outputImage } } } extension PhotoEditorViewController: UICollectionViewDataSource, UICollectionViewDelegate { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == filterCollectionView { return allFilters.count } return allTools.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == filterCollectionView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(FilterPickerCell.self), for: indexPath) as! FilterPickerCell let filter = allFilters[indexPath.item] cell.update(filter) cell.thumbnailImageView.image = thumbnails[filter.name] return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(ToolPickerCell.self), for: indexPath) as! ToolPickerCell let tool = allTools[indexPath.item] cell.update(tool) return cell } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if collectionView == filterCollectionView { if currentSelectFilterIndex == indexPath.item { if indexPath.item != 0 { let item = FilterToolItem(type: .adjustStrength, slider: .zeroToHundred) presentFilterControlView(for: item) currentAdjustStrengthFilter = allFilters[currentSelectFilterIndex].init() currentAdjustStrengthFilter?.inputImage = originInputImage } } else { let filter = allFilters[indexPath.item].init() filter.inputImage = originInputImage imageView.image = filter.outputImage currentSelectFilterIndex = indexPath.item } } else { let tool = allTools[indexPath.item] presentFilterControlView(for: tool) } } func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / size.width let heightRatio = targetSize.height / size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) } else { newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } // func buffer(from image: UIImage) -> CVPixelBuffer? { let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary var pixelBuffer : CVPixelBuffer? let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(image.size.width), Int(image.size.height), kCVPixelFormatType_32ARGB, attrs, &pixelBuffer) guard (status == kCVReturnSuccess) else { return nil } CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: pixelData, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) context?.translateBy(x: 0, y: image.size.height) context?.scaleBy(x: 1.0, y: -1.0) UIGraphicsPushContext(context!) image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) UIGraphicsPopContext() CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) return pixelBuffer } func predictImage(originImage: UIImage){ var input_data: [CVPixelBuffer] = [] // let original_buffer = buffer(from: originImage) // input_data.append(original_buffer!) for filter in self.allFilters { let temp_filter_image: UIImage? = self.thumbnails[filter.name] print(filter.name) // print(type(of: temp_filter_image)) if(temp_filter_image != nil){ let temp_filter_buffer = buffer(from: temp_filter_image!) input_data.append(temp_filter_buffer!) } } print(input_data.count) // TODO: input to model // Pass the pixel buffer to TensorFlow Lite to perform inference. result = modelDataHandler?.runModel(pixelBuffer: input_data) print(result as Any) var tempFilters: [MTFilter.Type] = [] tempFilters.append(allFilters[0]) for i in (result?.inferences)!{ if(i.label != 0){ tempFilters.append(allFilters[i.label]) } } // TODO : change allFilter order allFilters = tempFilters print(allFilters) } }
38.871355
262
0.643191
f9a1b2f7dbcc0025c618c55a342ae3800f4c57f0
1,795
// // NotificationListView.Cell.swift // NotificationHub // // Created by Yudai.Hirose on 2019/06/07. // Copyright © 2019 bannzai. All rights reserved. // import SwiftUI import Combine import NotificationHubCore import NotificationHubData import NotificationHubRedux extension NotificationListView { struct Cell: RenderableView { let notification: NotificationElement let didSelectCell: (NotificationElement) -> Void struct Props { let notification: NotificationElement } func map(state: AppState, dispatch: @escaping DispatchFunction) -> Props { Props( notification: notification ) } var cellGestuer: some Gesture { TapGesture().onEnded { self.didSelectCell(self.notification) } } func body(props: Props) -> some View { HStack { Group { ImageLoaderView(url: props.notification.repository.owner.avatarURL, defaultImage: UIImage(systemName: "person")!) .modifier(ThumbnailImageViewModifier()) VStack(alignment: .leading) { Text(props.notification.repository.fullName).font(.headline).lineLimit(1) Text(props.notification.subject.title).font(.subheadline) } } .gesture(cellGestuer) } } } } #if DEBUG struct NotificationListView_Cell_Previews : PreviewProvider { static var previews: some View { List { NotificationListView.Cell(notification: debugNotification) { (element) in print(element) } } } } #endif
28.492063
133
0.573259
9c50f11af07410a9cce06c2cb2c3a4578426e3bd
1,743
// // NSPersistentStoreCoordinator.swift // // // Created by 0xZala on 2/26/21. // import Foundation import CoreData extension NSPersistentStoreCoordinator { static func destroyStore(at storeURL: URL) { do { let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: NSManagedObjectModel()) try persistentStoreCoordinator.destroyPersistentStore(at: storeURL, ofType: NSSQLiteStoreType, options: nil) } catch let error { fatalError("failed to destroy persistent store at \(storeURL), error: \(error)") } } static func replaceStore(at targetURL: URL, withStoreAt sourceURL: URL) { do { let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: NSManagedObjectModel()) try persistentStoreCoordinator.replacePersistentStore(at: targetURL, destinationOptions: nil, withPersistentStoreFrom: sourceURL, sourceOptions: nil, ofType: NSSQLiteStoreType) } catch let error { fatalError("failed to replace persistent store at \(targetURL) with \(sourceURL), error: \(error)") } } static func metadata(at storeURL: URL) -> [String : Any]? { return try? NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: NSSQLiteStoreType, at: storeURL, options: nil) } func addPersistentStore(at storeURL: URL, options: [AnyHashable : Any]) -> NSPersistentStore { do { return try addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch let error { fatalError("failed to add persistent store to coordinator, error: \(error)") } } }
41.5
188
0.691337
4ab83a2374dd27f4e6cc5e3c8ec1f047417ea1b4
10,281
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ import XCTest @testable import ClientRuntime class DateFormatterTests: XCTestCase { var testDateFormatter: DateFormatter = DateFormatter() func testCreateDateFromValidRFC5322String() { let validDates = [ // standard "Sun, 20 Nov 1993 05:45:1 GMT": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 05, minute: 45, second: 1), // different timeZone from default GMT "Mon, 20 Nov 1993 05:45:1 CST": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 11, minute: 45, second: 1), "Tue, 1 Nov 1993 05:45:10 GMT": ExpectedDateComponents(day: 1, month: 11, year: 1993, hour: 05, minute: 45, second: 10), // Different offset specs "Tue, 20 Nov 1993 05:45:10 +0000": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 05, minute: 45, second: 10), "Tue, 20 Nov 1993 05:45:00 -0015": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 06, minute: 0, second: 0), "Mon, 20 Nov 1993 14:02:02 +000": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 14, minute: 2, second: 2), // default to GMT for unknown timeZones "Tue, 20 Nov 1993 05:45:10 UT": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 05, minute: 45, second: 10), "Tue, 20 Nov 1993 05:45:10 Z": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 05, minute: 45, second: 10), // components without padding "Mon, 20 Nov 193 05:45:10 GMT": ExpectedDateComponents(day: 20, month: 11, year: 193, hour: 05, minute: 45, second: 10), "Mon, 20 Nov 1993 4:2:7 GMT": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 4, minute: 2, second: 7) ] let formatter = DateFormatter.rfc5322DateFormatter for (dateString, dateComponents) in validDates { guard let constructedDate = formatter.date(from: dateString) else { XCTFail("could not parse RFC7231 string: \(dateString)") continue } matchDateComponents(date: constructedDate, components: dateComponents, dateString: dateString) } } func testCreateDateFromInValidRFC5322StringReturnsNil() { let inValidDates = [ "Sun, 06 Nov 1994 08:49 GMT", "06 Nov 1994 08:49:37 GMT", "Son, 06 Nov 1994 08:49:37 GMT", "Mon, 06 Now 1994 08:49:37 GMT", "Mon,06 Nov 1994 08:49:37 GMT", "Mon, 32 Nov 1994 08:49:37 GMT", "Mon, 07 Nov 1994 14:62:37 GMT", "Mon, 07 Nov 1994 14:02:72 GMT" ] let formatter = DateFormatter.rfc5322DateFormatter for dateString in inValidDates { let constructedDate: Date? = formatter.date(from: dateString) XCTAssertNil(constructedDate, "able to parse invalid RFC7231 string: \(dateString)") } } func testCreateDateFromValidISO8601StringWithoutFractionalSeconds() { let validDates = [ // standard "1993-11-20T05:45:01Z": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 45, second: 1), "1993-11-20T05:45:01z": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 45, second: 1), // with offset "1993-11-20T05:45:01+05:00": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 0, minute: 45, second: 1), "1993-11-20T05:45:01-05:00": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 10, minute: 45, second: 1), "1993-11-20T05:45:01-00:02": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 47, second: 1), "1993-11-20T05:45:01-00:00:10": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 45, second: 11), "1993-11-20T05:05:01 -0050": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 55, second: 1), "1993-11-20T05:50:01 +005001": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 0, second: 0), // padding zeroes is handled "193-7-022T05:00045:001 +005001": ExpectedDateComponents(day: 22, month: 7, year: 193, hour: 4, minute: 55, second: 0) ] let formatter = DateFormatter.iso8601DateFormatterWithoutFractionalSeconds for (dateString, dateComponents) in validDates { guard let constructedDate = formatter.date(from: dateString) else { XCTFail("could not parse ISO8601 string: \(dateString)") continue } matchDateComponents(date: constructedDate, components: dateComponents, dateString: dateString) } } func testCreateDateFromValidISO8601StringWithFractionalSeconds() { // TODO:: why is the precision for nanoSeconds low? let validDates = [ // standard "1993-11-20T05:45:01.1Z": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 45, second: 1, nanoSecond: 100000023), "1993-11-20T05:45:01.1z": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 45, second: 1, nanoSecond: 100000023), "1993-11-20T05:00:00.123456789z": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 0, second: 0, nanoSecond: 123000025), "1993-11-20T05:45:01.0-05:00": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 10, minute: 45, second: 1, nanoSecond: 0), "1993-11-20T05:45:01.010-00:02": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 47, second: 1, nanoSecond: 9999990), "1993-11-20T05:45:01.123456-00:00:10": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 45, second: 11, nanoSecond: 123000025), "1993-11-20T05:05:01.1 -0050": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 55, second: 1, nanoSecond: 100000023), "1993-11-20T05:50:01.007 +005001": ExpectedDateComponents(day: 20, month: 11, year: 1993, hour: 5, minute: 0, second: 0, nanoSecond: 6999969) ] let formatter = DateFormatter.iso8601DateFormatterWithFractionalSeconds for (dateString, dateComponents) in validDates { guard let constructedDate = formatter.date(from: dateString) else { XCTFail("could not parse ISO8601 string: \(dateString)") continue } matchDateComponents(date: constructedDate, components: dateComponents, dateString: dateString) } } func testCreateDateFromInValidISO8601StringReturnsNil() { let inValidDates = [ "1993-11-20", "20201105T02:31:22Z", "20201105", "2017-07-032T03:30:00Z", "2017-07-22T03::00Z", "2017-07-22T03:0f:00Z", "1993-11-20T05:45:01z+05:00" ] let formatterWithoutFractionalSeconds = DateFormatter.iso8601DateFormatterWithoutFractionalSeconds let formatterWithFractionalSeconds = DateFormatter.iso8601DateFormatterWithFractionalSeconds for dateString in inValidDates { var constructedDate: Date? = formatterWithoutFractionalSeconds.date(from: dateString) XCTAssertNil(constructedDate, "able to parse invalid ISO8601 string: \(dateString)") constructedDate = formatterWithFractionalSeconds.date(from: dateString) XCTAssertNil(constructedDate, "able to parse invalid ISO8601 string: \(dateString)") } } struct ExpectedDateComponents { let day: Int let month: Int let year: Int let hour: Int let minute: Int let second: Int let nanoSecond: Int? init(day: Int, month: Int, year: Int, hour: Int, minute: Int, second: Int, nanoSecond: Int? = nil) { self.day = day self.month = month self.year = year self.hour = hour self.minute = minute self.second = second self.nanoSecond = nanoSecond } } func matchDateComponents(date: Date, components: ExpectedDateComponents, dateString: String) { var calendar = Calendar.current calendar.timeZone = TimeZone(abbreviation: "GMT")! // It is known that GMT exists XCTAssertEqual(calendar.component(.day, from: date), components.day, "Failed to match day for \(dateString)") XCTAssertEqual(calendar.component(.month, from: date), components.month, "Failed to match month for \(dateString)") XCTAssertEqual(calendar.component(.year, from: date), components.year, "Failed to match year for \(dateString)") XCTAssertEqual(calendar.component(.hour, from: date), components.hour, "Failed to match hour for \(dateString)") XCTAssertEqual(calendar.component(.minute, from: date), components.minute, "Failed to match minute for \(dateString)") XCTAssertEqual(calendar.component(.second, from: date), components.second, "Failed to match second for \(dateString)") if components.nanoSecond != nil { XCTAssertEqual(calendar.component(.nanosecond, from: date), components.nanoSecond, "Failed to match nano second for \(dateString)") } } }
48.042056
127
0.58399
ff2ea98b757824d2fc4f29225d862bbb71182c31
12,745
// // Checkbox.swift // AnimatedCheckbox // // Created by Nicolás Miari on 2018/12/11. // Copyright © 2018 Nicolás Miari. All rights reserved. // import UIKit /** A checkbox-like toggle switch control. The box can be styled in rounded, square, circle or superellipse (squircle) shape. Additionally, an optional title label can be displayed to the left or right of the checkbox. The control receives touches both within the bounds of checkbox itself as well as on those of the title label. Transitions between the checked (selected) and unchecked (deselcted) states are animated much like the standard checkboxes in macOS. The colors of various components, as well as the label layout and checkbox shape can be customized; see the exposed properties for further details. */ @IBDesignable class Checkbox: UIControl { // MARK: - Configuration (Interfce Builder) @IBInspectable var title: String = "" { didSet { titleLabel.text = title updateComponentFrames() } } @IBInspectable var textColor: UIColor = .darkGray { didSet { titleLabel.textColor = textColor } } @IBInspectable var offBorder: UIColor { set { normalBorderColor = newValue } get { return normalBorderColor } } @IBInspectable var onBorder: UIColor { set { self.selectedBorderColor = newValue } get { return selectedBorderColor } } @IBInspectable var overcheck: Bool { set { self.overdrawFill = newValue } get { return overdrawFill } } /// If true, the title label is placed left of the checkbox; otherwise, it /// is placed to the right. @IBInspectable var leftTitle: Bool { set { self.titlePosition = newValue ? .left : .right } get { return titlePosition == .left } } @IBInspectable var radio: Bool { set { self.style = newValue ? .circle : .square } get { return style == .circle } } @IBInspectable var ellipsoid: Bool { set { self.style = newValue ? .superellipse : .square } get { return style == .superellipse } } // MARK: - Configuration (Programmatic) /// Color of the checkbox's outline when unchecked. var normalBorderColor: UIColor = .lightGray { didSet { if !isSelected { frameLayer.strokeColor = normalBorderColor.cgColor } } } /// Color of the checkbox's outline when checked. Ignored if `overdrawFill` /// is true. var selectedBorderColor: UIColor = .lightGray { didSet { if isSelected { frameLayer.strokeColor = selectedBorderColor.cgColor } } } /// Font used in the title label. var font: UIFont = UIFont.systemFont(ofSize: 17) enum Style { case square case circle case superellipse } var style: Style = .square { didSet { updatePaths() } } enum TitlePosition { case left case right } var titlePosition: TitlePosition = .left { didSet { updateComponentFrames() } } /** If true, the checked state is drawn on top, obscuring the box outline. In this case, the property `selectedBorderColor` is seen only briefly, during the transition. */ var overdrawFill: Bool = false { didSet { if overdrawFill { fillLayer.removeFromSuperlayer() self.layer.addSublayer(fillLayer) } else { fillLayer.removeFromSuperlayer() self.layer.insertSublayer(fillLayer, at: 0) } } } // MARK: - Internal Structure // Displayes the optional title. private let titleLabel: UILabel // Displayes the outline of the unchecked box or radio button. private var frameLayer: CAShapeLayer! // Displays the fill color and checkmark of the checked box or radio button. private var fillLayer: CAShapeLayer! // When checked, fill and checkmark fade in while growing from this scale // factor to full size (1.0). private let shrinkingFactor: CGFloat = 0.5 // The side length of the checkbox (or diameter of the radio button), in points. private let sideLength: CGFloat = 28 // 40 private var boxSize: CGSize { return CGSize(width: sideLength, height: sideLength) } // The corner radius of the checkbox. For radio button, it equals sideLength/2. private var cornerRadius: CGFloat = 6 // The color of the filled (checked) backgrond, when highlighted (about to deselect). private var adjustedTintColor: UIColor! { return tintColor.darkened(byPercentage: 0.2) } // MARK: - UIView override var tintColor: UIColor! { didSet { if isHighlighted { fillLayer.fillColor = adjustedTintColor.cgColor } else { fillLayer.fillColor = tintColor.cgColor } } } override var intrinsicContentSize: CGSize { titleLabel.sizeToFit() let labelSize = titleLabel.intrinsicContentSize let width: CGFloat = { guard labelSize.width > 0 else { return boxSize.width } return labelSize.width + 8 + boxSize.width }() let height = max(labelSize.height, boxSize.height) return CGSize(width: width, height: height) } override var frame: CGRect { didSet { updateComponentFrames() } } // MARK: - UIControl override var isEnabled: Bool { didSet { if isEnabled { self.alpha = 1 } else { self.alpha = 0.5 } } } override var isHighlighted: Bool { didSet { if isHighlighted { if isSelected { fillLayer.fillColor = adjustedTintColor.cgColor } else { frameLayer.lineWidth = 4 } } else { if isSelected { fillLayer.fillColor = tintColor.cgColor } else { frameLayer.lineWidth = 2 } //self.tintAdjustmentMode = .normal } } } override var isSelected: Bool { didSet { if isSelected { fillLayer.opacity = 1 fillLayer.transform = CATransform3DIdentity if overdrawFill { frameLayer.strokeColor = tintColor.cgColor } else { frameLayer.strokeColor = selectedBorderColor.cgColor } } else { fillLayer.opacity = 0 fillLayer.transform = CATransform3DMakeScale(shrinkingFactor, shrinkingFactor, 1) frameLayer.strokeColor = normalBorderColor.cgColor } sendActions(for: .valueChanged) } } override init(frame: CGRect) { self.titleLabel = UILabel(frame: .zero) super.init(frame: frame) addSubview(titleLabel) configureComponents() } required init?(coder aDecoder: NSCoder) { self.titleLabel = UILabel(frame: .zero) super.init(coder: aDecoder) addSubview(titleLabel) configureComponents() } override func tintColorDidChange() { super.tintColorDidChange() fillLayer.setNeedsDisplay() } override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { self.isHighlighted = true return true } override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { self.isHighlighted = isTouchInside return true } override func endTracking(_ touch: UITouch?, with event: UIEvent?) { self.isHighlighted = false if isTouchInside { isSelected = !isSelected } } // MARK: - Support private func configureComponents() { self.clipsToBounds = false titleLabel.text = title titleLabel.font = font titleLabel.textColor = UIColor.darkGray titleLabel.sizeToFit() // Rounded gray frame (uncheked state) self.frameLayer = CAShapeLayer() frameLayer.bounds = CGRect(origin: .zero, size: boxSize) frameLayer.lineWidth = 2 frameLayer.strokeColor = UIColor.lightGray.cgColor frameLayer.fillColor = UIColor.clear.cgColor self.layer.addSublayer(frameLayer) // Rounded blue square (checked state) //self.fillLayer = CALayer() self.fillLayer = CAShapeLayer() fillLayer.bounds = CGRect(origin: .zero, size: boxSize) fillLayer.strokeColor = UIColor.clear.cgColor fillLayer.fillColor = tintColor.cgColor fillLayer.opacity = 0 fillLayer.transform = CATransform3DMakeScale(shrinkingFactor, shrinkingFactor, 1) if overdrawFill { self.layer.addSublayer(fillLayer) } else { self.layer.insertSublayer(fillLayer, at: 0) } // White Tick (checked state) let scalingFactor: CGFloat = sideLength / 40 let tickPath = UIBezierPath() tickPath.move(to: CGPoint(x: 11 * scalingFactor, y: 21 * scalingFactor)) tickPath.addLine(to: CGPoint(x: 17 * scalingFactor, y: 28 * scalingFactor)) tickPath.addLine(to: CGPoint(x: 30 * scalingFactor, y: 12 * scalingFactor)) let tickLayer = CAShapeLayer() tickLayer.path = tickPath.cgPath tickLayer.fillColor = nil tickLayer.strokeColor = UIColor.white.cgColor tickLayer.lineWidth = 3 tickLayer.lineCap = .round tickLayer.lineJoin = .round /* tickLayer.shadowColor = UIColor.black.cgColor tickLayer.shadowOpacity = 0.25 tickLayer.shadowOffset = CGSize(width: 0, height: 2) tickLayer.shadowRadius = 1 */ fillLayer.addSublayer(tickLayer) updateComponentFrames() updatePaths() } private func updatePaths() { switch style { case .square: frameLayer.path = CGPath(roundedRect: frameLayer.bounds, cornerWidth: cornerRadius, cornerHeight: cornerRadius, transform: nil) fillLayer.path = CGPath(roundedRect: fillLayer.bounds, cornerWidth: cornerRadius, cornerHeight: cornerRadius, transform: nil) case .circle: frameLayer.path = CGPath(ellipseIn: frameLayer.bounds, transform: nil) fillLayer.path = CGPath(ellipseIn: fillLayer.bounds, transform: nil) case .superellipse: frameLayer.path = UIBezierPath.superellipse(in: frameLayer.bounds, cornerRadius: 15).cgPath fillLayer.path = UIBezierPath.superellipse(in: frameLayer.bounds, cornerRadius: 15).cgPath } } private func updateComponentFrames() { titleLabel.sizeToFit() guard frameLayer != nil else { return } let size = intrinsicContentSize let labelBounds = titleLabel.bounds let innerMargin: CGFloat = labelBounds.width > 0 ? 8 : 0 switch titlePosition { case .left: // Label: to the left, centered vertically let labelOrigin = CGPoint(x: 0, y: round((size.height - labelBounds.height)/2)) let labelFrame = CGRect(origin: labelOrigin, size: labelBounds.size) titleLabel.frame = labelFrame let boxOrigin = CGPoint( x: labelFrame.width + innerMargin, y: round((size.height - boxSize.height)/2) ) let boxFrame = CGRect(origin: boxOrigin, size: boxSize) frameLayer?.frame = boxFrame fillLayer?.frame = boxFrame fillLayer?.bounds = CGRect(origin: .zero, size: boxSize) case .right: let boxFrame = CGRect(origin: .zero, size: boxSize) frameLayer?.frame = boxFrame fillLayer?.frame = boxFrame fillLayer?.bounds = CGRect(origin: .zero, size: boxSize) let labelOrigin = CGPoint(x: boxSize.width + innerMargin, y: round((size.height - labelBounds.height)/2)) let labelFrame = CGRect(origin: labelOrigin, size: labelBounds.size) titleLabel.frame = labelFrame } } }
29.298851
139
0.589172
227f3624249ef094e65ee083e696c815dfd7a4fb
2,907
// // regions.swift // worldRegions // // Created by Usha Natarajan on 8/30/17. // Copyright © 2017 Usha Natarajan. All rights reserved. // import Foundation enum Subregions:String{ case eastAsia = "Eastern Asia" case westAsia = "Western Asia" case centralAsia = "Central Asia" case southAsia = "Southern Asia" case southEastAsia = "South-Eastern Asia" case northAfrica = "Northern Africa" case westAfrica = "Western Africa" case eastAfrica = "Eastern Africa" case centralAfrica = "Central Africa" case southernAfrica = "Southern Africa" case australiaNewzealand = "Australia and New Zealand" case polynesia = "Polynesia" case melanesia = "Melanesia" case micronesia = "Micronesia" case northEurope = "Northern Europe" case westEurope = "Western Europe" case eastEurope = "Eastern Europe" case southernEurope = "Southern Europe" case northAmerica = "Northern America" case caribbean = "Caribbean" case centralAmerica = "Central America" case andeanStates = "Andean States" case southernCone = "Southern Cone" case brazil = "Brazil" case guayanas = "Guayanas" case polar = "Polar" var description:String{ switch self{ case .eastAsia : return "Eastern Asia" case .westAsia : return "Western Asia" case .centralAsia : return "Central Asia" case .southAsia : return "Southern Asia" case .southEastAsia : return "South-Eastern Asia" case .northAfrica : return "Northern Africa" case .westAfrica : return "Western Africa" case .eastAfrica : return "Eastern Africa" case .centralAfrica : return "Central Africa" case .southernAfrica : return "Southern Africa" case .australiaNewzealand : return "Australia and New Zealand" case .polynesia : return "Polynesia" case .melanesia : return "Melanesia" case .micronesia : return "Micronesia" case .northEurope : return "Northern Europe" case .westEurope : return "Western Europe" case .eastEurope : return "Eastern Europe" case .southernEurope : return "Southern Europe" case .northAmerica : return "Northern America" case .caribbean : return "Caribbean" case .centralAmerica : return "Central America" case .andeanStates : return "Andean States" case .southernCone : return "Southern Cone" case .brazil : return "Brazil" case .guayanas : return "Guayanas" case .polar : return "Polar" } } }//end of Subregions
30.28125
58
0.592019
fb3dc1dad97fe78884d08c409a709127366be0e4
845
// // CalendarPickerModel.swift // CalendarPicker // // Created by Igor Drljic on 2.12.21.. // import Foundation extension Calendar { static var prefered: Calendar { var calendar = Calendar(identifier: .iso8601) calendar.locale = Locale.prefered calendar.timeZone = TimeZone.prefered return calendar } func nextMonth(for date: Date) throws -> Date { guard let nextMonth = self.date(byAdding: .month, value: 1, to: date) else { throw CalendarPickerError.nextMonthCreationFailed(date) } return nextMonth } func previousMonth(for date: Date) throws -> Date { guard let previousMonth = self.date(byAdding: .month, value: -1, to: date) else { throw CalendarPickerError.nextMonthCreationFailed(date) } return previousMonth } }
27.258065
82
0.653254
fb3c6a267d45a7f2d6b75bfea8333c3884c63184
4,913
// // ViewController.swift // MaterialShowcaseSample // // Created by Quang Nguyen on 5/10/17. // Copyright © 2017 Aromajoin. All rights reserved. // import UIKit import MaterialShowcase class ViewController: UIViewController { var tutorialStep = 1 @IBOutlet weak var searchItem: UIBarButtonItem! @IBOutlet weak var tabBar: UITabBar! @IBOutlet weak var button: UIButton! @IBOutlet weak var tableView: UITableView! // Mock data for table view let animals = ["Dolphin", "Penguin", "Panda", "Neko", "Inu"] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self } @IBAction func showButton(_ sender: Any) { let showcase = MaterialShowcase() showcase.setTargetView(view: button) showcase.primaryText = "Action 1" showcase.secondaryText = "Click here to go into details" showcase.shouldSetTintColor = false // It should be set to false when button uses image. showcase.backgroundPromptColor = UIColor.blue showcase.isTapRecognizerForTagretView = true showcase.delegate = self showcase.show(completion: { print("==== completion Action 1 ====") // You can save showcase state here }) } @IBAction func placementButton(_ sender: UIButton) { let showcase = MaterialShowcase() showcase.setTargetView(view: sender) showcase.primaryText = "Action 1.1" showcase.secondaryText = "Click here to go into details" showcase.isTapRecognizerForTagretView = true showcase.show(completion: { print("==== completion Action 1.1 ====") // You can save showcase state here }) } @IBAction func showBarButtonItem(_ sender: Any) { let showcase = MaterialShowcase() showcase.setTargetView(barButtonItem: searchItem) showcase.targetTintColor = UIColor.red showcase.targetHolderRadius = 50 showcase.targetHolderColor = UIColor.yellow showcase.aniComeInDuration = 0.3 showcase.aniRippleColor = UIColor.black showcase.aniRippleAlpha = 0.2 showcase.primaryText = "Action 2" showcase.secondaryText = "Click here to go into long long long long long long long long long long long long long long long details" showcase.secondaryTextSize = 14 showcase.isTapRecognizerForTagretView = true showcase.skipText = "Skip AppTour" showcase.isSkipButtonVisible = true showcase.skipButtonBackgroundColor = UIColor.red // showcase.targetTransparent = false // Delegate to handle other action after showcase is dismissed. showcase.delegate = self showcase.show(completion: { // You can save showcase state here print("==== completion Action 2 ====") }) } @IBAction func showTabBar(_ sender: Any) { let showcase = MaterialShowcase() showcase.setTargetView(tabBar: tabBar, itemIndex: 0) showcase.backgroundViewType = .full showcase.primaryText = "Action 3" showcase.secondaryText = "Click here to go into details" showcase.isTapRecognizerForTagretView = true showcase.delegate = self showcase.show(completion: nil) } @IBAction func showTableView(_ sender: Any) { let showcase = MaterialShowcase() showcase.setTargetView(tableView: tableView, section: 0, row: 2) showcase.primaryText = "Action 3" showcase.secondaryText = "Click here to go into details" showcase.isTapRecognizerForTagretView = true showcase.delegate = self showcase.show(completion: nil) } @IBAction func showInSeries(_ sender: UIButton) { // step 1 showButton(self) // to continue other showcases tutorialStep = 2 } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return animals.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "animalViewCell", for: indexPath) cell.textLabel?.text = animals[indexPath.row] return cell } } // If you need handle other actions (i.e: show other showcase), you can implement MaterialShowcaseDelegate extension ViewController: MaterialShowcaseDelegate { func showCaseWillDismiss(showcase: MaterialShowcase, didTapTarget: Bool) { print("Showcase \(showcase.primaryText) will dismiss.") } func showCaseDidDismiss(showcase: MaterialShowcase, didTapTarget: Bool) { print("Showcase \(showcase.primaryText) dimissed.") print("tutorialStep = \(tutorialStep)") switch tutorialStep { case 2: self.showBarButtonItem(self) case 3: self.showTabBar(self) case 4: self.showTableView(self) default: tutorialStep = 0 } tutorialStep += 1 } func showCaseSkipped(showcase: MaterialShowcase) { if showcase != nil && showcase.completeShowcase != nil { showcase.completeShowcase() } } }
33.195946
135
0.708528
21e5bdae1347211d6ae4932314f0c31d79197ac2
2,277
// // MoveSystem.swift // // Created by MARK BROWNSWORD on 20/11/16. // Copyright © 2016 MARK BROWNSWORD. All rights reserved. // import SpriteKit import GameplayKit class MoveSystem: GKComponentSystem<GKComponent> { // MARK: Public Properties weak var delegate: TileMapScene! // MARK: Initialisation override required init() { super.init(componentClass: MoveComponent.self) } // MARK: ComponentSystem Functions func process(entity: VisualEntity, input: CGPoint) { guard let healthSystem = self.delegate.system(ofType: HealthSystem.self, from: self.delegate.componentSystems) else { return } guard let moveComponent = entity.component(ofType: MoveComponent.self) else { return } entity.stateMachine.enter(VisualEntityPendingMove.self) let startCoordinate = self.delegate.mapCoordinate(from: entity.node.position) let endCoordinate = self.delegate.mapCoordinate(from: input) let path = self.delegate.findPath(from: startCoordinate, to: endCoordinate) var sequence = [SKAction]() for node in path.dropFirst() { let location = self.delegate.backgroundLayer.centerOfTile(atColumn: Int(node.gridPosition.x), row: Int(node.gridPosition.y)) let action = SKAction.move(to: location, duration: 1) let completionHandler = SKAction.run({ healthSystem.process(entity: entity, input: Int(node.costToEnter)) }) sequence += [action, completionHandler] } sequence.insert(SKAction.run({ entity.stateMachine.enter(VisualEntityMoving.self) }), at: 0) // Add at beginning sequence.append(SKAction.run({ entity.stateMachine.enter(VisualEntityIdle.self) })) // Add at end moveComponent.actions = sequence } // MARK: Override Functions override func update(deltaTime seconds: TimeInterval) { for component in (self.components as? [MoveComponent])! { if !component.updateRequired { continue } component.node.run(SKAction.sequence(component.actions)) component.updateRequired = false } } }
31.191781
136
0.642951
e8e7f93402b138a948896942a14f2409397b102d
4,662
// // CadastraProdutoViewController.swift // ERPLogistica // // Created by Bruna Gagliardi on 01/11/19. // Copyright © 2019 Bruna Gagliardi. All rights reserved. // import UIKit import Firebase class CadastraProdutoViewController: UIViewController { @IBOutlet weak var btnSalvar: UIButton! @IBOutlet weak var tableView: UITableView! var idPedido: Pedido? var prodArray: [Produto]? = [] override func viewDidLoad() { super.viewDidLoad() btnSalvar.layer.cornerRadius = 10 tableView.register(UINib(nibName: "CadastroProdutoCell", bundle: nil), forCellReuseIdentifier: "CadastroProdutoCell") navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addProduto)) } @IBAction func addProduto() { let alert = UIAlertController(title: "Cadastro Produto", message: "Preencher os campos corretamente.", preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "Produto" } alert.addTextField { (textField) in textField.placeholder = "Quantidade" textField.keyboardType = .numberPad } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in let textField = alert?.textFields![0] let textField2 = alert?.textFields![1] if (textField?.text!.isEmpty)! || (textField2?.text!.isEmpty)! { let alert = UIAlertController(title: "Produto não adicionado.", message: "Favor preencher todos os campos corretamente.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } else { let produto = Produto(nomeProduto: textField!.text!, quantidade: textField2!.text!) self.prodArray?.append(produto) let alert = UIAlertController(title: "Produto adicionado com sucesso!", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } self.tableView.reloadData() })) self.present(alert, animated: true, completion: nil) } @IBAction func actionSalvar(_ sender: Any) { var ref: DatabaseReference ref = Database.database().reference() if prodArray!.isEmpty { let alert = UIAlertController(title: "Pedidos sem produtos.", message: "Favor adicionar produtos no pedido.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } else { ref.child("Pedido").child(idPedido!.codVenda).setValue(["codVenda": idPedido!.codVenda, "notaFiscal": idPedido!.notaFiscal,"endereco": idPedido!.endereco,"nomeCliente": idPedido!.nomeCliente, "statusPedido": "Em Separação", "dataPedido": idPedido!.data]) for (index, pedido) in prodArray!.enumerated() { ref.child("Pedido").child(idPedido!.codVenda).child("produtos").child(String(index)).setValue(["nome": pedido.nomeProduto, "quantidade": pedido.quantidade]) } self.dismiss(animated: true, completion: nil) } } } extension CadastraProdutoViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { prodArray?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CadastroProdutoCell") as! CadastroPedidoTableViewCell print(prodArray![indexPath.row]) cell.nomeProduto?.text = prodArray![indexPath.row].nomeProduto cell.quantidade?.text = prodArray![indexPath.row].quantidade return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCell.EditingStyle.delete { prodArray?.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic) } } }
41.625
266
0.634277
62c06333ddae5b480aab094f8a32807924704f56
1,701
// // XMLLexer.swift // // // Created by Raghav Ahuja on 11/12/20. // import Foundation public class XMLLexer: SourceCodeRegexLexer { public static let shared = XMLLexer() lazy var generators: [TokenGenerator] = { var generators = [TokenGenerator?]() // DocType generators.append(regexGenerator("<![doctype|DOCTYPE](.*)>", tokenType: .docType)) // Tag generators.append(regexGenerator("<[?]*(?=[^!])([^!\"]\"[^\"]*\"|'[^']*'|[^'\">])*>", tokenType: .identifier)) // Attribute // generators.append(regexGenerator("[ ][\\w-]+(?=[^<]*>)", tokenType: .attribute)) generators.append(regexGenerator("[ ][\\w-]+[\\s]*[=](?=[^<]*>)", highlighterPattern: "[ ][\\w-]+", tokenType: .attribute)) // Number generators.append(regexGenerator("(?<=(\\s|\\[|,|:))(\\d|\\.|_)+", tokenType: .number)) // Single-line string literal generators.append(regexGenerator("(=\\s?\"|@\")[^\"\\n]*(@\"|\")", highlighterPattern: "(\"|@\")[^\"\\n]*(@\"|\")", tokenType: .string)) // Comment generators.append(regexGenerator("<!--[\\s\\S]*-->", options: .caseInsensitive, tokenType: .comment)) // Editor placeholder var editorPlaceholderPattern = "(<#)[^\"\\n]*" editorPlaceholderPattern += "(#>)" generators.append(regexGenerator(editorPlaceholderPattern, tokenType: .editorPlaceholder)) return generators.compactMap { $0 } }() public init() { } public func generators(source: String) -> [TokenGenerator] { return generators } }
32.09434
144
0.527337
0a042fe013c5121f51cbefd75e6daa58fed31f32
2,439
import UIKit import WebKit public class WebViewObserver: NSObject { enum KeyPath: String, CaseIterable { case title case url = "URL" case estimatedProgress case canGoBack case canGoForward case hasOnlySecureContent case loading } let webView: WKWebView private var context: UInt8 = 0 private let keyPaths: [KeyPath] = KeyPath.allCases public var onTitleChanged: (String?) -> Void = { _ in } public var onURLChanged: (URL?) -> Void = { _ in } public var onProgressChanged: (Double) -> Void = { _ in } public var onCanGoBackChanged: (Bool) -> Void = { _ in } public var onCanGoForwardChanged: (Bool) -> Void = { _ in } public var onHasOnlySecureContentChanged: (Bool) -> Void = { _ in } public var onLoadingStatusChanged: (Bool) -> Void = { _ in } // MARK: - public init(obserbee webView: WKWebView) { self.webView = webView super.init() observeProperties() } private func observeProperties() { for k in keyPaths { webView.addObserver(self, forKeyPath: k.rawValue, options: .new, context: &context) } } deinit { for k in keyPaths { webView.removeObserver(self, forKeyPath: k.rawValue, context: &context) } } private func dispatchObserver(_ keyPath: KeyPath) { switch keyPath { case .title: onTitleChanged(webView.title) case .url: onURLChanged(webView.url) case .estimatedProgress: onProgressChanged(webView.estimatedProgress) case .canGoBack: onCanGoBackChanged(webView.canGoBack) case .canGoForward: onCanGoForwardChanged(webView.canGoForward) case .hasOnlySecureContent: onHasOnlySecureContentChanged(webView.hasOnlySecureContent) case .loading: onLoadingStatusChanged(webView.isLoading) } } // MARK: - Key Value Observation public override func observeValue(forKeyPath keyPath: String?, of ofObject: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard context == &self.context else { return } if let keyPath = keyPath.flatMap(KeyPath.init) { dispatchObserver(keyPath) } } } public extension WebViewObserver { @available(*, unavailable, renamed: "init(obserbee:)") convenience init(_ webView: WKWebView) { fatalError() } }
31.675325
159
0.647396
8a285b360d21ca530dfe727698cdc573eb6e4c90
1,388
// // TableViewKit // // Copyright (c) 2017 Alek Åström. // Licensed under the MIT license, see LICENSE file. // import UIKit /// Wraps a standard `UITableViewHeaderFooterView` by adding reusability protocols & a view model. open class StandardHeaderFooterView: UITableViewHeaderFooterView, DataSetupable, ReusableViewClass { /// The model for a `StandardHeaderFooterView`. public struct Model: Hashable, AnyEquatable { /// The title to display. public var title: String? /// The detail text to display. public var detailText: String? /// :nodoc: public var hashValue: Int { return (title?.hashValue ?? 0) ^ (title?.hashValue ?? 0) } /// The designated initializer. /// /// - Parameters: /// - title: The title to display. /// - detailText: The detail text to display. public init(title: String? = nil, detailText: String? = nil) { self.title = title self.detailText = detailText } } /// :nodoc: open func setup(_ model: Model) { textLabel?.text = model.title detailTextLabel?.text = model.detailText } /// :nodoc: open static func estimatedHeight(forWidth width: CGFloat, model: Model) -> CGFloat? { return 28 } }
27.76
100
0.582853
1cd39bdbd4fe10551ede1a1dda5ec670ab1f0b27
848
// Queue // Piper Chester struct Queue<T> { var elements = T[]() mutating func enqueue(element: T){ elements.insert(element, atIndex: 0) } mutating func dequeue() -> T { return elements.removeLast() } func front() -> T { return elements[elements.endIndex - 1] } func back() -> T{ return elements[0] } func isEmpty() -> Bool { return elements.count == 0 ? true : false; } var size: Int { return elements.count } } var intQueue = Queue<Int>() intQueue.enqueue(4) intQueue.enqueue(12981237) intQueue.enqueue(-666) intQueue.enqueue(42) intQueue intQueue.isEmpty() intQueue.size intQueue.front() intQueue.back() intQueue.dequeue() intQueue.dequeue() intQueue.front() intQueue intQueue.dequeue() intQueue.dequeue() intQueue intQueue.isEmpty()
16
50
0.632075
f5cba629c6ad8de4d06b2aebcb5b78d74967907f
3,669
// // Heroes.Fetcher.swift // MultiSelectionTable // // Created by Nuno Gonçalves on 09/12/16. // Copyright © 2016 Nuno Gonçalves. All rights reserved. // import Foundation struct Heroes { struct Fetcher { static func fetch(named name: String? = nil, in page: Int = 0, got: @escaping (HeroesList) -> ()) { let url = buildUrl(with: page, and: name) Network.get(from: url) { result in switch result { case .success(let json): guard let dataDic = json["data"] as? [String : Any] else { return got(HeroesList(heroes: [], totalCount: 0, currentPage: 0, totalPages: 0)) } let totalCount = dataDic["total"] as? Int ?? 0 let offset = dataDic["offset"] as? Int ?? 0 let limit = dataDic["limit"] as? Int ?? 0 let totalPages = limit == 0 ? 0 : Int(ceil(Double(totalCount / limit))) let currentPage = totalCount == 0 ? 0 : Int(ceil(Double(totalPages) * Double(offset) / Double(totalCount))) let dicCharacters = dataDic["results"] as! [[String : Any]] let heroes = dicCharacters.flatMap { Hero(dictionary: $0) } let heroesList = HeroesList(heroes: heroes, totalCount: totalCount, currentPage: currentPage, totalPages: totalPages) got(heroesList) case .failure(_): //We should really propagate the Result the the caller return got(HeroesList(heroes: [], totalCount: 0, currentPage: 0, totalPages: 0)) } } } static let ts = "1" static let pub = "ab781b828ce0d61d8d053bde7d8c3fde" static let priv = "f9490b9557c2e8e7c52b72a632898b63658dcf5b" static let charactersUrl = "http://gateway.marvel.com:80/v1/public/characters" static var hash : String { return "\(ts)\(priv)\(pub)".md5ed } fileprivate static func buildUrl(with page: Int, and name: String? = nil) -> URL { let limit = 25 var urlStr = "\(charactersUrl)?limit=\(limit)&offset=\(page * limit)&apikey=\(pub)&ts=1&hash=\(hash)" if let name = name, !name.isEmpty { urlStr.append("&nameStartsWith=\(name)") urlStr = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! } return URL(string: urlStr)! } } } fileprivate extension String { var md5ed: String! { let str = self.cString(using: String.Encoding.utf8) let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.deallocate() return String(format: hash as String) } }
39.451613
127
0.483783
1cf883081fe67877a57e41704da1a1eb4666031c
3,310
// // AppDelegate.swift // OneSignalNotificationDemo // // Created by Soeng Saravit on 12/18/18. // Copyright © 2018 Soeng Saravit. All rights reserved. // import UIKit import OneSignal @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, OSSubscriptionObserver { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false] // Replace 'YOUR_APP_ID' with your OneSignal App ID. OneSignal.initWithLaunchOptions(launchOptions, appId: "3226be5d-3d2b-4771-ae35-7c62a0133d8b", handleNotificationAction: nil, settings: onesignalInitSettings) OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification; // Recommend moving the below line to prompt for push after informing the user about // how your app will use them. OneSignal.promptForPushNotifications(userResponse: { accepted in print("User accepted notifications: \(accepted)") }) OneSignal.add(self as OSSubscriptionObserver) return true } func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) { if let playerID = stateChanges.to.userId { print("==> Player id:\(playerID)") } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.342466
285
0.705438
f9cbef781dd8a9481d1bb2f74213204e51ba8e9f
2,258
/* * Copyright 2018, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Dispatch import Foundation import SwiftProtobuf public protocol ServerSessionUnary: ServerSession {} open class ServerSessionUnaryBase<InputType: Message, OutputType: Message>: ServerSessionBase, ServerSessionUnary { public typealias SentType = OutputType public typealias ProviderBlock = (InputType, ServerSessionUnaryBase) throws -> OutputType private var providerBlock: ProviderBlock public init(handler: Handler, providerBlock: @escaping ProviderBlock) { self.providerBlock = providerBlock super.init(handler: handler) } public func run() throws -> ServerStatus? { let requestData = try receiveRequestAndWait() let requestMessage = try InputType(serializedData: requestData) let responseMessage: OutputType do { responseMessage = try self.providerBlock(requestMessage, self) } catch { // Errors thrown by `providerBlock` should be logged in that method; // we return the error as a status code to avoid `ServiceServer` logging this as a "really unexpected" error. return (error as? ServerStatus) ?? .processingError } let sendResponseSignal = DispatchSemaphore(value: 0) var sendResponseError: Error? try self.handler.call.sendMessage(data: responseMessage.serializedData()) { sendResponseError = $0 sendResponseSignal.signal() } sendResponseSignal.wait() if let sendResponseError = sendResponseError { throw sendResponseError } return .ok } } /// Trivial fake implementation of ServerSessionUnary. open class ServerSessionUnaryTestStub: ServerSessionTestStub, ServerSessionUnary {}
35.28125
115
0.74225
3a5dc0b4ff02ac61129a7d56715b9ba0d6d374fe
432
// // Eth+Ext.swift // HackathonWallet // // Created by Nino Zhang on 2022/4/9. // import Foundation import BlockChain_SDK_iOS extension Eth.TransactionInformation: Equatable { public static func == (lhs: Eth.TransactionInformation, rhs: Eth.TransactionInformation) -> Bool { return lhs.hash == rhs.hash && lhs.blockNumber == rhs.blockNumber && lhs.blockHash == rhs.blockHash // ... } }
22.736842
102
0.655093
697e2363309dad3f62cb27f0f2b40299969e185c
1,627
import UIKit class NALoginViewController: UIViewController { @IBOutlet weak var idLabel: UILabel! @IBOutlet weak var idButton: UIButton! let biometricIDAuth = NABiometricIDAuth() override func viewDidLoad() { super.viewDidLoad() // display different labels and buttons based on the type of biometrics configured on the device switch biometricIDAuth.biometricType() { case .faceID: self.idLabel.text = "Log in with Face ID" self.idButton.setImage(UIImage(named: Icons.faceId), for: .normal) default: self.idLabel.text = "Log in with Touch ID" self.idButton.setImage(UIImage(named: Icons.touchId), for: .normal) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if biometricIDAuth.canEvaluatePolicy() { clickLoginButton(self.idButton) } } @IBAction func clickLoginButton(_ sender: UIButton) { biometricIDAuth.authenticateUser { [weak self] message in if let message = message { // if an error occurred, show an alert indicating it let alertView = UIAlertController(title: "Error", message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .default) alertView.addAction(okAction) self?.present(alertView, animated: true) } else { self?.performSegue(withIdentifier: SegueIdentifiers.mainView, sender: nil) } } } }
35.369565
107
0.614014
1efdface0eeac101669168e8debba917902eadee
211
// // Copyright © 2020. Orynko Artem // // MIT license, see LICENSE file for details // import XCTest import DataSourceTests var tests = [XCTestCaseEntry]() tests += DataSourceTests.allTests() XCTMain(tests)
15.071429
44
0.729858
f488a838810b92f5e81b8f8515e5816fee328165
13,425
// // Permission.swift // // Copyright (c) 2015-2016 Damien (http://delba.io) // // 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 PERMISSION_USER_NOTIFICATIONS import UserNotifications #endif open class Permission: NSObject { public typealias Callback = (PermissionStatus) -> Void #if PERMISSION_CONTACTS /// The permission to access the user's contacts. @available(iOS 9.0, *) public static let contacts = Permission(type: .contacts) #endif #if PERMISSION_ADDRESS_BOOK /// The permission to access the user's address book. (Deprecated in iOS 9.0) public static let addressBook = Permission(type: .addressBook) #endif #if PERMISSION_LOCATION /// The permission to access the user's location when the app is in background. public static let locationAlways = Permission(type: .locationAlways) /// The permission to access the user's location when the app is in use. public static let locationWhenInUse = Permission(type: .locationWhenInUse) #endif #if PERMISSION_MICROPHONE /// The permission to access the microphone. public static let microphone = Permission(type: .microphone) #endif #if PERMISSION_CAMERA /// The permission to access the camera. public static let camera = Permission(type: .camera) #endif #if PERMISSION_PHOTOS /// The permission to access the user's photos. public static let photos = Permission(type: .photos) #endif #if PERMISSION_REMINDERS /// The permission to access the user's reminders. public static let reminders = Permission(type: .reminders) #endif #if PERMISSION_EVENTS /// The permission to access the user's events. public static let events = Permission(type: .events) #endif #if PERMISSION_BLUETOOTH /// The permission to access the user's bluetooth. public static let bluetooth = Permission(type: .bluetooth) #endif #if PERMISSION_MOTION /// The permission to access the user's motion. public static let motion = Permission(type: .motion) #endif #if PERMISSION_SPEECH_RECOGNIZER /// The permission to access the user's SpeechRecognizer. @available(iOS 10.0, *) public static let speechRecognizer = Permission(type: .speechRecognizer) #endif #if PERMISSION_MEDIA_LIBRARY /// The permission to access the user's MediaLibrary. @available(iOS 9.3, *) public static let mediaLibrary = Permission(type: .mediaLibrary) #endif #if PERMISSION_SIRI /// The permission to access the user's Siri. @available(iOS 10.0, *) public static let siri = Permission(type: .siri) #endif #if PERMISSION_NOTIFICATIONS /// The permission to send notifications. public static let notifications: Permission = { let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil) return Permission(type: .notifications(settings)) }() /// Variable used to retain the notifications permission. fileprivate static var _notifications: Permission? /// The permission to send notifications. public static func notifications(types: UIUserNotificationType, categories: Set<UIUserNotificationCategory>?) -> Permission { let settings = UIUserNotificationSettings(types: types, categories: categories) let permission = Permission(type: .notifications(settings)) _notifications = permission return permission } /// The permission to send notifications. public static func notifications(types: UIUserNotificationType) -> Permission { let settings = UIUserNotificationSettings(types: types, categories: nil) let permission = Permission(type: .notifications(settings)) _notifications = permission return permission } /// The permission to send notifications. public static func notifications(categories: Set<UIUserNotificationCategory>?) -> Permission { let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: categories) let permission = Permission(type: .notifications(settings)) _notifications = permission return permission } #endif #if PERMISSION_USER_NOTIFICATIONS /// Variable used to retain the notifications permission. @available(iOS 10.0, *) fileprivate static var _userNotifications: Permission? /// The permission to send notifications. @available(iOS 10.0, *) public static let userNotifications: Permission = { let settings: UNAuthorizationOptions = [.alert, .badge, .sound] _userNotifications = Permission(type: .userNotifications(settings)) return _userNotifications! }() /// The permission to send notifications. @available(iOS 10.0, *) public static func userNotifications(options: UNAuthorizationOptions) -> Permission { _userNotifications = Permission(type: .userNotifications(options)) return _userNotifications! } #endif /// The permission domain. public let type: PermissionType /// The permission status. open var status: PermissionStatus { #if PERMISSION_CONTACTS if case .contacts = type { return statusContacts } #endif #if PERMISSION_ADDRESS_BOOK if case .addressBook = type { return statusAddressBook } #endif #if PERMISSION_LOCATION if case .locationAlways = type { return statusLocationAlways } if case .locationWhenInUse = type { return statusLocationWhenInUse } #endif #if PERMISSION_NOTIFICATIONS if case .notifications = type { return statusNotifications } #endif #if PERMISSION_USER_NOTIFICATIONS if case .userNotifications = type { return statusUserNotifications } #endif #if PERMISSION_MICROPHONE if case .microphone = type { return statusMicrophone } #endif #if PERMISSION_CAMERA if case .camera = type { return statusCamera } #endif #if PERMISSION_PHOTOS if case .photos = type { return statusPhotos } #endif #if PERMISSION_REMINDERS if case .reminders = type { return statusReminders } #endif #if PERMISSION_EVENTS if case .events = type { return statusEvents } #endif #if PERMISSION_BLUETOOTH if case .bluetooth = type { return statusBluetooth } #endif #if PERMISSION_MOTION if case .motion = type { return statusMotion } #endif #if PERMISSION_SPEECH_RECOGNIZER if case .speechRecognizer = type { return statusSpeechRecognizer } #endif #if PERMISSION_MEDIA_LIBRARY if case .mediaLibrary = type { return statusMediaLibrary } #endif #if PERMISSION_SIRI if case .siri = type { return statusSiri } #endif fatalError() } /// Determines whether to present the pre-permission alert. open var presentPrePermissionAlert = false /// The pre-permission alert. open lazy var prePermissionAlert: PermissionAlert = { return PrePermissionAlert(permission: self) }() /// Determines whether to present the denied alert. open var presentDeniedAlert = true /// The alert when the permission was denied. open lazy var deniedAlert: PermissionAlert = { return DeniedAlert(permission: self) }() /// Determines whether to present the disabled alert. open var presentDisabledAlert = true /// The alert when the permission is disabled. open lazy var disabledAlert: PermissionAlert = { return DisabledAlert(permission: self) }() internal var callback: Callback? internal var permissionSets: [PermissionSet] = [] /** Creates and return a new permission for the specified domain. - parameter domain: The permission domain. - returns: A newly created permission. */ fileprivate init(type: PermissionType) { self.type = type } /** Requests the permission. - parameter callback: The function to be triggered after the user responded to the request. */ open func request(_ callback: @escaping Callback) { self.callback = callback DispatchQueue.main.async { self.permissionSets.forEach { $0.willRequestPermission(self) } } let status = self.status switch status { case .authorized: callbacks(status) case .notDetermined: presentPrePermissionAlert ? prePermissionAlert.present() : requestAuthorization(callbacks) case .denied: presentDeniedAlert ? deniedAlert.present() : callbacks(status) case .disabled: presentDisabledAlert ? disabledAlert.present() : callbacks(status) } } internal func requestAuthorization(_ callback: @escaping Callback) { #if PERMISSION_CONTACTS if case .contacts = type { requestContacts(callback) return } #endif #if PERMISSION_ADDRESS_BOOK if case .addressBook = type { requestAddressBook(callback) return } #endif #if PERMISSION_LOCATION if case .locationAlways = type { requestLocationAlways(callback) return } if case .locationWhenInUse = type { requestLocationWhenInUse(callback) return } #endif #if PERMISSION_NOTIFICATIONS if case .notifications = type { requestNotifications(callback) return } #endif #if PERMISSION_USER_NOTIFICATIONS if case .userNotifications = type { requestUserNotifications(callback) return } #endif #if PERMISSION_MICROPHONE if case .microphone = type { requestMicrophone(callback) return } #endif #if PERMISSION_CAMERA if case .camera = type { requestCamera(callback) return } #endif #if PERMISSION_PHOTOS if case .photos = type { requestPhotos(callback) return } #endif #if PERMISSION_REMINDERS if case .reminders = type { requestReminders(callback) return } #endif #if PERMISSION_EVENTS if case .events = type { requestEvents(callback) return } #endif #if PERMISSION_BLUETOOTH if case .bluetooth = type { requestBluetooth(self.callback) return } #endif #if PERMISSION_MOTION if case .motion = type { requestMotion(self.callback) return } #endif #if PERMISSION_SPEECH_RECOGNIZER if case .speechRecognizer = type { requestSpeechRecognizer(callback) return } #endif #if PERMISSION_MEDIA_LIBRARY if case .mediaLibrary = type { requestMediaLibrary(callback) return } #endif #if PERMISSION_SIRI if case .siri = type { requestSiri(callback) return } #endif fatalError() } internal func callbacks(_ with: PermissionStatus) { DispatchQueue.main.async { self.callback?(self.status) self.permissionSets.forEach { $0.didRequestPermission(self) } } } } extension Permission { /// The textual representation of self. override open var description: String { return type.description } /// A textual representation of this instance, suitable for debugging. override open var debugDescription: String { return "\(type): \(status)" } }
31.737589
129
0.630912
f5fb056a1693db24e97597963fdac39eeb0315c4
2,722
// // MenuViewController.swift // AVPlayerSample // // Created by Tiago Pereira on 17/09/2020. // Copyright © 2020 NicePeopleAtWork. All rights reserved. // import UIKit import YouboraConfigUtils class MenuViewController: UIViewController { @IBOutlet var resourceTextField: UITextField! @IBOutlet var adsSegmentedControl: UISegmentedControl! @IBOutlet var playButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.addSettingsButton() self.resourceTextField.text = Resource.hlsApple self.adsSegmentedControl.selectedSegmentIndex = 0 } public static func initFromXIB() -> MenuViewController? { return MenuViewController( nibName: String(describing: MenuViewController.self), bundle: Bundle(for: MenuViewController.self)) } } // MARK: - Settings Section extension MenuViewController { func addSettingsButton() { guard let navigationController = self.navigationController else { return } addSettingsToNavigation(navigationBar: navigationController.navigationBar) } func addSettingsToNavigation(navigationBar: UINavigationBar) { let settingsButton = UIBarButtonItem(title: "Settings", style: .done, target: self, action: #selector(navigateToSettings)) navigationBar.topItem?.rightBarButtonItem = settingsButton } } // MARK: - Navigation Section extension MenuViewController { @IBAction func pressButtonToNavigate(_ sender: UIButton) { if sender == self.playButton { let playerViewController = PlayerViewController() playerViewController.resource = self.resourceTextField.text playerViewController.containAds = self.adsSegmentedControl.selectedSegmentIndex == 0 ? false : true navigateToViewController(viewController: playerViewController) return } } @objc func navigateToSettings() { let configViewController = YouboraConfigViewController.initFromXIB() guard let navigationController = self.navigationController else { self.present(configViewController, animated: true, completion: nil) return } navigationController.show(configViewController, sender: nil) } func navigateToViewController(viewController: UIViewController) { guard let navigationController = self.navigationController else { self.present(viewController, animated: true, completion: nil) return } navigationController.pushViewController(viewController, animated: true) } }
31.287356
130
0.681117
d9a2c7ea7b7ed5134d3430aeefdbc93449990a08
1,044
// // CurrencyCollectionViewCell.swift // ExchangeRate // // Created by lmcmz on 11/12/2017. // Copyright © 2017 lmcmz. All rights reserved. // import UIKit class CurrencyCollectionViewCell: UICollectionViewCell { @IBOutlet var imageView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var currencyLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configure(currency: Currency) { self.currencyLabel.text = Currency.symbol(currency: currency) self.nameLabel.text = currency.rawValue self.imageView.image = Currency.image(currency: currency) self.currencyLabel.font = self.currencyLabel.font.withSize(38) if currencyLabel.text?.count == 2 { self.currencyLabel.font = self.currencyLabel.font.withSize(25) } if currencyLabel.text?.count == 3 { self.currencyLabel.font = self.currencyLabel.font.withSize(20) } } }
26.769231
74
0.649425
bf86ff67c3116d37c62f612f716ee502a52b783d
493
// // UIViewController+Extension.swift // IMScrollPageView // // Created by Mazy on 2019/7/10. // Copyright © 2019 Mazy. All rights reserved. // import UIKit extension UIViewController { public weak var imScrollPageController: UIViewController? { get { var superVC = self.parent while superVC != nil { // if superVC is Contiguous superVC = superVC?.parent } return superVC } } }
20.541667
63
0.56998
9b96874dabad464fb18f757ad1cda71ac5c1613c
3,562
// // LoginViewController.swift // ELibrary // // Created by 赵芷涵 on 12/12/21. // import UIKit import Firebase import Realm import RealmSwift class LoginViewController: UIViewController { @IBOutlet weak var txtEmail: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBAction func unwind(_ segue: UIStoryboardSegue){} let realm = try! Realm() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func LoginAction(_ sender: Any) { let email = txtEmail.text let password = txtPassword.text if email?.count == 0{ print("email is null") UIAlertController.showAlert(message: "Please enter an email !") } else if isValidEmail(email!) == false{ UIAlertController.showAlert(message: "Please enter a valid email !") } if password?.count ?? 0 < 5{ UIAlertController.showAlert(message: "Please enter a valid password !") } Auth.auth().signIn(withEmail: email!, password: password!) { [weak self] authResult, error in guard let strongSelf = self else { return } if error != nil{ UIAlertController.showAlert(message: "\(error?.localizedDescription)") return } } if Auth.auth().currentUser?.uid != nil{ let uid = (Auth.auth().currentUser?.uid)! if checkUserExist(ID: uid) == false{ let newUser = User() newUser.userID = uid try! realm.write { realm.add(newUser) } } performSegue(withIdentifier: "HomeSegue", sender: self) } } func checkUserExist(ID: String) -> Bool { return realm.object(ofType: User.self, forPrimaryKey: ID) != nil } func isValidEmail(_ email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailPred.evaluate(with: email) } } extension UIAlertController { //在指定视图控制器上弹出普通消息提示框 static func showAlert(message: String, in viewController: UIViewController) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Confirm", style: .cancel)) viewController.present(alert, animated: true) } //在根视图控制器上弹出普通消息提示框 static func showAlert(message: String) { if let vc = UIApplication.shared.keyWindow?.rootViewController { showAlert(message: message, in: vc) } } //在指定视图控制器上弹出确认框 static func showConfirm(message: String, in viewController: UIViewController, confirm: ((UIAlertAction)->Void)?) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "取消", style: .cancel)) alert.addAction(UIAlertAction(title: "确定", style: .default, handler: confirm)) viewController.present(alert, animated: true) } //在根视图控制器上弹出确认框 static func showConfirm(message: String, confirm: ((UIAlertAction)->Void)?) { if let vc = UIApplication.shared.keyWindow?.rootViewController { showConfirm(message: message, in: vc, confirm: confirm) } } }
31.803571
101
0.596013
7a1e20980449c5af276fa158145d8f285f18b841
620
// // File.swift // // // Created by Ramy Wagdy on 9/16/21. // import Foundation struct LocalizableFileParser { private let filePath: String private var localizedKeyValue = [String: String]() init(filePath: String) { self.filePath = filePath } func parse() -> [String: String] { let bundle = Bundle(path: filePath) if let url = bundle?.url(forResource: "Localizable", withExtension: "strings"), let stringsDict = NSDictionary(contentsOf: url) as? [String: String] { return stringsDict } fatalError() } }
21.37931
88
0.58871
f526207c823a8a9852ec51f9f306d5bc825b1c9c
800
// // ContentView.swift // Example_SwiftUI // // Created by 伊藤凌也 on 2019/11/25. // Copyright © 2019 ry-itto. All rights reserved. // import SwiftUI struct ContentView: View { @ObservedObject var viewModel: ViewModel init(viewModel: ViewModel) { self.viewModel = viewModel } var body: some View { ScrollView { ForEach(viewModel.articles) { article in Row(title: article.title, likesCount: "\(article.likesCount)") .padding(.horizontal, 20) Divider() } } .onAppear { self.viewModel.onAppearSubject.send(()) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(viewModel: .init()) } }
21.621622
78
0.58
0e4aa2ad735ab7394182b44e77fa5c6edfce7a08
4,539
// // ViewController.swift // SimpleRealtimeFilterPlayback // // Created by RenZhu Macro on 2020/7/2. // Copyright © 2020 RenZhu Macro. All rights reserved. // import UIKit import AVFoundation import MetalVideoProcess class ViewController: UIViewController { @IBOutlet weak var renderView: MetalVideoProcessRenderView! @IBOutlet weak var progress: UISlider! var player: MetalVideoProcessPlayer? var beauty1: MetalVideoProcessBeautyFilter? var beauty2: MetalVideoProcessBeautyFilter? var blur1: MetalVideoProcessGaussianBlurFilter? var blur2: MetalVideoProcessGaussianBlurFilter? var grayFilter: MetalVideoProcessLuminance? override func viewDidLoad() { super.viewDidLoad() let asset1 = AVAsset(url: Bundle.main.url(forResource: "853", withExtension: "mp4")!) let asset2 = AVAsset(url: Bundle.main.url(forResource: "cute", withExtension: "mp4")!) let item1 = MetalVideoEditorItem(asset: asset1) let item2 = MetalVideoEditorItem(asset: asset2) do { let editor = try MetalVideoEditor(videoItems: [item1, item2], customVideoCompositorClass: MetalVideoProcessCompositor.self) let playerItem = editor.buildPlayerItem() self.progress.maximumValue = Float(playerItem.duration.seconds) let player = try MetalVideoProcessPlayer(playerItem: playerItem) let beautyFilter1 = MetalVideoProcessBeautyFilter() beautyFilter1.saveUniformSettings(forTimelineRange: item1.timeRange, trackID: 0) beautyFilter1.isEnable = false let beautyFilter2 = MetalVideoProcessBeautyFilter() beautyFilter2.saveUniformSettings(forTimelineRange: item2.timeRange, trackID: 0) beautyFilter2.isEnable = false let blurFilter1 = MetalVideoProcessGaussianBlurFilter() blurFilter1.saveUniformSettings(forTimelineRange: item1.timeRange, trackID: 0) blurFilter1.isEnable = false let blurFilter2 = MetalVideoProcessGaussianBlurFilter() blurFilter2.saveUniformSettings(forTimelineRange: item2.timeRange, trackID: 0) blurFilter2.isEnable = false player.addTarget(beautyFilter1, atTargetIndex: nil, trackID: item1.trackID, targetTrackId: 0) player.addTarget(beautyFilter1, atTargetIndex: nil, trackID: item2.trackID, targetTrackId: 0) //mapping trackId on mainTrack 0 let gray = MetalVideoProcessLuminance() gray.isEnable = false self.grayFilter = gray self.beauty1 = beautyFilter1 self.beauty2 = beautyFilter2 self.blur1 = blurFilter1 self.blur2 = blurFilter2 beautyFilter1 --> beautyFilter2 --> blurFilter1 --> blurFilter2 --> gray --> renderView self.player = player self.player?.playerDelegate = self } catch { debugPrint("init error") } } @IBAction func play(_ sender: Any) { self.player?.play() } @IBAction func pause(_ sender: Any) { self.player?.pause() } @IBAction func progressChanged(_ sender: UISlider) { let value = sender.value self.player?.seekTo(time: Float64(value)) } @IBAction func filterOn(_ sender: UISwitch) { var operation: MetalVideoProcessOperation? switch sender.tag { case 0: operation = self.beauty1 break case 1: operation = self.blur1 break case 2: operation = self.beauty2 break case 3: operation = self.blur2 break case 4: operation = self.grayFilter break default: break } operation?.isEnable = sender.isOn } } extension ViewController: MetalVideoProcessPlayerDelegate { func playbackFrameTimeChanged(frameTime time: CMTime, player: AVPlayer) { DispatchQueue.main.async { self.progress.value = Float(time.seconds) } } func playEnded(currentPlayer player: AVPlayer) { } func finishExport(error: NSError?) { } func exportProgressChanged(_ progress: Float) { } }
32.191489
107
0.610487
380568d644fa10a4b8cd53a6df4de430c32f6a5a
5,272
// Copyright © 2021 Brad Howes. All rights reserved. import UIKit import os /** Originally, the SoundFonts app loaded three separate config files. However, there was risk of data corruption if the files were not updated all at once. This was made worse with the AUv3 component, since it and the app shared the same configuration files. This consolidated version stores everything in one file, so the risk of corruption is reduced. Further, it relies on UIDocument which provides a safe and reliable means of making changes and writing them to disk even if there are two or more parties doing it. For our case, we just let the last one win without notifying the user that there was even a conflict. */ public struct ConsolidatedConfig: Codable { private static let log = Logging.logger("ConsolidatedConfig") private var log: OSLog { Self.log } /// The collection of installed sound fonts and their presets public var soundFonts: SoundFontCollection /// The collection of created favorites public var favorites: FavoriteCollection /// The collection of tags public var tags: TagCollection } extension ConsolidatedConfig { /// Construct a new default collection, such as when the app is first installed or there is a problem loading. public init() { os_log(.info, log: Self.log, "creating default collection") soundFonts = SoundFontsManager.defaultCollection favorites = FavoritesManager.defaultCollection tags = TagsManager.defaultCollection } } extension ConsolidatedConfig: CustomStringConvertible { public var description: String { "<Config \(soundFonts), \(favorites), \(tags)>" } } /// Extension of UIDocument that stores a ConsolidatedConfig value public final class ConsolidatedConfigFile: UIDocument { private static let log = Logging.logger("ConsolidatedConfigFile") private var log: OSLog { Self.log } /// The file name for the sole document static let filename = "Consolidated.plist" public lazy var config: ConsolidatedConfig = ConsolidatedConfig() @objc dynamic public private(set) var restored: Bool = false { didSet { self.updateChangeCount(.done) self.save(to: fileURL, for: .forOverwriting) } } override public init(fileURL: URL) { os_log(.info, log: Self.log, "init - fileURL: %{public}s", fileURL.absoluteString) super.init(fileURL: fileURL) initialize(fileURL) } public func save() { self.save(to: fileURL, for: .forOverwriting) } private func initialize(_ sharedArchivePath: URL) { os_log(.info, log: log, "initialize - %{public}s", sharedArchivePath.path) self.open { ok in if !ok { os_log(.error, log: Self.log, "failed to open - attempting legacy loading") // We are back on the main thread so do the loading in the background. DispatchQueue.global(qos: .userInitiated).async { self.attemptLegacyLoad(sharedArchivePath) } } } } override public func contents(forType typeName: String) throws -> Any { os_log(.info, log: log, "contents - typeName: %{public}s", typeName) let contents = try PropertyListEncoder().encode(config) os_log(.info, log: log, "-- pending save of %d bytes", contents.count) return contents } override public func load(fromContents contents: Any, ofType typeName: String?) throws { os_log(.info, log: log, "load - typeName: %{public}s", typeName ?? "nil") guard let data = contents as? Data else { os_log(.error, log: log, "failed to convert contents to Data") restoreConfig(ConsolidatedConfig()) NotificationCenter.default.post(Notification(name: .configLoadFailure, object: nil)) return } guard let config = try? PropertyListDecoder().decode(ConsolidatedConfig.self, from: data) else { os_log(.error, log: log, "failed to decode Data contents") restoreConfig(ConsolidatedConfig()) NotificationCenter.default.post(Notification(name: .configLoadFailure, object: nil)) return } os_log(.info, log: log, "decoded contents: %{public}s", config.description) restoreConfig(config) } override public func revert(toContentsOf url: URL, completionHandler: ((Bool) -> Void)? = nil) { completionHandler?(false) } } extension ConsolidatedConfigFile { private func attemptLegacyLoad(_ sharedArchivePath: URL) { os_log(.info, log: log, "attemptLegacyLoad") guard let soundFonts = LegacyConfigFileLoader<SoundFontCollection>.load(filename: "SoundFontLibrary.plist"), let favorites = LegacyConfigFileLoader<FavoriteCollection>.load(filename: "Favorites.plist"), let tags = LegacyConfigFileLoader<TagCollection>.load(filename: "Tags.plist") else { os_log(.info, log: log, "failed to load one or more legacy files") initializeCollections() return } os_log(.info, log: log, "using legacy contents") restoreConfig(ConsolidatedConfig(soundFonts: soundFonts, favorites: favorites, tags: tags)) } private func restoreConfig(_ config: ConsolidatedConfig) { os_log(.info, log: log, "restoreConfig") self.config = config self.restored = true } private func initializeCollections() { os_log(.info, log: log, "initializeCollections") self.restored = true } }
37.126761
118
0.716995
90adb664fff5420e7e887eed2a63c74a7c0b2ba2
215
import Foundation import Prettier public struct MarkdownPlugin: Plugin { public let fileURL = Bundle.module.url(forResource: "parser-markdown", withExtension: "js", subdirectory: "js")! public init() {} }
23.888889
116
0.730233
012e3ab1c40a877cf784cbb6134fa82f41d06f84
7,034
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import CoreData class NoticeManager { let session: Session init(session: Session) { self.session = session } func getNotice(id: Int64?, server: String? = nil) -> NoticeMO? { guard let id = id else { return nil } let server = server ?? session.account.server let query = NoticeMO.fetchRequest() as! NSFetchRequest<NoticeMO> query.predicate = NSPredicate(format: "server = %@ AND statusNetId = %ld", server, id) let results = session.fetch(request: query) return results.first } /// New way, using the parsed ActivityStreams XML objects func processNoticeEntries(sourceServer: String, entries: [ASEntry], idOverride: Int64? = nil) -> [NoticeMO] { var ret: [NoticeMO] = [] for entry in entries { guard let statusNetId = idOverride ?? entry.statusNetNoticeId else { continue } // If that notice is already in our DB skip creating a new one if let existing = getNotice(id: statusNetId, server: sourceServer) { // TODO possibly update things? Can they change? // To deal with repeated notices already having been processed in the same batch, // we need to include them inline again in the returned notices. // This will give screwy results if a server gives us more results than we asked for // Trust the server impl for the moment ret.append(existing) continue } // Make sure we have all the common data we care about first guard let tag = entry.id, let htmlContent = entry.htmlContent, let htmlLink = entry.htmlLink, let published = entry.published, let updated = entry.updated, let author = entry.author, let conversationUrl = entry.conversationUrl, let conversationNumber = entry.conversationNumber, let conversationThread = entry.conversationThread else // not actually a big deal but common { continue } // Process author (User object in core data) // Get either an existing or new user based on the DTO // If we can't parse the user then we can't use this notice guard let user = session.userManager.processFeedAuthor(sourceServer: sourceServer, author: author) else { continue } // Must be a better way to organise this but it'll do for now // Ensure we have all the data for the specific subtype _before_ we commit to making the new NoticeMO if entry.isReply { guard entry.inReplyToNoticeUrl != nil && entry.inReplyToNoticeRef != nil else { continue } } if entry.isFavourite { guard entry.object?.statusNetNoticeId != nil && entry.object?.htmlLink != nil else { continue } } var repeatedNotice: NoticeMO? = nil if entry.isRepeat { if let object = entry.object, let repeatedId = entry.repeatOfNoticeId { repeatedNotice = processNoticeEntries(sourceServer: sourceServer, entries: [object], idOverride: repeatedId).first } // It's okay if the repeated notice goes into the DB but we hit a parse error for the containing one below guard repeatedNotice != nil else { continue } } if entry.isDelete { // TODO either purge the old one from the DB or mark it hidden } let new = NSEntityDescription.insertNewObject(forEntityName: "Notice", into: session.moc) as! NoticeMO // As yet unused, sadly. Put in sentinel values so numbers will be hidden in UI. new.faveNum = -1 new.repeatNum = -1 // Fill in all the info we have new.server = sourceServer new.statusNetId = statusNetId new.tag = tag new.htmlContent = htmlContent new.htmlLink = htmlLink new.published = published as NSDate new.lastUpdated = updated as NSDate new.conversationUrl = conversationUrl new.conversationId = conversationNumber new.conversationThread = conversationThread new.client = entry.client ?? "" // kind of optional new.user = user new.isOwnPost = entry.isPost || entry.isComment new.isReply = entry.isReply new.isRepeat = entry.isRepeat new.isFavourite = entry.isFavourite new.isDelete = entry.isDelete // Store extra data depending on the type of notice it was // If anything is missing this is an inconsistent notice and we should just ignore the whole thing if entry.isReply { guard let repliedTag = entry.inReplyToNoticeRef, let repliedUrl = entry.inReplyToNoticeRef else { continue } new.inReplyToNoticeTag = repliedTag new.inReplyToNoticeUrl = repliedUrl } if entry.isFavourite { guard let favouritedId = entry.object?.statusNetNoticeId, let favouritedHtmlLink = entry.object?.htmlLink else { continue } new.favouritedStatusNetId = favouritedId new.favouritedHtmlLink = favouritedHtmlLink } // The feed recursively embeds the repeated entry so we can recursively parse it too if entry.isRepeat { // If it's a repeat this will definitely have been set above new.repeatedNotice = repeatedNotice } session.persist() NSLog("Created new object with server \(new.server) and id \(new.statusNetId)") ret.append(new) } return ret } }
42.630303
134
0.574637
48ce43ac81987ed73eac8e1e50de406c13ff9579
3,794
// // DetailController.swift // CollectionAnimationDemo // // Created by Andrew on 16/7/20. // Copyright © 2016年 Andrew. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class DetailController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource { var itemCount:Int = 0 var layout:UICollectionViewLayout! var detailCollectionview:UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white() let rect = CGRect(x: 0, y: 0, width: screen_width, height: screen_height) detailCollectionview = UICollectionView(frame:rect,collectionViewLayout:layout) detailCollectionview.delegate = self detailCollectionview.dataSource = self self.detailCollectionview?.collectionViewLayout = layout self.view.addSubview(detailCollectionview) detailCollectionview.backgroundColor = UIColor.white() self.detailCollectionview!.register(CollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return itemCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var cell:UICollectionViewCell? = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) if(cell == nil){ cell = CollectionCell() } cell?.backgroundColor = getRandomColor() return cell! } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: AnyObject?) { } */ }
32.706897
176
0.697153
f7ea5ef8a3487f69bae63b7c4c2b63a3c98467f5
1,611
// // VCTrackBundle.swift // VideoClap // // Created by lai001 on 2020/12/4. // import Foundation open class VCTrackBundle: NSObject, NSCopying, NSMutableCopying { public var imageTracks: [VCImageTrackDescription] = [] public var videoTracks: [VCVideoTrackDescription] = [] public var audioTracks: [VCAudioTrackDescription] = [] public var lottieTracks: [VCLottieTrackDescription] { return imageTracks.filter({ $0 is VCLottieTrackDescription }) as! [VCLottieTrackDescription] } public var laminationTracks: [VCLaminationTrackDescription] { return imageTracks.filter({ $0 is VCLaminationTrackDescription }) as! [VCLaminationTrackDescription] } public var textTracks: [VCTextTrackDescription] { return imageTracks.filter({ $0 is VCTextTrackDescription }) as! [VCTextTrackDescription] } internal func otherTracks() -> [VCTrackDescriptionProtocol] { var tracks: [VCTrackDescriptionProtocol] = [] tracks.append(contentsOf: imageTracks) return tracks } public func copy(with zone: NSZone? = nil) -> Any { return self } public func mutableCopy(with zone: NSZone? = nil) -> Any { let copyObj = VCTrackBundle() copyObj.imageTracks = imageTracks.map({ $0.mutableCopy() as! VCImageTrackDescription }) copyObj.videoTracks = videoTracks.map({ $0.mutableCopy() as! VCVideoTrackDescription }) copyObj.audioTracks = audioTracks.map({ $0.mutableCopy() as! VCAudioTrackDescription }) return copyObj } }
32.877551
108
0.66977
dbfd63a9cc917516d01bab29ae6530d353d97fd5
2,839
// // WalletDetailDefaultTableViewCell.swift // Ballet // // Created by Koray Koska on 25.05.18. // Copyright © 2018 Boilertalk. All rights reserved. // import UIKit import Web3 import Material import BigInt import MarqueeLabel import DateToolsSwift class WalletDetailDefaultTableViewCell: TableViewCell { // MARK: - Properties @IBOutlet weak var inOutArrow: UIImageView! @IBOutlet weak var fromToAddress: MarqueeLabel! @IBOutlet weak var value: MarqueeLabel! @IBOutlet weak var age: MarqueeLabel! // MARK: - Initialization override func awakeFromNib() { super.awakeFromNib() setupUI() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } // MARK: - UI setup private func setupUI() { fromToAddress.setupSubTitleLabel() value.setupSubTitleLabel() value.textAlignment = .center age.setupSubTitleLabel() age.textAlignment = .center } // MARK: - Cell setup func setup(for address: EthereumAddress, with transaction: EtherscanTransaction) { let fromIsSelf = transaction.from == address let toIsSelf = transaction.to == address if fromIsSelf && toIsSelf { // Self tx inOutArrow.image = UIImage(named: "baseline_loop_black_24pt")?.withRenderingMode(.alwaysTemplate) inOutArrow.tintColor = Color.blue.base // self -> self fromToAddress.text = "self -> self" } else if fromIsSelf { // Out tx inOutArrow.image = UIImage(named: "baseline_arrow_upward_black_24pt")?.withRenderingMode(.alwaysTemplate) inOutArrow.tintColor = Color.red.base // Only to is relevant fromToAddress.text = "self -> \(transaction.to.hex(eip55: true))" } else { // In tx inOutArrow.image = UIImage(named: "baseline_arrow_downward_black_24pt")?.withRenderingMode(.alwaysTemplate) inOutArrow.tintColor = Color.green.base // Only from is relevant fromToAddress.text = "\(transaction.from.hex(eip55: true)) -> self" } var valueStr = String(transaction.value.intValue, radix: 10).weiToEthStr() if valueStr.count > 6 { let startIndex = valueStr.startIndex let endIndex = valueStr.index(valueStr.startIndex, offsetBy: 6) valueStr = "~ \(String(valueStr[startIndex..<endIndex]))" } value.text = "\(valueStr) ETH" if let timeStamp = Int(String(transaction.timeStamp.intValue, radix: 10)) { let date = Date(timeIntervalSince1970: Double(timeStamp)) age.text = date.shortTimeAgoSinceNow } else { age.text = "???" } } }
30.526882
119
0.630151
383fb7e65542503fe9b66eaa978b9dc6607511df
18,140
// // Arguments.swift // SwiftFormat // // Created by Nick Lockwood on 07/08/2018. // Copyright © 2018 Nick Lockwood. // // Distributed under the permissive MIT license // Get the latest version from here: // // https://github.com/nicklockwood/SwiftFormat // // 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 extension Options { init(_ args: [String: String], in directory: String) throws { fileOptions = try fileOptionsFor(args, in: directory) formatOptions = try formatOptionsFor(args) rules = try rulesFor(args) } mutating func addArguments(_ args: [String: String], in directory: String) throws { let oldArguments = argumentsFor(self) let newArguments = try mergeArguments(args, into: oldArguments) var newOptions = try Options(newArguments, in: directory) if let fileInfo = self.formatOptions?.fileInfo { newOptions.formatOptions?.fileInfo = fileInfo } self = newOptions } } // Parse a space-delimited string into an array of command-line arguments // Replicates the behavior implemented by the console when parsing input func parseArguments(_ argumentString: String, ignoreComments: Bool = true) -> [String] { var arguments = [""] // Arguments always begin with script path var characters = String.UnicodeScalarView.SubSequence(argumentString.unicodeScalars) var string = "" var escaped = false var quoted = false loop: while let char = characters.popFirst() { switch char { case "#" where !ignoreComments && !escaped && !quoted: break loop // comment case "\\" where !escaped: escaped = true case "\"" where !escaped && !quoted: quoted = true case "\"" where !escaped && quoted: quoted = false fallthrough case " " where !escaped && !quoted: if !string.isEmpty { arguments.append(string) } string.removeAll() case "\"" where escaped: escaped = false string.append("\"") case _ where escaped && quoted: string.append("\\") fallthrough default: escaped = false string.append(Character(char)) } } if !string.isEmpty { arguments.append(string) } return arguments } // Parse a flat array of command-line arguments into a dictionary of flags and values func preprocessArguments(_ args: [String], _ names: [String]) throws -> [String: String] { var anonymousArgs = 0 var namedArgs: [String: String] = [:] var name = "" for arg in args { if arg.hasPrefix("--") { // Long argument names let key = String(arg.unicodeScalars.dropFirst(2)) if !names.contains(key) { throw FormatError.options("Unknown option --\(key)") } name = key namedArgs[name] = namedArgs[name] ?? "" continue } else if arg.hasPrefix("-") { // Short argument names let flag = String(arg.unicodeScalars.dropFirst()) let matches = names.filter { $0.hasPrefix(flag) } if matches.count > 1 { throw FormatError.options("Ambiguous flag -\(flag)") } else if matches.isEmpty { throw FormatError.options("Unknown flag -\(flag)") } else { name = matches[0] namedArgs[name] = namedArgs[name] ?? "" } continue } if name == "" { // Argument is anonymous name = String(anonymousArgs) anonymousArgs += 1 } if let existing = namedArgs[name], !existing.isEmpty, // TODO: find a more general way to represent merge-able options ["exclude", "unexclude", "disable", "enable", "rules"].contains(name) || FormatOptions.Descriptor.all.contains(where: { $0.argumentName == name && $0.isSetType }) { namedArgs[name] = existing + "," + arg } else { namedArgs[name] = arg } name = "" } return namedArgs } // Parse a comma-delimited list of items func parseCommaDelimitedList(_ string: String) -> [String] { return string.components(separatedBy: ",").compactMap { let item = $0.trimmingCharacters(in: .whitespacesAndNewlines) return item.isEmpty ? nil : item } } // Parse a comma-delimited string into an array of rules let allRules = Set(FormatRules.byName.keys) func parseRules(_ rules: String) throws -> [String] { let rules = parseCommaDelimitedList(rules) try rules.first(where: { !allRules.contains($0) }).map { throw FormatError.options("Unknown rule '\($0)'") } return rules } // Parse single file path func parsePath(_ path: String, for argument: String, in directory: String) throws -> URL { let expandedPath = expandPath(path, in: directory) if !FileManager.default.fileExists(atPath: expandedPath.path) { if path.contains(",") { throw FormatError.options("\(argument) argument does not support multiple paths") } if pathContainsGlobSyntax(path) { throw FormatError.options("\(argument) path cannot contain wildcards") } } return expandedPath } // Parse one or more comma-delimited file paths func parsePaths(_ paths: String, for argument: String, in directory: String) throws -> [URL] { return try parseCommaDelimitedList(paths).map { try parsePath($0, for: argument, in: directory) } } // Merge two dictionaries of arguments func mergeArguments(_ args: [String: String], into config: [String: String]) throws -> [String: String] { var input = config var output = args // Merge excluded urls if let exclude = output["exclude"].map(parseCommaDelimitedList), var excluded = input["exclude"].map({ Set(parseCommaDelimitedList($0)) }) { excluded.formUnion(exclude) output["exclude"] = Array(excluded).sorted().joined(separator: ",") } // Merge unexcluded urls if let unexclude = output["unexclude"].map(parseCommaDelimitedList), var unexcluded = input["unexclude"].map({ Set(parseCommaDelimitedList($0)) }) { unexcluded.formUnion(unexclude) output["unexclude"] = Array(unexcluded).sorted().joined(separator: ",") } // Merge rules if let rules = try output["rules"].map(parseRules) { if rules.isEmpty { output["rules"] = nil } else { input["rules"] = nil input["enable"] = nil input["disable"] = nil } } else { if let _disable = try output["disable"].map(parseRules) { if let rules = try input["rules"].map(parseRules) { input["rules"] = Set(rules).subtracting(_disable).sorted().joined(separator: ",") } if let enable = try input["enable"].map(parseRules) { input["enable"] = Set(enable).subtracting(_disable).sorted().joined(separator: ",") } if let disable = try input["disable"].map(parseRules) { input["disable"] = Set(disable).union(_disable).sorted().joined(separator: ",") output["disable"] = nil } } if let _enable = try args["enable"].map(parseRules) { if let enable = try input["enable"].map(parseRules) { input["enable"] = Set(enable).union(_enable).sorted().joined(separator: ",") output["enable"] = nil } if let disable = try input["disable"].map(parseRules) { input["disable"] = Set(disable).subtracting(_enable).sorted().joined(separator: ",") } } } // Merge other arguments for (key, inValue) in input { guard let outValue = output[key] else { output[key] = inValue continue } if FormatOptions.Descriptor.all.contains(where: { $0.argumentName == key && $0.isSetType }) { let inOptions = parseCommaDelimitedList(inValue) let outOptions = parseCommaDelimitedList(outValue) output[key] = Set(inOptions).union(outOptions).sorted().joined(separator: ",") } } return output } // Parse a configuration file into a dictionary of arguments func parseConfigFile(_ data: Data) throws -> [String: String] { guard let input = String(data: data, encoding: .utf8) else { throw FormatError.reading("Unable to read data for configuration file") } let lines = input.components(separatedBy: .newlines) let arguments = try lines.flatMap { line -> [String] in // TODO: parseArguments isn't a perfect fit here - should we use a different approach? let line = line.replacingOccurrences(of: "\\n", with: "\n") let parts = parseArguments(line, ignoreComments: false).dropFirst().map { $0.replacingOccurrences(of: "\n", with: "\\n") } guard let key = parts.first else { return [] } if !key.hasPrefix("-") { throw FormatError.options("Unknown option '\(key)' in configuration file") } return [key, parts.dropFirst().joined(separator: " ")] } do { return try preprocessArguments(arguments, optionsArguments) } catch let FormatError.options(message) { throw FormatError.options("\(message) in configuration file") } } // Serialize a set of options into either an arguments string or a file func serialize(options: Options, excludingDefaults: Bool = false, separator: String = "\n") -> String { var optionSets = [Options]() if let fileOptions = options.fileOptions { optionSets.append(Options(fileOptions: fileOptions)) } if let formatOptions = options.formatOptions { optionSets.append(Options(formatOptions: formatOptions)) } if let rules = options.rules { optionSets.append(Options(rules: rules)) } return optionSets.map { let arguments = argumentsFor($0, excludingDefaults: excludingDefaults) return serialize(arguments: arguments, separator: separator) }.filter { !$0.isEmpty }.joined(separator: separator) } // Serialize arguments func serialize(arguments: [String: String], separator: String = "\n") -> String { return arguments.map { var value = $1 if value.contains(" ") { value = "\"\(value.replacingOccurrences(of: "\"", with: "\\\""))\"" } return "--\($0) \(value)" }.sorted().joined(separator: separator) } // Get command line arguments from options (excludes deprecated/renamed options) func argumentsFor(_ options: Options, excludingDefaults: Bool = false) -> [String: String] { var args = [String: String]() if let fileOptions = options.fileOptions { var arguments = Set(fileArguments) do { if !excludingDefaults || fileOptions.followSymlinks != FileOptions.default.followSymlinks { args["symlinks"] = fileOptions.followSymlinks ? "follow" : "ignore" } arguments.remove("symlinks") } do { if !fileOptions.excludedGlobs.isEmpty { // TODO: find a better alternative to stringifying url args["exclude"] = fileOptions.excludedGlobs.map { $0.description }.sorted().joined(separator: ",") } arguments.remove("exclude") } do { if !fileOptions.unexcludedGlobs.isEmpty { // TODO: find a better alternative to stringifying url args["unexclude"] = fileOptions.unexcludedGlobs.map { $0.description }.sorted().joined(separator: ",") } arguments.remove("unexclude") } assert(arguments.isEmpty) } if let formatOptions = options.formatOptions { for descriptor in FormatOptions.Descriptor.all where !descriptor.isDeprecated { let value = descriptor.fromOptions(formatOptions) if !excludingDefaults || value != descriptor.fromOptions(.default) { // Special case for swiftVersion // TODO: find a better solution for this if descriptor.argumentName == FormatOptions.Descriptor.swiftVersion.argumentName, value == Version.undefined.rawValue { continue } args[descriptor.argumentName] = value } } } if let rules = options.rules { let defaultRules = allRules.subtracting(FormatRules.disabledByDefault) let enabled = rules.subtracting(defaultRules) if !enabled.isEmpty { args["enable"] = enabled.sorted().joined(separator: ",") } let disabled = defaultRules.subtracting(rules) if !disabled.isEmpty { args["disable"] = disabled.sorted().joined(separator: ",") } } return args } private func processOption(_ key: String, in args: [String: String], from: inout Set<String>, handler: (String) throws -> Void) throws { precondition(optionsArguments.contains(key)) var arguments = from arguments.remove(key) from = arguments guard let value = args[key] else { return } do { try handler(value) } catch { guard !value.isEmpty else { throw FormatError.options("--\(key) option expects a value") } throw FormatError.options("Unsupported --\(key) value '\(value)'") } } // Parse rule names from arguments func rulesFor(_ args: [String: String]) throws -> Set<String> { var rules = allRules rules = try args["rules"].map { try Set(parseRules($0)) } ?? rules.subtracting(FormatRules.disabledByDefault) try args["enable"].map { try rules.formUnion(parseRules($0)) } try args["disable"].map { try rules.subtract(parseRules($0)) } return rules } // Parse FileOptions from arguments func fileOptionsFor(_ args: [String: String], in directory: String) throws -> FileOptions? { var options = FileOptions() var arguments = Set(fileArguments) var containsFileOption = false try processOption("symlinks", in: args, from: &arguments) { containsFileOption = true switch $0.lowercased() { case "follow": options.followSymlinks = true case "ignore": options.followSymlinks = false default: throw FormatError.options("") } } try processOption("exclude", in: args, from: &arguments) { containsFileOption = true options.excludedGlobs += expandGlobs($0, in: directory) } try processOption("unexclude", in: args, from: &arguments) { containsFileOption = true options.unexcludedGlobs += expandGlobs($0, in: directory) } assert(arguments.isEmpty, "\(arguments.joined(separator: ","))") return containsFileOption ? options : nil } // Parse FormatOptions from arguments // Returns nil if the arguments dictionary does not contain any formatting arguments func formatOptionsFor(_ args: [String: String]) throws -> FormatOptions? { var options = FormatOptions.default var arguments = Set(formattingArguments) var containsFormatOption = false for option in FormatOptions.Descriptor.all { try processOption(option.argumentName, in: args, from: &arguments) { containsFormatOption = true try option.toOptions($0, &options) } } assert(arguments.isEmpty, "\(arguments.joined(separator: ","))") return containsFormatOption ? options : nil } // Get deprecation warnings from a set of arguments func warningsForArguments(_ args: [String: String]) -> [String] { var warnings = [String]() for option in FormatOptions.Descriptor.all { if args[option.argumentName] != nil, let message = option.deprecationMessage { warnings.append(message) } } return warnings } let fileArguments = [ "symlinks", "exclude", "unexclude", ] let rulesArguments = [ "disable", "enable", "rules", ] let formattingArguments = FormatOptions.Descriptor.formatting.map { $0.argumentName } let internalArguments = FormatOptions.Descriptor.internal.map { $0.argumentName } let optionsArguments = fileArguments + rulesArguments + formattingArguments + internalArguments let commandLineArguments = [ // Input options "config", "inferoptions", "output", "cache", "verbose", "quiet", "dryrun", "lint", // Misc "help", "version", "options", "ruleinfo", ] + optionsArguments let deprecatedArguments = FormatOptions.Descriptor.all.compactMap { $0.isDeprecated ? $0.argumentName : nil }
37.096115
118
0.614939
cc66bb0e1362a98e5d77bd4fbcee78c63a5b2f8c
273
import CoreBluetooth import Foundation extension CBPeripheral { /// There is still no identifier property for macOS, that's why we need to retrieve it by value method var uuidIdentifier: UUID { return value(forKey: "identifier") as! NSUUID as UUID } }
27.3
106
0.721612
d65c071ed95518409ec8d877c219b5749b7f543d
11,468
// // DirectoryProvider.swift // Arkevia // // Created by Reqven on 10/07/2020. // Copyright © 2020 Manu Marchand. All rights reserved. // import Foundation import CoreData class DirectoryProvider { static let rootName = "MySafe" static let rootPath = "/MySafe/" private let openAction = "https://www.arkevia.com/safe-secured/browser/open.action" private let openFolderAction = "https://www.arkevia.com/safe-secured/browser/openFolder.action" private let deleteDefinitly = "https://www.arkevia.com/safe-secured/browser/deleteDefinitly.action" private let deleteTemporarilyAction = "https://www.arkevia.com/safe-secured/browser/deleteTemporarily.action" lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "Arkevia") container.loadPersistentStores { storeDesription, error in guard error == nil else { fatalError("Unresolved error \(error!)") } } container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy container.viewContext.automaticallyMergesChangesFromParent = false container.viewContext.shouldDeleteInaccessibleFaults = true container.viewContext.undoManager = nil return container }() func createFetchedResultsController() -> NSFetchedResultsController<Directory> { let fetchRequest = Directory.createFetchRequest() fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] let controller = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil ) return controller } private func newTaskContext() -> NSManagedObjectContext { let taskContext = persistentContainer.newBackgroundContext() taskContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy taskContext.undoManager = nil return taskContext } private func decode(from data: Data, with context: NSManagedObjectContext) throws -> Directory { let decoder = JSONDecoder() let codingUserInfoKey = CodingUserInfoKey(rawValue: "context")! decoder.userInfo[codingUserInfoKey] = context // print(String(decoding: data, as: UTF8.self)) let root = try decoder.decode(Root.self, from: data) let directory = root.cwd if let _ = root.tree { directory.name = DirectoryProvider.rootName directory.path = DirectoryProvider.rootPath } /*if let notIn = fetchNotIn(directory: directory, context: context) { context.delete(objects: notIn) }*/ context.delete(objects: fetchNotIn(directory: directory, context: context)) if let cached = fetchPersisted(path: directory.path, context: context) { directory.name = cached.name if let parent = cached.parent { directory.parent = parent } } return directory } private func fetchPersisted(path: String, context: NSManagedObjectContext) -> Directory? { let request = Directory.createFetchRequest() request.predicate = NSPredicate(format: "path == %@", path) request.includesPendingChanges = false guard let results = try? context.fetch(request) else { return nil } guard let item = results.first else { return nil } return item } private func fetchNotIn(directory: Directory, context: NSManagedObjectContext) -> [NSManagedObject] { let directoryRequest = Directory.createFetchRequest() directoryRequest.predicate = NSPredicate(format: "parent.path == %@", directory.path) directoryRequest.includesPendingChanges = false let fileRequest = File.createFetchRequest() fileRequest.predicate = NSPredicate(format: "directory.path == %@", directory.path) fileRequest.includesPendingChanges = false var found = [NSManagedObject]() if let results = try? context.fetch(directoryRequest) { found.append(contentsOf: results.filter { dir -> Bool in return !directory.directoriesArray.contains(where: { dir.path == $0.path }) }) } if let results = try? context.fetch(fileRequest) { found.append(contentsOf: results.filter { file -> Bool in return !directory.filesArray.contains(where: { file.name == $0.name && file.mime == $0.mime }) }) } return found } func fetchDirectory(for path: String? = nil, completionHandler: @escaping (Error?) -> Void) { let queryItems = [ URLQueryItem(name: "target", value: path ?? DirectoryProvider.rootPath), URLQueryItem(name: "sortName", value: "name"), URLQueryItem(name: "sortType", value: "asc"), ] let endpoint = path == nil ? openAction : openFolderAction var urlComponents = URLComponents(string: endpoint)! urlComponents.queryItems = queryItems let taskContext = newTaskContext() NetworkManager.shared.loadUser { result in switch(result) { case .failure(let error): completionHandler(error) case .success(_): let session = URLSession(configuration: .default) let task = session.dataTask(with: urlComponents.url!) { data, _, urlSessionError in guard urlSessionError == nil else { completionHandler(urlSessionError) return } guard let data = data else { completionHandler(NSError(domain: "Network Unavailable", code: 0)) return } taskContext.performAndWait { do { let _ = try self.decode(from: data, with: taskContext) } catch { completionHandler(error) return } if taskContext.hasChanges { do { try taskContext.save() } catch { completionHandler(error) return } taskContext.reset() } } completionHandler(nil) } task.resume() } } } func delete(files: [File], completionHandler: @escaping (Error?) -> Void) { var queryItems = [ URLQueryItem(name: "lastOperation", value: "openFolder"), URLQueryItem(name: "cmd", value: "deleteTemporarily") ] files.forEach { file in queryItems.append(contentsOf: [ URLQueryItem(name: "currentFolders", value: file.path), URLQueryItem(name: "targets", value: file.id), ]) } var urlComponents = URLComponents(string: deleteTemporarilyAction)! urlComponents.queryItems = queryItems print(urlComponents.url!) NetworkManager.shared.loadUser { result in switch(result) { case .failure(let error): completionHandler(error) case .success(_): let session = URLSession(configuration: .default) let task = session.dataTask(with: urlComponents.url!) { data, _, urlSessionError in guard urlSessionError == nil else { completionHandler(urlSessionError) return } guard let data = data else { completionHandler(NSError(domain: "Network Unavailable", code: 0)) return } guard !String(decoding: data, as: UTF8.self).contains("error") else { completionHandler(NSError(domain: "Unknown error", code: 0)) return } completionHandler(nil) } task.resume() } } } func emptyBin(completionHandler: @escaping (Error?) -> Void) { NetworkManager.shared.loadUser { result in switch(result) { case .failure(let error): completionHandler(error) case .success(_): let queryItems = [ URLQueryItem(name: "cmd", value: "deleteDefinitly"), URLQueryItem(name: "target", value: "/MySafe/MyRecycleBin/") ] var urlComponents = URLComponents(string: self.deleteDefinitly)! urlComponents.queryItems = queryItems let session = URLSession(configuration: .default) let task = session.dataTask(with: urlComponents.url!) { data, _, urlSessionError in guard urlSessionError == nil else { completionHandler(urlSessionError) return } guard let data = data else { completionHandler(NSError(domain: "Network Unavailable", code: 0)) return } print(String(decoding: data, as: UTF8.self)) guard !String(decoding: data, as: UTF8.self).contains("error") else { completionHandler(NSError(domain: "Unknown error", code: 0)) return } completionHandler(nil) } task.resume() } } } func deleteAll(completionHandler: @escaping (Error?) -> Void) { let taskContext = newTaskContext() taskContext.perform { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Directory") let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) batchDeleteRequest.resultType = .resultTypeCount // Execute the batch insert if let batchDeleteResult = try? taskContext.execute(batchDeleteRequest) as? NSBatchDeleteResult, batchDeleteResult.result != nil { completionHandler(nil) } else { completionHandler(NSError(domain: "batchDeleteError", code: 0)) } } } }
40.811388
113
0.532264
d9d39ec1adeeb8999671ba1d4765345ed5225aec
5,886
// // CustomerServices.swift // PayDock // // Created by Round Table Apps on 22/4/17. // Copyright © 2017 PayDock. All rights reserved. // import Foundation /// Customer Services class CustomerServices { weak var network: PayDockNetwork? var publicKey: String = "" init(network: PayDockNetwork) { self.network = network } init(network: PayDockNetwork, publicKey: String) { self.network = network self.publicKey = publicKey } /// add a customer with defualt payment source /// /// - parameter customer: customer request instance /// - parameter completion: returns a closure which returns customer or throws error /// - paramter customer: customer item from server func add(customer: CustomerRequest, completion: @escaping (_ result: @escaping () throws -> Customer) -> Void ) { network?.post(to: Constants.customers , with: customer.toDictionary(), completion: { (result) in do { let data = try result() let json: [String: Any] = try data.getResource() let customer: Customer = try Customer(json: json) completion { return customer } } catch let error { completion { throw error } } }) } /// get details for a customer /// /// - parameter with: customer's id /// - parameter completion: returns a closure which returns customer or throws error /// - paramter customer: customer item from server func getCustomer(with id: String, completion: @escaping (_ result: @escaping () throws -> Customer) -> Void) { let param: [String: Any] = [ "_id" : id] network?.get(from: Constants.customers, with: param, completion: { (result) in do { let data = try result() let json: [String: Any] = try data.getResource() let customer: Customer = try Customer(json: json) completion { return customer } } catch let error { completion { throw error } } }) } /// get list of customers from server /// /// - parameter with: filter properties /// - parameter completion: returns a closure which returns customers or throws error /// - paramter customer: customers item from server func getCustomers(with parameters: ListParameters?, completion: @escaping (_ charges: @escaping () throws -> [Customer]) -> Void) { network?.get(from: Constants.customers, with: parameters?.toDictionary(), completion: { (result) in do { let data = try result() var customers: [Customer] = [] let json: [Dictionary<String, Any>] = try data.getResource() for object in json { customers.append( try Customer(json: object)) } completion {return customers } } catch let error { completion { throw error } } }) } /// get list of cusomers Payment sources /// /// - parameter with: filter properties /// - parameter completion: returns a closure which returns customers or throws error /// - paramter customer: customers item from server func getCustomerPaymentSources(with parameters: ListParameters?, completion: @escaping (_ paymentSources: @escaping () throws -> [PaymentSource]) -> Void) { let relativeUrl = Constants.paymentSources + "?public_key=\(publicKey)" network?.get(from: relativeUrl, with: parameters?.toDictionary(), completion: { (result) in do { let data = try result() var paymentSources: [PaymentSource] = [] let json: [Dictionary<String, Any>] = try data.getResource() for object in json { paymentSources.append( try PaymentSource(json: object)) } completion {return paymentSources } } catch let error { completion { throw error } } }) } /// updates the customer's detail /// /// - parameter with: customer id /// - parameter customer: customer request instance /// - parameter completion: returns a closure which returns customer or throws error /// - paramter customer: customer item from server func updateCustomer(with id: String, customer: CustomerRequest, completion: @escaping (_ subscription: @escaping () throws -> Customer) -> Void) { let url = Constants.customers + "/" + id network?.put(to: url, with: customer.toDictionary(), completion: { (result) in do { let data = try result() let json: [String: Any] = try data.getResource() let customer: Customer = try Customer(json: json) completion { return customer } } catch let error { completion { throw error } } }) } /// archive a customer /// /// - parameter with: customer id /// - parameter completion: returns a closure which returns customer or throws error /// - paramter customer: customer item from server func archiveCustomer(with id: String, completion: @escaping (_ result: @escaping () throws -> Customer) -> Void) { let param: [String: Any] = [ "_id" : id] network?.delete(from: Constants.customers, with: param, completion: { (result) in do { let data = try result() let json: [String: Any] = try data.getResource() let customer: Customer = try Customer(json: json) completion { return customer } } catch let error { completion { throw error } } }) } }
40.875
160
0.577982
5df79371979e2e29f9d13449e03c5c822e65d036
1,386
// // ProfileViewModel.swift // UHShield // // Created by Tianhui Zhou on 11/3/20. // import Foundation import FirebaseFirestore import FirebaseFirestoreSwift class ProfileViewModel: ObservableObject { @Published var profiles = [Profile]() private var db = Firestore.firestore() // load profiles from firebase func fetchData() { db.collection("Profiles").addSnapshotListener { (querySnapshot, error) in guard let documents = querySnapshot?.documents else { print("No documents") return } self.profiles = documents.compactMap { (queryDocumentSnapshot) -> Profile? in return try? queryDocumentSnapshot.data(as: Profile.self) } print(self.profiles) print("Done for fetching profile data") } } // update profile when users use EditProfile View func updateProfile(profile: Profile) { do { try db.collection("Profiles").document(profile.email).setData(from: profile, merge: true) } catch { print(error) } } func addProfile(profile: Profile) { do { let _ = try db.collection("Profiles").document(profile.id!).setData(from: profile) } catch { print(error) } } }
26.653846
101
0.576479
7a5f02f753ca9fe19d09513633cdfda56653daf7
5,941
import Foundation import UIKit import SKPhotoBrowser import SafariServices public typealias JSONArray = [[String : Any]] public typealias JSONDictionary = [String : Any] public typealias Action = () -> Void //typealias L10n = R.string.localizable func clearAccount() { // JPUSHService.deleteAlias({ (code, alia, seq) in }, seq: 1) if let username = AccountModel.current?.username { Network.request(target: API.userLogout(username: username), success: nil, failure: nil) } AccountModel.delete() HTTPCookieStorage.shared.cookies?.forEach { HTTPCookieStorage.shared.deleteCookie($0) } URLCache.shared.removeAllCachedResponses() } /// Present 登录 func presentLoginVC() { clearAccount() let nav = NavigationViewController(rootViewController: LoginViewController()) AppWindow.shared.window.rootViewController?.present(nav, animated: true, completion: nil) } enum PhotoBrowserType { case image(UIImage) case imageURL(String) } /// 预览图片 func showImageBrowser(imageType: PhotoBrowserType) { var photo: SKPhoto? switch imageType { case .image(let image): photo = SKPhoto.photoWithImage(image) case .imageURL(let url): photo = SKPhoto.photoWithImageURL(url) photo?.shouldCachePhotoURLImage = true } guard let photoItem = photo else { return } SKPhotoBrowserOptions.bounceAnimation = true SKPhotoBrowserOptions.enableSingleTapDismiss = true // SKPhotoBrowserOptions.displayCloseButton = false SKPhotoBrowserOptions.displayStatusbar = false let photoBrowser = SKPhotoBrowser(photos: [photoItem]) photoBrowser.initializePageIndex(0) // photoBrowser.showToolbar(bool: true) var currentVC = AppWindow.shared.window.rootViewController?.currentViewController() if currentVC == nil { currentVC = AppWindow.shared.window.rootViewController } currentVC?.present(photoBrowser, animated: true, completion: nil) } /// 设置状态栏背景颜色 /// 需要设置的页面需要重载此方法 /// - Parameter color: 颜色 func setStatusBarBackground(_ color: UIColor, borderColor: UIColor = .clear) { guard let statusBarWindow = UIApplication.shared.value(forKey: "statusBarWindow") as? UIView, let statusBar = statusBarWindow.value(forKey: "statusBar") as? UIView, statusBar.responds(to:#selector(setter: UIView.backgroundColor)) else { return } if statusBar.backgroundColor == color { return } statusBar.backgroundColor = color statusBar.layer.borderColor = borderColor.cgColor statusBar.layer.borderWidth = 0.5 // statusBar.borderBottom = Border(color: borderColor) // DispatchQueue.once(token: "com.v2er.statusBar") { // statusBar.layer.shadowColor = UIColor.black.cgColor // statusBar.layer.shadowOpacity = 0.09 // statusBar.layer.shadowRadius = 3 // // 阴影向下偏移 6 // statusBar.layer.shadowOffset = CGSize(width: 0, height: 6) // statusBar.clipsToBounds = false // } } /// 打开浏览器 (内置 或 Safari) /// /// - Parameter url: url func openWebView(url: URL?) { guard let `url` = url else { return } var currentVC = AppWindow.shared.window.rootViewController?.currentViewController() if currentVC == nil { currentVC = AppWindow.shared.window.rootViewController } if Preference.shared.useSafariBrowser { let safariVC = SFHandoffSafariViewController(url: url, entersReaderIfAvailable: false) if #available(iOS 10.0, *) { safariVC.preferredControlTintColor = Theme.Color.globalColor } else { safariVC.navigationController?.navigationBar.tintColor = Theme.Color.globalColor } currentVC?.present(safariVC, animated: true, completion: nil) return } if let nav = currentVC?.navigationController { let webView = SweetWebViewController() webView.url = url nav.pushViewController(webView, animated: true) } else { let safariVC = SFHandoffSafariViewController(url: url) currentVC?.present(safariVC, animated: true, completion: nil) } } func openWebView(url: String) { guard let urlString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let `url` = URL(string: urlString) else { return } openWebView(url: url) } func clickCommentLinkHandle(urlString: String) { guard let url = URL(string: urlString) else { return } let link = url.absoluteString if url.host == nil || (url.host ?? "").lowercased().contains(".v2ex.com") { if url.path.contains("/member/") { let href = url.path let name = href.lastPathComponent let member = MemberModel(username: name, url: href, avatar: "") let memberPageVC = MemberPageViewController(memberName: member.username) AppWindow.shared.window.rootViewController?.currentViewController().navigationController?.pushViewController(memberPageVC, animated: true) } else if url.path.contains("/t/") { let topicID = url.path.lastPathComponent let topicDetailVC = TopicDetailViewController(topicID: topicID) // topicDetailVC.anchor = url.fragment?.deleteOccurrences(target: "reply").int AppWindow.shared.window.rootViewController?.currentViewController().navigationController?.pushViewController(topicDetailVC, animated: true) } else if url.path.contains("/go/") { let nodeDetailVC = NodeDetailViewController(node: NodeModel(title: "", href: url.path)) AppWindow.shared.window.rootViewController?.currentViewController().navigationController?.pushViewController(nodeDetailVC, animated: true) } else if link.hasPrefix("https://") || link.hasPrefix("http://") || link.hasPrefix("www."){ openWebView(url: url) } } else if link.hasPrefix("https://") || link.hasPrefix("http://") || link.hasPrefix("www."){ openWebView(url: url) } }
38.329032
151
0.692308
672f4d0539295b3cb50de64f4db715dd26db4403
711
// // QuestionsURLRequestFactory.swift // NetworkingInOperations-Example // // Created by William Boles on 29/07/2018. // Copyright © 2018 Boles. All rights reserved. // import Foundation class QuestionsURLRequestFactory: URLRequestFactory { // MARK: - Retrieval func requestToRetrieveQuestions(pageIndex: Int) -> URLRequest { var urlString = "questions?order=desc&sort=activity&tagged=ios&pagesize=30&site=stackoverflow" if pageIndex != 0 { urlString += "&page=\(pageIndex)" } var request = jsonRequest(endPoint: urlString) request.httpMethod = HTTPRequestMethod.get.rawValue return request } }
25.392857
102
0.651195
72c3077112a912dae21a8c881426a6bc5b2b405a
1,353
// // Image.swift // TrackFinder // // Created by Niels Hoogendoorn on 20/06/2020. // Copyright © 2020 Nihoo. All rights reserved. // import Foundation // MARK: - Image struct CoverImage: Codable { let height: Int let url: String let width: Int } // MARK: Image convenience initializers and mutators extension CoverImage { init(data: Data) throws { self = try newJSONDecoder().decode(CoverImage.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( height: Int? = nil, url: String? = nil, width: Int? = nil ) -> CoverImage { return CoverImage( height: height ?? self.height, url: url ?? self.url, width: width ?? self.width ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } }
24.160714
74
0.585366
20a58fd2263888af0f4c95d8d053040aabf5eb9c
6,209
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension AppStoreConnect.Builds { public enum BuildsPreReleaseVersionGetToOneRelated { public static let service = APIService<Response>(id: "builds-preReleaseVersion-get_to_one_related", tag: "Builds", method: "GET", path: "/v1/builds/{id}/preReleaseVersion", hasBody: false, securityRequirements: [SecurityRequirement(type: "itc-bearer-token", scopes: [])]) /** the fields to include for returned resources of type preReleaseVersions */ public enum FieldspreReleaseVersions: String, Codable, Equatable, CaseIterable { case app = "app" case builds = "builds" case platform = "platform" case version = "version" } public final class Request: APIRequest<Response> { public struct Options { /** the id of the requested resource */ public var id: String /** the fields to include for returned resources of type preReleaseVersions */ public var fieldspreReleaseVersions: [FieldspreReleaseVersions]? public init(id: String, fieldspreReleaseVersions: [FieldspreReleaseVersions]? = nil) { self.id = id self.fieldspreReleaseVersions = fieldspreReleaseVersions } } public var options: Options public init(options: Options) { self.options = options super.init(service: BuildsPreReleaseVersionGetToOneRelated.service) } /// convenience initialiser so an Option doesn't have to be created public convenience init(id: String, fieldspreReleaseVersions: [FieldspreReleaseVersions]? = nil) { let options = Options(id: id, fieldspreReleaseVersions: fieldspreReleaseVersions) self.init(options: options) } public override var path: String { return super.path.replacingOccurrences(of: "{" + "id" + "}", with: "\(self.options.id)") } public override var queryParameters: [String: Any] { var params: [String: Any] = [:] if let fieldspreReleaseVersions = options.fieldspreReleaseVersions?.encode().map({ String(describing: $0) }).joined(separator: ",") { params["fields[preReleaseVersions]"] = fieldspreReleaseVersions } return params } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = PrereleaseVersionResponse /** Related resource */ case status200(PrereleaseVersionResponse) /** Parameter error(s) */ case status400(ErrorResponse) /** Forbidden error */ case status403(ErrorResponse) /** Not found error */ case status404(ErrorResponse) public var success: PrereleaseVersionResponse? { switch self { case .status200(let response): return response default: return nil } } public var failure: ErrorResponse? { switch self { case .status400(let response): return response case .status403(let response): return response case .status404(let response): return response default: return nil } } /// either success or failure value. Success is anything in the 200..<300 status code range public var responseResult: APIResponseResult<PrereleaseVersionResponse, ErrorResponse> { if let successValue = success { return .success(successValue) } else if let failureValue = failure { return .failure(failureValue) } else { fatalError("Response does not have success or failure response") } } public var response: Any { switch self { case .status200(let response): return response case .status400(let response): return response case .status403(let response): return response case .status404(let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 case .status400: return 400 case .status403: return 403 case .status404: return 404 } } public var successful: Bool { switch self { case .status200: return true case .status400: return false case .status403: return false case .status404: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode(PrereleaseVersionResponse.self, from: data)) case 400: self = try .status400(decoder.decode(ErrorResponse.self, from: data)) case 403: self = try .status403(decoder.decode(ErrorResponse.self, from: data)) case 404: self = try .status404(decoder.decode(ErrorResponse.self, from: data)) default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
39.297468
279
0.558866
468786cfa66cc2c535e6a4384ed9187f52f3557d
226
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for var b { func g { deinit { case { init { class case ,
16.142857
87
0.734513
8a91539c6b4cc335b34dcd65c5b974f8d8ce49b1
9,160
// // BLETask.swift // BLE-Swift // // Created by SuJiang on 2018/10/9. // Copyright © 2018年 ss. All rights reserved. // import UIKit public enum BLETaskState { case plain case start case cancel case failed case success } @objcMembers public class BLETask: NSObject { var timer:Timer? var state:BLETaskState = .plain var error:BLEError? var timeout:TimeInterval = kDefaultTimeout var ob:NSKeyValueObservation? var startTimeInterval: TimeInterval = Date().timeIntervalSince1970 var isTimeout: Bool { get { let now = Date().timeIntervalSince1970 return (now - startTimeInterval >= timeout) } } func start() { self.state = .start startTimer() } func cancel() { self.state = .cancel } func startTimer() { self.stopTimer() DispatchQueue.main.async { self.timer = Timer(timeInterval: self.timeout, target: self, selector: #selector(self.timeoutHandler), userInfo: nil, repeats: false) self.timer!.fireDate = Date(timeIntervalSinceNow: self.timeout) RunLoop.main.add(self.timer!, forMode: .common) } } func stopTimer() { DispatchQueue.main.async { self.timer?.invalidate() self.timer = nil; } } @objc func timeoutHandler() { self.state = .failed } } public class BLEScanTask: BLETask { var priority = 0 var isConnectScan = false var scanCallback: ScanBlock? var stopCallback: EmptyBlock? var taskID: String public init(taskID: String, scanCallback: ScanBlock?, stopCallback: EmptyBlock?) { self.taskID = taskID self.scanCallback = scanCallback self.stopCallback = stopCallback } override public var hash: Int { return self.taskID.hash } override public func isEqual(_ object: Any?) -> Bool { guard let other = object as? BLEScanTask else { return false } return self.taskID == other.taskID } } @objcMembers public class BLEConnectTask: BLETask { var deviceName:String? var device:BLEDevice? var connectBlock:ConnectBlock? var isDisconnect = false var isConnecting = false var name:String? { return self.device?.name ?? self.deviceName; } deinit { connectBlock = nil ob = nil } init(deviceName:String, connectBlock:ConnectBlock?, timeout:TimeInterval = kDefaultTimeout) { super.init() self.deviceName = deviceName self.timeout = timeout self.connectBlock = connectBlock } init(device:BLEDevice, connectBlock:ConnectBlock?, timeout:TimeInterval = kDefaultTimeout) { super.init() self.device = device self.timeout = timeout self.connectBlock = connectBlock } func connectFailed(err: BLEError) { error = err device = nil state = .failed isConnecting = false stopTimer() } func connectSuccess() { error = nil device!.state = .ready state = .success isConnecting = false stopTimer() } override func timeoutHandler() { super.timeoutHandler() connectFailed(err: BLEError.taskError(reason: .timeout)) BLEDevicesManager.shared.deviceConnectTimeout(withTask: self) } override public var hash: Int { return self.name?.hash ?? 0 } override public func isEqual(_ object: Any?) -> Bool { guard let other = object as? BLEConnectTask else { return false } return self.name == other.name } } // MARK: - Data Task @objcMembers public class BLEDataTask: BLETask, BLEDataParserProtocol { var device:BLEDevice? var data:BLEData var callback:CommonCallback? var parser:BLEDataParser! // var name:String? { // return self.device?.name ?? self.deviceName; // } private var stateOb : NSKeyValueObservation? deinit { stateOb = nil callback = nil ob = nil } init(data:BLEData) { self.data = data super.init() } init(device:BLEDevice, data:BLEData, callback:CommonCallback?, timeout:TimeInterval = kDefaultTimeout) { self.data = data self.device = device self.callback = callback super.init() self.timeout = timeout self.parser = BLEDataParser() self.parser.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(deviceDataUpdate), name: BLEInnerNotification.deviceDataUpdate, object: nil) // 监听 weak var weakSelf = self stateOb = data.observe(\BLEData.stateRaw) { (bleData, change) in // print("hello") switch bleData.state { case .plain: return case .sending: return case .sent: return case .sendFailed: let error = weakSelf?.data.error weakSelf?.error = error ?? BLEError.taskError(reason: .sendFailed) weakSelf?.state = .failed weakSelf?.device = nil weakSelf?.data.recvData = nil weakSelf?.data.recvDatas = nil weakSelf?.parser.clear() case .recvFailed: let error = weakSelf?.data.error weakSelf?.error = error ?? BLEError.taskError(reason: .dataError) weakSelf?.state = .failed weakSelf?.device = nil weakSelf?.data.recvData = nil weakSelf?.data.recvDatas = nil weakSelf?.parser.clear() case .recving: return case .recved: weakSelf?.error = nil weakSelf?.state = .success weakSelf?.parser.clear() case .timeout: let error = BLEError.taskError(reason: .timeout) weakSelf?.error = error weakSelf?.state = .failed weakSelf?.device = nil weakSelf?.data.recvData = nil weakSelf?.data.recvDatas = nil weakSelf?.parser.clear() } weakSelf?.stopTimer() if weakSelf != nil { NotificationCenter.default.post(name: BLEInnerNotification.taskFinish, object: nil, userInfo: [BLEKey.task : weakSelf!]) } } } override func start() { super.start() parser.clear() data.state = .sending if data.sendToUuid == nil { guard let uuid = BLEConfig.shared.sendUUID[data.type] else { data.error = BLEError.deviceError(reason: .noCharacteristics) data.state = .sendFailed return } data.sendToUuid = uuid let recvUuid = BLEConfig.shared.recvUUID[data.type] data.recvFromUuid = recvUuid } guard let sendDevice = device else { data.error = BLEError.deviceError(reason: .disconnected) data.state = .sendFailed return } if !sendDevice.write(data.sendData, characteristicUUID: data.sendToUuid!) { data.error = BLEError.deviceError(reason: .disconnected) data.state = .sendFailed } else { if BLEConfig.shared.shouldSend03End { _ = sendDevice.write(Data(bytes: [0x03]), characteristicUUID: data.recvFromUuid!) } data.state = .sent } } @objc func deviceDataUpdate(notification: Notification) { guard let uuid = notification.userInfo?[BLEKey.uuid] as? String else { return } guard let data = notification.userInfo?[BLEKey.data] as? Data else { return } guard let device = notification.userInfo?[BLEKey.device] as? BLEDevice else { return } if uuid == self.data.recvFromUuid && device == self.device { startTimer() parser.standardParse(data: data, sendData: self.data.sendData, recvCount: self.data.recvDataCount) } } override func timeoutHandler() { super.timeoutHandler() if self.data.state == .timeout || self.data.state == .sendFailed || self.data.state == .recvFailed { return } // 在kvo里面处理 self.data.state = .timeout } /// MARK: - 代理实现 func didFinishParser(data: Data, dataArr: Array<Data>, recvCount: Int) { // kvo 里面处理完成任务 if self.data.recvDataCount == recvCount { self.data.recvDatas = dataArr self.data.recvData = data self.data.state = .recved } else { self.data.state = .recvFailed } } }
28.714734
149
0.559716
485930eec8fc1a4fdc76305c7abb7c403d3d65db
939
// // NASTests.swift // NASTests // // Created by Andrew Morris on 6/6/20. // Copyright © 2020 MIDS Capstone 2020. All rights reserved. // import XCTest @testable import NAS class NASTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.828571
111
0.661342
9b88c92a373e7f6660c3ceb36cb475a0b79fc041
8,534
import Foundation import SwiftGenKit import TSCBasic import TuistCore import TuistGraph import TuistSupport // swiftlint:disable:next type_name enum SynthesizedResourceInterfaceProjectMapperError: FatalError, Equatable { case defaultTemplateNotAvailable(ResourceSynthesizer.Parser) var type: ErrorType { switch self { case .defaultTemplateNotAvailable: return .bug } } var description: String { switch self { case let .defaultTemplateNotAvailable(parser): return "Default template for parser \(parser) not available." } } } /// A project mapper that synthesizes resource interfaces public final class SynthesizedResourceInterfaceProjectMapper: ProjectMapping { // swiftlint:disable:this type_name private let synthesizedResourceInterfacesGenerator: SynthesizedResourceInterfacesGenerating private let contentHasher: ContentHashing public convenience init( contentHasher: ContentHashing ) { self.init( synthesizedResourceInterfacesGenerator: SynthesizedResourceInterfacesGenerator(), contentHasher: contentHasher ) } init( synthesizedResourceInterfacesGenerator: SynthesizedResourceInterfacesGenerating, contentHasher: ContentHashing ) { self.synthesizedResourceInterfacesGenerator = synthesizedResourceInterfacesGenerator self.contentHasher = contentHasher } public func map(project: Project) throws -> (Project, [SideEffectDescriptor]) { let mappings = try project.targets .map { try mapTarget($0, project: project) } let targets: [Target] = mappings.map(\.0) let sideEffects: [SideEffectDescriptor] = mappings.map(\.1).flatMap { $0 } return (project.with(targets: targets), sideEffects) } // MARK: - Helpers private struct RenderedFile: Hashable { let path: AbsolutePath let contents: Data? } /// Map and generate resource interfaces for a given `Target` and `Project` private func mapTarget(_ target: Target, project: Project) throws -> (Target, [SideEffectDescriptor]) { guard !target.resources.isEmpty, target.supportsSources else { return (target, []) } var target = target let sideEffects: [SideEffectDescriptor] = try project.resourceSynthesizers .map { resourceSynthesizer throws -> (ResourceSynthesizer, String) in switch resourceSynthesizer.template { case let .file(path): let templateString = try FileHandler.shared.readTextFile(path) return (resourceSynthesizer, templateString) case .defaultTemplate: return (resourceSynthesizer, try templateString(for: resourceSynthesizer.parser)) } } .reduce([]) { acc, current in let (parser, templateString) = current let interfaceTypeEffects: [SideEffectDescriptor] (target, interfaceTypeEffects) = try renderAndMapTarget( parser, templateString: templateString, target: target, project: project ) return acc + interfaceTypeEffects } return (target, sideEffects) } /// - Returns: Modified `Target`, side effects, input paths and output paths which can then be later used in generate script private func renderAndMapTarget( _ resourceSynthesizer: ResourceSynthesizer, templateString: String, target: Target, project: Project ) throws -> ( target: Target, sideEffects: [SideEffectDescriptor] ) { let derivedPath = project.path .appending(component: Constants.DerivedDirectory.name) .appending(component: Constants.DerivedDirectory.sources) let paths = try self.paths(for: resourceSynthesizer, target: target, developmentRegion: project.developmentRegion) .filter(isResourceEmpty) let templateName: String switch resourceSynthesizer.template { case let .defaultTemplate(name): templateName = name case let .file(path): templateName = path.basenameWithoutExt } let renderedInterfaces: [(String, String)] if paths.isEmpty { renderedInterfaces = [] } else { let name = target.name.camelized.uppercasingFirst renderedInterfaces = [ ( templateName + "+" + name, try synthesizedResourceInterfacesGenerator.render( parser: resourceSynthesizer.parser, templateString: templateString, name: name, paths: paths ) ), ] } let renderedResources = Set( renderedInterfaces.map { name, contents in RenderedFile( path: derivedPath.appending(component: name + ".swift"), contents: contents.data(using: .utf8) ) } ) var target = target target.sources += try renderedResources .map { resource in let hash = try resource.contents.map(contentHasher.hash) return SourceFile(path: resource.path, contentHash: hash) } let sideEffects = renderedResources .map { FileDescriptor(path: $0.path, contents: $0.contents) } .map(SideEffectDescriptor.file) return ( target: target, sideEffects: sideEffects ) } private func paths( for resourceSynthesizer: ResourceSynthesizer, target: Target, developmentRegion: String? ) -> [AbsolutePath] { let resourcesPaths = target.resources .map(\.path) var paths = resourcesPaths .filter { $0.extension.map(resourceSynthesizer.extensions.contains) ?? false } .sorted() switch resourceSynthesizer.parser { case .strings: // This file kind is localizable, let's order files based on it var regionPriorityQueue = ["Base", "en"] if let developmentRegion = developmentRegion { regionPriorityQueue.insert(developmentRegion, at: 0) } // Let's sort paths moving the development region localization's one at first let prioritizedPaths = paths.filter { path in regionPriorityQueue.map { path.parentDirectory.basename.contains($0) }.contains(true) } let unprioritizedPaths = paths.filter { path in !regionPriorityQueue.map { path.parentDirectory.basename.contains($0) }.contains(true) } paths = prioritizedPaths + unprioritizedPaths case .assets, .coreData, .fonts, .interfaceBuilder, .json, .plists, .yaml, .files: break } var seen: Set<String> = [] return paths.filter { seen.insert($0.basename).inserted } } private func isResourceEmpty(_ path: AbsolutePath) throws -> Bool { if FileHandler.shared.isFolder(path) { if try !FileHandler.shared.contentsOfDirectory(path).isEmpty { return true } } else { if try !FileHandler.shared.readFile(path).isEmpty { return true } } logger.log( level: .warning, "Skipping synthesizing accessors for \(path.pathString) because its contents are empty." ) return false } private func templateString(for parser: ResourceSynthesizer.Parser) throws -> String { switch parser { case .assets: return SynthesizedResourceInterfaceTemplates.assetsTemplate case .strings: return SynthesizedResourceInterfaceTemplates.stringsTemplate case .plists: return SynthesizedResourceInterfaceTemplates.plistsTemplate case .fonts: return SynthesizedResourceInterfaceTemplates.fontsTemplate case .coreData, .interfaceBuilder, .json, .yaml: throw SynthesizedResourceInterfaceProjectMapperError.defaultTemplateNotAvailable(parser) case .files: return SynthesizedResourceInterfaceTemplates.filesTemplate } } }
36.161017
128
0.617881
1c026c64cc85709e19d8382b221188995de0bc3d
1,421
// // DRGameViewController+Result.swift // DReversi // // Created by DIO on 2020/03/21. // Copyright © 2020 DIO. All rights reserved. // import UIKit extension DRGameViewController { func updateResultMessage() { let palyerStoneCount = self.gameManager.stoneCount(stoneType: self.playerStone) let computerStoneCount = self.gameManager.stoneCount(stoneType: self.comStone) let result = self.gameResult(playerStoneCount: palyerStoneCount, computerStoneCount: computerStoneCount) self.gameResultView.gameResult = result } func gameResult(playerStoneCount: Int, computerStoneCount: Int) -> DRGameResult { if playerStoneCount == computerStoneCount { return .DRAW } if playerStoneCount > computerStoneCount { return .PLAYER } if playerStoneCount < computerStoneCount { return .COMPUTER } return .DRAW } func setupResultViewButtonsAction() { self.gameResultView.retryButton.addTarget(self, action: #selector(retryButtonAction(_:)), for: .touchUpInside) self.gameResultView.backTitleButton.addTarget(self, action: #selector(backTitleButtonAction(_:)), for: .touchUpInside) } @objc func backTitleButtonAction(_ sender: Any) { self.performSegue(withIdentifier: "DRGameViewPopSegue", sender: self) } @objc func retryButtonAction(_ sender: Any) { self.gameRestart() } }
36.435897
126
0.706545
3a4257c78b5ce8b2b681a0259d66180c4c9a0a53
1,286
// // MBConfigurationHelperUITests.swift // MBConfigurationHelperUITests // // Created by Romain ASNAR on 19/11/15. // Copyright © 2015 Romain ASNAR. All rights reserved. // import XCTest class MBConfigurationHelperUITests: 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. } }
34.756757
182
0.673406
ebb8400cc60db0cd7b6fd18ef3d69ae1507e7fd0
608
// // CityTableViewCell.swift // WeatherAppDemo // // Created by Marcelo José on 21/02/2019. // Copyright © 2019 Marcelo Oscar José. All rights reserved. // import UIKit class CityTableViewCell: UITableViewCell { var cityId: Int! @IBOutlet weak var cityNameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func updateCellData(cityName: String, id: Int) { cityNameLabel.text = cityName cityId = id } }
20.965517
65
0.667763
dbfb75ae10c811eccbecb7a339ddde58fb12e201
9,232
// // Created by Jake Lin on 12/13/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit /// A protocol provides mask designable feature. public protocol MaskDesignable { /** The type of the mask used for masking an IBAnimatable UI element. When you create a class and conform to `MaskDesignable`, you need to implement this computed property like ``` public var maskType: MaskType = .none { didSet { configureMask() configureBorder() } } ``` Because Interface Builder doesn't support `enum` for `@IBInspectable` property. You need to create an `internal` property using optional String as the type like ``` @IBInspectable var _maskType: String? { didSet { maskType = MaskType(string: _maskType) } } ``` */ var maskType: MaskType { get set } } public extension MaskDesignable where Self: UIView { /// Mask the IBAnimatable UI element with provided `maskType` public func configureMask() { switch maskType { case .circle: maskCircle() case .parallelogram(let angle): maskParallelogram(with: angle) case .polygon(let sides): maskPolygon(with: sides) case .star(let points): maskStar(with: points ) case .wave(let direction, let width, let offset): maskWave(with: direction, width: width, offset: offset) case .triangle: maskTriangle() case .none: layer.mask?.removeFromSuperlayer() } } } // MARK: - Private mask functions private extension MaskDesignable where Self: UIView { // MARK: - Circle /// Mask a circle shape. func maskCircle() { let diameter = ceil(min(bounds.width, bounds.height)) let origin = CGPoint(x: (bounds.width - diameter) / 2.0, y: (bounds.height - diameter) / 2.0) let size = CGSize(width: diameter, height: diameter) let circlePath = UIBezierPath(ovalIn: CGRect(origin: origin, size: size)) draw(circlePath) } // MARK: - Polygon /** Mask a polygon shape. - Parameter sides: The number of the polygon sides. */ func maskPolygon(with sides: Int) { let polygonPath = getPolygonBezierPath(with: max(sides, 3)) draw(polygonPath) } /** Get a Bezier path for a polygon shape with provided sides. - Parameter sides: The number of the polygon sides. - Returns: A Bezier path for a polygon shape. */ func getPolygonBezierPath(with sides: Int) -> UIBezierPath { let path = UIBezierPath() let center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0) var angle: CGFloat = -.pi / 2 let angleIncrement = .pi * 2 / CGFloat(sides) let length = min(bounds.width, bounds.height) let radius = length / 2.0 path.move(to: point(from: angle, radius: radius, offset: center)) for _ in 1...sides - 1 { angle += angleIncrement path.addLine(to: point(from: angle, radius: radius, offset: center)) } path.close() return path } // MARK: - Star /** Mask a star shape. - Parameter points: The number of the star points. */ func maskStar(with points: Int) { // FIXME: Do not mask the shadow. // Stars must has at least 3 points. var starPoints = points if points <= 2 { starPoints = 5 } let path = getStarPath(with: starPoints) draw(path) } /** Get a Bezier path for a star shape with provided points. - Parameter sides: The number of the star points. - Returns: A Bezier path for a star shape. */ func getStarPath(with points: Int, borderWidth: CGFloat = 0) -> UIBezierPath { let path = UIBezierPath() let radius = min(bounds.size.width, bounds.size.height) / 2 - borderWidth let starExtrusion = radius / 2 let angleIncrement = .pi * 2 / CGFloat(points) let center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0) var angle: CGFloat = -.pi / 2 for _ in 1...points { let aPoint = point(from: angle, radius: radius, offset: center) let nextPoint = point(from: angle + angleIncrement, radius: radius, offset: center) let midPoint = point(from: angle + angleIncrement / 2.0, radius: starExtrusion, offset: center) if path.isEmpty { path.move(to: aPoint) } path.addLine(to: midPoint) path.addLine(to: nextPoint) angle += angleIncrement } path.close() return path } // MARK: - Parallelogram /** Mask a parallelogram shape with provided top-left angle. - Parameter topLeftAngle: The top-left angle of the parallelogram shape. */ func maskParallelogram(with topLeftAngle: Double) { let parallelogramPath = getParallelogramBezierPath(with: topLeftAngle) draw(parallelogramPath) } /** Get a Bezier path for a parallelogram shape with provided top-left angle. - Parameter sides: The top-left angle of the parallelogram shape. - Returns: A Bezier path for a parallelogram shape. */ func getParallelogramBezierPath(with topLeftAngle: Double) -> UIBezierPath { let topLeftAngleRad = topLeftAngle * .pi / 180 let path = UIBezierPath() let offset = abs(CGFloat(tan(topLeftAngleRad - .pi / 2)) * bounds.height) if topLeftAngle <= 90 { path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: bounds.width - offset, y: 0)) path.addLine(to: CGPoint(x: bounds.width, y: bounds.height)) path.addLine(to: CGPoint(x: offset, y: bounds.height)) } else { path.move(to: CGPoint(x: offset, y: 0)) path.addLine(to: CGPoint(x: bounds.width, y: 0)) path.addLine(to: CGPoint(x: bounds.width - offset, y: bounds.height)) path.addLine(to: CGPoint(x: 0, y: bounds.height)) } path.close() return path } // MARK: - Triangle /** Mask a triangle shape. */ func maskTriangle() { let trianglePath = getTriangleBezierPath() draw(trianglePath) } /** Get a Bezier path for a triangle shape. - Returns: A Bezier path for a triangle shape. */ func getTriangleBezierPath() -> UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint(x: bounds.width / 2.0, y: bounds.origin.y)) path.addLine(to: CGPoint(x: bounds.width, y: bounds.height)) path.addLine(to: CGPoint(x: bounds.origin.x, y: bounds.height)) path.close() return path } // MARK: - Wave /** Mask a wave shape with provided prameters. - Parameter direction: The direction of the wave shape. - Parameter width: The width of the wave shape. - Parameter offset: The offset of the wave shape. */ func maskWave(with direction: MaskType.WaveDirection, width: Double, offset: Double) { let wavePath = getWaveBezierPath(with: direction == .up, width: CGFloat(width), offset: CGFloat(offset)) draw(wavePath) } /** Get a Bezier path for a parallelogram wave with provided prameters. - Parameter isUp: The flag to indicate whether the wave is up or not. - Parameter width: The width of the wave shape. - Parameter offset: The offset of the wave shape. - Returns: A Bezier path for a wave shape. */ func getWaveBezierPath(with isUp: Bool, width: CGFloat, offset: CGFloat) -> UIBezierPath { let originY = isUp ? bounds.maxY : bounds.minY let halfWidth = width / 2.0 let halfHeight = bounds.height / 2.0 let quarterWidth = width / 4.0 var isUp = isUp var startX = bounds.minX - quarterWidth - (offset.truncatingRemainder(dividingBy: width)) var endX = startX + halfWidth let path = UIBezierPath() path.move(to: CGPoint(x: startX, y: originY)) path.addLine(to: CGPoint(x: startX, y: bounds.midY)) repeat { path.addQuadCurve( to: CGPoint(x: endX, y: bounds.midY), controlPoint: CGPoint( x: startX + quarterWidth, y: isUp ? bounds.maxY + halfHeight : bounds.minY - halfHeight) ) startX = endX endX += halfWidth isUp = !isUp } while startX < bounds.maxX path.addLine(to: CGPoint(x: path.currentPoint.x, y: originY)) return path } } // MARK: - Private helper functions private extension MaskDesignable where Self: UIView { /** Draw a Bezier path on `layer.mask` using `CAShapeLayer`. - Parameter path: The Bezier path to draw. */ func draw(_ path: UIBezierPath) { layer.mask?.removeFromSuperlayer() let maskLayer = CAShapeLayer() maskLayer.frame = CGRect(origin: .zero, size: bounds.size) maskLayer.path = path.cgPath layer.mask = maskLayer } /** Return a radian from a provided degree a Bezier path on `layer.mask` using `CAShapeLayer`. - Parameter degree: The degree to convert. - Returns: A radian converted from the provided degree. */ func degree2radian(degree: CGFloat) -> CGFloat { return .pi * degree / 180 } /** Return a CGPoint from provided parameters. - Parameter angle: The angle to determine a point. - Parameter radius: The radius to determine a point. - Parameter offset: The offset to determine a point. - Returns: A CGPoint based on provided parameters. */ func point(from angle: CGFloat, radius: CGFloat, offset: CGPoint) -> CGPoint { return CGPoint(x: radius * cos(angle) + offset.x, y: radius * sin(angle) + offset.y) } }
29.401274
163
0.657712
e4a8bd9e51299aec67751b15184c1da233e69541
7,390
// // Archive+Reading.swift // ZIPFoundation // // Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation extension Archive { /// Read a ZIP `Entry` from the receiver and write it to `url`. /// /// - Parameters: /// - entry: The ZIP `Entry` to read. /// - url: The destination file URL. /// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed). /// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance. /// - progress: A progress object that can be used to track or cancel the extract operation. /// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`. /// - Throws: An error if the destination file cannot be written or the entry contains malformed content. public func extract(_ entry: Entry, to url: URL, bufferSize: UInt32 = defaultReadChunkSize, skipCRC32: Bool = false, progress: Progress? = nil) throws -> CRC32 { let fileManager = FileManager() var checksum = CRC32(0) switch entry.type { case .file: guard !fileManager.itemExists(at: url) else { throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path]) } try fileManager.createParentDirectoryStructure(for: url) let destinationRepresentation = fileManager.fileSystemRepresentation(withPath: url.path) guard let destinationFile: UnsafeMutablePointer<FILE> = fopen(destinationRepresentation, "wb+") else { throw CocoaError(.fileNoSuchFile) } defer { fclose(destinationFile) } let consumer = { _ = try Data.write(chunk: $0, to: destinationFile) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) case .directory: let consumer = { (_: Data) in try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) case .symlink: guard !fileManager.itemExists(at: url) else { throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path]) } let consumer = { (data: Data) in guard let linkPath = String(data: data, encoding: .utf8) else { throw ArchiveError.invalidEntryPath } try fileManager.createParentDirectoryStructure(for: url) try fileManager.createSymbolicLink(atPath: url.path, withDestinationPath: linkPath) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) } let attributes = FileManager.attributes(from: entry) try fileManager.setAttributes(attributes, ofItemAtPath: url.path) return checksum } /// Read a ZIP `Entry` from the receiver and forward its contents to a `Consumer` closure. /// /// - Parameters: /// - entry: The ZIP `Entry` to read. /// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed). /// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance. /// - progress: A progress object that can be used to track or cancel the extract operation. /// - consumer: A closure that consumes contents of `Entry` as `Data` chunks. /// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`.. /// - Throws: An error if the destination file cannot be written or the entry contains malformed content. public func extract(_ entry: Entry, bufferSize: UInt32 = defaultReadChunkSize, skipCRC32: Bool = false, progress: Progress? = nil, consumer: Consumer) throws -> CRC32 { var checksum = CRC32(0) let localFileHeader = entry.localFileHeader fseek(self.archiveFile, entry.dataOffset, SEEK_SET) progress?.totalUnitCount = self.totalUnitCountForReading(entry) switch entry.type { case .file: guard let compressionMethod = CompressionMethod(rawValue: localFileHeader.compressionMethod) else { throw ArchiveError.invalidCompressionMethod } switch compressionMethod { case .none: checksum = try self.readUncompressed(entry: entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, with: consumer) case .deflate: checksum = try self.readCompressed(entry: entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, with: consumer) } case .directory: try consumer(Data()) progress?.completedUnitCount = self.totalUnitCountForReading(entry) case .symlink: let localFileHeader = entry.localFileHeader let size = Int(localFileHeader.compressedSize) let data = try Data.readChunk(of: size, from: self.archiveFile) checksum = data.crc32(checksum: 0) try consumer(data) progress?.completedUnitCount = self.totalUnitCountForReading(entry) } return checksum } // MARK: - Helpers private func readUncompressed(entry: Entry, bufferSize: UInt32, skipCRC32: Bool, progress: Progress? = nil, with consumer: Consumer) throws -> CRC32 { let size = Int(entry.centralDirectoryStructure.uncompressedSize) return try Data.consumePart(of: size, chunkSize: Int(bufferSize), skipCRC32: skipCRC32, provider: { (_, chunkSize) -> Data in return try Data.readChunk(of: Int(chunkSize), from: self.archiveFile) }, consumer: { (data) in if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } try consumer(data) progress?.completedUnitCount += Int64(data.count) }) } private func readCompressed(entry: Entry, bufferSize: UInt32, skipCRC32: Bool, progress: Progress? = nil, with consumer: Consumer) throws -> CRC32 { let size = Int(entry.centralDirectoryStructure.compressedSize) return try Data.decompress(size: size, bufferSize: Int(bufferSize), skipCRC32: skipCRC32, provider: { (_, chunkSize) -> Data in return try Data.readChunk(of: chunkSize, from: self.archiveFile) }, consumer: { (data) in if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } try consumer(data) progress?.completedUnitCount += Int64(data.count) }) } }
55.149254
120
0.625575
5b1a20bb2345651534b7d13e576f21ff90befe56
1,062
// // UIButtonExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension UIButton { /// EZSwiftExtensions // swiftlint:disable function_parameter_count public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, target: AnyObject, action: Selector) { self.init(frame: CGRect(x: x, y: y, width: w, height: h)) addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside) } // swiftlint:enable function_parameter_count /// EZSwiftExtensions public func setBackgroundColor(color: UIColor, forState: UIControlState) { UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext()!, color.CGColor) CGContextFillRect(UIGraphicsGetCurrentContext()!, CGRect(x: 0, y: 0, width: 1, height: 1)) let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setBackgroundImage(colorImage, forState: forState) } }
34.258065
111
0.765537
1676972c5a54f4ca30a5bbf879cee91dce4a1304
959
/* fundoc name - */ /* fundoc example (- 12 -13 14) */ /* fundoc expect 11 */ /* fundoc text `-` is the subtraction operator. It operates on integers or doubles. It converts integers to doubles if it receives both as arguments. */ private func subtractf(_ values: [IntermediateValue]) throws -> IntermediateValue { guard let numbers = IntermediateValue.numbers(from: values) else { throw EvaluatorError.badFunctionParameters(values, "Subtract requires numbers") } switch numbers { case let .integers(array): guard let first = array.first else { return .integer(0) } return .integer(array.dropFirst().reduce(first, -)) case let .doubles(array): guard let first = array.first else { return .double(0) } return .double(array.dropFirst().reduce(first, -)) } } extension Callable { static let subtractFunction = Callable.functionVarargs(FunctionVarargs(noContext: subtractf(_:))) }
27.4
101
0.684046
cc9f7455d3ab60bd4ba437a60433a10f8824d908
2,812
// // Copyright 2020 Swiftkube Project // // 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. // /// /// Generated by Swiftkube:ModelGen /// Kubernetes v1.20.9 /// core.v1.EndpointAddress /// import Foundation public extension core.v1 { /// /// EndpointAddress is a tuple that describes single IP address. /// struct EndpointAddress: KubernetesResource { /// /// The Hostname of this endpoint /// public var hostname: String? /// /// The IP of this endpoint. May not be loopback (127.0.0.0/8), link-local (169.254.0.0/16), or link-local multicast ((224.0.0.0/24). IPv6 is also accepted but not fully supported on all platforms. Also, certain kubernetes components, like kube-proxy, are not IPv6 ready. /// public var ip: String /// /// Optional: Node hosting this endpoint. This can be used to determine endpoints local to a node. /// public var nodeName: String? /// /// Reference to object providing the endpoint. /// public var targetRef: core.v1.ObjectReference? /// /// Default memberwise initializer /// public init( hostname: String? = nil, ip: String, nodeName: String? = nil, targetRef: core.v1.ObjectReference? = nil ) { self.hostname = hostname self.ip = ip self.nodeName = nodeName self.targetRef = targetRef } } } /// /// Codable conformance /// public extension core.v1.EndpointAddress { private enum CodingKeys: String, CodingKey { case hostname = "hostname" case ip = "ip" case nodeName = "nodeName" case targetRef = "targetRef" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.hostname = try container.decodeIfPresent(String.self, forKey: .hostname) self.ip = try container.decode(String.self, forKey: .ip) self.nodeName = try container.decodeIfPresent(String.self, forKey: .nodeName) self.targetRef = try container.decodeIfPresent(core.v1.ObjectReference.self, forKey: .targetRef) } func encode(to encoder: Encoder) throws { var encodingContainer = encoder.container(keyedBy: CodingKeys.self) try encodingContainer.encode(hostname, forKey: .hostname) try encodingContainer.encode(ip, forKey: .ip) try encodingContainer.encode(nodeName, forKey: .nodeName) try encodingContainer.encode(targetRef, forKey: .targetRef) } }
29.914894
273
0.717639
fb542c0db0e4a62e19098d9580fab3f8899fcc5f
27,555
// // SideMenuNavigationController.swift // // Created by Jon Kent on 1/14/16. // Copyright © 2016 Jon Kent. All rights reserved. // import UIKit @objc public enum SideMenuPushStyle: Int { case `default`, popWhenPossible, preserve, preserveAndHideBackButton, replace, subMenu internal var hidesBackButton: Bool { switch self { case .preserveAndHideBackButton, .replace: return true case .default, .popWhenPossible, .preserve, .subMenu: return false } } } internal protocol MenuModel { /// Prevents the same view controller (or a view controller of the same class) from being pushed more than once. Defaults to true. var allowPushOfSameClassTwice: Bool { get } /// Forces menus to always animate when appearing or disappearing, regardless of a pushed view controller's animation. var alwaysAnimate: Bool { get } /** The blur effect style of the menu if the menu's root view controller is a UITableViewController or UICollectionViewController. - Note: If you want cells in a UITableViewController menu to show vibrancy, make them a subclass of UITableViewVibrantCell. */ var blurEffectStyle: UIBlurEffect.Style? { get } /// Animation curve of the remaining animation when the menu is partially dismissed with gestures. Default is .easeIn. var completionCurve: UIView.AnimationCurve { get } /// Automatically dismisses the menu when another view is presented from it. var dismissOnPresent: Bool { get } /// Automatically dismisses the menu when another view controller is pushed from it. var dismissOnPush: Bool { get } /// Automatically dismisses the menu when the screen is rotated. var dismissOnRotation: Bool { get } /// Automatically dismisses the menu when app goes to the background. var dismissWhenBackgrounded: Bool { get } /// Enable or disable a swipe gesture that dismisses the menu. Will not be triggered when `presentingViewControllerUserInteractionEnabled` is set to true. Default is true. var enableSwipeToDismissGesture: Bool { get } /// Enable or disable a tap gesture that dismisses the menu. Will not be triggered when `presentingViewControllerUserInteractionEnabled` is set to true. Default is true. var enableTapToDismissGesture: Bool { get } /** The push style of the menu. There are six modes in MenuPushStyle: - defaultBehavior: The view controller is pushed onto the stack. - popWhenPossible: If a view controller already in the stack is of the same class as the pushed view controller, the stack is instead popped back to the existing view controller. This behavior can help users from getting lost in a deep navigation stack. - preserve: If a view controller already in the stack is of the same class as the pushed view controller, the existing view controller is pushed to the end of the stack. This behavior is similar to a UITabBarController. - preserveAndHideBackButton: Same as .preserve and back buttons are automatically hidden. - replace: Any existing view controllers are released from the stack and replaced with the pushed view controller. Back buttons are automatically hidden. This behavior is ideal if view controllers require a lot of memory or their state doesn't need to be preserved.. - subMenu: Unlike all other behaviors that push using the menu's presentingViewController, this behavior pushes view controllers within the menu. Use this behavior if you want to display a sub menu. */ var pushStyle: SideMenuPushStyle { get } } @objc public protocol SideMenuNavigationControllerDelegate { @objc optional func sideMenuWillAppear(menu: SideMenuNavigationController, animated: Bool) @objc optional func sideMenuDidAppear(menu: SideMenuNavigationController, animated: Bool) @objc optional func sideMenuWillDisappear(menu: SideMenuNavigationController, animated: Bool) @objc optional func sideMenuDidDisappear(menu: SideMenuNavigationController, animated: Bool) } internal protocol SideMenuNavigationControllerTransitionDelegate: class { func sideMenuTransitionDidDismiss(menu: Menu) } public struct SideMenuSettings: SideMenuNavigationController.Model, InitializableStruct { public var allowPushOfSameClassTwice: Bool = true public var alwaysAnimate: Bool = true public var animationOptions: UIView.AnimationOptions = .curveEaseInOut public var blurEffectStyle: UIBlurEffect.Style? = nil public var completeGestureDuration: Double = 0.35 public var completionCurve: UIView.AnimationCurve = .easeIn public var dismissDuration: Double = 0.35 public var dismissOnPresent: Bool = true public var dismissOnPush: Bool = true public var dismissOnRotation: Bool = true public var dismissWhenBackgrounded: Bool = true public var enableSwipeToDismissGesture: Bool = true public var enableTapToDismissGesture: Bool = true public var initialSpringVelocity: CGFloat = 1 public var menuWidth: CGFloat = { let appScreenRect = UIApplication.shared.keyWindow?.bounds ?? UIWindow().bounds let minimumSize = min(appScreenRect.width, appScreenRect.height) return min(round(minimumSize * 0.75), 240) }() public var presentingViewControllerUserInteractionEnabled: Bool = false public var presentingViewControllerUseSnapshot: Bool = false public var presentDuration: Double = 0.35 public var presentationStyle: SideMenuPresentationStyle = .viewSlideOut public var pushStyle: SideMenuPushStyle = .default public var statusBarEndAlpha: CGFloat = 1 public var usingSpringWithDamping: CGFloat = 1 public init() {} } internal typealias Menu = SideMenuNavigationController @objcMembers open class SideMenuNavigationController: UINavigationController { internal typealias Model = MenuModel & PresentationModel & AnimationModel private lazy var _leftSide = Protected(false) { [weak self] oldValue, newValue in guard self?.isHidden != false else { Print.warning(.property, arguments: .leftSide, required: true) return oldValue } return newValue } private weak var _sideMenuManager: SideMenuManager? private weak var foundViewController: UIViewController? private var originalBackgroundColor: UIColor? private var rotating: Bool = false private var transitionController: SideMenuTransitionController? /// Delegate for receiving appear and disappear related events. If `nil` the visible view controller that displays a `SideMenuNavigationController` automatically receives these events. public weak var sideMenuDelegate: SideMenuNavigationControllerDelegate? /// The swipe to dismiss gesture. open private(set) weak var swipeToDismissGesture: UIPanGestureRecognizer? = nil /// The tap to dismiss gesture. open private(set) weak var tapToDismissGesture: UITapGestureRecognizer? = nil open var sideMenuManager: SideMenuManager { get { return _sideMenuManager ?? SideMenuManager.default } set { newValue.setMenu(self, forLeftSide: leftSide) if let sideMenuManager = _sideMenuManager, sideMenuManager !== newValue { let side = SideMenuManager.PresentDirection(leftSide: leftSide) Print.warning(.menuAlreadyAssigned, arguments: String(describing: self.self), side.name, String(describing: newValue)) } _sideMenuManager = newValue } } /// The menu settings. open var settings = SideMenuSettings() { didSet { setupBlur() if !enableSwipeToDismissGesture { swipeToDismissGesture?.remove() } if !enableTapToDismissGesture { tapToDismissGesture?.remove() } } } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setup() } public init(rootViewController: UIViewController, settings: SideMenuSettings = SideMenuSettings()) { self.settings = settings super.init(rootViewController: rootViewController) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override open func awakeFromNib() { super.awakeFromNib() sideMenuManager.setMenu(self, forLeftSide: leftSide) } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if topViewController == nil { Print.warning(.emptyMenu) } // Dismiss keyboard to prevent weird keyboard animations from occurring during transition presentingViewController?.view.endEditing(true) foundViewController = nil activeDelegate?.sideMenuWillAppear?(menu: self, animated: animated) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // We had presented a view before, so lets dismiss ourselves as already acted upon if view.isHidden { transitionController?.transition(presenting: false, animated: false) dismiss(animated: false, completion: { [weak self] in self?.view.isHidden = false }) } else { activeDelegate?.sideMenuDidAppear?(menu: self, animated: animated) } } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) defer { activeDelegate?.sideMenuWillDisappear?(menu: self, animated: animated) } guard !isBeingDismissed else { return } // When presenting a view controller from the menu, the menu view gets moved into another transition view above our transition container // which can break the visual layout we had before. So, we move the menu view back to its original transition view to preserve it. if let presentingView = presentingViewController?.view, let containerView = presentingView.superview { containerView.addSubview(view) } if dismissOnPresent { // We're presenting a view controller from the menu, so we need to hide the menu so it isn't showing when the presented view is dismissed. transitionController?.transition(presenting: false, animated: animated, alongsideTransition: { [weak self] in guard let self = self else { return } self.activeDelegate?.sideMenuWillDisappear?(menu: self, animated: animated) }, complete: false, completion: { [weak self] _ in guard let self = self else { return } self.activeDelegate?.sideMenuDidDisappear?(menu: self, animated: animated) self.view.isHidden = true }) } } override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // Work-around: if the menu is dismissed without animation the transition logic is never called to restore the // the view hierarchy leaving the screen black/empty. This is because the transition moves views within a container // view, but dismissing without animation removes the container view before the original hierarchy is restored. // This check corrects that. if let foundViewController = findViewController, foundViewController.view.window == nil { transitionController?.transition(presenting: false, animated: false) } // Clear selecton on UITableViewControllers when reappearing using custom transitions if let tableViewController = topViewController as? UITableViewController, let tableView = tableViewController.tableView, let indexPaths = tableView.indexPathsForSelectedRows, tableViewController.clearsSelectionOnViewWillAppear { indexPaths.forEach { tableView.deselectRow(at: $0, animated: false) } } activeDelegate?.sideMenuDidDisappear?(menu: self, animated: animated) if isBeingDismissed { transitionController = nil } else if dismissOnPresent { view.isHidden = true } } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // Don't bother resizing if the view isn't visible guard let transitionController = transitionController, !view.isHidden else { return } rotating = true let dismiss = self.presentingViewControllerUseSnapshot || self.dismissOnRotation coordinator.animate(alongsideTransition: { _ in if dismiss { transitionController.transition(presenting: false, animated: false, complete: false) } else { transitionController.layout() } }) { [weak self] _ in guard let self = self else { return } if dismiss { self.dismissMenu(animated: false) } self.rotating = false } } open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() transitionController?.layout() } override open func pushViewController(_ viewController: UIViewController, animated: Bool) { guard viewControllers.count > 0 else { // NOTE: pushViewController is called by init(rootViewController: UIViewController) // so we must perform the normal super method in this case return super.pushViewController(viewController, animated: animated) } var alongsideTransition: (() -> Void)? = nil if dismissOnPush { alongsideTransition = { [weak self] in guard let self = self else { return } self.dismissAnimation(animated: animated || self.alwaysAnimate) } } let pushed = SideMenuPushCoordinator(config: .init( allowPushOfSameClassTwice: allowPushOfSameClassTwice, alongsideTransition: alongsideTransition, animated: animated, fromViewController: self, pushStyle: pushStyle, toViewController: viewController ) ).start() if !pushed { super.pushViewController(viewController, animated: animated) } } override open var transitioningDelegate: UIViewControllerTransitioningDelegate? { get { transitionController = transitionController ?? SideMenuTransitionController(leftSide: leftSide, config: settings) transitionController?.delegate = self return transitionController } set { Print.warning(.transitioningDelegate, required: true) } } } // Interface extension SideMenuNavigationController: SideMenuNavigationController.Model { @IBInspectable open var allowPushOfSameClassTwice: Bool { get { return settings.allowPushOfSameClassTwice } set { settings.allowPushOfSameClassTwice = newValue } } @IBInspectable open var alwaysAnimate: Bool { get { return settings.alwaysAnimate } set { settings.alwaysAnimate = newValue } } @IBInspectable open var animationOptions: UIView.AnimationOptions { get { return settings.animationOptions } set { settings.animationOptions = newValue } } open var blurEffectStyle: UIBlurEffect.Style? { get { return settings.blurEffectStyle } set { settings.blurEffectStyle = newValue } } @IBInspectable open var completeGestureDuration: Double { get { return settings.completeGestureDuration } set { settings.completeGestureDuration = newValue } } @IBInspectable open var completionCurve: UIView.AnimationCurve { get { return settings.completionCurve } set { settings.completionCurve = newValue } } @IBInspectable open var dismissDuration: Double { get { return settings.dismissDuration } set { settings.dismissDuration = newValue } } @IBInspectable open var dismissOnPresent: Bool { get { return settings.dismissOnPresent } set { settings.dismissOnPresent = newValue } } @IBInspectable open var dismissOnPush: Bool { get { return settings.dismissOnPush } set { settings.dismissOnPush = newValue } } @IBInspectable open var dismissOnRotation: Bool { get { return settings.dismissOnRotation } set { settings.dismissOnRotation = newValue } } @IBInspectable open var dismissWhenBackgrounded: Bool { get { return settings.dismissWhenBackgrounded } set { settings.dismissWhenBackgrounded = newValue } } @IBInspectable open var enableSwipeToDismissGesture: Bool { get { return settings.enableSwipeToDismissGesture } set { settings.enableSwipeToDismissGesture = newValue } } @IBInspectable open var enableTapToDismissGesture: Bool { get { return settings.enableTapToDismissGesture } set { settings.enableTapToDismissGesture = newValue } } @IBInspectable open var initialSpringVelocity: CGFloat { get { return settings.initialSpringVelocity } set { settings.initialSpringVelocity = newValue } } /// Whether the menu appears on the right or left side of the screen. Right is the default. This property cannot be changed after the menu has loaded. @IBInspectable open var leftSide: Bool { get { return _leftSide.value } set { _leftSide.value = newValue } } /// Indicates if the menu is anywhere in the view hierarchy, even if covered by another view controller. open override var isHidden: Bool { return super.isHidden } @IBInspectable open var menuWidth: CGFloat { get { return settings.menuWidth } set { settings.menuWidth = newValue } } @IBInspectable open var presentingViewControllerUserInteractionEnabled: Bool { get { return settings.presentingViewControllerUserInteractionEnabled } set { settings.presentingViewControllerUserInteractionEnabled = newValue } } @IBInspectable open var presentingViewControllerUseSnapshot: Bool { get { return settings.presentingViewControllerUseSnapshot } set { settings.presentingViewControllerUseSnapshot = newValue } } @IBInspectable open var presentDuration: Double { get { return settings.presentDuration } set { settings.presentDuration = newValue } } open var presentationStyle: SideMenuPresentationStyle { get { return settings.presentationStyle } set { settings.presentationStyle = newValue } } @IBInspectable open var pushStyle: SideMenuPushStyle { get { return settings.pushStyle } set { settings.pushStyle = newValue } } @IBInspectable open var statusBarEndAlpha: CGFloat { get { return settings.statusBarEndAlpha } set { settings.statusBarEndAlpha = newValue } } @IBInspectable open var usingSpringWithDamping: CGFloat { get { return settings.usingSpringWithDamping } set { settings.usingSpringWithDamping = newValue } } } extension SideMenuNavigationController: SideMenuTransitionControllerDelegate { func sideMenuTransitionController(_ transitionController: SideMenuTransitionController, didDismiss viewController: UIViewController) { sideMenuManager.sideMenuTransitionDidDismiss(menu: self) } func sideMenuTransitionController(_ transitionController: SideMenuTransitionController, didPresent viewController: UIViewController) { swipeToDismissGesture?.remove() swipeToDismissGesture = addSwipeToDismissGesture(to: view.superview) tapToDismissGesture = addTapToDismissGesture(to: view.superview) } } internal extension SideMenuNavigationController { func handleMenuPan(_ gesture: UIPanGestureRecognizer, _ presenting: Bool) { let width = menuWidth let distance = gesture.xTranslation / width let progress = max(min(distance * factor(presenting), 1), 0) switch (gesture.state) { case .began: if !presenting { dismissMenu(interactively: true) } if gesture.xTranslation == 0 {transitionController?.handle(state: .finish) } transitionController?.handle(state: .update(progress: progress)) case .changed: if gesture.xTranslation == 0 {transitionController?.handle(state: .cancel) } transitionController?.handle(state: .update(progress: progress)) case .ended: if gesture.xTranslation == 0 {transitionController?.handle(state: .cancel) } let velocity = gesture.xVelocity * factor(presenting) let finished = velocity >= 100 || velocity >= -50 && abs(progress) >= 0.5 transitionController?.handle(state: finished ? .finish : .cancel) default: transitionController?.handle(state: .cancel) } } func cancelMenuPan(_ gesture: UIPanGestureRecognizer) { transitionController?.handle(state: .cancel) } func dismissMenu(animated flag: Bool = true, interactively interactive: Bool = false, completion: (() -> Void)? = nil) { guard !isHidden else { return } transitionController?.interactive = interactive dismiss(animated: flag, completion: completion) } // Note: although this method is syntactically reversed it allows the interactive property to scoped privately func present(_ viewControllerToPresentFrom: UIViewController?, interactively: Bool, completion: (() -> Void)? = nil) { guard let viewControllerToPresentFrom = viewControllerToPresentFrom, transitioningDelegate != nil else { return } transitionController?.interactive = interactively viewControllerToPresentFrom.present(self, animated: true, completion: completion) } } private extension SideMenuNavigationController { weak var activeDelegate: SideMenuNavigationControllerDelegate? { guard !view.isHidden else { return nil } if let sideMenuDelegate = sideMenuDelegate { return sideMenuDelegate } return findViewController as? SideMenuNavigationControllerDelegate } var findViewController: UIViewController? { foundViewController = foundViewController ?? presentingViewController?.activeViewController return foundViewController } func dismissAnimation(animated: Bool) { transitionController?.transition(presenting: false, animated: animated, alongsideTransition: { [weak self] in guard let self = self else { return } self.activeDelegate?.sideMenuWillDisappear?(menu: self, animated: animated) }, completion: { [weak self] _ in guard let self = self else { return } self.activeDelegate?.sideMenuDidDisappear?(menu: self, animated: animated) self.dismiss(animated: false, completion: nil) self.foundViewController = nil }) } func setup() { modalPresentationStyle = .overFullScreen setupBlur() if #available(iOS 13.0, *) {} else { registerForNotifications() } } func setupBlur() { removeBlur() guard let blurEffectStyle = blurEffectStyle, let view = topViewController?.view, !UIAccessibility.isReduceTransparencyEnabled else { return } originalBackgroundColor = originalBackgroundColor ?? view.backgroundColor let blurEffect = UIBlurEffect(style: blurEffectStyle) let blurView = UIVisualEffectView(effect: blurEffect) view.backgroundColor = UIColor.clear if let tableViewController = topViewController as? UITableViewController { tableViewController.tableView.backgroundView = blurView tableViewController.tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect) tableViewController.tableView.reloadData() } else { blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] blurView.frame = view.bounds view.insertSubview(blurView, at: 0) } } func removeBlur() { guard let originalBackgroundColor = originalBackgroundColor, let view = topViewController?.view else { return } self.originalBackgroundColor = nil view.backgroundColor = originalBackgroundColor if let tableViewController = topViewController as? UITableViewController { tableViewController.tableView.backgroundView = nil tableViewController.tableView.separatorEffect = nil tableViewController.tableView.reloadData() } else if let blurView = view.subviews.first as? UIVisualEffectView { blurView.removeFromSuperview() } } @available(iOS, deprecated: 13.0) func registerForNotifications() { NotificationCenter.default.removeObserver(self) [UIApplication.willChangeStatusBarFrameNotification, UIApplication.didEnterBackgroundNotification].forEach { NotificationCenter.default.addObserver(self, selector: #selector(handleNotification), name: $0, object: nil) } } @available(iOS, deprecated: 13.0) @objc func handleNotification(notification: NSNotification) { guard isHidden else { return } switch notification.name { case UIApplication.willChangeStatusBarFrameNotification: // Dismiss for in-call status bar changes but not rotation if !rotating { dismissMenu() } case UIApplication.didEnterBackgroundNotification: if dismissWhenBackgrounded { dismissMenu() } default: break } } @discardableResult func addSwipeToDismissGesture(to view: UIView?) -> UIPanGestureRecognizer? { guard enableSwipeToDismissGesture else { return nil } return UIPanGestureRecognizer(addTo: view, target: self, action: #selector(handleDismissMenuPan(_:)))?.with { $0.cancelsTouchesInView = false } } @discardableResult func addTapToDismissGesture(to view: UIView?) -> UITapGestureRecognizer? { guard enableTapToDismissGesture else { return nil } return UITapGestureRecognizer(addTo: view, target: self, action: #selector(handleDismissMenuTap(_:)))?.with { $0.cancelsTouchesInView = false } } @objc func handleDismissMenuTap(_ tap: UITapGestureRecognizer) { let hitTest = view.window?.hitTest(tap.location(in: view.superview), with: nil) guard hitTest == view.superview else { return } dismissMenu() } @objc func handleDismissMenuPan(_ gesture: UIPanGestureRecognizer) { handleMenuPan(gesture, false) } func factor(_ presenting: Bool) -> CGFloat { return presenting ? presentFactor : hideFactor } var presentFactor: CGFloat { return leftSide ? 1 : -1 } var hideFactor: CGFloat { return -presentFactor } }
41.686838
271
0.687026
4a60dc4c8cc23017b986623bd198389b8fcc6d2f
1,699
// // Complex.swift // Ronchigram // // Created by James LeBeau on 5/19/17. // Copyright © 2017 The Handsome Microscopist. All rights reserved. // import Foundation struct Complex:CustomStringConvertible{ // a+ib var a: Float = 0.0 var b: Float = 0.0 init(_ a:Float, _ b:Float) { self.a = a self.b = b } init(_ a:Int, _ b:Int) { self.a = Float(a) self.b = Float(b) } init(_ a:Int) { self.a = Float(a) } init(_ a:Float) { self.a = a } var description: String{ var sign:String; if(b < 0){ sign = "-" }else{ sign = "+" } return String(a) + sign + String(Swift.abs(b)) + "i" } func abs() -> Float { return sqrt(a*a+b*b) } func conj() -> Complex{ return Complex(a, -b) } func real() -> Float { return a } func imag() -> Float { return b } } func -(lhs:Complex,rhs:Complex) -> Complex { return Complex(lhs.a-rhs.a, lhs.b-rhs.b) } func +(lhs:Complex,rhs:Complex) -> Complex { return Complex(lhs.a+rhs.a, lhs.b+rhs.b) } func *(lhs:Complex,rhs:Complex) -> Complex { let prodA = lhs.a*rhs.a-lhs.b*rhs.b; let prodB = lhs.a*rhs.b+lhs.b*rhs.a; return Complex(prodA, prodB) } func /(lhs:Complex,rhs:Complex) -> Complex { let numer = lhs*rhs.conj() let denom = rhs*rhs.conj() return numer/denom.a } func /(lhs:Complex,rhs:Float) -> Complex { let divA = lhs.a/rhs let divB = lhs.b/rhs return Complex(divA, divB) }
16.495146
68
0.496763
ed8e7dfe787f0229e3f28ac802fa9e206ce4dbeb
23,572
/* * Copyright 2022 LiveKit * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Network import Promises import WebRTC public class Room: MulticastDelegate<RoomDelegate> { // MARK: - Public public var sid: Sid? { _state.sid } public var name: String? { _state.name } public var metadata: String? { _state.metadata } public var serverVersion: String? { _state.serverVersion } public var serverRegion: String? { _state.serverRegion } public var localParticipant: LocalParticipant? { _state.localParticipant } public var remoteParticipants: [Sid: RemoteParticipant] { _state.remoteParticipants } public var activeSpeakers: [Participant] { _state.activeSpeakers } // expose engine's vars public var url: String? { engine._state.url } public var token: String? { engine._state.token } public var connectionState: ConnectionState { engine._state.connectionState } public var connectStopwatch: Stopwatch { engine._state.connectStopwatch } // MARK: - Internal // Reference to Engine internal let engine: Engine internal private(set) var options: RoomOptions internal struct State { var sid: String? var name: String? var metadata: String? var serverVersion: String? var serverRegion: String? var localParticipant: LocalParticipant? var remoteParticipants = [Sid: RemoteParticipant]() var activeSpeakers = [Participant]() } // MARK: - Private private var _state = StateSync(State()) public init(delegate: RoomDelegate? = nil, connectOptions: ConnectOptions = ConnectOptions(), roomOptions: RoomOptions = RoomOptions()) { self.options = roomOptions self.engine = Engine(connectOptions: connectOptions, roomOptions: roomOptions) super.init() log() // listen to engine & signalClient engine.add(delegate: self) engine.signalClient.add(delegate: self) if let delegate = delegate { add(delegate: delegate) } // listen to app states AppStateListener.shared.add(delegate: self) } deinit { log() } @discardableResult public func connect(_ url: String, _ token: String, connectOptions: ConnectOptions? = nil, roomOptions: RoomOptions? = nil) -> Promise<Room> { // update options if specified self.options = roomOptions ?? self.options log("connecting to room", .info) guard _state.localParticipant == nil else { log("localParticipant is not nil", .warning) return Promise(EngineError.state(message: "localParticipant is not nil")) } // monitor.start(queue: monitorQueue) return engine.connect(url, token, connectOptions: connectOptions, roomOptions: roomOptions).then(on: .sdk) { () -> Room in self.log("connected to \(String(describing: self)) \(String(describing: self.localParticipant))", .info) return self } } @discardableResult public func disconnect() -> Promise<Void> { // return if already disconnected state if case .disconnected = connectionState { return Promise(()) } return engine.signalClient.sendLeave() .recover(on: .sdk) { self.log("Failed to send leave, error: \($0)") } .then(on: .sdk) { self.cleanUp(reason: .user) } } } // MARK: - Internal internal extension Room.State { @discardableResult mutating func getOrCreateRemoteParticipant(sid: Sid, info: Livekit_ParticipantInfo? = nil, room: Room) -> RemoteParticipant { if let participant = remoteParticipants[sid] { return participant } let participant = RemoteParticipant(sid: sid, info: info, room: room) remoteParticipants[sid] = participant return participant } } // MARK: - Private private extension Room { // Resets state of Room @discardableResult private func cleanUp(reason: DisconnectReason? = nil) -> Promise<Void> { log("reason: \(String(describing: reason))") return engine.cleanUp(reason: reason) .then(on: .sdk) { self.cleanUpParticipants() }.then(on: .sdk) { // reset state self._state.mutate { $0 = State() } }.catch(on: .sdk) { error in // this should never happen self.log("Engine cleanUp failed", .error) } } @discardableResult func cleanUpParticipants(notify _notify: Bool = true) -> Promise<Void> { log("notify: \(_notify)") // Stop all local & remote tracks let allParticipants = ([[localParticipant], _state.remoteParticipants.map { $0.value }] as [[Participant?]]) .joined() .compactMap { $0 } let cleanUpPromises = allParticipants.map { $0.cleanUp(notify: _notify) } return cleanUpPromises.all(on: .sdk).then { // self._state.mutate { $0.localParticipant = nil $0.remoteParticipants = [:] } } } @discardableResult func onParticipantDisconnect(sid: Sid) -> Promise<Void> { guard let participant = _state.mutate({ $0.remoteParticipants.removeValue(forKey: sid) }) else { return Promise(EngineError.state(message: "Participant not found for \(sid)")) } return participant.cleanUp(notify: true) } } // MARK: - Internal internal extension Room { func set(metadata: String?) { guard self.metadata != metadata else { return } self._state.mutate { state in state.metadata = metadata } notify { $0.room(self, didUpdate: metadata) } } } // MARK: - Debugging extension Room { @discardableResult public func sendSimulate(scenario: SimulateScenario) -> Promise<Void> { engine.signalClient.sendSimulate(scenario: scenario) } } // MARK: - Session Migration internal extension Room { func resetTrackSettings() { log("resetting track settings...") // create an array of RemoteTrackPublication let remoteTrackPublications = _state.remoteParticipants.values.map { $0._state.tracks.values.compactMap { $0 as? RemoteTrackPublication } }.joined() // reset track settings for all RemoteTrackPublication for publication in remoteTrackPublications { publication.resetTrackSettings() } } func sendSyncState() -> Promise<Void> { guard let subscriber = engine.subscriber, let localDescription = subscriber.localDescription else { // No-op return Promise(()) } let sendUnSub = engine.connectOptions.autoSubscribe let participantTracks = _state.remoteParticipants.values.map { participant in Livekit_ParticipantTracks.with { $0.participantSid = participant.sid $0.trackSids = participant._state.tracks.values .filter { $0.subscribed != sendUnSub } .map { $0.sid } } } // Backward compatibility let trackSids = participantTracks.map { $0.trackSids }.flatMap { $0 } log("trackSids: \(trackSids)") let subscription = Livekit_UpdateSubscription.with { $0.trackSids = trackSids // Deprecated $0.participantTracks = participantTracks $0.subscribe = !sendUnSub } return engine.signalClient.sendSyncState(answer: localDescription.toPBType(), subscription: subscription, publishTracks: _state.localParticipant?.publishedTracksInfo(), dataChannels: engine.dataChannelInfo()) } } // MARK: - SignalClientDelegate extension Room: SignalClientDelegate { func signalClient(_ signalClient: SignalClient, didReceiveLeave canReconnect: Bool) -> Bool { log("canReconnect: \(canReconnect)") if canReconnect { // force .full for next reconnect engine._state.mutate { $0.nextPreferredReconnectMode = .full } } else { // server indicates it's not recoverable cleanUp(reason: .networkError(NetworkError.disconnected(message: "did receive leave"))) } return true } func signalClient(_ signalClient: SignalClient, didUpdate trackSid: String, subscribedQualities: [Livekit_SubscribedQuality]) -> Bool { log() guard let localParticipant = _state.localParticipant else { return true } localParticipant.onSubscribedQualitiesUpdate(trackSid: trackSid, subscribedQualities: subscribedQualities) return true } func signalClient(_ signalClient: SignalClient, didReceive joinResponse: Livekit_JoinResponse) -> Bool { log("server version: \(joinResponse.serverVersion), region: \(joinResponse.serverRegion)", .info) _state.mutate { $0.sid = joinResponse.room.sid $0.name = joinResponse.room.name $0.metadata = joinResponse.room.metadata $0.serverVersion = joinResponse.serverVersion $0.serverRegion = joinResponse.serverRegion.isEmpty ? nil : joinResponse.serverRegion if joinResponse.hasParticipant { $0.localParticipant = LocalParticipant(from: joinResponse.participant, room: self) } if !joinResponse.otherParticipants.isEmpty { for otherParticipant in joinResponse.otherParticipants { $0.getOrCreateRemoteParticipant(sid: otherParticipant.sid, info: otherParticipant, room: self) } } } return true } func signalClient(_ signalClient: SignalClient, didUpdate room: Livekit_Room) -> Bool { set(metadata: room.metadata) return true } func signalClient(_ signalClient: SignalClient, didUpdate speakers: [Livekit_SpeakerInfo]) -> Bool { log("speakers: \(speakers)", .trace) let activeSpeakers = _state.mutate { state -> [Participant] in var lastSpeakers = state.activeSpeakers.reduce(into: [Sid: Participant]()) { $0[$1.sid] = $1 } for speaker in speakers { guard let participant = speaker.sid == state.localParticipant?.sid ? state.localParticipant : state.remoteParticipants[speaker.sid] else { continue } participant._state.mutate { $0.audioLevel = speaker.level $0.isSpeaking = speaker.active } if speaker.active { lastSpeakers[speaker.sid] = participant } else { lastSpeakers.removeValue(forKey: speaker.sid) } } state.activeSpeakers = lastSpeakers.values.sorted(by: { $1.audioLevel > $0.audioLevel }) return state.activeSpeakers } notify { $0.room(self, didUpdate: activeSpeakers) } return true } func signalClient(_ signalClient: SignalClient, didUpdate connectionQuality: [Livekit_ConnectionQualityInfo]) -> Bool { log("connectionQuality: \(connectionQuality)", .trace) for entry in connectionQuality { if let localParticipant = _state.localParticipant, entry.participantSid == localParticipant.sid { // update for LocalParticipant localParticipant._state.mutate { $0.connectionQuality = entry.quality.toLKType() } } else if let participant = _state.remoteParticipants[entry.participantSid] { // udpate for RemoteParticipant participant._state.mutate { $0.connectionQuality = entry.quality.toLKType() } } } return true } func signalClient(_ signalClient: SignalClient, didUpdateRemoteMute trackSid: String, muted: Bool) -> Bool { log("trackSid: \(trackSid) muted: \(muted)") guard let publication = _state.localParticipant?._state.tracks[trackSid] as? LocalTrackPublication else { // publication was not found but the delegate was handled return true } if muted { publication.mute() } else { publication.unmute() } return true } func signalClient(_ signalClient: SignalClient, didUpdate subscriptionPermission: Livekit_SubscriptionPermissionUpdate) -> Bool { log("did update subscriptionPermission: \(subscriptionPermission)") guard let participant = _state.remoteParticipants[subscriptionPermission.participantSid], let publication = participant.getTrackPublication(sid: subscriptionPermission.trackSid) else { return true } publication.set(subscriptionAllowed: subscriptionPermission.allowed) return true } func signalClient(_ signalClient: SignalClient, didUpdate trackStates: [Livekit_StreamStateInfo]) -> Bool { log("did update trackStates: \(trackStates.map { "(\($0.trackSid): \(String(describing: $0.state)))" }.joined(separator: ", "))") for update in trackStates { // Try to find RemoteParticipant guard let participant = _state.remoteParticipants[update.participantSid] else { continue } // Try to find RemoteTrackPublication guard let trackPublication = participant._state.tracks[update.trackSid] as? RemoteTrackPublication else { continue } // Update streamState (and notify) trackPublication._state.mutate { $0.streamState = update.state.toLKType() } } return true } func signalClient(_ signalClient: SignalClient, didUpdate participants: [Livekit_ParticipantInfo]) -> Bool { log("participants: \(participants)") var disconnectedParticipants = [Sid]() var newParticipants = [RemoteParticipant]() _state.mutate { for info in participants { if info.sid == $0.localParticipant?.sid { $0.localParticipant?.updateFromInfo(info: info) continue } let isNewParticipant = $0.remoteParticipants[info.sid] == nil let participant = $0.getOrCreateRemoteParticipant(sid: info.sid, info: info, room: self) if info.state == .disconnected { disconnectedParticipants.append(info.sid) } else if isNewParticipant { newParticipants.append(participant) } else { participant.updateFromInfo(info: info) } } } for sid in disconnectedParticipants { onParticipantDisconnect(sid: sid) } for participant in newParticipants { notify { $0.room(self, participantDidJoin: participant) } } return true } func signalClient(_ signalClient: SignalClient, didUnpublish localTrack: Livekit_TrackUnpublishedResponse) -> Bool { log() guard let localParticipant = localParticipant, let publication = localParticipant._state.tracks[localTrack.trackSid] as? LocalTrackPublication else { log("track publication not found", .warning) return true } localParticipant.unpublish(publication: publication).then(on: .sdk) { [weak self] _ in self?.log("unpublished track(\(localTrack.trackSid)") }.catch(on: .sdk) { [weak self] error in self?.log("failed to unpublish track(\(localTrack.trackSid), error: \(error)", .warning) } return true } } // MARK: - EngineDelegate extension Room: EngineDelegate { func engine(_ engine: Engine, didUpdate dataChannel: RTCDataChannel, state: RTCDataChannelState) { // } func engine(_ engine: Engine, didMutate state: Engine.State, oldState: Engine.State) { if state.connectionState != oldState.connectionState { // connectionState did update // only if quick-reconnect if case .connected = state.connectionState, case .quick = state.reconnectMode { sendSyncState().catch(on: .sdk) { error in self.log("Failed to sendSyncState, error: \(error)", .error) } resetTrackSettings() } // re-send track permissions if case .connected = state.connectionState, let localParticipant = localParticipant { localParticipant.sendTrackSubscriptionPermissions().catch(on: .sdk) { error in self.log("Failed to send track subscription permissions, error: \(error)", .error) } } notify { $0.room(self, didUpdate: state.connectionState, oldValue: oldState.connectionState) } } if state.connectionState.isReconnecting && state.reconnectMode == .full && oldState.reconnectMode != .full { // started full reconnect cleanUpParticipants(notify: true) } } func engine(_ engine: Engine, didGenerate trackStats: [TrackStats], target: Livekit_SignalTarget) { let allParticipants = ([[localParticipant], _state.remoteParticipants.map { $0.value }] as [[Participant?]]) .joined() .compactMap { $0 } let allTracks = allParticipants.map { $0._state.tracks.values.map { $0.track } }.joined() .compactMap { $0 } // this relies on the last stat entry being the latest for track in allTracks { if let stats = trackStats.last(where: { $0.trackId == track.mediaTrack.trackId }) { track.set(stats: stats) } } } func engine(_ engine: Engine, didUpdate speakers: [Livekit_SpeakerInfo]) { let activeSpeakers = _state.mutate { state -> [Participant] in var activeSpeakers: [Participant] = [] var seenSids = [String: Bool]() for speaker in speakers { seenSids[speaker.sid] = true if let localParticipant = state.localParticipant, speaker.sid == localParticipant.sid { localParticipant._state.mutate { $0.audioLevel = speaker.level $0.isSpeaking = true } activeSpeakers.append(localParticipant) } else { if let participant = state.remoteParticipants[speaker.sid] { participant._state.mutate { $0.audioLevel = speaker.level $0.isSpeaking = true } activeSpeakers.append(participant) } } } if let localParticipant = state.localParticipant, seenSids[localParticipant.sid] == nil { localParticipant._state.mutate { $0.audioLevel = 0.0 $0.isSpeaking = false } } for participant in state.remoteParticipants.values { if seenSids[participant.sid] == nil { participant._state.mutate { $0.audioLevel = 0.0 $0.isSpeaking = false } } } return activeSpeakers } notify { $0.room(self, didUpdate: activeSpeakers) } } func engine(_ engine: Engine, didAdd track: RTCMediaStreamTrack, streams: [RTCMediaStream]) { guard !streams.isEmpty else { log("Received onTrack with no streams!", .warning) return } let unpacked = streams[0].streamId.unpack() let participantSid = unpacked.sid var trackSid = unpacked.trackId if trackSid == "" { trackSid = track.trackId } let participant = _state.mutate { $0.getOrCreateRemoteParticipant(sid: participantSid, room: self) } log("added media track from: \(participantSid), sid: \(trackSid)") _ = retry(attempts: 10, delay: 0.2) { _, error in // if error is invalidTrackState, retry guard case TrackError.state = error else { return false } return true } _: { participant.addSubscribedMediaTrack(rtcTrack: track, sid: trackSid) } } func engine(_ engine: Engine, didRemove track: RTCMediaStreamTrack) { // find the publication guard let publication = _state.remoteParticipants.values.map({ $0._state.tracks.values }).joined() .first(where: { $0.sid == track.trackId }) else { return } publication.set(track: nil) } func engine(_ engine: Engine, didReceive userPacket: Livekit_UserPacket) { // participant could be null if data broadcasted from server let participant = _state.remoteParticipants[userPacket.participantSid] notify { $0.room(self, participant: participant, didReceive: userPacket.payload) } participant?.notify { [weak participant] (delegate) -> Void in guard let participant = participant else { return } delegate.participant(participant, didReceive: userPacket.payload) } } } // MARK: - AppStateDelegate extension Room: AppStateDelegate { func appDidEnterBackground() { guard options.suspendLocalVideoTracksInBackground else { return } guard let localParticipant = localParticipant else { return } let promises = localParticipant.localVideoTracks.map { $0.suspend() } guard !promises.isEmpty else { return } promises.all(on: .sdk).then(on: .sdk) { self.log("suspended all video tracks") } } func appWillEnterForeground() { guard let localParticipant = localParticipant else { return } let promises = localParticipant.localVideoTracks.map { $0.resume() } guard !promises.isEmpty else { return } promises.all(on: .sdk).then(on: .sdk) { self.log("resumed all video tracks") } } func appWillTerminate() { // attempt to disconnect if already connected. // this is not guranteed since there is no reliable way to detect app termination. disconnect() } }
34.512445
154
0.600076
8f66d1989d1f2bc9c76c81c85acc6b2a80cb61b7
6,526
// // HelpViewController.swift // Konnex // // Created by Sean Simmons on 2021-08-26. // Copyright © 2021 Unit Circle Inc. All rights reserved. // import UIKit class HelpViewController: UIViewController, UIScrollViewDelegate { var slides:[HelpSlide] = [] @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var doneButton: UIButton! override func viewDidLoad() { super.viewDidLoad() scrollView.delegate = self slides = createSlides() setupSlideScrollView(slides: slides) pageControl.numberOfPages = slides.count pageControl.currentPage = 0 view.bringSubviewToFront(pageControl) } @IBAction func doneButtonPressed(_ sender: Any) { navigationController?.popViewController(animated: true) } @IBAction func pageChanged(_ sender: Any) { var frame = scrollView.frame frame.origin.x = frame.size.width * CGFloat(pageControl.currentPage) frame.origin.y = 0 scrollView.scrollRectToVisible(frame, animated: true) } func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageIndex = round(scrollView.contentOffset.x/view.frame.width) pageControl.currentPage = Int(pageIndex) let maximumHorizontalOffset: CGFloat = scrollView.contentSize.width - scrollView.frame.width let currentHorizontalOffset: CGFloat = scrollView.contentOffset.x let maximumVerticalOffset: CGFloat = scrollView.contentSize.height - scrollView.frame.height let currentVerticalOffset: CGFloat = scrollView.contentOffset.y let percentageHorizontalOffset: CGFloat = currentHorizontalOffset / maximumHorizontalOffset let percentageVerticalOffset: CGFloat = currentVerticalOffset / maximumVerticalOffset let percentOffset: CGPoint = CGPoint(x: percentageHorizontalOffset, y: percentageVerticalOffset) if(percentOffset.x > 0 && percentOffset.x <= 0.5) { slides[0].imageView.transform = CGAffineTransform(scaleX: (0.5-percentOffset.x)/0.5, y: (0.5-percentOffset.x)/0.5) slides[1].imageView.transform = CGAffineTransform(scaleX: percentOffset.x/0.5, y: percentOffset.x/0.5) } else if(percentOffset.x > 0.5 && percentOffset.x <= 1) { slides[1].imageView.transform = CGAffineTransform(scaleX: (1-percentOffset.x)/0.5, y: (1-percentOffset.x)/0.5) slides[2].imageView.transform = CGAffineTransform(scaleX: (percentOffset.x-0.5)/0.5, y: (percentOffset.x-0.5)/0.5) } // if(percentOffset.x > 0 && percentOffset.x <= 0.25) { // // slides[0].imageView.transform = CGAffineTransform(scaleX: (0.25-percentOffset.x)/0.25, y: (0.25-percentOffset.x)/0.25) // slides[1].imageView.transform = CGAffineTransform(scaleX: percentOffset.x/0.25, y: percentOffset.x/0.25) // // } else if(percentOffset.x > 0.25 && percentOffset.x <= 0.50) { // slides[1].imageView.transform = CGAffineTransform(scaleX: (0.50-percentOffset.x)/0.25, y: (0.50-percentOffset.x)/0.25) // slides[2].imageView.transform = CGAffineTransform(scaleX: percentOffset.x/0.50, y: percentOffset.x/0.50) // // } else if(percentOffset.x > 0.50 && percentOffset.x <= 0.75) { // slides[2].imageView.transform = CGAffineTransform(scaleX: (0.75-percentOffset.x)/0.25, y: (0.75-percentOffset.x)/0.25) // slides[3].imageView.transform = CGAffineTransform(scaleX: percentOffset.x/0.75, y: percentOffset.x/0.75) // // } else if(percentOffset.x > 0.75 && percentOffset.x <= 1) { // slides[3].imageView.transform = CGAffineTransform(scaleX: (1-percentOffset.x)/0.25, y: (1-percentOffset.x)/0.25) // slides[4].imageView.transform = CGAffineTransform(scaleX: percentOffset.x, y: percentOffset.x) // } scrollView.contentOffset.y = 0 } func setupSlideScrollView(slides : [HelpSlide]) { scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) scrollView.contentSize = CGSize(width: view.frame.width * CGFloat(slides.count), height: view.frame.height) scrollView.isPagingEnabled = true for i in 0 ..< slides.count { slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height) scrollView.addSubview(slides[i]) } } func createSlides() -> [HelpSlide] { let slide1:HelpSlide = Bundle.main.loadNibNamed("HelpSlide", owner: self, options: nil)?.first as! HelpSlide slide1.imageView.image = UIImage(named: "help.1") slide1.labelTitle.text = "Installation Process" slide1.labelDescription.text = "Place corresponding QR codes on the unit doors" let slide2:HelpSlide = Bundle.main.loadNibNamed("HelpSlide", owner: self, options: nil)?.first as! HelpSlide slide2.imageView.image = UIImage(named: "help.2") slide2.labelTitle.text = "Installation Process" slide2.labelDescription.text = "Use the camera found in the Install Lock tab to scan the QR on the lock with the QR on the unit door" let slide3:HelpSlide = Bundle.main.loadNibNamed("HelpSlide", owner: self, options: nil)?.first as! HelpSlide slide3.imageView.image = UIImage(named: "help.3") slide3.labelTitle.text = "Installation Process" slide3.labelDescription.text = "Once the association is made, press the power button to unlock the lock and place on the corresponding unit hasp" // let slide4:HelpSlide = Bundle.main.loadNibNamed("HelpSlide", owner: self, options: nil)?.first as! HelpSlide // slide4.imageView.image = UIImage(named: "Image") // slide4.labelTitle.text = "A real-life bear" // slide4.labelDescription.text = "Did you know that Winnie the chubby little cubby was based on a real, young bear in London" // // // let slide5:HelpSlide = Bundle.main.loadNibNamed("HelpSlide", owner: self, options: nil)?.first as! HelpSlide // slide5.imageView.image = UIImage(named: "Image") // slide5.labelTitle.text = "A real-life bear" // slide5.labelDescription.text = "Did you know that Winnie the chubby little cubby was based on a real, young bear in London" // // return [slide1, slide2, slide3, slide4, slide5] return [slide1, slide2, slide3] } }
51.385827
153
0.669016
d72ddd9c3a51e4913766d4bd19e6640793ef0f74
825
// // LogOutViewController.swift // FBLA2017 // // Created by Luke Mann on 4/15/17. // Copyright © 2017 Luke Mann. All rights reserved. // import UIKit import FirebaseAuth class LogOutViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24.264706
106
0.675152
ef69fd867af6983e2c1c6bd56dce5842a27c0406
2,879
// // Copyright © 2019 Essential Developer. All rights reserved. // import UIKit import CoreData import Combine import EssentialFeed class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? private lazy var httpClient: HTTPClient = { URLSessionHTTPClient(session: URLSession(configuration: .ephemeral)) }() private lazy var store: FeedStore & FeedImageDataStore = { try! CoreDataFeedStore( storeURL: NSPersistentContainer .defaultDirectoryURL() .appendingPathComponent("feed-store.sqlite")) }() private lazy var localFeedLoader: LocalFeedLoader = { LocalFeedLoader(store: store, currentDate: Date.init) }() private lazy var baseURL = URL(string: "https://ile-api.essentialdeveloper.com/essential-feed")! private lazy var navigationController = UINavigationController( rootViewController: FeedUIComposer.feedComposedWith( feedLoader: makeRemoteFeedLoaderWithLocalFallback, imageLoader: makeLocalImageLoaderWithRemoteFallback, selection: showComments)) convenience init(httpClient: HTTPClient, store: FeedStore & FeedImageDataStore) { self.init() self.httpClient = httpClient self.store = store } func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let scene = (scene as? UIWindowScene) else { return } window = UIWindow(windowScene: scene) configureWindow() } func configureWindow() { window?.rootViewController = navigationController window?.makeKeyAndVisible() } func sceneWillResignActive(_ scene: UIScene) { localFeedLoader.validateCache { _ in } } private func showComments(for image: FeedImage) { let url = ImageCommentsEndpoint.get(image.id).url(baseURL: baseURL) let comments = CommentsUIComposer.commentsComposedWith(loader: makeRemoteCommentsLoader(url: url)) navigationController.pushViewController(comments, animated: true) } private func makeRemoteFeedLoaderWithLocalFallback() -> AnyPublisher<[FeedImage], Error> { let url = FeedEndpoint.get.url(baseURL: baseURL) return httpClient .getPublisher(url: url) .tryMap(FeedItemsMapper.map) .caching(to: localFeedLoader) .fallback(to: localFeedLoader.loadPublisher) } private func makeRemoteCommentsLoader(url: URL) -> () -> AnyPublisher<[ImageComment], Error> { return { [httpClient] in return httpClient .getPublisher(url: url) .tryMap(ImageCommentsMapper.map) .eraseToAnyPublisher() } } private func makeLocalImageLoaderWithRemoteFallback(url: URL) -> FeedImageDataLoader.Publisher { let localImageLoader = LocalFeedImageDataLoader(store: store) return localImageLoader .loadImageDataPublisher(from: url) .fallback(to: { [httpClient] in httpClient .getPublisher(url: url) .tryMap(FeedImageDataMapper.map) .caching(to: localImageLoader, using: url) }) } }
29.989583
124
0.762765
5d841105f75e7ebdd9bd186c5da7f63fce7230af
272
// // ViewController.swift // GoodNews // // Created by Kas Song on 2/11/21. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
13.6
58
0.639706
f8c5880fbb1bbff58e44800982841cca15b1b4b7
197
// // Copyright © 2020 Tasuku Tozawa. All rights reserved. // import Combine /// @mockable public protocol ClipListQuery: AnyObject { var clips: CurrentValueSubject<[Clip], Error> { get } }
17.909091
57
0.700508
0e98614f8d5e46be855b116aab577e37340fb1ba
16,012
/* See LICENSE folder for this sample’s licensing information. Abstract: View controllers that are used to verify approved medical tests, enter known symptoms, and report the data to a server. */ import UIKit import ExposureNotification class TestVerificationViewController: StepNavigationController { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let testResult = TestResult(id: UUID(), isAdded: false, dateAdministered: Date(), isShared: false) LocalStore.shared.testResults[testResult.id] = testResult pushViewController(BeforeYouGetStartedViewController.make(testResultID: testResult.id), animated: false) } init?<CustomItem: Hashable>(rootViewController: TestStepViewController<CustomItem>, coder aDecoder: NSCoder) { super.init(coder: aDecoder) pushViewController(rootViewController, animated: false) } class TestStepViewController<CustomItem: Hashable>: ValueStepViewController<UUID, CustomItem> { var testResultID: UUID { value } var testResult: TestResult { get { LocalStore.shared.testResults[value]! } set { LocalStore.shared.testResults[value] = newValue } } static func make(testResultID: UUID) -> Self { return make(value: testResultID) } } class BeforeYouGetStartedViewController: TestStepViewController<Never> { var requirementsView: RequirementView! override var step: Step { Step( rightBarButton: .init(item: .cancel) { TestVerificationViewController.cancel(from: self) }, title: NSLocalizedString("VERIFICATION_START_TITLE", comment: "Title"), text: NSLocalizedString("VERIFICATION_START_TEXT", comment: "Text"), customView: requirementsView, isModal: false, buttons: [Step.Button(title: NSLocalizedString("NEXT", comment: "Button"), isProminent: true, action: { self.show(TestIdentifierViewController.make(testResultID: self.testResultID), sender: nil) })] ) } override func viewDidLoad() { requirementsView = RequirementView(text: NSLocalizedString("VERIFICATION_START_REQUIREMENT_TEXT", comment: "Requirement text")) super.viewDidLoad() } } class TestIdentifierViewController: TestStepViewController<Never> { var customStackView: UIStackView! var entryView: EntryView! override func viewDidLoad() { entryView = EntryView() entryView.textDidChange = { [unowned self] in self.updateButtons() } let warningLabel = UILabel() warningLabel.text = NSLocalizedString("VERIFICATION_IDENTIFIER_DEVELOPER", comment: "Label") warningLabel.textColor = .systemOrange warningLabel.font = .preferredFont(forTextStyle: .body) warningLabel.adjustsFontForContentSizeCategory = true warningLabel.textAlignment = .center warningLabel.numberOfLines = 0 customStackView = UIStackView(arrangedSubviews: [entryView, warningLabel]) customStackView.axis = .vertical customStackView.spacing = 16.0 super.viewDidLoad() } override var step: Step { let learnMoreURL = URL(string: "learn-more:")! let text = NSMutableAttributedString(string: NSLocalizedString("VERIFICATION_IDENTIFIER_TEXT", comment: "Text"), attributes: Step.bodyTextAttributes) text.replaceCharacters(in: (text.string as NSString).range(of: "%@"), with: NSAttributedString(string: NSLocalizedString("LEARN_MORE", comment: "Button"), attributes: Step.linkTextAttributes(learnMoreURL))) return Step( rightBarButton: .init(item: .cancel) { TestVerificationViewController.cancel(from: self) }, title: NSLocalizedString("VERIFICATION_IDENTIFIER_TITLE", comment: "Title"), text: text, urlHandler: { url, interaction in if interaction == .invokeDefaultAction { switch url { case learnMoreURL: let navigationController = StepNavigationController(rootViewController: AboutTestIdentifiersViewController.make()) self.present(navigationController, animated: true, completion: nil) return false default: preconditionFailure() } } else { return false } }, customView: customStackView, buttons: [Step.Button(title: NSLocalizedString("NEXT", comment: "Button"), isProminent: true, isEnabled: isViewLoaded ? entryView.text.count == entryView.numberOfDigits : false, action: { // Confirm entryView.text is valid Server.shared.verifyUniqueTestIdentifier(self.entryView.text) { result in switch result { case let .success(valid): if valid { self.show(TestAdministrationDateViewController.make(testResultID: self.testResultID), sender: nil) } else { let alertController = UIAlertController( title: NSLocalizedString("VERIFICATION_IDENTIFIER_INVALID", comment: "Alert title"), message: nil, preferredStyle: .alert ) alertController.addAction(.init(title: NSLocalizedString("OK", comment: "Button"), style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } case let .failure(error): showError(error, from: self) } } })] ) } } class AboutTestIdentifiersViewController: StepViewController { override var step: Step { Step( rightBarButton: .init(item: .done) { self.dismiss(animated: true, completion: nil) }, title: NSLocalizedString("VERIFICATION_IDENTIFIER_ABOUT_TITLE", comment: "Title"), text: NSLocalizedString("VERIFICATION_IDENTIFIER_ABOUT_TEXT", comment: "Text"), isModal: false ) } } class TestAdministrationDateViewController: TestStepViewController<TestAdministrationDateViewController.CustomItem> { var date: Date? { didSet { updateTableView(animated: true, reloading: [.custom(.date)]) updateButtons() } } var showingDatePicker = false { didSet { updateTableView(animated: true) } } enum CustomItem: Hashable { case date case datePicker } override var step: Step { Step( rightBarButton: .init(item: .cancel) { TestVerificationViewController.cancel(from: self) }, title: NSLocalizedString("VERIFICATION_ADMINISTRATION_DATE_TITLE", comment: "Title"), text: NSLocalizedString("VERIFICATION_ADMINISTRATION_DATE_TEXT", comment: "Text"), buttons: [Step.Button(title: NSLocalizedString("NEXT", comment: "Button"), isProminent: true, isEnabled: self.date != nil, action: { self.testResult.dateAdministered = self.date! self.show(ReviewViewController.make(testResultID: self.testResultID), sender: nil) })] ) } override func viewDidLoad() { tableView.register(UINib(nibName: "TestAdministrationDateCell", bundle: nil), forCellReuseIdentifier: "Date") tableView.register(UINib(nibName: "TestAdministrationDatePickerCell", bundle: nil), forCellReuseIdentifier: "DatePicker") super.viewDidLoad() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, customItem: CustomItem) -> UITableViewCell { switch customItem { case .date: let cell = tableView.dequeueReusableCell(withIdentifier: "Date", for: indexPath) cell.textLabel!.text = NSLocalizedString("VERIFICATION_ADMINISTRATION_DATE_LABEL", comment: "Label") if let date = date { cell.detailTextLabel!.text = DateFormatter.localizedString(from: date, dateStyle: .long, timeStyle: .none) } else { cell.detailTextLabel!.text = NSLocalizedString("VERIFICATION_ADMINISTRATION_DATE_NOT_SET", comment: "Value") } return cell case .datePicker: let cell = tableView.dequeueReusableCell(withIdentifier: "DatePicker", for: indexPath) as! TestAdministrationDatePickerCell cell.datePicker.maximumDate = Date() cell.datePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged) return cell } } override func modifySnapshot(_ snapshot: inout NSDiffableDataSourceSnapshot<Section, Item>) { snapshot.appendItems([.custom(.date)], toSection: .main) if showingDatePicker { snapshot.appendItems([.custom(.datePicker)], toSection: .main) } } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { switch dataSource.itemIdentifier(for: indexPath) { case .custom(.date): return true default: return super.tableView(tableView, shouldHighlightRowAt: indexPath) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch dataSource.itemIdentifier(for: indexPath) { case .custom(.date): tableView.deselectRow(at: indexPath, animated: true) showingDatePicker.toggle() default: super.tableView(tableView, didSelectRowAt: indexPath) } } @objc func datePickerValueChanged(_ datePicker: UIDatePicker) { date = datePicker.date } } class ReviewViewController: TestStepViewController<ReviewViewController.CustomItem> { enum CustomItem: Hashable { case diagnosis case administrationDate } override var step: Step { Step( rightBarButton: .init(item: .cancel) { TestVerificationViewController.cancel(from: self) }, title: NSLocalizedString("VERIFICATION_REVIEW_TITLE", comment: "Title"), text: NSLocalizedString("VERIFICATION_REVIEW_TEXT", comment: "Text"), isModal: false, buttons: [Step.Button(title: NSLocalizedString("TEST_RESULT_SHARE", comment: "Button"), isProminent: true, action: { ExposureManager.shared.getAndPostDiagnosisKeys(testResult: self.testResult) { error in if let error = error as? ENError, error.code == .notAuthorized { self.saveAndFinish() } else if let error = error { showError(error, from: self) self.saveAndFinish() } else { self.testResult.isShared = true self.saveAndFinish() } } })] ) } override func viewDidLoad() { tableView.register(UINib(nibName: "TestReviewCell", bundle: nil), forCellReuseIdentifier: "Cell") super.viewDidLoad() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, customItem: CustomItem) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) switch customItem { case .diagnosis: cell.textLabel!.text = NSLocalizedString("TEST_RESULT_DIAGNOSIS", comment: "Label") cell.detailTextLabel!.text = NSLocalizedString("TEST_RESULT_DIAGNOSIS_POSITIVE", comment: "Value") case .administrationDate: cell.textLabel!.text = NSLocalizedString("TEST_RESULT_ADMINISTRATION_DATE", comment: "Label") cell.detailTextLabel!.text = DateFormatter.localizedString(from: self.testResult.dateAdministered, dateStyle: .long, timeStyle: .none) } return cell } override func modifySnapshot(_ snapshot: inout NSDiffableDataSourceSnapshot<Section, Item>) { snapshot.appendItems([.custom(.diagnosis), .custom(.administrationDate)], toSection: .main) } func saveAndFinish() { testResult.isAdded = true show(FinishedViewController.make(testResultID: testResultID), sender: nil) } } static func cancel<CustomItem: Hashable>(from viewController: TestStepViewController<CustomItem>) { let testResult = viewController.testResult if !testResult.isAdded { LocalStore.shared.testResults.removeValue(forKey: testResult.id) } viewController.dismiss(animated: true, completion: nil) } class FinishedViewController: TestStepViewController<Never> { override var step: Step { return Step( hidesNavigationBackButton: true, title: testResult.isShared ? NSLocalizedString("VERIFICATION_SHARED_TITLE", comment: "Title") : NSLocalizedString("VERIFICATION_NOT_SHARED_TITLE", comment: "Title"), text: testResult.isShared ? NSLocalizedString("VERIFICATION_SHARED_TEXT", comment: "Text") : NSLocalizedString("VERIFICATION_NOT_SHARED_TEXT", comment: "Text"), buttons: [Step.Button(title: NSLocalizedString("DONE", comment: "Button"), isProminent: true, action: { self.dismiss(animated: true, completion: nil) })] ) } } } class TestAdministrationDatePickerCell: StepOptionalSeparatorCell { @IBOutlet var datePicker: UIDatePicker! }
47.372781
150
0.552461
2fed440fb2a780e8a9ebb5c065a1bdcff6e15497
2,078
// // Date+Utils.swift // Prego // // Created by Filipe Dias on 04/05/2018. // import Foundation public extension Date { init?(dotNetJSONString: String) { guard !dotNetJSONString.isEmpty && dotNetJSONString.hasPrefix("/Date(") && dotNetJSONString.hasSuffix(")/") else { return nil } do { let dateRegEx = try NSRegularExpression(pattern: "^\\/date\\((-?\\d++)(?:([+-])(\\d{2})(\\d{2}))?\\)\\/$", options: .caseInsensitive) if let regexResult = dateRegEx.firstMatch(in: dotNetJSONString, options: .reportProgress, range: NSMakeRange(0,dotNetJSONString.count)), let jsonString: NSString = dotNetJSONString as NSString?, let num = Double(jsonString.substring(with: regexResult.range(at: 1))) { var seconds: TimeInterval = num / 1000.0 // timezone offset if regexResult.range(at: 2).location != NSNotFound { let sign = jsonString.substring(with: regexResult.range(at: 2)) if let hours = Double(jsonString.substring(with: regexResult.range(at: 3))), let hour = Double(sign + String(hours * 60.0 * 60.0)) { seconds += hour } if let minutes = Double(jsonString.substring(with: regexResult.range(at: 4))), let minute = Double(sign + String(minutes * 60.0)) { seconds += minute } } self.init(timeIntervalSince1970: seconds) return } } catch { return nil } return nil } }
34.065574
145
0.432628
7276d6c6dc540d2874cf61c3c764db672d943aec
4,534
// // BeaconController.swift // cbeacon // // Created by ohya on 2018/09/03. // Copyright © 2018年 ohya. All rights reserved. // import Foundation import CoreLocation import CoreBluetooth // Wait time until Bluetooth turns on let WAIT_BT_TIME = 10.0 enum BleEvent { case power_on, power_off, advertising_ok, advertising_fail, error } @available(OSX 10.12, *) class BeaconController: NSObject, CBPeripheralManagerDelegate { enum State { case none, setup, ready, advertising, done, fail } var state = State.none let runLoop = RunLoop.current var manager: CBPeripheralManager! let beacon: BeaconData let duration: TimeInterval init(beacon:BeaconData, duration:UInt16) { self.beacon = beacon self.duration = TimeInterval(duration) super.init() manager = CBPeripheralManager(delegate: self, queue: nil) } // MARK: - State & Task Control func exec() { setState(newState:.setup) Timer.scheduledTimer(withTimeInterval: WAIT_BT_TIME, repeats: false, block: { (timer) in if (self.state == .setup) { self.setState(newState:.fail) // RunLoop 停止 CFRunLoopStop(self.runLoop.getCFRunLoop()) } }) while true { if !runLoop.run(mode: RunLoop.Mode.default, before: Date.distantFuture) { break } if (state == .done || state == .fail) { break } } } private func setState(newState:State) { state = newState } func receiveEvent(event: BleEvent) { switch state { case .none: return case .setup: if (event == .power_on) { // print("Bluetooth turns ON.") setState(newState:.ready) startAdvertising(beaconData: beacon) return } if (event == .power_off) { print("Please turn bluetooth ON.") return } case .ready: if (event == .advertising_ok) { print("advertising...", terminator: "") fflush(stdout) setState(newState:.advertising) Timer.scheduledTimer(withTimeInterval: duration, repeats: false, block: { (timer) in self.stopAdvertising() print("stop") self.setState(newState:.done) }) return } case .advertising: if (event == .power_off) { print("Bluetooth turned OFF.") setState(newState:.fail) return } default: return } } // MARK: - Blutooth Control func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { switch peripheral.state { case .poweredOn: receiveEvent(event: .power_on) case .poweredOff: receiveEvent(event: .power_off) case .unauthorized, .resetting, .unsupported, .unknown: receiveEvent(event: .error) default: break } } func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { if error == nil { receiveEvent(event: .advertising_ok) } else { receiveEvent(event: .advertising_fail) } } func startAdvertising(beaconData: BeaconData) { manager.startAdvertising(beaconData.data()) } func stopAdvertising() { if manager.isAdvertising { manager.stopAdvertising() } } } // MARK: - class BeaconData: NSObject { let dataToBeAdvertised: [String: Any] init(uuid:UUID, major:UInt16, minor: UInt16, measuredPower: Int8) { var buffer = [CUnsignedChar](repeating: 0, count: 21) (uuid as NSUUID).getBytes(&buffer) buffer[16] = CUnsignedChar(major >> 8) buffer[17] = CUnsignedChar(major & 255) buffer[18] = CUnsignedChar(minor >> 8) buffer[19] = CUnsignedChar(minor & 255) buffer[20] = CUnsignedChar(bitPattern: measuredPower) let data = NSData(bytes: buffer, length: buffer.count) self.dataToBeAdvertised = ["kCBAdvDataAppleBeaconKey": data] super.init() } func data() -> [String: Any] { return dataToBeAdvertised } }
28.3375
100
0.554477
914fc622d0972b1ffb8458a43155416dab8a5b04
1,411
// // RatingView.swift // Bookworm // // Created by RAJ RAVAL on 23/02/20. // Copyright © 2020 Buck. All rights reserved. // import SwiftUI struct RatingView: View { @Binding var rating: Int var label = "" var maximumRating = 5 var offImage: Image? var onImage = Image(systemName: "star.fill") var offColor = Color.gray var onColor = Color.yellow var body: some View { HStack { if label.isEmpty == false { Text(label) } ForEach(1..<maximumRating + 1) { number in self.image(for: number) .foregroundColor(number > self.rating ? self.offColor : self.onColor) .onTapGesture { self.rating = number } .accessibility(label: Text("\(number == 1 ? "1 Star" : "\(number) Stars")")) .accessibility(removeTraits: .isImage) .accessibility(addTraits: number > self.rating ? .isButton : [.isButton, .isSelected]) } } } func image(for number: Int) -> Image { if number > rating { return offImage ?? onImage } else { return onImage } } } struct RatingView_Previews: PreviewProvider { static var previews: some View { RatingView(rating: .constant(4)) } }
25.196429
102
0.522325
87ee2fe497c98196e4a21e180b805a6340ce79a4
4,094
import SwiftUI public enum TabStyle { case `default` case product case underlined(Color) case underlinedGradient(Orbit.Gradient) public var textColor: Color { switch self { case .default: return .inkNormal case .product: return .inkNormal case .underlined(let color): return color case .underlinedGradient(let gradient): return gradient.color } } public var startColor: Color { switch self { case .default: return .whiteNormal case .product: return .productNormal case .underlined(let color): return color case .underlinedGradient(let gradient): return gradient.startColor } } public var endColor: Color { switch self { case .default: return .whiteNormal case .product: return .productNormal case .underlined(let color): return color case .underlinedGradient(let gradient): return gradient.endColor } } } /// An Orbit sub-component for constructing ``Tabs`` component. /// /// - Important: The Tab can only be used as a part of ``Tabs`` component, not standalone. public struct Tab: View { let label: String let iconContent: Icon.Content let style: TabStyle public var body: some View { // FIXME: Convert to Button with .title4 style for a background touch feedback HStack(spacing: .xSmall) { Icon(content: iconContent) Text(label, color: nil, weight: .medium, alignment: .center) } .padding(.horizontal, .medium) .padding(.vertical, .xSmall) .contentShape(Rectangle()) .anchorPreference(key: PreferenceKey.self, value: .bounds) { [TabPreference(label: label, style: style, bounds: $0)] } } /// Creates Orbit Tab component, a building block for Tabs component. public init(_ label: String, icon: Icon.Content = .none, style: TabStyle = .default) { self.label = label self.iconContent = icon self.style = style } } // MARK: - Types extension Tab { struct PreferenceKey: SwiftUI.PreferenceKey { typealias Value = [TabPreference] static var defaultValue: Value = [] static func reduce(value: inout Value, nextValue: () -> Value) { value.append(contentsOf: nextValue()) } } } struct TabPreference { let label: String let style: TabStyle let bounds: Anchor<CGRect> } // MARK: - Previews struct TabPreviews: PreviewProvider { static var previews: some View { PreviewWrapper { standalone styles gradients } .previewLayout(.sizeThatFits) } static var standalone: some View { Tab("Light", icon: .grid, style: .underlinedGradient(.bundleBasic)) .padding(.medium) } static var styles: some View { HStack(spacing: 0) { Group { Tab("Default", style: .default) Tab("Product", style: .product) Tab("Underlined", style: .underlined(.inkNormal)) } .border(Color.cloudDark) } .padding(.medium) .previewDisplayName("TabStyle") } static var gradients: some View { HStack(spacing: 0) { Group { Tab("Light", style: .underlinedGradient(.bundleBasic)) .foregroundColor(.bundleBasic) Tab("Comfort longer option", style: .underlinedGradient(.bundleMedium)) .foregroundColor(.bundleMedium) Tab("All", style: .underlinedGradient(.bundleTop)) } .border(Color.cloudDark) } .padding(.medium) .previewDisplayName("TabStyle - Gradients") } }
30.781955
90
0.554226
e2526304b3bebef8258d1743fce138b0c2328daa
11,348
// // ImmunizationEvaluation.swift // HealthSoftware // // Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/ImmunizationEvaluation) // Copyright 2020 Apple Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import FMCore /** Immunization evaluation information. Describes a comparison of an immunization event against published recommendations to determine if the administration is "valid" in relation to those recommendations. */ open class ImmunizationEvaluation: DomainResource { override open class var resourceType: ResourceType { return .immunizationEvaluation } /// All possible types for "doseNumber[x]" public enum DoseNumberX: Hashable { case positiveInt(FHIRPrimitive<FHIRPositiveInteger>) case string(FHIRPrimitive<FHIRString>) } /// All possible types for "seriesDoses[x]" public enum SeriesDosesX: Hashable { case positiveInt(FHIRPrimitive<FHIRPositiveInteger>) case string(FHIRPrimitive<FHIRString>) } /// Business identifier public var identifier: [Identifier]? /// Indicates the current status of the evaluation of the vaccination administration event. /// Restricted to: ['completed', 'entered-in-error'] public var status: FHIRPrimitive<MedicationAdministrationStatusCodes> /// Who this evaluation is for public var patient: Reference /// Date evaluation was performed public var date: FHIRPrimitive<DateTime>? /// Who is responsible for publishing the recommendations public var authority: Reference? /// Evaluation target disease public var targetDisease: CodeableConcept /// Immunization being evaluated public var immunizationEvent: Reference /// Status of the dose relative to published recommendations public var doseStatus: CodeableConcept /// Reason for the dose status public var doseStatusReason: [CodeableConcept]? /// Evaluation notes public var description_fhir: FHIRPrimitive<FHIRString>? /// Name of vaccine series public var series: FHIRPrimitive<FHIRString>? /// Dose number within series /// One of `doseNumber[x]` public var doseNumber: DoseNumberX? /// Recommended number of doses for immunity /// One of `seriesDoses[x]` public var seriesDoses: SeriesDosesX? /// Designated initializer taking all required properties public init(doseStatus: CodeableConcept, immunizationEvent: Reference, patient: Reference, status: FHIRPrimitive<MedicationAdministrationStatusCodes>, targetDisease: CodeableConcept) { self.doseStatus = doseStatus self.immunizationEvent = immunizationEvent self.patient = patient self.status = status self.targetDisease = targetDisease super.init() } /// Convenience initializer public convenience init( authority: Reference? = nil, contained: [ResourceProxy]? = nil, date: FHIRPrimitive<DateTime>? = nil, description_fhir: FHIRPrimitive<FHIRString>? = nil, doseNumber: DoseNumberX? = nil, doseStatus: CodeableConcept, doseStatusReason: [CodeableConcept]? = nil, `extension`: [Extension]? = nil, id: FHIRPrimitive<FHIRString>? = nil, identifier: [Identifier]? = nil, immunizationEvent: Reference, implicitRules: FHIRPrimitive<FHIRURI>? = nil, language: FHIRPrimitive<FHIRString>? = nil, meta: Meta? = nil, modifierExtension: [Extension]? = nil, patient: Reference, series: FHIRPrimitive<FHIRString>? = nil, seriesDoses: SeriesDosesX? = nil, status: FHIRPrimitive<MedicationAdministrationStatusCodes>, targetDisease: CodeableConcept, text: Narrative? = nil) { self.init(doseStatus: doseStatus, immunizationEvent: immunizationEvent, patient: patient, status: status, targetDisease: targetDisease) self.authority = authority self.contained = contained self.date = date self.description_fhir = description_fhir self.doseNumber = doseNumber self.doseStatusReason = doseStatusReason self.`extension` = `extension` self.id = id self.identifier = identifier self.implicitRules = implicitRules self.language = language self.meta = meta self.modifierExtension = modifierExtension self.series = series self.seriesDoses = seriesDoses self.text = text } // MARK: - Codable private enum CodingKeys: String, CodingKey { case authority case date; case _date case description_fhir = "description"; case _description_fhir = "_description" case doseNumberPositiveInt; case _doseNumberPositiveInt case doseNumberString; case _doseNumberString case doseStatus case doseStatusReason case identifier case immunizationEvent case patient case series; case _series case seriesDosesPositiveInt; case _seriesDosesPositiveInt case seriesDosesString; case _seriesDosesString case status; case _status case targetDisease } /// Initializer for Decodable public required init(from decoder: Decoder) throws { let _container = try decoder.container(keyedBy: CodingKeys.self) // Decode all our properties self.authority = try Reference(from: _container, forKeyIfPresent: .authority) self.date = try FHIRPrimitive<DateTime>(from: _container, forKeyIfPresent: .date, auxiliaryKey: ._date) self.description_fhir = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .description_fhir, auxiliaryKey: ._description_fhir) var _t_doseNumber: DoseNumberX? = nil if let doseNumberPositiveInt = try FHIRPrimitive<FHIRPositiveInteger>(from: _container, forKeyIfPresent: .doseNumberPositiveInt, auxiliaryKey: ._doseNumberPositiveInt) { if _t_doseNumber != nil { throw DecodingError.dataCorruptedError(forKey: .doseNumberPositiveInt, in: _container, debugDescription: "More than one value provided for \"doseNumber\"") } _t_doseNumber = .positiveInt(doseNumberPositiveInt) } if let doseNumberString = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .doseNumberString, auxiliaryKey: ._doseNumberString) { if _t_doseNumber != nil { throw DecodingError.dataCorruptedError(forKey: .doseNumberString, in: _container, debugDescription: "More than one value provided for \"doseNumber\"") } _t_doseNumber = .string(doseNumberString) } self.doseNumber = _t_doseNumber self.doseStatus = try CodeableConcept(from: _container, forKey: .doseStatus) self.doseStatusReason = try [CodeableConcept](from: _container, forKeyIfPresent: .doseStatusReason) self.identifier = try [Identifier](from: _container, forKeyIfPresent: .identifier) self.immunizationEvent = try Reference(from: _container, forKey: .immunizationEvent) self.patient = try Reference(from: _container, forKey: .patient) self.series = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .series, auxiliaryKey: ._series) var _t_seriesDoses: SeriesDosesX? = nil if let seriesDosesPositiveInt = try FHIRPrimitive<FHIRPositiveInteger>(from: _container, forKeyIfPresent: .seriesDosesPositiveInt, auxiliaryKey: ._seriesDosesPositiveInt) { if _t_seriesDoses != nil { throw DecodingError.dataCorruptedError(forKey: .seriesDosesPositiveInt, in: _container, debugDescription: "More than one value provided for \"seriesDoses\"") } _t_seriesDoses = .positiveInt(seriesDosesPositiveInt) } if let seriesDosesString = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .seriesDosesString, auxiliaryKey: ._seriesDosesString) { if _t_seriesDoses != nil { throw DecodingError.dataCorruptedError(forKey: .seriesDosesString, in: _container, debugDescription: "More than one value provided for \"seriesDoses\"") } _t_seriesDoses = .string(seriesDosesString) } self.seriesDoses = _t_seriesDoses self.status = try FHIRPrimitive<MedicationAdministrationStatusCodes>(from: _container, forKey: .status, auxiliaryKey: ._status) self.targetDisease = try CodeableConcept(from: _container, forKey: .targetDisease) try super.init(from: decoder) } /// Encodable public override func encode(to encoder: Encoder) throws { var _container = encoder.container(keyedBy: CodingKeys.self) // Encode all our properties try authority?.encode(on: &_container, forKey: .authority) try date?.encode(on: &_container, forKey: .date, auxiliaryKey: ._date) try description_fhir?.encode(on: &_container, forKey: .description_fhir, auxiliaryKey: ._description_fhir) if let _enum = doseNumber { switch _enum { case .positiveInt(let _value): try _value.encode(on: &_container, forKey: .doseNumberPositiveInt, auxiliaryKey: ._doseNumberPositiveInt) case .string(let _value): try _value.encode(on: &_container, forKey: .doseNumberString, auxiliaryKey: ._doseNumberString) } } try doseStatus.encode(on: &_container, forKey: .doseStatus) try doseStatusReason?.encode(on: &_container, forKey: .doseStatusReason) try identifier?.encode(on: &_container, forKey: .identifier) try immunizationEvent.encode(on: &_container, forKey: .immunizationEvent) try patient.encode(on: &_container, forKey: .patient) try series?.encode(on: &_container, forKey: .series, auxiliaryKey: ._series) if let _enum = seriesDoses { switch _enum { case .positiveInt(let _value): try _value.encode(on: &_container, forKey: .seriesDosesPositiveInt, auxiliaryKey: ._seriesDosesPositiveInt) case .string(let _value): try _value.encode(on: &_container, forKey: .seriesDosesString, auxiliaryKey: ._seriesDosesString) } } try status.encode(on: &_container, forKey: .status, auxiliaryKey: ._status) try targetDisease.encode(on: &_container, forKey: .targetDisease) try super.encode(to: encoder) } // MARK: - Equatable & Hashable public override func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? ImmunizationEvaluation else { return false } guard super.isEqual(to: _other) else { return false } return authority == _other.authority && date == _other.date && description_fhir == _other.description_fhir && doseNumber == _other.doseNumber && doseStatus == _other.doseStatus && doseStatusReason == _other.doseStatusReason && identifier == _other.identifier && immunizationEvent == _other.immunizationEvent && patient == _other.patient && series == _other.series && seriesDoses == _other.seriesDoses && status == _other.status && targetDisease == _other.targetDisease } public override func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(authority) hasher.combine(date) hasher.combine(description_fhir) hasher.combine(doseNumber) hasher.combine(doseStatus) hasher.combine(doseStatusReason) hasher.combine(identifier) hasher.combine(immunizationEvent) hasher.combine(patient) hasher.combine(series) hasher.combine(seriesDoses) hasher.combine(status) hasher.combine(targetDisease) } }
40.241135
185
0.752379
2f0deaff1075983c46347a54dde1d8d901c79c55
3,559
// // ViewController.swift // Flicks // // Created by Yat Choi on 5/16/16. // Copyright © 2016 yatchoi. All rights reserved. // import UIKit import MBProgressHUD class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var movies: [NSDictionary]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.dataSource = self tableView.delegate = self let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "triggerRefresh:", forControlEvents: UIControlEvents.ValueChanged) tableView.insertSubview(refreshControl, atIndex: 0) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.contentInset = UIEdgeInsetsZero tableView.scrollIndicatorInsets = UIEdgeInsetsZero } func triggerRefresh(refreshControl: UIRefreshControl) { let mainVC = self.parentViewController as! MainViewController mainVC.makeMovieRequest(refreshControl) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("movieCell", forIndexPath: indexPath) as? MovieTableViewCell let movie = movies[indexPath.row] let movieName = movie["original_title"] as? String let movieSynopsis = movie["overview"] as? String if let posterPath = movie["poster_path"] as? String { let posterFullURL = NSURL(string: MovieModel.BaseImagePath + posterPath)! cell?.setImageFromUrl(posterFullURL) } else { cell?.movieImageView.image = nil } cell?.movieTitleLabel.text = movieName cell?.movieSynopsisLabel.text = movieSynopsis let backgroundView = UIView() backgroundView.backgroundColor = UIColor(red: 200, green: 0, blue: 90, alpha: 1) cell?.selectedBackgroundView = backgroundView var tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onPosterTap:") cell?.movieImageView.userInteractionEnabled = true cell?.movieImageView.addGestureRecognizer(tapGestureRecognizer) return cell! } func onPosterTap(sender: UITapGestureRecognizer) { print("poster tapped") guard let cell = sender.view?.superview?.superview as? MovieTableViewCell else { return } guard let indexPath = tableView.indexPathForCell(cell) else { return } performSegueWithIdentifier("fullScreenSegue", sender: cell) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destinationVC: HasMovieData? if (segue.identifier == "movieDetailsSegue") { destinationVC = segue.destinationViewController as! MovieDetailsViewController } else if (segue.identifier == "fullScreenSegue") { destinationVC = segue.destinationViewController as! FullPosterViewController } guard let sourceCell = sender as? UITableViewCell else { return } guard let indexPath = tableView.indexPathForCell(sourceCell) else { return } destinationVC?.setMovieDataObject(movies[indexPath.row]) } }
31.776786
119
0.72408
0a03050deedac9e9a9356e70e27569c7a61bedda
453
// // Result.swift // RGMapper // // Created by Ritesh Gupta on 16/05/18. // Copyright © 2018 Ritesh. All rights reserved. // import Foundation enum Result { case value(Any) case error(MappableError) } extension Result { var value: Any? { if case .value(let value) = self { return value } else { return nil } } var error: MappableError? { if case .error(let error) = self { return error } else { return nil } } }
12.942857
49
0.626932
4ae2d1736cf65eb784df57337ea74ab2145c69f9
224
// 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 a { let h = 1 } { protocol A { class case c, let h
17.230769
87
0.727679