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
111effbf70975d5424239bf5aece6411040d2c77
1,042
import Foundation /// RawTransaction constructs necessary information to publish transaction. public struct EthereumRawTransaction { /// Amount value to send, unit is in Wei public let value: Wei /// Address to send ether to public let to: EthereumAddress /// Gas price for this transaction, unit is in Wei /// you need to convert it if it is specified in GWei /// use Converter.toWei method to convert GWei value to Wei public let gasPrice: Int /// Gas limit for this transaction /// Total amount of gas will be (gas price * gas limit) public let gasLimit: Int /// Nonce of your address public let nonce: Int /// Data to attach to this transaction public let data: Data public init(value: Wei, to: String, gasPrice: Int, gasLimit: Int, nonce: Int, data: Data = Data()) { self.value = value self.to = EthereumAddress(string: to) self.gasPrice = gasPrice self.gasLimit = gasLimit self.nonce = nonce self.data = data } }
29.771429
104
0.661228
030b1ea42c27449799c4d9ace3fc2e33e8be315d
2,336
/* CompatibilityLabel.swift This source file is part of the SDGInterface open source project. https://sdggiesbrecht.github.io/SDGInterface Copyright ©2020–2021 Jeremy David Giesbrecht and the SDGInterface project contributors. Soli Deo gloria. Licensed under the Apache Licence, Version 2.0. See http://www.apache.org/licenses/LICENSE-2.0 for licence information. */ #if canImport(SwiftUI) || canImport(AppKit) || canImport(UIKit) #if canImport(SwiftUI) import SwiftUI #endif #if canImport(AppKit) import AppKit #endif #if canImport(UIKit) import UIKit #endif import SDGControlFlow import SDGText import SDGLocalization /// A text label that preservers legacy characters in their noncanonical forms. @available(watchOS 6, *) public struct CompatibilityLabel<L>: LegacyView where L: Localization { // MARK: - Initialization /// Creates a label. /// /// - Parameters: /// - text: The text of the label. /// - colour: Optional. The colour of the text. public init( _ text: UserFacing<String, L>, colour: Colour = .black ) { self.init(Shared(text), colour: colour) } /// Creates a label. /// /// - Parameters: /// - text: The text of the label. /// - colour: Optional. The colour of the text. public init( _ text: Shared<UserFacing<String, L>>, colour: Colour = .black ) { genericLabel = GenericLabel(text, colour: colour) } // MARK: - Properties private let genericLabel: GenericLabel<L, String> // MARK: - LegacyView #if canImport(AppKit) || (canImport(UIKit) && !os(watchOS)) public func cocoa() -> CocoaView { return genericLabel.cocoa() } #endif } // #workaround(Swift 5.3.2, SwiftUI would be a step backward from AppKit or UIKit without the ability to interact properly with menus such as “Copy”.) #if !canImport(AppKit) && !(canImport(UIKit) && !os(watchOS)) @available(watchOS 6, *) extension CompatibilityLabel: View { // MARK: - View #if canImport(SwiftUI) && !(os(iOS) && arch(arm)) public func swiftUI() -> some SwiftUI.View { return genericLabel.swiftUI() } #endif } #else extension CompatibilityLabel: CocoaViewImplementation {} #endif #endif
25.955556
152
0.648116
50c19fff55166dbf82cd0b37bc264eadffb9b235
1,427
// // KMNameSpaceUITests.swift // KMNameSpaceUITests // // Created by MAC on 2019/11/15. // Copyright © 2019 KM. All rights reserved. // import XCTest class KMNameSpaceUITests: XCTestCase { override func 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 // 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. } func testExample() { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
32.431818
182
0.652418
e52447a4798dc2995c1ecae1069ae3ecf124ed46
408
// // FavoritesViewControllerFactory.swift // BartenderApp // // Created by Christian Slanzi on 26.06.21. // import UIKit protocol FavoritesViewControllerFactory { func makeFavoritesViewController() -> UIViewController } extension BartenderAppDependencies: FavoritesViewControllerFactory { func makeFavoritesViewController() -> UIViewController { return UIViewController() } }
20.4
68
0.752451
d54736417ea0da85f7478fc74f82a60b54a2062f
2,769
// // AppDelegate.swift // NoteDemo // // Created by Hao's iMac on 2019/6/14. // Copyright © 2019 Hao's iMac. 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. var rootVc: UIViewController let userName: String? = NoteHelper.loginedUser() if userName?.lengthOfBytes(using: .utf8) ?? 0 > 0 { let token: String? = NoteHelper.tokenForUserName(userName!) if token != nil { rootVc = NoteViewController() } else { rootVc = LoginViewController() } } else { rootVc = RegisterViewController() } window = UIWindow.init(frame: UIScreen.main.bounds) window!.rootViewController = rootVc window!.makeKeyAndVisible() 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:. } }
44.66129
285
0.711809
d6ccda4b066b5b9c8d2f0c9eb0369709524f77a0
5,122
public enum JSONParserError: Error, CustomStringConvertible { public enum Reason: CustomStringConvertible { case expectedObjectKey case expectedObjectClose case expectedTopLevelObject case expectedValue case expectedColon case expectedComma case expectedArrayClose public var description: String { switch self { case .expectedObjectKey: return "Expected Object Key" case .expectedObjectClose: return "Expected End of Object: `}`" case .expectedTopLevelObject: return "Expected Top Level Object" case .expectedValue: return "Expected a Value Literal" case .expectedColon: return "Expected a colon" case .expectedComma: return "Expected a comma" case .expectedArrayClose: return "Expected End of Array: `]`" } } } public var description: String { switch self { case .expectedArray: return "Expected JSON Array" case .expectedObject: return "Expected JSON Object" case .internalStateError, .unknownJSONStrategy, .missingKeyedContainer, .missingUnkeyedContainer, .decodingError, .endOfArray, .missingSuperDecoder: return "JSON Decoder Error" case .invalidDate: return "Incorrect Date" case .invalidData: return "Invalid String" case .endOfObject: return "Unexpected end of object" case .invalidTopLevelObject: return "Invalid Top Level Object" case .missingData: return "Unexpected End of File" case .invalidLiteral: return "Invalid Literal" case .invalidObjectIdLiteral: return "Invalid ObjectId" case .missingToken(_, _, let uInt8, let reason): return "Missing token '\(Character(.init(uInt8)))': \(reason)" case .unexpectedToken(_, _, let uInt8, let reason): return "Unexpected token '\(Character(.init(uInt8)))': \(reason)" } } var column: Int? { switch self { case .expectedObject, .expectedArray: return nil case .internalStateError(_, column: let column): return column case .invalidDate, .invalidData: return nil case .endOfObject(_, column: let column): return column case .unknownJSONStrategy, .missingKeyedContainer, .missingUnkeyedContainer, .decodingError, .missingSuperDecoder, .endOfArray: return nil case .invalidTopLevelObject(_, column: let column): return column case .missingData(_, column: let column): return column case .invalidLiteral(_, column: let column): return column case .invalidObjectIdLiteral(_, column: let column): return column case .missingToken(_, column: let column, token: _, reason: _): return column case .unexpectedToken(_, column: let column, token: _, reason: _): return column } } var line: Int? { switch self { case .expectedObject, .expectedArray: return nil case .internalStateError(line: let line, _): return line case .invalidDate, .invalidData: return nil case .endOfObject(line: let line, _): return line case .unknownJSONStrategy, .missingKeyedContainer, .missingUnkeyedContainer, .decodingError, .missingSuperDecoder, .endOfArray: return nil case .invalidTopLevelObject(line: let line, _): return line case .missingData(line: let line, _): return line case .invalidLiteral(line: let line, _): return line case .invalidObjectIdLiteral(let line, _): return line case .missingToken(line: let line, _, token: _, reason: _): return line case .unexpectedToken(line: let line, _, token: _, reason: _): return line } } case expectedArray case expectedObject case internalStateError(line: Int, column: Int) case invalidDate(String?) case invalidData(String?) case endOfObject(line: Int, column: Int) case unknownJSONStrategy case missingKeyedContainer case missingUnkeyedContainer case missingSuperDecoder case endOfArray case decodingError(expected: Any.Type, keyPath: [CodingKey]) case invalidTopLevelObject(line: Int, column: Int) case missingData(line: Int, column: Int) case invalidLiteral(line: Int, column: Int) case invalidObjectIdLiteral(line: Int, column: Int) case missingToken(line: Int, column: Int, token: UInt8, reason: Reason) case unexpectedToken(line: Int, column: Int, token: UInt8, reason: Reason) } internal struct TypeConversionError<F: FixedWidthInteger>: Error { let from: F let to: Any.Type }
37.115942
156
0.609918
f4cc92477b6e329467684a0b059dea70cf166f74
2,171
// // AppDelegate.swift // e-sk8 V2 // // Created by Jean LESUR on 07.03.21. // Copyright © 2021 Jean LESUR. 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:. } }
46.191489
285
0.75357
d611892b0656227b3c0ab5e9093fe2dce0203752
412
// // URLSessionDataTaskMock.swift // NetworkingTests // // Created by Majd Alfhaily on 29.05.22. // import Foundation import Networking final class URLSessionDataTaskMock: URLSessionDataTaskInterface { var onResume: (() -> Void)? func resume() { guard let onResume = onResume else { fatalError("Override implementation using `onResume`.") } onResume() } }
18.727273
67
0.650485
d92c2d62b55766c84fbd591eba8958377fcefbe3
4,851
import Argo @testable import KsApi import XCTest final class ProjectStatsEnvelopeTests: XCTestCase { func testJSONDecoding() { let fundingStats: [[String: Any]] = [ [ "cumulative_backers_count": 7, "cumulative_pledged": "30", "pledged": "38.0", "date": 555_444_333, "backers_count": 13 ], [ "cumulative_backers_count": 14, "cumulative_pledged": 1_000, "pledged": "909.0", "date": 333_222_111, "backers_count": 1 ], ["date": 555_444_334], ["date": 555_444_335] ] let json: [String: Any] = [ "referral_aggregates": [ "custom": 1.0, "external": "15.0", "internal": 14.0 ], "referral_distribution": [ [ "code": "my_wonderful_referrer_code", "referrer_name": "My wonderful referrer name", "percentage_of_dollars": "0.250", "referrer_type": "External", "pledged": "20.5", "backers_count": 8 ], [ "code": "my_okay_referrer_code", "referrer_name": "My okay referrer name", "percentage_of_dollars": "0.001", "referrer_type": "Kickstarter", "pledged": "1.0", "backers_count": 1 ] ], "reward_distribution": [ [ "pledged": "1.0", "reward_id": 0, "backers_count": 5 ], [ "pledged": "25.0", "reward_id": 123_456, "backers_count": 10, "minimum": 5.0 ], [ "pledged": "25.0", "reward_id": 57_393_985, "backers_count": 20, "minimum": "25.0" ] ], "cumulative": [ "pledged": "40.0", "average_pledge": 17.38, "percent_raised": 2.666666666666667, "backers_count": 20, "goal": "15.0" ], "funding_distribution": fundingStats, "video_stats": [ "external_completions": 5, "external_starts": 14, "internal_completions": 10, "internal_starts": 14 ] ] let stats = ProjectStatsEnvelope.decodeJSONDictionary(json) XCTAssertNotNil(stats) XCTAssertEqual(40, stats.value?.cumulativeStats.pledged) XCTAssertEqual(17, stats.value?.cumulativeStats.averagePledge) XCTAssertEqual(20, stats.value?.cumulativeStats.backersCount) XCTAssertEqual(5, stats.value?.videoStats?.externalCompletions) XCTAssertEqual(14, stats.value?.videoStats?.internalStarts) XCTAssertEqual(1.0, stats.value?.referralAggregateStats.custom) XCTAssertEqual(15.0, stats.value?.referralAggregateStats.external) XCTAssertEqual(14.0, stats.value?.referralAggregateStats.kickstarter) let fundingDistribution = stats.value?.fundingDistribution ?? [] let rewardDistribution = stats.value?.rewardDistribution ?? [] let referralDistribution = stats.value?.referralDistribution ?? [] XCTAssertEqual(7, fundingDistribution[0].cumulativeBackersCount) XCTAssertEqual(14, fundingDistribution[1].cumulativeBackersCount) XCTAssertEqual(2, fundingDistribution.count, "Funding stats with nil values discarded.") XCTAssertEqual("my_wonderful_referrer_code", referralDistribution[0].code) XCTAssertEqual(8, referralDistribution[0].backersCount) XCTAssertEqual(20.5, referralDistribution[0].pledged) XCTAssertEqual( ProjectStatsEnvelope.ReferrerStats.ReferrerType.external, referralDistribution[0].referrerType ) XCTAssertEqual("my_okay_referrer_code", referralDistribution[1].code) XCTAssertEqual(1, referralDistribution[1].backersCount) XCTAssertEqual( ProjectStatsEnvelope.ReferrerStats.ReferrerType.internal, referralDistribution[1].referrerType ) XCTAssertEqual(0, rewardDistribution[0].rewardId) XCTAssertEqual(123_456, rewardDistribution[1].rewardId) XCTAssertEqual(1, rewardDistribution[0].pledged) XCTAssertEqual(25, rewardDistribution[1].pledged) XCTAssertEqual(5, rewardDistribution[0].backersCount) XCTAssertEqual(10, rewardDistribution[1].backersCount) XCTAssertEqual(nil, rewardDistribution[0].minimum) XCTAssertEqual(5, rewardDistribution[1].minimum) XCTAssertEqual(25, rewardDistribution[2].minimum) } func testJSONDecoding_MissingData() { let json: [String: Any] = [ "referral_distribution": [], "reward_distribution": [], "cumulative": [], "funding_distribution": [], "video_stats": [] ] let stats = ProjectStatsEnvelope.decodeJSONDictionary(json) XCTAssertNil(stats.value?.cumulativeStats) XCTAssertNil(stats.value?.fundingDistribution) XCTAssertNil(stats.value?.referralDistribution) XCTAssertNil(stats.value?.rewardDistribution) XCTAssertNil(stats.value?.videoStats) } }
32.557047
92
0.643991
e9a18b8b4a49553109750a732e6f61e4026b60e9
2,207
// // MultibranchPipeline.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public class MultibranchPipeline: JSONEncodable { public var displayName: String? public var estimatedDurationInMillis: Int32? public var latestRun: String? public var name: String? public var organization: String? public var weatherScore: Int32? public var branchNames: [String]? public var numberOfFailingBranches: Int32? public var numberOfFailingPullRequests: Int32? public var numberOfSuccessfulBranches: Int32? public var numberOfSuccessfulPullRequests: Int32? public var totalNumberOfBranches: Int32? public var totalNumberOfPullRequests: Int32? public var _class: String? public init() {} // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() nillableDictionary["displayName"] = self.displayName nillableDictionary["estimatedDurationInMillis"] = self.estimatedDurationInMillis?.encodeToJSON() nillableDictionary["latestRun"] = self.latestRun nillableDictionary["name"] = self.name nillableDictionary["organization"] = self.organization nillableDictionary["weatherScore"] = self.weatherScore?.encodeToJSON() nillableDictionary["branchNames"] = self.branchNames?.encodeToJSON() nillableDictionary["numberOfFailingBranches"] = self.numberOfFailingBranches?.encodeToJSON() nillableDictionary["numberOfFailingPullRequests"] = self.numberOfFailingPullRequests?.encodeToJSON() nillableDictionary["numberOfSuccessfulBranches"] = self.numberOfSuccessfulBranches?.encodeToJSON() nillableDictionary["numberOfSuccessfulPullRequests"] = self.numberOfSuccessfulPullRequests?.encodeToJSON() nillableDictionary["totalNumberOfBranches"] = self.totalNumberOfBranches?.encodeToJSON() nillableDictionary["totalNumberOfPullRequests"] = self.totalNumberOfPullRequests?.encodeToJSON() nillableDictionary["_class"] = self._class let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } }
44.14
114
0.746262
d9ee1f12fc4ddacfb20d0a067b4cce0f1b2edc1c
349
// // RegisterViewController.swift // voicy-ios // // Created by Eliel A. Gordon on 1/5/18. // Copyright © 2018 Eliel Gordon. All rights reserved. // import UIKit class RegisterViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
18.368421
58
0.673352
0ede99c0b45ce4eeb561c3d644d945a1e3e1bfd3
417
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T> { func b: A? { if true { func b: T) -> Void>: a { protocol A { class case c, var d { func g<T> { func e(i: B<T) { map() -> Void>(s(x(((n: A : d = c, typealias h> <H : A? { enum S<T) -> <T>(n: Int = [B protocol c : T) -> { { { ((n: B fun
18.130435
87
0.59952
f8c1f0549934bf9f5450386bdca2a0fa53c2214e
1,672
// // ViewController.swift // Capture // // Created by davix on 9/3/16. // Copyright © 2016 geniemedialabs. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var V1 : MainViewController = MainViewController(nibName: "MainViewController", bundle: nil) var V2 : SecondViewController = SecondViewController(nibName: "SecondViewController", bundle: nil) var V3 : ThirdViewController = ThirdViewController(nibName: "ThirdViewController", bundle: nil) self.addChildViewController(V1) self.scrollView.addSubview(V1.view) V1.didMoveToParentViewController(self) self.addChildViewController(V2) self.scrollView.addSubview(V2.view) V2.didMoveToParentViewController(self) self.addChildViewController(V3) self.scrollView.addSubview(V3.view) V3.didMoveToParentViewController(self) var V2Frame : CGRect = V2.view.frame V2Frame.origin.x = self.view.frame.width V2.view.frame = V2Frame var V3Frame : CGRect = V3.view.frame V3Frame.origin.x = 2 * self.view.frame.width V3.view.frame = V3Frame self.scrollView.contentSize = CGSizeMake(self.view.frame.width * 3, self.view.frame.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
30.962963
106
0.662081
5d386be7973664eb9e621fb42037b37674447502
3,186
import Overture import Styleguide import SwiftUI @testable import GameOverFeature @main struct GameOverPreviewApp: App { init() { Styleguide.registerFonts() } var body: some Scene { WindowGroup { // GameOverView( // store: .init( // initialState: .init( // completedGame: .init( // cubes: .mock, // gameContext: .solo, // gameMode: .unlimited, // gameStartTime: .mock, // language: .en, // moves: [ // .highScoringMove, // .highScoringMove, // .highScoringMove, // .highScoringMove, // .highScoringMove, // .highScoringMove, // .highScoringMove, // ], // secondsPlayed: 0 // ), // isDemo: false, // summary: .dailyChallenge( // .init( // outOf: 149, // rank: 23, // score: 12491 // ) // ) //// summary: .leaderboard([ //// .allTime: .init(outOf: 152122, rank: 3828), //// .lastDay: .init(outOf: 512, rank: 79), //// .lastWeek: .init(outOf: 1603, rank: 605), //// ]) // ), // reducer: gameOverReducer, // environment: .init( // apiClient: .noop, // audioPlayer: .noop, // database: .autoMigratingLive( // path: FileManager.default // .urls(for: .documentDirectory, in: .userDomainMask) // .first! // .appendingPathComponent("co.pointfree.Isowords") // .appendingPathComponent("Isowords.sqlite3") // ), // fileClient: .noop, // mainQueue: .main, // mainRunLoop: .main, // remoteNotifications: .noop, // serverConfig: .noop, // storeKit: .live(), // userDefaults: update(.live()) { // $0.boolForKey = { _ in false } // }, // userNotifications: .noop // ) // ) // ) GameOverView( store: .init( initialState: .init( completedGame: .turnBased, isDemo: false, summary: nil, turnBasedContext: .init( localPlayer: .mock, match: update(.mock) { $0.participants = [ update(.local) { $0.matchOutcome = .won }, update(.remote) { $0.matchOutcome = .lost }, ] }, metadata: .init(lastOpenedAt: nil, playerIndexToId: [:]) ) ), reducer: gameOverReducer, environment: .preview ) ) } } }
32.510204
75
0.387633
22cc5748fd775d7b32ca9469b35760c479bf6c13
796
import SwiftUI struct StartButtonView: View { // MARK: - PROPERTIES @AppStorage("isOnboarding") var isOnboarding: Bool? // MARK: - BODY var body: some View { Button(action: { isOnboarding = false }) { HStack(spacing: 8) { Text("Start") Image(systemName: "arrow.right.circle") .imageScale(.large) } .padding(.horizontal, 16) .padding(.vertical, 10) .background( Capsule().strokeBorder(Color.white, lineWidth: 1.25) ) } //: BUTTON .accentColor(Color.white) } } // MARK: - PREVIEW #if DEBUG struct StartButtonView_Previews: PreviewProvider { static var previews: some View { StartButtonView() .preferredColorScheme(.dark) .previewLayout(.sizeThatFits) } } #endif
20.947368
60
0.609296
e6d6b37d6a61f1f848a73c3d6797f4c3f0b82c70
357
// // ViewController.swift // SpaceInvaders // // Created by CoderDream on 2019/3/25. // Copyright © 2019 CoderDream. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
17
80
0.67507
de124a93eafe720a7966eccb473f3621687a87be
5,947
// // STPCardNumberInputTextFieldValidatorTests.swift // StripeiOS Tests // // Created by Cameron Sabol on 10/29/20. // Copyright © 2020 Stripe, Inc. All rights reserved. // import XCTest @testable import Stripe class STPCardNumberInputTextFieldValidatorTests: XCTestCase { static let cardData: [(STPCardBrand, String, STPValidatedInputState)] = { return [ ( .visa, "4242424242424242", .valid(message: nil) ), ( .visa, "4242424242422", .incomplete(description: "Your card number is incomplete.") ), ( .visa, "4012888888881881", .valid(message: nil) ), ( .visa, "4000056655665556", .valid(message: nil) ), ( .mastercard, "5555555555554444", .valid(message: nil) ), ( .mastercard, "5200828282828210", .valid(message: nil) ), ( .mastercard, "5105105105105100", .valid(message: nil) ), ( .mastercard, "2223000010089800", .valid(message: nil) ), ( .amex, "378282246310005", .valid(message: nil) ), ( .amex, "371449635398431", .valid(message: nil) ), ( .discover, "6011111111111117", .valid(message: nil) ), ( .discover, "6011000990139424", .valid(message: nil) ), ( .dinersClub, "36227206271667", .valid(message: nil) ), ( .dinersClub, "3056930009020004", .valid(message: nil) ), ( .JCB, "3530111333300000", .valid(message: nil) ), ( .JCB, "3566002020360505", .valid(message: nil) ), ( .unknown, "1234567812345678", .invalid(errorMessage: "Your card number is invalid.") ), ] }() func testValidation() { // same tests as in STPCardValidatorTest#testNumberValidation var tests: [(STPValidatedInputState, String, STPCardBrand)] = [] for card in STPCardNumberInputTextFieldValidatorTests.cardData { tests.append((card.2, card.1, card.0)) } tests.append((.valid(message: nil), "4242 4242 4242 4242", .visa)) tests.append((.valid(message: nil), "4136000000008", .visa)) let badCardNumbers: [(String, STPCardBrand)] = [ ("0000000000000000", .unknown), ("9999999999999995", .unknown), ("1", .unknown), ("1234123412341234", .unknown), ("xxx", .unknown), ("9999999999999999999999", .unknown), ("42424242424242424242", .visa), ("4242-4242-4242-4242", .visa), ] for card in badCardNumbers { tests.append((.invalid(errorMessage: "Your card number is invalid."), card.0, card.1)) } let possibleCardNumbers: [(String, STPCardBrand)] = [ ("4242", .visa), ("5", .mastercard), ("3", .unknown), ("", .unknown), (" ", .unknown), ("6011", .discover), ("4012888888881", .visa), ] for card in possibleCardNumbers { tests.append( ( .incomplete( description: card.0.isEmpty ? nil : "Your card number is incomplete."), card.0, card.1 )) } let validator = STPCardNumberInputTextFieldValidator() for test in tests { let card = test.1 validator.inputValue = card let validationState = validator.validationState let expected = test.0 if !(validationState == expected) { XCTFail("Expected \(expected), got \(validationState) for number \"\(card)\"") } let expectedCardBrand = test.2 if !(validator.cardBrand == expectedCardBrand) { XCTFail( "Expected \(expectedCardBrand), got \(validator.cardBrand) for number \(card)") } } validator.inputValue = "1" XCTAssertEqual( .invalid(errorMessage: "Your card number is invalid."), validator.validationState) validator.inputValue = "0000000000000000" XCTAssertEqual( .invalid(errorMessage: "Your card number is invalid."), validator.validationState) validator.inputValue = "9999999999999995" XCTAssertEqual( .invalid(errorMessage: "Your card number is invalid."), validator.validationState) validator.inputValue = "0000000000000000000" XCTAssertEqual( .invalid(errorMessage: "Your card number is invalid."), validator.validationState) validator.inputValue = "9999999999999999998" XCTAssertEqual( .invalid(errorMessage: "Your card number is invalid."), validator.validationState) validator.inputValue = "4242424242424" XCTAssertEqual( .incomplete(description: "Your card number is incomplete."), validator.validationState) validator.inputValue = nil XCTAssertEqual(.incomplete(description: nil), validator.validationState) } }
31.465608
99
0.486632
7ae4059e9fd2b5c8be9627bc690e06e649c28903
11,536
// // PageViewController.swift // Segnify // // Created by Bart Hopster on 29/10/2018. // Copyright © 2021 Bart Hopster. All rights reserved. // import UIKit /// The `PageViewController` controls and maintains both `Segnify` and `PageViewController` instances. open class PageViewController: UIViewController { // MARK: - Public variables /// A `UIPageViewController` instance will show the main content, below the `Segnify` instance and, optionally, its footer view. public lazy var pageViewController: UIPageViewController = { let pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal) pageViewController.dataSource = self pageViewController.delegate = self return pageViewController }() /// A `Segnify` instance will be shown above the `Segnify` instance and, optionally, its footer view. public lazy var segnify: Segnify = { let segnify = Segnify() segnify.eventsDelegate = self segnify.segnicator = Segnicator(configurator: DefaultSegnicatorConfigurator()) return segnify }() // MARK: - Delegates /// The delegate object of `SegnifyDataSourceProtocol` specifies the content for the `Segnify` instance and this `PageViewController` instance. public private(set) weak var dataSource: SegnifyDataSourceProtocol? /// The delegate object of `PageViewControllerProtocol` offers customization possibilities for this `PageViewController` instance. public weak var configurator: PageViewControllerConfiguratorProtocol? { didSet { if let configurator = configurator { // Background color. view.backgroundColor = configurator.backgroundColor // Update the height ... segnify.height = configurator.segnifyHeight // ... and trigger a layout update. view.setNeedsLayout() } } } /// The delegate object of `ForwardedEventsProtocol` will be notified of various `Segnify` and `UIPageViewController` events. public weak var forwardedEventsDelegate: ForwardedEventsProtocol? { didSet { segnify.forwardedEventsDelegate = forwardedEventsDelegate } } // MARK: - Lifecycle public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: - Setup private func setup(dataSource: SegnifyDataSourceProtocol? = DefaultSegnifyDataSource(), configurator: PageViewControllerConfiguratorProtocol? = DefaultPageViewControllerConfigurator()) { do { try setDataSource(dataSource) self.configurator = configurator } catch { // Fail. print("Failed to set the data source. Make sure it isn't nil.") } } /// Sets the data source for the `Segnify` instance and `UIPageViewController` instance. public func setDataSource(_ dataSource: SegnifyDataSourceProtocol?) throws { if dataSource == nil { // Let the user know we're dealing with an invalid data source. throw SegnifyError.invalidDataSource } self.dataSource = dataSource // Populate. segnify.dataSource = dataSource segnify.populate() if dataSource!.contentElements.isEmpty == false { // Reset the view controllers of the page view controller. pageViewController.setViewControllers([dataSource!.contentElements.first!.viewController], direction: .forward, animated: false) } } // MARK: - View lifecycle override open func viewDidLoad() { super.viewDidLoad() // Load up the Segnify instance. view.addSubview(segnify) // Give it some Auto Layout constraints. NSLayoutConstraint.activate([ segnify.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), segnify.leadingAnchor.constraint(equalTo: view.leadingAnchor), segnify.trailingAnchor.constraint(equalTo: view.trailingAnchor), ], for: segnify) // Add the page view controller. if let pageView = pageViewController.view { addChild(pageViewController) view.addSubview(pageView) pageViewController.didMove(toParent: self) // Give it some Auto Layout constraints. NSLayoutConstraint.activate([ pageView.topAnchor.constraint(equalTo: segnify.bottomAnchor), pageView.leadingAnchor.constraint(equalTo: view.leadingAnchor), pageView.bottomAnchor.constraint(equalTo: view.bottomAnchor), pageView.trailingAnchor.constraint(equalTo: view.trailingAnchor), ], for: pageView) } } } // MARK: - SegnifyEventsProtocol extension PageViewController: SegnifyEventsProtocol { public func didSelect(segment: Segment, of segnify: Segnify, previousIndex: Int?, currentIndex: Int) { if previousIndex == nil { // `previousIndex` is nil on initial selection. No need to continue in this case. return } // We need content elements. guard let contentElements = dataSource?.contentElements else { return } // Define the navigation direction, depending on the indices. let navigationDirection: UIPageViewController.NavigationDirection = (currentIndex > previousIndex!) ? .forward : .reverse // Programmatically set the view controllers in order to scroll. pageViewController.setViewControllers([contentElements[currentIndex].viewController], direction: navigationDirection, animated: true) } } // MARK: - UIPageViewControllerDataSource extension PageViewController: UIPageViewControllerDataSource { public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { // We need content elements. guard let contentElements = dataSource?.contentElements else { return nil } // Check if we can get a valid index. guard let currentIndex = firstIndexOf(viewController) else { return nil } // One step back. let previousIndex = currentIndex - 1 var viewControllerToReturn: UIViewController? = nil if previousIndex >= 0 { // Just return the previous view controller. viewControllerToReturn = contentElements[previousIndex].viewController } else if segnify.configurator?.isScrollingInfinitely == true { // When `previousIndex` becomes negative, the user wants to scroll backwards from the first page. // Show the last page. viewControllerToReturn = contentElements.last?.viewController } else { // Nothing to return in this case, when `isScrollingInfinitely` is `false`. } // Notify our 'custom' delegate. forwardedEventsDelegate?.pageViewController(pageViewController, requested: viewControllerToReturn, before: viewController) return viewControllerToReturn } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { // We need content elements. guard let contentElements = dataSource?.contentElements else { return nil } // Check if we can get a valid index. guard let currentIndex = firstIndexOf(viewController) else { return nil } // One step forward. let nextIndex = currentIndex + 1 var viewControllerToReturn: UIViewController? = nil if nextIndex < contentElements.count { // Just return the next view controller. viewControllerToReturn = contentElements[nextIndex].viewController } else if segnify.configurator?.isScrollingInfinitely == true { // When `nextIndex` exceeds the number of available view controllers, // the user wants to scroll forwards from the last page. // Show the first page. viewControllerToReturn = contentElements.first?.viewController } else { // Nothing to return in this case, when `isScrollingInfinitely` is `false`. } // Notify our 'custom' delegate. forwardedEventsDelegate?.pageViewController(pageViewController, requested: viewControllerToReturn, after: viewController) return viewControllerToReturn } } // MARK: - UIPageViewControllerDelegate extension PageViewController: UIPageViewControllerDelegate { public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { // Notify our 'custom' delegate. forwardedEventsDelegate?.pageViewController(pageViewController, willTransitionTo: pendingViewControllers) } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { // Grab the current view controller. guard let currentViewController = pageViewController.viewControllers?.first else { return } // Notify our 'custom' delegate. forwardedEventsDelegate?.pageViewController(pageViewController, didFinishAnimating: finished, previousViewControllers: previousViewControllers, transitionCompleted: completed) if let indexOfCurrentViewController = firstIndexOf(currentViewController) { // Switch segment. segnify.switchSegment(indexOfCurrentViewController) } } } // MARK: - Page view controller helper extension PageViewController { private func firstIndexOf(_ viewController: UIViewController) -> Int? { // We need content elements. guard let contentElements = dataSource?.contentElements else { return nil } return contentElements.firstIndex {($0.viewController == viewController)} } }
40.195122
147
0.614945
5b83d5b06091477ad839dad8d8ef8ab968748b34
963
// // NSView+Animations.swift // macOS Utilities // // Created by Keaton Burleson on 8/27/19. // Copyright © 2019 Keaton Burleson. All rights reserved. // import Foundation extension NSView { public func hide(animated: Bool = true, completion: @escaping () -> () = { }) { if !animated { self.alphaValue = 0.0 completion() } NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 self.animator().alphaValue = 0.0 }) { completion() } } public func show(animated: Bool = true, completion: @escaping () -> () = { }) { if !animated { self.alphaValue = 1.0 completion() } NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 self.animator().alphaValue = 1.0 }) { completion() } } }
24.075
83
0.517134
e88b8d3d365ef69a047f3ef87ce4c5342104207e
820
import UIKit class GridViewCell: UICollectionViewCell { var label:UILabel! var paddingLeft:CGFloat = 3 override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white self.clipsToBounds = true self.layer.borderWidth = 1 self.label = UILabel(frame: .zero) self.label.textAlignment = .center self.addSubview(self.label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() label.frame = CGRect(x: paddingLeft, y: 0, width: frame.width - paddingLeft * 2, height: frame.height) } }
24.117647
66
0.569512
b9dcd683781fdd829e459561ad8516d07752296d
3,379
// // CharacterDetailViewModelUnitTest.swift // MarvelCharactersTests // // Created by Daniel Pérez Parreño on 21/4/22. // import XCTest @testable import MarvelCharacters class CharacterDetailViewModelUnitTest: XCTestCase { private(set) var characterDetailViewModel: CharacterDetailViewModel? override func setUp() { let characterDummyService = CharacterDummyService() let navigationController = UINavigationController() let homeCoordinator = HomeCoordinator(navigationController) let character = Character(id: 0, name: "", description: "", thumbnail: Thumbnail(path: "", typeExtension: "")) characterDetailViewModel = CharacterDetailViewModel(coordinatorDelegate: homeCoordinator, character: character, characterService: characterDummyService) characterDetailViewModel?.start() let expectation = XCTestExpectation(description: "test") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) { expectation.fulfill() } wait(for: [expectation], timeout: 2.5) } func testGetComicsCharacterDetailViewModel() { let numComics = characterDetailViewModel?.comics.count XCTAssertEqual(numComics, 3) } func testGetSeriesCharacterDetailViewModel() { let numComics = characterDetailViewModel?.series.count XCTAssertEqual(numComics, 2) } func testNumberOfSectionsInCollectionView() { let numberOfSections = characterDetailViewModel?.numberOfSections let returnNumberOfSections = characterDetailViewModel?.numberOfSectionsInCollectionView() XCTAssertEqual(numberOfSections, returnNumberOfSections) } func testNumberOfItemsInSection() { let numComics = characterDetailViewModel?.comics.count let comicsNumberOfItemsInSection = characterDetailViewModel?.numberOfItemsInSection(section: 0) let numSeries = characterDetailViewModel?.series.count let seriesNumberOfItemsInSection = characterDetailViewModel?.numberOfItemsInSection(section: 1) XCTAssertEqual(comicsNumberOfItemsInSection, numComics) XCTAssertEqual(seriesNumberOfItemsInSection, numSeries) } func testTitleAtIndex() { let comicTitleAtIndex = characterDetailViewModel?.titleAtIndex(index: 0, type: .comic) let serieTitleAtIndex = characterDetailViewModel?.titleAtIndex(index: 0, type: .serie) XCTAssertEqual(comicTitleAtIndex, "Avengers: The Initiative (2007) #19") XCTAssertEqual(serieTitleAtIndex, "Avengers: The Initiative (2007 - 2010)") } func testYearAtIndex() { let comicYearAtIndex = characterDetailViewModel?.yearAtIndex(index: 0, type: .comic) let serieYearAtIndex = characterDetailViewModel?.yearAtIndex(index: 0, type: .serie) XCTAssertEqual(comicYearAtIndex, "dic. 17, 2008") XCTAssertEqual(serieYearAtIndex, "2007") } func testUrlImgeAtIndex() { let comicUrlImgeAtIndex = characterDetailViewModel?.urlImgeAtIndex(index: 0, type: .comic) let serieUrlImgeAtIndex = characterDetailViewModel?.urlImgeAtIndex(index: 0, type: .serie) XCTAssertEqual(comicUrlImgeAtIndex, "http://i.annihil.us/u/prod/marvel/i/mg/d/03/58dd080719806.jpg") XCTAssertEqual(serieUrlImgeAtIndex, "http://i.annihil.us/u/prod/marvel/i/mg/5/a0/514a2ed3302f5.jpg") } }
42.772152
160
0.733353
39e76a3a46e6b0fbb4806c9c2945cc084fafc754
290
import PackageDescription let package = Package( name: "App", dependencies: [ .Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", majorVersion: 2), .Package(url: "https://github.com/PerfectlySoft/Perfect-Logger.git", majorVersion: 1), ] )
29
98
0.675862
560e523d8645c4c53d4d4a844114ac16e1a5a4aa
10,220
// // CwlCatchBadInstruction.swift // CwlPreconditionTesting // // Created by Matt Gallagher on 2016/01/10. // Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #if (os(macOS) || os(iOS)) && arch(x86_64) import Foundation import Swift #if canImport(NimbleCwlCatchException) && canImport(NimbleCwlMachBadInstructionHandler) import NimbleCwlCatchException import NimbleCwlMachBadInstructionHandler #endif private enum PthreadError: Error { case code(Int32) } private enum MachExcServer: Error { case code(kern_return_t) } /// A quick function for converting Mach error results into Swift errors private func kernCheck(_ f: () -> Int32) throws { let r = f() guard r == KERN_SUCCESS else { throw NSError(domain: NSMachErrorDomain, code: Int(r), userInfo: nil) } } extension request_mach_exception_raise_t { mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> R) -> R { return withUnsafeMutablePointer(to: &self) { p -> R in return p.withMemoryRebound(to: mach_msg_header_t.self, capacity: 1) { ptr -> R in return block(ptr) } } } } extension reply_mach_exception_raise_state_t { mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> R) -> R { return withUnsafeMutablePointer(to: &self) { p -> R in return p.withMemoryRebound(to: mach_msg_header_t.self, capacity: 1) { ptr -> R in return block(ptr) } } } } /// A structure used to store context associated with the Mach message port private struct MachContext { var masks = execTypesCountTuple<exception_mask_t>() var count: mach_msg_type_number_t = 0 var ports = execTypesCountTuple<mach_port_t>() var behaviors = execTypesCountTuple<exception_behavior_t>() var flavors = execTypesCountTuple<thread_state_flavor_t>() var currentExceptionPort: mach_port_t = 0 var handlerThread: pthread_t? = nil static func internalMutablePointers<R>(_ m: UnsafeMutablePointer<execTypesCountTuple<exception_mask_t>>, _ c: UnsafeMutablePointer<mach_msg_type_number_t>, _ p: UnsafeMutablePointer<execTypesCountTuple<mach_port_t>>, _ b: UnsafeMutablePointer<execTypesCountTuple<exception_behavior_t>>, _ f: UnsafeMutablePointer<execTypesCountTuple<thread_state_flavor_t>>, _ block: (UnsafeMutablePointer<exception_mask_t>, UnsafeMutablePointer<mach_msg_type_number_t>, UnsafeMutablePointer<mach_port_t>, UnsafeMutablePointer<exception_behavior_t>, UnsafeMutablePointer<thread_state_flavor_t>) -> R) -> R { return m.withMemoryRebound(to: exception_mask_t.self, capacity: 1) { masksPtr in return c.withMemoryRebound(to: mach_msg_type_number_t.self, capacity: 1) { countPtr in return p.withMemoryRebound(to: mach_port_t.self, capacity: 1) { portsPtr in return b.withMemoryRebound(to: exception_behavior_t.self, capacity: 1) { behaviorsPtr in return f.withMemoryRebound(to: thread_state_flavor_t.self, capacity: 1) { flavorsPtr in return block(masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr) } } } } } } mutating func withUnsafeMutablePointers<R>(in block: @escaping (UnsafeMutablePointer<exception_mask_t>, UnsafeMutablePointer<mach_msg_type_number_t>, UnsafeMutablePointer<mach_port_t>, UnsafeMutablePointer<exception_behavior_t>, UnsafeMutablePointer<thread_state_flavor_t>) -> R) -> R { return MachContext.internalMutablePointers(&masks, &count, &ports, &behaviors, &flavors, block) } } /// A function for receiving mach messages and parsing the first with mach_exc_server (and if any others are received, throwing them away). private func machMessageHandler(_ arg: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? { let context = arg.assumingMemoryBound(to: MachContext.self).pointee var request = request_mach_exception_raise_t() var reply = reply_mach_exception_raise_state_t() var handledfirstException = false repeat { do { // Request the next mach message from the port request.Head.msgh_local_port = context.currentExceptionPort request.Head.msgh_size = UInt32(MemoryLayout<request_mach_exception_raise_t>.size) let requestSize = request.Head.msgh_size try kernCheck { request.withMsgHeaderPointer { requestPtr in mach_msg(requestPtr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0, requestSize, context.currentExceptionPort, 0, UInt32(MACH_PORT_NULL)) } } // Prepare the reply structure reply.Head.msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(request.Head.msgh_bits), 0) reply.Head.msgh_local_port = UInt32(MACH_PORT_NULL) reply.Head.msgh_remote_port = request.Head.msgh_remote_port reply.Head.msgh_size = UInt32(MemoryLayout<reply_mach_exception_raise_state_t>.size) reply.NDR = NDR_record if !handledfirstException { // Use the MiG generated server to invoke our handler for the request and fill in the rest of the reply structure guard request.withMsgHeaderPointer(in: { requestPtr in reply.withMsgHeaderPointer { replyPtr in mach_exc_server(requestPtr, replyPtr) } }) != 0 else { throw MachExcServer.code(reply.RetCode) } handledfirstException = true } else { // If multiple fatal errors occur, don't handle subsquent errors (let the program crash) reply.RetCode = KERN_FAILURE } // Send the reply let replySize = reply.Head.msgh_size try kernCheck { reply.withMsgHeaderPointer { replyPtr in mach_msg(replyPtr, MACH_SEND_MSG, replySize, 0, UInt32(MACH_PORT_NULL), 0, UInt32(MACH_PORT_NULL)) } } } catch let error as NSError where (error.domain == NSMachErrorDomain && (error.code == Int(MACH_RCV_PORT_CHANGED) || error.code == Int(MACH_RCV_INVALID_NAME))) { // Port was already closed before we started or closed while we were listening. // This means the controlling thread shut down. return nil } catch { // Should never be reached but this is testing code, don't try to recover, just abort fatalError("Mach message error: \(error)") } } while true } /// Run the provided block. If a mach "BAD_INSTRUCTION" exception is raised, catch it and return a BadInstructionException (which captures stack information about the throw site, if desired). Otherwise return nil. /// NOTE: This function is only intended for use in test harnesses – use in a distributed build is almost certainly a bad choice. If a "BAD_INSTRUCTION" exception is raised, the block will be exited before completion via Objective-C exception. The risks associated with an Objective-C exception apply here: most Swift/Objective-C functions are *not* exception-safe. Memory may be leaked and the program will not necessarily be left in a safe state. /// - parameter block: a function without parameters that will be run /// - returns: if an EXC_BAD_INSTRUCTION is raised during the execution of `block` then a BadInstructionException will be returned, otherwise `nil`. public func catchBadInstruction(in block: @escaping () -> Void) -> BadInstructionException? { // Suppress Swift runtime's direct triggering of the debugger and exclusivity checking which crashes when we throw past it let previousExclusivity = _swift_disableExclusivityChecking let previousReporting = _swift_reportFatalErrorsToDebugger _swift_disableExclusivityChecking = true _swift_reportFatalErrorsToDebugger = false defer { _swift_reportFatalErrorsToDebugger = previousReporting _swift_disableExclusivityChecking = previousExclusivity } var context = MachContext() var result: BadInstructionException? = nil do { var handlerThread: pthread_t? = nil defer { // 8. Wait for the thread to terminate *if* we actually made it to the creation point // The mach port should be destroyed *before* calling pthread_join to avoid a deadlock. if handlerThread != nil { pthread_join(handlerThread!, nil) } } try kernCheck { // 1. Create the mach port mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &context.currentExceptionPort) } defer { // 7. Cleanup the mach port mach_port_destroy(mach_task_self_, context.currentExceptionPort) } try kernCheck { // 2. Configure the mach port mach_port_insert_right(mach_task_self_, context.currentExceptionPort, context.currentExceptionPort, MACH_MSG_TYPE_MAKE_SEND) } let currentExceptionPtr = context.currentExceptionPort try kernCheck { context.withUnsafeMutablePointers { masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr in // 3. Apply the mach port as the handler for this thread thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, currentExceptionPtr, Int32(bitPattern: UInt32(EXCEPTION_STATE) | MACH_EXCEPTION_CODES), x86_THREAD_STATE64, masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr) } } defer { context.withUnsafeMutablePointers { masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr in // 6. Unapply the mach port _ = thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, 0, EXCEPTION_DEFAULT, THREAD_STATE_NONE, masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr) } } try withUnsafeMutablePointer(to: &context) { c throws in // 4. Create the thread let e = pthread_create(&handlerThread, nil, machMessageHandler, c) guard e == 0 else { throw PthreadError.code(e) } // 5. Run the block result = BadInstructionException.catchException(in: block) } } catch { // Should never be reached but this is testing code, don't try to recover, just abort fatalError("Mach port error: \(error)") } return result } #endif
48.436019
592
0.771526
33cfcf54f500bfc992ee256d324270a98477554e
827
// // FeatureSource.swift // FeaturesFlagsKit // // Created by Andrey Ermoshin on 26.02.2022. // Copyright © 2022 andreiermoshin. All rights reserved. // import ReactiveSwift #if canImport(Combine) import Combine #endif public protocol FeatureSource { func currentValue<F: BasicFeature>(of feature: ApplicationFeature<F>) -> F.Value func setValue<F: BasicFeature>(of feature: ApplicationFeature<F>, value: F.Value?) } /** Replace all cases where NoError was used in a Signal or SignalProducer with Never https://github.com/ReactiveCocoa/ReactiveSwift/releases/tag/6.0.0 */ protocol ObservableFeatureSource { @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) var futureFeatureChanges: AnyPublisher<AnyFeature, Never> { get } var rxFutureFeatureChanges: Signal<AnyFeature, Never> { get } }
29.535714
86
0.741233
64c7c39a5b8cd9f319eccb5ca6b4ec8224a61f51
294
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation /// A type that represents an archive. public protocol Archive { /// Unarchive data from the archive. static func unarchive(archive: Data) throws -> Data }
22.615385
55
0.727891
d7af8fa75accb2343027b862a892bd5ab2fcc891
7,922
// // IAWSelectListVC.swift // LeisureAssistant // // Created by winston on 17/2/15. // Copyright © 2017年 winston. All rights reserved. // import UIKit public protocol IAW_SelectListViewDelegate: NSObjectProtocol { func editClick(editKey: String,editValue:(String,String)) } open class IAW_SelectListVC: IAW_BaseViewController { var titleValue :String = "" var editKey:String = "" var editValue: (String,String) = ("","") weak var delegate: IAW_SelectListViewDelegate? var commonDict = Dictionary<String,Any>(); let cellHeight = IAW_PX(px: 84) var selectedIndex:IndexPath? = nil fileprivate var tableView: UITableView! override open func viewDidLoad() { self.view.backgroundColor = IAW_HEXColor("#eeeeee") initUI() } func initUI(){ self.automaticallyAdjustsScrollViewInsets = false tableView = UITableView(frame: CGRect(x:0,y:0, width:IAW_ScreenW, height:IAW_ScreenH), style: UITableView.Style.grouped) tableView.backgroundColor = UIColor(red:245/255, green: 245/255, blue: 245/255, alpha: 1) // tableView.backgroundColor = UIColor.red tableView.allowsMultipleSelectionDuringEditing=true tableView.delegate = self tableView.dataSource = self tableView.bounces = false tableView.rowHeight = cellHeight tableView.separatorColor = IAW_HEXColor("#eeeeee") tableView.sectionFooterHeight = 0.1 tableView.showsHorizontalScrollIndicator = false tableView.showsVerticalScrollIndicator = false tableView.separatorStyle = UITableViewCell.SeparatorStyle.singleLine view.addSubview(tableView) let count = commonDict.count tableView.snp.makeConstraints{ (make) in make.top.equalTo(self.view).offset(0) make.left.equalTo(self.view) make.width.equalTo(IAW_ScreenW) // 不需要 行数 * 高度 高 // make.bottom.equalTo(self.view).offset(20) make.height.equalTo(Int(cellHeight) * count) } tableView.tableHeaderView = UIView(frame:CGRect(x:0,y:0,width:IAW_ScreenW,height:0.01)) if tableView.responds(to: #selector(setter: UITableViewCell.separatorInset)) { tableView.separatorInset = UIEdgeInsets.zero } if tableView.responds(to: #selector(setter: UIView.layoutMargins)) { tableView.layoutMargins = UIEdgeInsets.zero } let enterOrderBtn_Main = UIButton() enterOrderBtn_Main.backgroundColor = self.navigationController?.navigationBar.barTintColor enterOrderBtn_Main.setTitleColor(UIColor.white, for: UIControl.State()) enterOrderBtn_Main.layer.cornerRadius = 10 enterOrderBtn_Main.titleLabel?.font = UIFont.systemFont(ofSize: IAW_PX(px: 30)) enterOrderBtn_Main.setTitle("确定", for: UIControl.State()) enterOrderBtn_Main.addTarget(self, action: #selector(enterSubmit), for: .touchUpInside) self.view.addSubview(enterOrderBtn_Main) enterOrderBtn_Main.snp.makeConstraints{ (make) in make.top.equalTo(tableView.snp.bottom).offset(IAW_PX(px: 100)) make.left.equalTo(self.view).offset(IAW_LeftMargin) make.width.equalTo(IAW_ScreenW-IAW_LeftMargin*2) make.height.equalTo(IAW_PX(px: 96)) } } @objc func enterSubmit(){ if selectedIndex == nil{ _ = self.navigationController?.popViewController(animated: true) return } var value:(String,String) = ("","") value = (Array(commonDict.keys)[(selectedIndex?.row)!],"\(Array(commonDict.values)[(selectedIndex?.row)!])") if editValue == value{ _ = self.navigationController?.popViewController(animated: true) return } delegate?.editClick(editKey: editKey,editValue:value) } func selected() -> UIImageView { let mSelected = UIImageView() mSelected.image = UIImage(named:"select") mSelected.height = IAW_PX(px: 40) mSelected.width = IAW_PX(px: 40) mSelected.isUserInteractionEnabled = false return mSelected } func noSelected()->UIImageView{ let mSelected = UIImageView() mSelected.image = UIImage(named:"unselect") mSelected.height = IAW_PX(px: 40) mSelected.width = IAW_PX(px: 40) mSelected.isUserInteractionEnabled = false return mSelected } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension IAW_SelectListVC: UITableViewDelegate, UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = commonDict.count return count } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // 让分割线靠左封闭 if cell.responds(to: #selector(setter: UIView.layoutMargins)) { cell.layoutMargins = UIEdgeInsets.zero } if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) { cell.separatorInset = UIEdgeInsets.zero } } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier: String = "cell" var cell = tableView.dequeueReusableCell(withIdentifier: identifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: identifier) cell!.selectionStyle = .none } cell!.textLabel?.textColor = UIColor.black cell!.textLabel?.font = UIFont.systemFont(ofSize: IAW_PX(px: 24)) let m = noSelected() cell?.addSubview(m) let dataKey = Array(commonDict.keys)[(indexPath as NSIndexPath).row] let dataValue = Array(commonDict.values)[(indexPath as NSIndexPath).row] cell?.textLabel?.text = dataKey m.tag = Int("\(dataValue)")! if "\((dataKey))" == editValue.0{ selectedIndex = indexPath } m.snp.makeConstraints{ (make) in make.centerY.equalTo(cell!) make.width.height.equalTo(IAW_PX(px: 48)) make.right.equalTo(cell!).offset(-15) } if(editValue.0 == "" && (indexPath as NSIndexPath).row == 0){ selectedIndex = indexPath } //当上下拉动的时候因为cell的复用性,我们需要重新判断哪一行是否打钩 if(selectedIndex == indexPath){ // cell.accessoryType = .checkmark m.image = UIImage(named:"select") }else{ // cell.accessoryType = .none m.image = UIImage(named:"unselect") } cell?.accessoryView?.isUserInteractionEnabled = false return cell! } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //之前选中的,取消选择 let celled:UITableViewCell = tableView.cellForRow(at: selectedIndex!)! let dataValue_selected = Array(commonDict.values)[(selectedIndex?.row)!] if let m = celled.viewWithTag(Int("\(dataValue_selected)")!) as? UIImageView { m.image = UIImage(named:"unselect") } let cell:UITableViewCell = tableView.cellForRow(at: indexPath)! selectedIndex = indexPath; let dataValue = Array(commonDict.values)[(indexPath as NSIndexPath).row] if let m = cell.viewWithTag(Int("\(dataValue)")!) as? UIImageView { m.image = UIImage(named:"select") } } }
37.72381
128
0.62459
674d3ebf0d7916954127bd1a5dc49562f7da523f
3,723
// // AppLogoSwitchViewController.swift // V2EX // // Created by xu.shuifeng on 2018/12/29. // Copyright © 2018 shuifeng.me. All rights reserved. // import UIKit fileprivate struct AppLogo { let icon: String let key: String? static func logos() -> [AppLogo] { var list: [AppLogo] = [] list.append(AppLogo(icon: "Logo_Default", key: nil)) list.append(AppLogo(icon: "Logo_White", key: "AppLogo_White")) list.append(AppLogo(icon: "Logo_Fast", key: "AppLogo_Fast")) list.append(AppLogo(icon: "Logo_Hacker", key: "AppLogo_Hacker")) list.append(AppLogo(icon: "Logo_HackGreen", key: "AppLogo_HackGreen")) return list } } class AppLogoSwitchViewController: UIViewController { private var collectionView: UICollectionView! private let dataSource: [AppLogo] = AppLogo.logos() override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsAppLogo view.backgroundColor = Theme.current.backgroundColor setupCollectionView() } private func setupCollectionView() { let layout = UICollectionViewFlowLayout() let itemWidth = CGFloat(floorf(Float(view.bounds.width/4.0))) layout.itemSize = CGSize(width: itemWidth, height: itemWidth) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = .clear collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.delegate = self collectionView.dataSource = self collectionView.register(AppLogoViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(AppLogoViewCell.self)) view.addSubview(collectionView) } } extension AppLogoSwitchViewController: UICollectionViewDataSource, UICollectionViewDelegate { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(AppLogoViewCell.self), for: indexPath) as! AppLogoViewCell let name = dataSource[indexPath.row].icon cell.imageView.image = UIImage(named: name) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: false) if UIApplication.shared.supportsAlternateIcons { let logo = dataSource[indexPath.row] UIApplication.shared.setAlternateIconName(logo.key, completionHandler: nil) } } } class AppLogoViewCell: UICollectionViewCell { let imageView: UIImageView override init(frame: CGRect) { imageView = UIImageView() super.init(frame: frame) self.clipsToBounds = true contentView.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ imageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
34.155963
151
0.683857
e5ccd5133c60cdc9c91b1390db1e32d967f21090
517
// // WKWebViewExt.swift // iOSFrame // // Created by 杨建祥 on 2020/5/13. // import UIKit import WebKit import QMUIKit import RxSwift import RxCocoa public extension Reactive where Base: WKWebView { var loadHTMLString: Binder<String> { return Binder(self.base) { webView, string in webView.loadHTMLString(string, baseURL: nil) } } var load: Binder<URL> { return Binder(self.base) { webView, url in webView.load(URLRequest(url: url)) } } }
17.827586
56
0.628627
08e9a58bae738f4712294ad7fe96702830e49c1c
29,915
/// Something about x let x = 1 _ = x /** Something about y */ private var y: String { return "hello" } _ = y /// Something about /// Foo struct Foo<T> { /** Something about bar */ func bar(x: T) where T: Equatable {} } Foo<Int>().bar(x: 1) Foo<String>().bar(x: "hello") extension Foo where T == Int { func blah() { bar(x: 4) } } /// MyEnum doc. enum MyEnum { /// Text in a code line with no indicated semantic meaning. case someCase } // RUN: %sourcekitd-test -req=cursor -pos=2:5 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKX %s // RUN: %sourcekitd-test -req=cursor -pos=3:5 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKX %s // RUN: %sourcekitd-test -req=cursor -pos=8:13 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKY %s // RUN: %sourcekitd-test -req=cursor -pos=9:5 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKY %s // RUN: %sourcekitd-test -req=cursor -pos=13:8 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKFOO %s // RUN: %sourcekitd-test -req=cursor -pos=17:1 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKFOO %s // RUN: %sourcekitd-test -req=cursor -pos=18:1 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKFOO %s // RUN: %sourcekitd-test -req=cursor -pos=20:11 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKFOO %s // RUN: %sourcekitd-test -req=cursor -pos=15:10 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKBAR_ALL,CHECKBAR_GEN %s // RUN: %sourcekitd-test -req=cursor -pos=17:12 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKBAR_ALL,CHECKBAR_INT %s // RUN: %sourcekitd-test -req=cursor -pos=22:9 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKBAR_ALL,CHECKBAR_INT %s // RUN: %sourcekitd-test -req=cursor -pos=18:15 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKBAR_ALL,CHECKBAR_STR %s // RUN: %sourcekitd-test -req=cursor -pos=29:10 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKCASE %s // CHECKX: SYMBOL GRAPH BEGIN // CHECKX: { // CHECKX: "metadata": { // CHECKX: "formatVersion": { // CHECKX: "major": // CHECKX: "minor": // CHECKX: "patch": // CHECKX: }, // CHECKX: "generator": // CHECKX: }, // CHECKX: "module": { // CHECKX: "name": "cursor_symbol_graph", // CHECKX: "platform": { // CHECKX: "architecture": // CHECKX: "operatingSystem": // CHECKX: "vendor": // CHECKX: } // CHECKX: }, // CHECKX: "relationships": [], // CHECKX: "symbols": [ // CHECKX: { // CHECKX: "accessLevel": "internal", // CHECKX: "declarationFragments": [ // CHECKX: { // CHECKX: "kind": "keyword", // CHECKX: "spelling": "let" // CHECKX: }, // CHECKX: { // CHECKX: "kind": "text", // CHECKX: "spelling": " " // CHECKX: }, // CHECKX: { // CHECKX: "kind": "identifier", // CHECKX: "spelling": "x" // CHECKX: }, // CHECKX: { // CHECKX: "kind": "text", // CHECKX: "spelling": ": " // CHECKX: }, // CHECKX: { // CHECKX: "kind": "typeIdentifier", // CHECKX: "preciseIdentifier": "s:Si", // CHECKX: "spelling": "Int" // CHECKX: } // CHECKX: ], // CHECKX: "docComment": { // CHECKX: "lines": [ // CHECKX: { // CHECKX: "range": { // CHECKX: "end": { // CHECKX: "character": 21, // CHECKX: "line": 0 // CHECKX: }, // CHECKX: "start": { // CHECKX: "character": 4, // CHECKX: "line": 0 // CHECKX: } // CHECKX: }, // CHECKX: "text": "Something about x" // CHECKX: } // CHECKX: ] // CHECKX: }, // CHECKX: "identifier": { // CHECKX: "interfaceLanguage": "swift", // CHECKX: "precise": "s:19cursor_symbol_graph1xSivp" // CHECKX: }, // CHECKX: "kind": { // CHECKX: "displayName": "Global Variable", // CHECKX: "identifier": "swift.var" // CHECKX: }, // CHECKX: "location": { // CHECKX: "position": { // CHECKX: "character": 4, // CHECKX: "line": 1 // CHECKX: }, // CHECKX: "uri": "{{.*}}cursor_symbol_graph.swift" // CHECKX: }, // CHECKX: "names": { // CHECKX: "navigator": [ // CHECKX: { // CHECKX: "kind": "keyword", // CHECKX: "spelling": "let" // CHECKX: }, // CHECKX: { // CHECKX: "kind": "text", // CHECKX: "spelling": " " // CHECKX: }, // CHECKX: { // CHECKX: "kind": "identifier", // CHECKX: "spelling": "x" // CHECKX: }, // CHECKX: { // CHECKX: "kind": "text", // CHECKX: "spelling": ": " // CHECKX: }, // CHECKX: { // CHECKX: "kind": "typeIdentifier", // CHECKX: "preciseIdentifier": "s:Si", // CHECKX: "spelling": "Int" // CHECKX: } // CHECKX: ], // CHECKX: "subHeading": [ // CHECKX: { // CHECKX: "kind": "keyword", // CHECKX: "spelling": "let" // CHECKX: }, // CHECKX: { // CHECKX: "kind": "text", // CHECKX: "spelling": " " // CHECKX: }, // CHECKX: { // CHECKX: "kind": "identifier", // CHECKX: "spelling": "x" // CHECKX: }, // CHECKX: { // CHECKX: "kind": "text", // CHECKX: "spelling": ": " // CHECKX: }, // CHECKX: { // CHECKX: "kind": "typeIdentifier", // CHECKX: "preciseIdentifier": "s:Si", // CHECKX: "spelling": "Int" // CHECKX: } // CHECKX: ], // CHECKX: "title": "x" // CHECKX: }, // CHECKX: "pathComponents": [ // CHECKX: "x" // CHECKX: ] // CHECKX: } // CHECKX: ] // CHECKX: } // CHECKX: SYMBOL GRAPH END // CHECKY: SYMBOL GRAPH BEGIN // CHECKY: { // CHECKY: "metadata": { // CHECKY: "formatVersion": { // CHECKY: "major": // CHECKY: "minor": // CHECKY: "patch": // CHECKY: }, // CHECKY: "generator": // CHECKY: }, // CHECKY: "module": { // CHECKY: "name": "cursor_symbol_graph", // CHECKY: "platform": { // CHECKY: "architecture": // CHECKY: "operatingSystem": // CHECKY: "vendor": // CHECKY: } // CHECKY: }, // CHECKY: "relationships": [], // CHECKY: "symbols": [ // CHECKY: { // CHECKY: "accessLevel": "private", // CHECKY: "declarationFragments": [ // CHECKY: { // CHECKY: "kind": "keyword", // CHECKY: "spelling": "private" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": " " // CHECKY: }, // CHECKY: { // CHECKY: "kind": "keyword", // CHECKY: "spelling": "var" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": " " // CHECKY: }, // CHECKY: { // CHECKY: "kind": "identifier", // CHECKY: "spelling": "y" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": ": " // CHECKY: }, // CHECKY: { // CHECKY: "kind": "typeIdentifier", // CHECKY: "preciseIdentifier": "s:SS", // CHECKY: "spelling": "String" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": " { " // CHECKY: }, // CHECKY: { // CHECKY: "kind": "keyword", // CHECKY: "spelling": "get" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": " }" // CHECKY: } // CHECKY: ], // CHECKY: "docComment": { // CHECKY: "lines": [ // CHECKY: { // CHECKY: "range": { // CHECKY: "end": { // CHECKY: "character": 18, // CHECKY: "line": 5 // CHECKY: }, // CHECKY: "start": { // CHECKY: "character": 1, // CHECKY: "line": 5 // CHECKY: } // CHECKY: }, // CHECKY: "text": "Something about y" // CHECKY: }, // CHECKY: { // CHECKY: "range": { // CHECKY: "end": { // CHECKY: "character": 1, // CHECKY: "line": 6 // CHECKY: }, // CHECKY: "start": { // CHECKY: "character": 1, // CHECKY: "line": 6 // CHECKY: } // CHECKY: }, // CHECKY: "text": "" // CHECKY: } // CHECKY: ] // CHECKY: }, // CHECKY: "identifier": { // CHECKY: "interfaceLanguage": "swift", // CHECKY: "precise": "s:19cursor_symbol_graph1y33_153B1E8D9396FFABCE21DE5D3EC1833ALLSSvp" // CHECKY: }, // CHECKY: "kind": { // CHECKY: "displayName": "Global Variable", // CHECKY: "identifier": "swift.var" // CHECKY: }, // CHECKY: "location": { // CHECKY: "position": { // CHECKY: "character": 12, // CHECKY: "line": 7 // CHECKY: }, // CHECKY: "uri": "{{.*}}cursor_symbol_graph.swift" // CHECKY: }, // CHECKY: "names": { // CHECKY: "navigator": [ // CHECKY: { // CHECKY: "kind": "keyword", // CHECKY: "spelling": "var" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": " " // CHECKY: }, // CHECKY: { // CHECKY: "kind": "identifier", // CHECKY: "spelling": "y" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": ": " // CHECKY: }, // CHECKY: { // CHECKY: "kind": "typeIdentifier", // CHECKY: "preciseIdentifier": "s:SS", // CHECKY: "spelling": "String" // CHECKY: } // CHECKY: ], // CHECKY: "subHeading": [ // CHECKY: { // CHECKY: "kind": "keyword", // CHECKY: "spelling": "var" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": " " // CHECKY: }, // CHECKY: { // CHECKY: "kind": "identifier", // CHECKY: "spelling": "y" // CHECKY: }, // CHECKY: { // CHECKY: "kind": "text", // CHECKY: "spelling": ": " // CHECKY: }, // CHECKY: { // CHECKY: "kind": "typeIdentifier", // CHECKY: "preciseIdentifier": "s:SS", // CHECKY: "spelling": "String" // CHECKY: } // CHECKY: ], // CHECKY: "title": "y" // CHECKY: }, // CHECKY: "pathComponents": [ // CHECKY: "y" // CHECKY: ] // CHECKY: } // CHECKY: ] // CHECKY: } // CHECKY: SYMBOL GRAPH END // CHECKFOO: SYMBOL GRAPH BEGIN // CHECKFOO: { // CHECKFOO: "metadata": { // CHECKFOO: "formatVersion": { // CHECKFOO: "major": // CHECKFOO: "minor": // CHECKFOO: "patch": // CHECKFOO: }, // CHECKFOO: "generator": // CHECKFOO: }, // CHECKFOO: "module": { // CHECKFOO: "name": "cursor_symbol_graph", // CHECKFOO: "platform": { // CHECKFOO: "architecture": // CHECKFOO: "operatingSystem": // CHECKFOO: "vendor": // CHECKFOO: } // CHECKFOO: }, // CHECKFOO: "relationships": [], // CHECKFOO: "symbols": [ // CHECKFOO: { // CHECKFOO: "accessLevel": "internal", // CHECKFOO: "declarationFragments": [ // CHECKFOO: { // CHECKFOO: "kind": "keyword", // CHECKFOO: "spelling": "struct" // CHECKFOO: }, // CHECKFOO: { // CHECKFOO: "kind": "text", // CHECKFOO: "spelling": " " // CHECKFOO: }, // CHECKFOO: { // CHECKFOO: "kind": "identifier", // CHECKFOO: "spelling": "Foo" // CHECKFOO: }, // CHECKFOO: { // CHECKFOO: "kind": "text", // CHECKFOO: "spelling": "<" // CHECKFOO: }, // CHECKFOO: { // CHECKFOO: "kind": "genericParameter", // CHECKFOO: "spelling": "T" // CHECKFOO: }, // CHECKFOO: { // CHECKFOO: "kind": "text", // CHECKFOO: "spelling": ">" // CHECKFOO: } // CHECKFOO: ], // CHECKFOO: "docComment": { // CHECKFOO: "lines": [ // CHECKFOO: { // CHECKFOO: "range": { // CHECKFOO: "end": { // CHECKFOO: "character": 19, // CHECKFOO: "line": 10 // CHECKFOO: }, // CHECKFOO: "start": { // CHECKFOO: "character": 4, // CHECKFOO: "line": 10 // CHECKFOO: } // CHECKFOO: }, // CHECKFOO: "text": "Something about" // CHECKFOO: }, // CHECKFOO: { // CHECKFOO: "range": { // CHECKFOO: "end": { // CHECKFOO: "character": 7, // CHECKFOO: "line": 11 // CHECKFOO: }, // CHECKFOO: "start": { // CHECKFOO: "character": 4, // CHECKFOO: "line": 11 // CHECKFOO: } // CHECKFOO: }, // CHECKFOO: "text": "Foo" // CHECKFOO: } // CHECKFOO: ] // CHECKFOO: }, // CHECKFOO: "identifier": { // CHECKFOO: "interfaceLanguage": "swift", // CHECKFOO: "precise": "s:19cursor_symbol_graph3FooV" // CHECKFOO: }, // CHECKFOO: "kind": { // CHECKFOO: "displayName": "Structure", // CHECKFOO: "identifier": "swift.struct" // CHECKFOO: }, // CHECKFOO: "location": { // CHECKFOO: "position": { // CHECKFOO: "character": 7, // CHECKFOO: "line": 12 // CHECKFOO: }, // CHECKFOO: "uri": "{{.*}}cursor_symbol_graph.swift" // CHECKFOO: }, // CHECKFOO: "names": { // CHECKFOO: "navigator": [ // CHECKFOO: { // CHECKFOO: "kind": "identifier", // CHECKFOO: "spelling": "Foo" // CHECKFOO: } // CHECKFOO: ], // CHECKFOO: "subHeading": [ // CHECKFOO: { // CHECKFOO: "kind": "keyword", // CHECKFOO: "spelling": "struct" // CHECKFOO: }, // CHECKFOO: { // CHECKFOO: "kind": "text", // CHECKFOO: "spelling": " " // CHECKFOO: }, // CHECKFOO: { // CHECKFOO: "kind": "identifier", // CHECKFOO: "spelling": "Foo" // CHECKFOO: } // CHECKFOO: ], // CHECKFOO: "title": "Foo" // CHECKFOO: }, // CHECKFOO: "pathComponents": [ // CHECKFOO: "Foo" // CHECKFOO: ], // CHECKFOO: "swiftGenerics": { // CHECKFOO: "parameters": [ // CHECKFOO: { // CHECKFOO: "depth": 0, // CHECKFOO: "index": 0, // CHECKFOO: "name": "T" // CHECKFOO: } // CHECKFOO: ] // CHECKFOO: } // CHECKFOO: } // CHECKFOO: ] // CHECKFOO: } // CHECKBAR_ALL: SYMBOL GRAPH BEGIN // CHECKBAR_ALL: { // CHECKBAR_ALL: "metadata": { // CHECKBAR_ALL: "formatVersion": { // CHECKBAR_ALL: "major": // CHECKBAR_ALL: "minor": // CHECKBAR_ALL: "patch": // CHECKBAR_ALL: }, // CHECKBAR_ALL: "generator": // CHECKBAR_ALL: }, // CHECKBAR_ALL: "module": { // CHECKBAR_ALL: "name": "cursor_symbol_graph", // CHECKBAR_ALL: "platform": { // CHECKBAR_ALL: "architecture": // CHECKBAR_ALL: "operatingSystem": // CHECKBAR_ALL: "vendor": // CHECKBAR_ALL: } // CHECKBAR_ALL: }, // CHECKBAR_ALL: "relationships": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "memberOf", // CHECKBAR_ALL: "source": "s:19cursor_symbol_graph3FooV3bar1xyx_tSQRzlF", // CHECKBAR_ALL: "target": "s:19cursor_symbol_graph3FooV" // CHECKBAR_ALL: } // CHECKBAR_ALL: ], // CHECKBAR_ALL: "symbols": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "accessLevel": "internal", // CHECKBAR_ALL: "declarationFragments": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "keyword", // CHECKBAR_ALL: "spelling": "func" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": " " // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "identifier", // CHECKBAR_ALL: "spelling": "bar" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": "(" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "externalParam", // CHECKBAR_ALL: "spelling": "x" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": ": " // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "typeIdentifier", // CHECKBAR_GEN: "spelling": "T" // CHECKBAR_INT: "preciseIdentifier": "s:Si", // CHECKBAR_INT: "spelling": "Int" // CHECKBAR_STR: "preciseIdentifier": "s:SS", // CHECKBAR_STR: "spelling": "String" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_GEN: "spelling": ") " // CHECKBAR_INT: "spelling": ")" // CHECKBAR_STR: "spelling": ")" // CHECKBAR_INT-NOT: where // CHECKBAR_STR-NOT: where // CHECKBAR_GEN: }, // CHECKBAR_GEN: { // CHECKBAR_GEN: "kind": "keyword", // CHECKBAR_GEN: "spelling": "where" // CHECKBAR_GEN: }, // CHECKBAR_GEN: { // CHECKBAR_GEN: "kind": "text", // CHECKBAR_GEN: "spelling": " " // CHECKBAR_GEN: }, // CHECKBAR_GEN: { // CHECKBAR_GEN: "kind": "typeIdentifier", // CHECKBAR_GEN: "spelling": "T" // CHECKBAR_GEN: }, // CHECKBAR_GEN: { // CHECKBAR_GEN: "kind": "text", // CHECKBAR_GEN: "spelling": " : " // CHECKBAR_GEN: }, // CHECKBAR_GEN: { // CHECKBAR_GEN: "kind": "typeIdentifier", // CHECKBAR_GEN: "preciseIdentifier": "s:SQ", // CHECKBAR_GEN: "spelling": "Equatable" // CHECKBAR_ALL: } // CHECKBAR_ALL: ], // CHECKBAR_ALL: "docComment": { // CHECKBAR_ALL: "lines": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "range": { // CHECKBAR_ALL: "end": { // CHECKBAR_ALL: "character": 28, // CHECKBAR_ALL: "line": 13 // CHECKBAR_ALL: }, // CHECKBAR_ALL: "start": { // CHECKBAR_ALL: "character": 8, // CHECKBAR_ALL: "line": 13 // CHECKBAR_ALL: } // CHECKBAR_ALL: }, // CHECKBAR_ALL: "text": "Something about bar " // CHECKBAR_ALL: } // CHECKBAR_ALL: ] // CHECKBAR_ALL: }, // CHECKBAR_ALL: "functionSignature": { // CHECKBAR_ALL: "parameters": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "declarationFragments": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "identifier", // CHECKBAR_ALL: "spelling": "x" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": ": " // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "typeIdentifier", // CHECKBAR_GEN: "spelling": "T" // CHECKBAR_INT: "preciseIdentifier": "s:Si", // CHECKBAR_INT: "spelling": "Int" // CHECKBAR_STR: "preciseIdentifier": "s:SS", // CHECKBAR_STR: "spelling": "String" // CHECKBAR_ALL: } // CHECKBAR_ALL: ], // CHECKBAR_ALL: "name": "x" // CHECKBAR_ALL: } // CHECKBAR_ALL: ], // CHECKBAR_ALL: "returns": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": "()" // CHECKBAR_ALL: } // CHECKBAR_ALL: ] // CHECKBAR_ALL: }, // CHECKBAR_ALL: "identifier": { // CHECKBAR_ALL: "interfaceLanguage": "swift", // CHECKBAR_ALL: "precise": "s:19cursor_symbol_graph3FooV3bar1xyx_tSQRzlF" // CHECKBAR_ALL: }, // CHECKBAR_ALL: "kind": { // CHECKBAR_ALL: "displayName": "Instance Method", // CHECKBAR_ALL: "identifier": "swift.method" // CHECKBAR_ALL: }, // CHECKBAR_ALL: "location": { // CHECKBAR_ALL: "position": { // CHECKBAR_ALL: "character": 9, // CHECKBAR_ALL: "line": 14 // CHECKBAR_ALL: }, // CHECKBAR_ALL: "uri": "{{.*}}cursor_symbol_graph.swift" // CHECKBAR_ALL: }, // CHECKBAR_ALL: "names": { // CHECKBAR_ALL: "navigator": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "keyword", // CHECKBAR_ALL: "spelling": "func" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": " " // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "identifier", // CHECKBAR_ALL: "spelling": "bar" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": "(" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "externalParam", // CHECKBAR_ALL: "spelling": "x" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": ": " // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "typeIdentifier", // CHECKBAR_GEN: "spelling": "T" // CHECKBAR_INT: "preciseIdentifier": "s:Si", // CHECKBAR_INT: "spelling": "Int" // CHECKBAR_STR: "preciseIdentifier": "s:SS", // CHECKBAR_STR: "spelling": "String" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": ")" // CHECKBAR_ALL: } // CHECKBAR_ALL: ], // CHECKBAR_ALL: "subHeading": [ // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "keyword", // CHECKBAR_ALL: "spelling": "func" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": " " // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "identifier", // CHECKBAR_ALL: "spelling": "bar" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": "(" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "externalParam", // CHECKBAR_ALL: "spelling": "x" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": ": " // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "typeIdentifier", // CHECKBAR_GEN: "spelling": "T" // CHECKBAR_INT: "preciseIdentifier": "s:Si", // CHECKBAR_INT: "spelling": "Int" // CHECKBAR_STR: "preciseIdentifier": "s:SS", // CHECKBAR_STR: "spelling": "String" // CHECKBAR_ALL: }, // CHECKBAR_ALL: { // CHECKBAR_ALL: "kind": "text", // CHECKBAR_ALL: "spelling": ")" // CHECKBAR_ALL: } // CHECKBAR_ALL: ], // CHECKBAR_ALL: "title": "bar(x:)" // CHECKBAR_ALL: }, // CHECKBAR_ALL: "pathComponents": [ // CHECKBAR_ALL: "Foo", // CHECKBAR_ALL: "bar(x:)" // CHECKBAR_GEN: ], // CHECKBAR_INT-NOT: "swiftGenerics": // CHECKBAR_STR-NOT: "swiftGenerics": // CHECKBAR_GEN: "swiftGenerics": { // CHECKBAR_GEN: "constraints": [ // CHECKBAR_GEN: { // CHECKBAR_GEN: "kind": "conformance", // CHECKBAR_GEN: "lhs": "T", // CHECKBAR_GEN: "rhs": "Equatable" // CHECKBAR_GEN: } // CHECKBAR_GEN: ], // CHECKBAR_GEN: "parameters": [ // CHECKBAR_GEN: { // CHECKBAR_GEN: "depth": 0, // CHECKBAR_GEN: "index": 0, // CHECKBAR_GEN: "name": "T" // CHECKBAR_GEN: } // CHECKBAR_GEN: ] // CHECKBAR_GEN: } // CHECKBAR_ALL: } // CHECKBAR_ALL: ] // CHECKBAR_ALL: } // CHECKCASE: SYMBOL GRAPH BEGIN // CHECKCASE: { // CHECKCASE: "metadata": { // CHECKCASE: "formatVersion": { // CHECKCASE: "major": // CHECKCASE: "minor": // CHECKCASE: "patch": // CHECKCASE: }, // CHECKCASE: "generator": // CHECKCASE: }, // CHECKCASE: "module": { // CHECKCASE: "name": "cursor_symbol_graph", // CHECKCASE: "platform": // CHECKCASE: }, // CHECKCASE: "relationships": [ // CHECKCASE: { // CHECKCASE: "kind": "memberOf", // CHECKCASE: "source": "s:19cursor_symbol_graph6MyEnumO8someCaseyA2CmF", // CHECKCASE: "target": "s:19cursor_symbol_graph6MyEnumO" // CHECKCASE: } // CHECKCASE: ], // CHECKCASE: "symbols": [ // CHECKCASE: { // CHECKCASE: "accessLevel": "internal", // CHECKCASE: "declarationFragments": [ // CHECKCASE: { // CHECKCASE: "kind": "keyword", // CHECKCASE: "spelling": "case" // CHECKCASE: }, // CHECKCASE: { // CHECKCASE: "kind": "text", // CHECKCASE: "spelling": " " // CHECKCASE: }, // CHECKCASE: { // CHECKCASE: "kind": "identifier", // CHECKCASE: "spelling": "someCase" // CHECKCASE: } // CHECKCASE: ], // CHECKCASE: "docComment": { // CHECKCASE: "lines": [ // CHECKCASE: { // CHECKCASE: "range": { // CHECKCASE: "end": { // CHECKCASE: "character": 63, // CHECKCASE: "line": 27 // CHECKCASE: }, // CHECKCASE: "start": { // CHECKCASE: "character": 8, // CHECKCASE: "line": 27 // CHECKCASE: } // CHECKCASE: }, // CHECKCASE: "text": "Text in a code line with no indicated semantic meaning." // CHECKCASE: } // CHECKCASE: ] // CHECKCASE: }, // CHECKCASE: "identifier": { // CHECKCASE: "interfaceLanguage": "swift", // CHECKCASE: "precise": "s:19cursor_symbol_graph6MyEnumO8someCaseyA2CmF" // CHECKCASE: }, // CHECKCASE: "kind": { // CHECKCASE: "displayName": "Case", // CHECKCASE: "identifier": "swift.enum.case" // CHECKCASE: }, // CHECKCASE: "location": { // CHECKCASE: "position": { // CHECKCASE: "character": 9, // CHECKCASE: "line": 28 // CHECKCASE: }, // CHECKCASE: "uri": "{{.*}}cursor_symbol_graph.swift" // CHECKCASE: }, // CHECKCASE: "names": { // CHECKCASE: "navigator": [ // CHECKCASE: { // CHECKCASE: "kind": "keyword", // CHECKCASE: "spelling": "case" // CHECKCASE: }, // CHECKCASE: { // CHECKCASE: "kind": "text", // CHECKCASE: "spelling": " " // CHECKCASE: }, // CHECKCASE: { // CHECKCASE: "kind": "identifier", // CHECKCASE: "spelling": "someCase" // CHECKCASE: } // CHECKCASE: ], // CHECKCASE: "subHeading": [ // CHECKCASE: { // CHECKCASE: "kind": "keyword", // CHECKCASE: "spelling": "case" // CHECKCASE: }, // CHECKCASE: { // CHECKCASE: "kind": "text", // CHECKCASE: "spelling": " " // CHECKCASE: }, // CHECKCASE: { // CHECKCASE: "kind": "identifier", // CHECKCASE: "spelling": "someCase" // CHECKCASE: } // CHECKCASE: ], // CHECKCASE: "title": "someCase" // CHECKCASE: }, // CHECKCASE: "pathComponents": [ // CHECKCASE: "MyEnum", // CHECKCASE: "someCase" // CHECKCASE: ] // CHECKCASE: } // CHECKCASE: ] // CHECKCASE: } // CHECKCASE: SYMBOL GRAPH END
34.94743
172
0.470032
3a4acecc244fcff850d96297e9f15908485868fc
28,774
// // UtilsSQLCipher.swift // Plugin // // Created by Quéau Jean Pierre on 18/01/2021. // Copyright © 2021 Max Lynch. All rights reserved. // import Foundation import SQLCipher enum UtilsSQLCipherError: Error { case openOrCreateDatabase(message: String) case bindFailed case setForeignKeyConstraintsEnabled(message: String) case getVersion(message: String) case setVersion(message: String) case closeDB(message: String) case close(message: String) case changePassword(message: String) case rollbackTransaction(message: String) case beginTransaction(message: String) case commitTransaction(message: String) case execute(message: String) case prepareSQL(message: String) case querySQL(message: String) case fetchColumnInfo(message: String) case deleteDB(message: String) case executeSet(message: String) case restoreDB(message: String) case deleteBackupDB(message: String) case openDBNoPassword(message: String) case openDBStoredPassword(message: String) case openDBGlobalPassword(message: String) } enum State: String { case DOESNOTEXIST, UNENCRYPTED, ENCRYPTEDSECRET, ENCRYPTEDGLOBALSECRET, UNKNOWN, ERROR } // swiftlint:disable file_length // swiftlint:disable type_body_length class UtilsSQLCipher { class func getDatabaseState(databaseLocation: String, databaseName: String) -> State { do { let path: String = try UtilsFile .getFilePath(databaseLocation: databaseLocation, fileName: databaseName) if UtilsFile.isFileExist(filePath: path) { do { try openDBNoPassword(dBPath: path) return State.UNENCRYPTED } catch UtilsSQLCipherError.openDBNoPassword(let message) { if message == "Open" { do { try openDBStoredPassword(dBPath: path) return State.ENCRYPTEDSECRET } catch UtilsSQLCipherError.openDBStoredPassword(let message) { if message == "Open" { do { try openDBGlobalPassword(dBPath: path) return State.ENCRYPTEDGLOBALSECRET } catch UtilsSQLCipherError.openDBGlobalPassword(let message) { if message == "Open" { return State.UNKNOWN } else { return State.ERROR } } } else { return State.ERROR } } } else { return State.ERROR } } } else { return State.DOESNOTEXIST } } catch { return State.UNKNOWN } } class func openDBNoPassword(dBPath: String) throws { do { let oDb: OpaquePointer? = try openOrCreateDatabase( filename: dBPath, password: "", readonly: true) try close(oDB: oDb) return } catch UtilsSQLCipherError.openOrCreateDatabase(_) { throw UtilsSQLCipherError.openDBNoPassword(message: "Open") } catch UtilsSQLCipherError.close(_) { throw UtilsSQLCipherError.openDBNoPassword(message: "Close") } } class func openDBStoredPassword(dBPath: String) throws { do { let password: String = UtilsSecret.getPassphrase() let oDb: OpaquePointer? = try openOrCreateDatabase( filename: dBPath, password: password, readonly: true) try close(oDB: oDb) return } catch UtilsSQLCipherError.openOrCreateDatabase(_) { throw UtilsSQLCipherError.openDBStoredPassword(message: "Open") } catch UtilsSQLCipherError.close(_) { throw UtilsSQLCipherError.openDBStoredPassword(message: "Close") } } class func openDBGlobalPassword(dBPath: String) throws { do { let globalData: GlobalSQLite = GlobalSQLite() let password: String = globalData.secret let oDb: OpaquePointer? = try openOrCreateDatabase( filename: dBPath, password: password, readonly: true) try close(oDB: oDb) return } catch UtilsSQLCipherError.openOrCreateDatabase(_) { throw UtilsSQLCipherError.openDBGlobalPassword(message: "Open") } catch UtilsSQLCipherError.close(_) { throw UtilsSQLCipherError.openDBGlobalPassword(message: "Close") } } // MARK: - OpenOrCreateDatabase class func openOrCreateDatabase(filename: String, password: String = "", readonly: Bool = false ) throws -> OpaquePointer? { let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE var mDB: OpaquePointer? if sqlite3_open_v2(filename, &mDB, flags | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK { if password.count > 0 { let keyStatementString = """ PRAGMA key = '\(password)'; """ if sqlite3_exec(mDB, keyStatementString, nil, nil, nil) != SQLITE_OK { let msg: String = "Wrong Secret" throw UtilsSQLCipherError.openOrCreateDatabase(message: msg) } } let retB: Bool = checkDB(mDB: mDB) if !retB { let msg: String = "Cannot open the DB" throw UtilsSQLCipherError.openOrCreateDatabase(message: msg) } /* this should work but doe not sqlite3_key_v2 is not known if password.count > 0 { let nKey:Int32 = Int32(password.count) if sqlite3_key_v2(mDB!, filename, password, nKey) == SQLITE_OK { var stmt: String = "SELECT count(*) FROM " stmt.append("sqlite_master;") if sqlite3_exec(mDB, stmt, nil, nil, nil) != SQLITE_OK { print("Unable to open a database \(filename)") throw UtilsSQLCipherError .openOrCreateDatabase(message: msg) } } else { print("Unable to open a database \(filename)") throw UtilsSQLCipherError .openOrCreateDatabase(message: msg) } } print("Successfully opened database \(filename)") */ return mDB } else { let message: String = "open_v2 failed" throw UtilsSQLCipherError .openOrCreateDatabase(message: message) } } // MARK: - CheckDB class func checkDB(mDB: OpaquePointer?) -> Bool { var ret: Bool = false var stmt: String = "SELECT count(*) FROM " stmt.append("sqlite_master;") if sqlite3_exec(mDB, stmt, nil, nil, nil) == SQLITE_OK { ret = true } return ret } // MARK: - ChangePassword class func changePassword(filename: String, password: String, newpassword: String) throws { do { // open the db with password let oDB: OpaquePointer? = try openOrCreateDatabase(filename: filename, password: password, readonly: false) // change password let keyStatementString = """ PRAGMA rekey = '\(newpassword)'; """ let returnCode: Int32 = sqlite3_exec( oDB, keyStatementString, nil, nil, nil) if returnCode != SQLITE_OK { throw UtilsSQLCipherError .changePassword(message: "change password") } // close the db try UtilsSQLCipher.close(oDB: oDB) } catch UtilsSQLCipherError.openOrCreateDatabase(let message) { throw UtilsSQLCipherError .changePassword(message: message) } catch UtilsSQLCipherError.close(_) { throw UtilsSQLCipherError .changePassword(message: "close failed") } } // MARK: - SetForeignKeyConstraintsEnabled class func setForeignKeyConstraintsEnabled(mDB: Database, toggle: Bool) throws { var msg: String = "Error Set Foreign Key: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError .setForeignKeyConstraintsEnabled(message: msg) } var key: String = "OFF" if toggle { key = "ON" } let sqltr: String = "PRAGMA foreign_keys = \(key);" if sqlite3_exec(mDB.mDb, sqltr, nil, nil, nil) != SQLITE_OK { msg.append("not successful") throw UtilsSQLCipherError .setForeignKeyConstraintsEnabled(message: msg) } } // MARK: - GetVersion class func getVersion(mDB: Database) throws -> Int { var msg: String = "Error Get Version: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.getVersion(message: msg) } var version: Int = 0 let sqltr: String = "PRAGMA user_version;" do { let resVersion = try UtilsSQLCipher.querySQL(mDB: mDB, sql: sqltr, values: []) if resVersion.count > 0 { guard let res: Int64 = resVersion[0]["user_version"] as? Int64 else { throw UtilsSQLCipherError.getVersion( message: "Error get version failed") } if res > 0 { version = Int(truncatingIfNeeded: res) } } return version } catch UtilsSQLCipherError.querySQL(let message) { throw UtilsUpgradeError.getDatabaseVersionFailed( message: message) } } // MARK: - SetVersion class func setVersion(mDB: Database, version: Int) throws { var msg: String = "Error Set Version: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.setVersion(message: msg) } let sqltr: String = "PRAGMA user_version = \(version);" if sqlite3_exec(mDB.mDb, sqltr, nil, nil, nil) != SQLITE_OK { throw UtilsSQLCipherError.setVersion(message: msg) } } // MARK: - CloseDB class func closeDB(mDB: Database) throws { var msg: String = "Error closeDB: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.closeDB(message: msg) } do { try UtilsSQLCipher.close(oDB: mDB.mDb) } catch UtilsSQLCipherError.close(let message) { throw UtilsSQLCipherError.closeDB(message: message) } } // MARK: - Close class func close(oDB: OpaquePointer?) throws { var message: String = "" let returnCode: Int32 = sqlite3_close_v2(oDB) if returnCode != SQLITE_OK { let errmsg: String = String( cString: sqlite3_errmsg(oDB)) message = "Error: closing the database rc: " + "\(returnCode) message: \(errmsg)" throw UtilsSQLCipherError.close(message: message) } } // MARK: - BeginTransaction class func beginTransaction(mDB: Database) throws { var msg: String = "Error beginTransaction: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.beginTransaction(message: msg) } let sql: String = "BEGIN TRANSACTION;" let returnCode = sqlite3_exec(mDB.mDb, sql, nil, nil, nil) if returnCode != SQLITE_OK { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) msg.append("failed rc: ") msg.append("\(returnCode) message: \(errmsg)") throw UtilsSQLCipherError.beginTransaction( message: msg) } } // MARK: - RollBackTransaction class func rollbackTransaction(mDB: Database) throws { var msg: String = "Error rollbackTransaction: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.rollbackTransaction(message: msg) } let sql: String = "ROLLBACK TRANSACTION;" let returnCode = sqlite3_exec(mDB.mDb, sql, nil, nil, nil) if returnCode != SQLITE_OK { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) msg.append("failed rc: ") msg.append("\(returnCode) message: \(errmsg)") throw UtilsSQLCipherError.rollbackTransaction( message: msg) } } // MARK: - CommitTransaction class func commitTransaction(mDB: Database) throws { var msg: String = "Error commitTransaction: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.commitTransaction(message: msg) } let sql: String = "COMMIT TRANSACTION;" let returnCode = sqlite3_exec(mDB.mDb, sql, nil, nil, nil) if returnCode != SQLITE_OK { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) msg.append("failed rc: ") msg.append("\(returnCode) message: \(errmsg)") throw UtilsSQLCipherError.commitTransaction( message: msg) } } // MARK: - PrepareSQL // swiftlint:disable function_body_length class func prepareSQL(mDB: Database, sql: String, values: [Any]) throws -> Int64 { var msg: String = "Error prepareSQL: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.prepareSQL(message: msg) } var runSQLStatement: OpaquePointer? var message: String = "" var lastId: Int64 = -1 var returnCode: Int32 = sqlite3_prepare_v2( mDB.mDb, sql, -1, &runSQLStatement, nil) if returnCode == SQLITE_OK { if !values.isEmpty { // do the binding of values var idx: Int = 1 for value in values { do { try UtilsBinding.bind(handle: runSQLStatement, value: value, idx: idx) idx += 1 } catch let error as NSError { message = "Error: prepareSQL bind failed " message.append(error.localizedDescription) } if message.count > 0 { break } } } returnCode = sqlite3_step(runSQLStatement) if returnCode != SQLITE_DONE { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) message = "Error: prepareSQL step failed rc: " message.append("\(returnCode) message: \(errmsg)") } } else { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) message = "Error: prepareSQL prepare failed rc: " message.append("\(returnCode) message: \(errmsg)") } returnCode = sqlite3_finalize(runSQLStatement) if returnCode != SQLITE_OK { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) message = "Error: prepareSQL finalize failed rc: " message.append("\(returnCode) message: \(errmsg)") } if message.count > 0 { throw UtilsSQLCipherError.prepareSQL(message: message) } else { lastId = Int64(sqlite3_last_insert_rowid(mDB.mDb)) return lastId } } // swiftlint:enable function_body_length // MARK: - querySQL class func querySQL(mDB: Database, sql: String, values: [Any]) throws -> [[String: Any]] { var msg: String = "Error prepareSQL: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.querySQL(message: msg) } var selectSQLStatement: OpaquePointer? var result: [[String: Any]] = [] var message: String = "" var returnCode: Int32 = sqlite3_prepare_v2(mDB.mDb, sql, -1, &selectSQLStatement, nil) if returnCode == SQLITE_OK { if !values.isEmpty { // do the binding of values message = UtilsBinding.bindValues( handle: selectSQLStatement, values: values) } if message.count == 0 { do { result = try UtilsSQLCipher.fetchColumnInfo( handle: selectSQLStatement) } catch UtilsSQLCipherError .fetchColumnInfo(let message) { throw UtilsSQLCipherError.querySQL(message: message) } } } else { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) message = "Error: querySQL prepare failed rc: " message.append("\(returnCode) message: \(errmsg)") } returnCode = sqlite3_finalize(selectSQLStatement) if returnCode != SQLITE_OK { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) message = "Error: querySQL finalize failed rc: " message.append("\(returnCode) message: \(errmsg)") } if message.count > 0 { throw UtilsSQLCipherError.querySQL(message: message) } else { return result } } // MARK: - FetchColumnInfo // swiftlint:disable function_body_length class func fetchColumnInfo(handle: OpaquePointer?) throws -> [[String: Any]] { var result: [[String: Any]] = [] var columnCount: Int32 = 0 while sqlite3_step(handle) == SQLITE_ROW { columnCount = sqlite3_column_count(handle) var rowData: [String: Any] = [:] for index in 0..<columnCount { guard let name = sqlite3_column_name(handle, index) else { var message = "Error: fetchColumnInfo column_name " message.append("failed") throw UtilsSQLCipherError .fetchColumnInfo(message: message) } switch sqlite3_column_type(handle, Int32(index)) { case SQLITE_INTEGER: let val: Int64 = sqlite3_column_int64(handle, index) rowData[String(cString: name)] = val case SQLITE_FLOAT: let val: Double = sqlite3_column_double(handle, index) rowData[String(cString: name)] = val case SQLITE_BLOB: let data = sqlite3_column_blob(handle, index) let size = sqlite3_column_bytes(handle, index) let val = NSData(bytes: data, length: Int(size)) // Convert to string let strVal: String = String(decoding: val, as: UTF8.self) rowData[String(cString: name)] = strVal case SQLITE_TEXT: let buffer = sqlite3_column_text(handle, index) if let mBuffer = buffer { let val = String(cString: mBuffer) rowData[String(cString: name)] = val } else { rowData[String(cString: name)] = NSNull() } case SQLITE_NULL: rowData[String(cString: name)] = NSNull() case let type: var message = "Error: fetchColumnInfo column_type \(type) " message.append("failed") throw UtilsSQLCipherError .fetchColumnInfo(message: message) } } result.append(rowData) } return result } // swiftlint:enable function_body_length // MARK: - dbChanges class func dbChanges(mDB: OpaquePointer?) -> Int { return Int(sqlite3_total_changes(mDB)) } // MARK: - Execute class func execute(mDB: Database, sql: String) throws { var msg: String = "Error execute: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.execute(message: msg) } let returnCode: Int32 = sqlite3_exec(mDB.mDb, sql, nil, nil, nil) if returnCode != SQLITE_OK { let errmsg: String = String( cString: sqlite3_errmsg(mDB.mDb)) var msg: String = "Error: execute failed rc: \(returnCode)" msg.append(" message: \(errmsg)") throw UtilsSQLCipherError.execute( message: msg) } return } // MARK: - DeleteDB class func deleteDB(databaseLocation: String, databaseName: String) throws { do { let dir: URL = try UtilsFile .getFolderURL(folderPath: databaseLocation) let fileURL = dir.appendingPathComponent(databaseName) let isFileExists = FileManager.default.fileExists( atPath: fileURL.path) if isFileExists { do { try FileManager.default.removeItem(at: fileURL) } catch let error { var msg: String = "Error: deleteDB: " msg.append(" \(error.localizedDescription)") throw UtilsSQLCipherError.deleteDB( message: msg) } } } catch UtilsFileError.getFolderURLFailed(let message) { let msg = "Error: deleteDB: \(message)" throw UtilsSQLCipherError.deleteDB(message: msg) } } // MARK: - ExecuteSet class func executeSet(mDB: Database, set: [[String: Any]]) throws -> Int64 { var msg: String = "Error executeSet: " if !mDB.isDBOpen() { msg.append("Database not opened") throw UtilsSQLCipherError.executeSet(message: msg) } var lastId: Int64 = -1 do { for dict in set { guard let sql: String = dict["statement"] as? String else { throw UtilsSQLCipherError.executeSet( message: "No statement given") } guard let values: [Any] = dict["values"] as? [Any] else { throw UtilsSQLCipherError.executeSet( message: "No values given") } let isArray = values.count > 0 ? UtilsSQLCipher.parse(mVar: values[0]) : false if isArray { if let arrValues = values as? [[Any]] { for vals in arrValues { lastId = try UtilsSQLCipher .prepareSQL(mDB: mDB, sql: sql, values: vals) if lastId == -1 { let message: String = "lastId < 0" throw UtilsSQLCipherError .executeSet(message: message) } } } } else { lastId = try UtilsSQLCipher .prepareSQL(mDB: mDB, sql: sql, values: values) if lastId == -1 { let message: String = "lastId < 0" throw UtilsSQLCipherError.executeSet( message: message) } } } return lastId } catch UtilsSQLCipherError.prepareSQL(let message) { throw UtilsSQLCipherError.executeSet( message: message) } } // MARK: - RestoreDB class func restoreDB(databaseLocation: String, databaseName: String) throws { do { let dir: URL = try UtilsFile .getFolderURL(folderPath: databaseLocation) let fileURL = dir.appendingPathComponent(databaseName) let backupURL = dir .appendingPathComponent("backup-\(databaseName)") let isBackupExists = FileManager.default.fileExists( atPath: backupURL.path) if isBackupExists { let isFileExists = FileManager.default.fileExists( atPath: fileURL.path) if isFileExists { do { try FileManager.default.removeItem(at: fileURL) try FileManager .default.copyItem(atPath: backupURL.path, toPath: fileURL.path) try FileManager.default .removeItem(at: backupURL) } catch { var msg = "Error: restoreDB : \(databaseName)" msg += " \(error)" throw UtilsSQLCipherError.restoreDB( message: msg) } } else { var msg = "Error: restoreDB: \(databaseName)" msg += " does not exist" throw UtilsSQLCipherError.restoreDB( message: msg) } } else { var msg = "Error: restoreDB: backup-\(databaseName)" msg += " does not exist" throw UtilsSQLCipherError.restoreDB( message: msg) } } catch UtilsFileError.getFolderURLFailed(let message) { let msg = "Error: restoreDB: \(message)" throw UtilsSQLCipherError.restoreDB(message: msg) } } // MARK: - deleteBackupDB class func deleteBackupDB(databaseLocation: String, databaseName: String) throws { do { let dir: URL = try UtilsFile .getFolderURL(folderPath: databaseLocation) let backupURL = dir .appendingPathComponent("backup-\(databaseName)") let isBackupExists = FileManager.default.fileExists( atPath: backupURL.path) if isBackupExists { do { try FileManager.default .removeItem(at: backupURL) } catch { var msg = "Error: deleteBackupDB : \(databaseName)" msg += " \(error)" throw UtilsSQLCipherError.deleteBackupDB( message: msg) } } else { var msg = "Error: deleteBackupDB: " msg.append("backup-\(databaseName) does not exist") throw UtilsSQLCipherError.deleteBackupDB(message: msg) } } catch UtilsFileError.getFolderURLFailed(let message) { let msg = "Error: deleteBackupDB: \(message)" throw UtilsSQLCipherError.deleteBackupDB( message: msg) } } class func parse(mVar: Any) -> Bool { var ret: Bool = false if mVar is NSArray { ret = true } return ret } } // swiftlint:enable type_body_length // swiftlint:enable file_length
37.711664
95
0.518072
894ac618bc224dd8ccc30c2c25f3904ffc2cc04b
875
// // LocationManager.swift // WeatherDemo2 // // Created by 李仰脩 on 2021/12/9. // import Foundation import CoreLocation class LocationManager: NSObject,ObservableObject,CLLocationManagerDelegate{ let manager = CLLocationManager() @Published var location:CLLocationCoordinate2D? @Published var isLoading = false override init() { super.init() manager.delegate = self } func requestLocation(){ isLoading = true manager.requestLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations.first?.coordinate isLoading = false } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Error getting location",error) isLoading = false } }
23.648649
100
0.669714
e284894429a51ff953a633b40f149c1d154d93e8
467
// // ModelUtil.swift // App // // Created by Harley.xk on 2018/5/29. // import Vapor extension Encodable { public func encodeToJsonBody(use encoder: JSONEncoder = JSONEncoder()) throws -> HTTPBody { let data = try encoder.encode(self) return HTTPBody(data: data) } } final class RequestData<M: Content>: Content { var device: UserDevice? var user: User? var data: M init(data: M) { self.data = data } }
17.961538
95
0.616702
ffb400637db5548f38ed0363f01042dab927e6e2
1,126
import Foundation /// Order item as described in: https://matomo.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required public struct OrderItem: Codable { /// The SKU of the order item let sku: String /// The name of the order item let name: String /// The category of the order item let category: String /// The price of the order item let price: Float /// The quantity of the order item let quantity: Int /// Creates a new OrderItem /// /// - Parameters: /// - sku: The SKU of the item /// - name: The name of the item. Empty string per default. /// - category: The category of the item. Empty string per default. /// - price: The price of the item. 0 per default. /// - quantity: The quantity of the item. 1 per default. public init(sku: String, name: String = "", category: String = "", price: Float = 0.0, quantity: Int = 1) { self.sku = sku self.name = name self.category = category self.price = price self.quantity = quantity } }
28.871795
127
0.605684
eb2718530ed31a5deb9e8bc6481fe424f00349af
1,825
// // Quadrant.swift // InteractiveClusteringMap // // Created by Seungeon Kim on 2020/11/27. // import Foundation enum Quadrant: Int { case first = 0, second = 1, third = 2, fourth = 3 static func findQuadrant(angle: Double) -> Quadrant { guard angle != .zero else { return Quadrant.first } let number = Int(angle / Degree.right) if angle.truncatingRemainder(dividingBy: Degree.right) == 0 { return Quadrant(rawValue: number - 1) ?? Quadrant.first } else { return Quadrant(rawValue: number) ?? Quadrant.first } } func theta(angle: Double) -> Double { if self == .first || self == .third { return Degree.right - angle } else { return angle } } func degree(center: Coordinate, boundary: Coordinate) -> Coordinate { switch self { case .first: return Coordinate(x: center.x + boundary.x, y: center.y) case .second: return Coordinate(x: center.x, y: center.y - boundary.y) case .third: return Coordinate(x: center.x - boundary.x, y: center.y) case .fourth: return Coordinate(x: center.x, y: center.y + boundary.y) } } func convertToCoordinate(center: Coordinate, distance: Coordinate) -> Coordinate { switch self { case .first: return Coordinate(x: center.x + distance.x, y: center.y + distance.y) case .second: return Coordinate(x: center.x + distance.x, y: center.y - distance.y) case .third: return Coordinate(x: center.x - distance.x, y: center.y - distance.y) case .fourth: return Coordinate(x: center.x - distance.x, y: center.y + distance.y) } } }
31.465517
86
0.566027
eb0c1fa866951e2eba9872bb887f0b101cc847d4
908
// // FoodTrackerTests.swift // FoodTrackerTests // // Created by Go7hic on 2019/9/1. // Copyright © 2019 Go7hic. All rights reserved. // import XCTest @testable import FoodTracker class FoodTrackerTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.942857
111
0.657489
62b4b7bf3fce3123cd9e7699e7deaadba7b8e50f
1,812
// // File.swift // EasyComponents // // Created by 范晓鑫 on 2021/2/18. // #if canImport(PromiseKit) import UIKit import PromiseKit // MARK: Event public extension EasyEventManagerType { func promise() -> Promise<EventParameterType> { let identifier = Date.timeIntervalBetween1970AndReferenceDate.description return Promise { (seal) in self.add(identifier, block: seal.fulfill) }.ensure { self.remove(identifier) } } } public extension EasyEventManagerType where Self: AnyObject { func promise() -> Promise<EventParameterType> { let identifier = Date.timeIntervalBetween1970AndReferenceDate.description return Promise { [weak self] (seal) in self?.add(identifier, block: seal.fulfill) }.ensure { [weak self] in self?.remove(identifier) } } } public extension EasyEventPublisherType { func promise(_ event: EventType) -> Promise<EasyNull> { let identifier = Date.timeIntervalBetween1970AndReferenceDate.description return Promise { (seal) in self.register(event: event, identifier: identifier) { seal.fulfill(easyNull) } }.ensure { self.unregister(event: event, identifier: identifier) } } } public extension EasyEventPublisherType where Self: AnyObject{ func promise(_ event: EventType) -> Promise<EasyNull> { let identifier = Date.timeIntervalBetween1970AndReferenceDate.description return Promise { [weak self](seal) in self?.register(event: event, identifier: identifier) { seal.fulfill(easyNull) } }.ensure { [weak self] in self?.unregister(event: event, identifier: identifier) } } } #endif
30.711864
81
0.640177
61fd1f3420b660ee80b2242047d11db17930f63a
1,321
/*: ## Exercise - Structs, Instances, and Default Values Imagine you are creating an app that will monitor location. Create a `GPS` struct with two variable properties, `latitude` and `longitude`, both with default values of 0.0. */ /*: Create a variable instance of `GPS` called `somePlace`. It should be initialized without supplying any arguments. Print out the latitude and longitude of `somePlace`, which should be 0.0 for both. */ /*: Change `somePlace`'s latitude to 51.514004, and the longitude to 0.125226, then print the updated values. */ /*: Now imagine you are making a social app for sharing your favorite books. Create a `Book` struct with four variable properties: `title`, `author`, `pages`, and `price`. The default values for both `title` and `author` should be an empty string. `pages` should default to 0, and `price` should default to 0.0. */ /*: Create a variable instance of `Book` called `favoriteBook` without supplying any arguments. Print out the title of `favoriteBook`. Does it currently reflect the title of your favorite book? Probably not. Change all four properties of `favoriteBook` to reflect your favorite book. Then, using the properties of `favoriteBook`, print out facts about the book. */ //: page 1 of 10 | [Next: App Exercise - Workout Tracking](@next)
45.551724
358
0.73732
612b15cff11c458bcb20e030bd8168e6c91172a2
462
import Foundation import ObjectMapper import Alamofire open class OauthPath: PathSegment { public override var pathSegment: String { get{ return "oauth" } } open func `authorize`() -> AuthorizePath { return AuthorizePath(parent: self) } open func `revoke`() -> RevokePath { return RevokePath(parent: self) } open func `token`() -> TokenPath { return TokenPath(parent: self) } }
23.1
46
0.61039
4b3f6299061a6df181750f69fe4576ca67ddfc45
2,481
// // SceneDelegate.swift // Notepad // // Created by WilliamYang on 2022/2/7. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
44.303571
147
0.715437
8a9375ae80db606e9ffac5deab536f6e157c463a
2,355
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// /// Keeps track of whether or not a `Channel` should be able to write based on flow control windows. struct OutboundFlowController { /// The current free space in the window. internal private(set) var freeWindowSpace: UInt32 /// The number of bytes currently buffered, not sent to the network. internal private(set) var bufferedBytes: UInt /// Whether the `Channel` should consider itself writable or not. internal var isWritable: Bool { UInt(self.freeWindowSpace) > self.bufferedBytes } internal init(initialWindowSize: UInt32) { self.freeWindowSpace = initialWindowSize self.bufferedBytes = 0 } } extension OutboundFlowController { /// Notifies the flow controller that we have buffered some bytes to send to the network. mutating func bufferedBytes(_ bufferedBytes: Int) { self.bufferedBytes += UInt(bufferedBytes) } /// Notifies the flow controller that we have successfully written some bytes to the network. mutating func wroteBytes(_ writtenBytes: Int) { self.bufferedBytes -= UInt(writtenBytes) self.freeWindowSpace -= UInt32(writtenBytes) } mutating func outboundWindowIncremented(_ increment: UInt32) throws { let (newWindowSpace, overflow) = self.freeWindowSpace.addingReportingOverflow(increment) if overflow { throw NIOSSHError.protocolViolation(protocolName: "channel", violation: "Peer incremented flow control window past UInt32.max") } self.freeWindowSpace = newWindowSpace } } extension OutboundFlowController: Hashable {} extension OutboundFlowController: CustomDebugStringConvertible { var debugDescription: String { "OutboundFlowController(freeWindowSpace: \(self.freeWindowSpace), bufferedBytes: \(self.bufferedBytes), isWritable: \(self.isWritable))" } }
37.983871
144
0.675584
283371c0f975eb83f9a77dff6bcd3d3d6fe2218d
1,528
// // DatePickerSample.swift // SwiftUICatalog // // Copyright (c) 2019 Kazuhiro Hayashi // // 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 SwiftUI struct DatePickerSample: View { @State var selection: Date = Date() var body: some View { DatePicker("Date Picker", selection: $selection).frame(width: 200) } } #if DEBUG struct DatePickerSample_Previews: PreviewProvider { static var previews: some View { DatePickerSample() } } #endif
35.534884
81
0.73233
4aaa1b427c683cafc622ce5af663d2237c304b40
883
import Foundation import Minerva import UIKit public final class WorkoutCellModel: SwipeableLabelCellModel, ListSelectableCellModel { public let workout: Workout public init(workout: Workout) { self.workout = workout super .init( identifier: workout.description, attributedText: NSAttributedString(string: "\(workout.details)\n\(workout.text)") ) backgroundColor = .systemBackground } override public var cellType: ListCollectionViewCell.Type { SwipeableLabelCell.self } override public func identical(to model: ListCellModel) -> Bool { guard let model = model as? Self, super.identical(to: model) else { return false } return workout.proto == model.workout.proto } // MARK: - ListSelectableCellModel public typealias SelectableModelType = WorkoutCellModel public var selectionAction: SelectionAction? }
26.757576
89
0.736127
d5bf8991d5b37ce56ff5614e22d3573b2b11eaef
36
import Foundation import GQLSchema
9
17
0.861111
388c3e58b949e1f4d8153a7f591247a186e02e55
2,011
// SwiftGridCell.swift // Copyright (c) 2016 - Present Nathan Lampi (http://nathanlampi.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 /** `SwiftGridCell` is the base cell type used by the `SwiftGridView` class. This class inherits from `UICollectionViewCell` and doesn't currently have much further funcitonality. */ open class SwiftGridCell: UICollectionViewCell { public override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.clear } /** Returns the reuse identifier string to be used for the cell. Override to provide a custom identifier. - Returns: String identifier for the cell. */ open class func reuseIdentifier() -> String { return "SwiftGridCellReuseId" } }
39.431373
176
0.722526
2f059e1e164979f68ef2da1bdfdfee144b6a3fcf
1,452
// // CountryTableViewCell.swift // ViewSwapper // // Created by Julius Camba Abarra on 10/17/19. // Copyright © 2019 iamjcabarra. All rights reserved. // import UIKit // MARK: - Protocol public protocol CountryTableViewCellDelegate: class { func didTapHeartButton(fromCell cell: CountryTableViewCell) } public final class CountryTableViewCell: UITableViewCell { // MARK: - Delegate public weak var delegate: CountryTableViewCellDelegate? // MARK: - Outlets @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var heartButton: UIButton! // MARK: - Overrides public override func prepareForReuse() { super.prepareForReuse() self.delegate = nil } public override func awakeFromNib() { super.awakeFromNib() self.heartButton.addTarget( self, action: #selector(CountryTableViewCell.didTapHeartButton(_:)), for: UIControl.Event.touchUpInside ) } public override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } // MARK: - Target Action Methods extension CountryTableViewCell { @objc private func didTapHeartButton(_ sender: UIButton) { guard let delegate = self.delegate else { print("Error: Delegate is nil!") return } delegate.didTapHeartButton(fromCell: self) } }
24.610169
74
0.654959
e8d043223dbb34c925356fbdb316f0660ba373cf
2,504
// // PyWrapper.swift // Pyto // // Created by Emma Labbé on 28-06-19. // Copyright © 2018-2021 Emma Labbé. All rights reserved. // import Foundation /// A class for wrapping an UIKit object. @available(iOS 13.0, *) @objc public class PyWrapper: NSObject { /// The managed object. @objc public var managed: NSObject! public override init() {} /// Initializes with the given object. /// /// - Parameters: /// - managed: The wrapped object. @objc public init(managed: NSObject! = NSObject()) { super.init() self.managed = managed } /// Gets an object in the main thread. /// /// - Parameters: /// - code: Code to execute in the main thread. Returns the object to be returned by the function. /// /// - Returns: The object returned by `code`. func get <T: Any>(code: @escaping () -> T) -> T { return PyWrapper.get(code: code) } /// Runs code on the main thread. Should be used for setting values. /// /// - Parameters: /// - code: Code to execute. func set(code: @escaping () -> Void) { return PyWrapper.set(code: code) } /// Gets an object in the main thread. /// /// - Parameters: /// - code: Code to execute in the main thread. Returns the object to be returned by the function. /// /// - Returns: The object returned by `code`. class func get <T: Any>(code: @escaping () -> T) -> T { let semaphore = Python.Semaphore(value: 0) var value: T! if !Thread.current.isMainThread { DispatchQueue.main.async { value = code() semaphore.signal() } } else { value = code() } if !Thread.current.isMainThread { semaphore.wait() } return value } /// Runs code on the main thread. Should be used for setting values. /// /// - Parameters: /// - code: Code to execute. class func set(code: @escaping () -> Void) { let semaphore = Python.Semaphore(value: 0) if !Thread.current.isMainThread { DispatchQueue.main.async { code() semaphore.signal() } } else { code() } if !Thread.current.isMainThread { semaphore.wait() } } }
25.55102
106
0.515176
f94dfa230cb706887c0e3b1daedb1eddd4afdf70
809
// // RFModuleHandling.swift // Pods-RFModule_Example // // Created by RFMacBook on 17.03.2018. // import Foundation import UIKit @objc public protocol RFModuleHandling: NSObjectProtocol { var view: UIViewController? { get set } @objc(input) weak var inputObjc: AnyObject? { get set } @objc(moduleOutputBlock) var setModuleOutput: ((_ moduleOutput: AnyObject?) -> Void)? { get set } } public extension RFModuleHandling { var input: AnyObject? { get { return inputObjc } set { inputObjc = newValue} } } public protocol ModuleHandling: class { associatedtype Input associatedtype Output var view: UIViewController? { get set } var input: Input? { get set } var setModuleOutput: ((_ moduleOutput: Output?) -> Void)? { get set } }
21.289474
82
0.666255
acde1df1cc26e7ec44e7a2192dbc6ff8dc3edb7e
12,804
// // TestViewController.swift // VideoPlayback // // Created by Daniel Lin on 11/16/16. // Copyright © 2016 Qualcomm. All rights reserved. // import UIKit class TestViewController: UIViewController { @IBOutlet weak var ui_button: UIButton! @IBOutlet weak var main_label: UILabel! //Define a variable for an array to hold the ViewControllers named, viewControllers. @IBOutlet weak var bottom_gradient: UIView! @IBOutlet weak var contentView: UIView! var AR_viewController: UIViewController! @IBOutlet weak var testButton: UIButton! var profileView: UIView! var bgBarView: UIView! var progressBarArray: [UIView] = [] var progressBarArray_active: [UIView] = [] let padding_fromSides = 30.0 let padding_fromBottom = 25 let interVideoPadding = 2.0 let progressBarHeight = 2.0 var numberOfVideos: Int! @IBOutlet weak var button: UIView! @IBAction func buttonTouchDown(_ sender: AnyObject) { print("down") } // @IBAction func buttonTouchUp(_ sender: AnyObject) { // print("up") // // if ui_button.currentImage == UIImage(named: "icon_dl_default") { // print("true") // } // } // //var AR = VideoPlaybackEAGLView() //AR.someProperty = "Hello World" //instanceOfCustomObject.someMethod() @IBOutlet weak var holdingBox: UIView! override func viewDidLoad() { super.viewDidLoad() holdingBox.frame.size = CGSize(width: Double(self.view.frame.size.width)-padding_fromSides * 2, height: progressBarHeight) holdingBox.frame.origin.x = CGFloat(padding_fromSides) holdingBox.frame.origin.y = self.view.bounds.maxY - CGFloat(padding_fromBottom) - CGFloat(progressBarHeight) holdingBox.backgroundColor = UIColor(red:1, green:1.00, blue:1, alpha:0.0) display_AR_viewController() createScanner() //createProgressBars(numberOfVideos: 10) // Style button button.layer.cornerRadius = 22 button.layer.shadowColor = UIColor.black.cgColor button.layer.shadowOpacity = 0.15 button.layer.shadowOffset = CGSize.zero button.layer.shadowRadius = 10 // Style Gradient let topColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) let bottomColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6) let gradientColors: [CGColor] = [topColor.cgColor, bottomColor.cgColor] let gradientLocations: [Float] = [0.0,1.0] let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = gradientColors gradientLayer.locations = gradientLocations as [NSNumber]? gradientLayer.frame = bottom_gradient.layer.bounds //frame bottom_gradient.layer.insertSublayer(gradientLayer, at: 0) // Position & Style Button button.frame.origin.y = holdingBox.frame.origin.y - CGFloat(padding_fromBottom) - (button.frame.height*3/4) button.frame.origin.x = self.view.bounds.width - CGFloat(padding_fromSides) - button.frame.width button.backgroundColor = UIColor(red:0.54, green:1.00, blue:0.99, alpha: 0.0) // Position & Style Label main_label.frame.origin.x = CGFloat(padding_fromSides) main_label.frame.origin.y = holdingBox.frame.origin.y - CGFloat(padding_fromBottom) - main_label.frame.height // SWIFT NOTIFICATION: PROGRESS UPDATE NotificationCenter.default.addObserver(forName: NSNotification.Name.init(rawValue: "progressUpdate"), object: nil, queue: OperationQueue.main) { (notification: Notification!) in let progress = Float(notification?.userInfo?["progress"] as! NSNumber.FloatLiteralType) let current_index = Int(notification?.userInfo?["current_index"] as! NSNumber.FloatLiteralType) print("THE PROGRESS IS ",progress) print("THE CURRENT INDEX IS ",current_index) // self.updateProgressBars(progress: progress, current_index: current_index) } // SWIFT NOTIFICATION: TAP LEFT NotificationCenter.default.addObserver(forName: NSNotification.Name.init(rawValue: "tapLeft"), object: nil, queue: OperationQueue.main) { (notification: Notification!) in let userInfo = notification?.userInfo print("Hey....we tapped LEFT") } // SWIFT NOTIFICATION: TAP RIGHT NotificationCenter.default.addObserver(forName: NSNotification.Name.init(rawValue: "tapRight"), object: nil, queue: OperationQueue.main) { (notification: Notification!) in let userInfo = notification?.userInfo print("Hey....we tapped RIGHT") } // SWIFT NOTIFICATION: SCAN ON (not set) NotificationCenter.default.addObserver(forName: NSNotification.Name.init(rawValue: "scanOn"), object: nil, queue: OperationQueue.main) { (notification: Notification!) in let previous_numberOfVideos = self.numberOfVideos let new_numberOfVideos = Int(notification?.userInfo?["numberOfVideos"] as! NSNumber.FloatLiteralType) if new_numberOfVideos != previous_numberOfVideos{ if new_numberOfVideos == 0 { self.createScanner() self.destroyProgressBars() self.main_label.text = "Searching..." self.ui_button.setImage(UIImage(named: "icon_dl_default"), for: UIControlState.normal) } else { self.createProgressBars(numberOfVideos: new_numberOfVideos) self.destroyScanner() //self.main_label.text = "CodePath Memories" self.ui_button.setImage(UIImage(named: "icon_dl_pause"), for: UIControlState.normal) } self.numberOfVideos = new_numberOfVideos //DL: DLIN LATEST: // - find a way to kill progressbar/scanner // - make a gradient // - border animation? // - button shadow interaction (touchdown/dtouch up) } print(self.numberOfVideos) } // SWIFT NOTIFICATION: SCANON_NAME NotificationCenter.default.addObserver(forName: NSNotification.Name.init(rawValue: "scanOn_name"), object: nil, queue: OperationQueue.main) { (notification: Notification!) in //let name = self.name let name = String(notification?.userInfo?["name"] as! String) self.main_label.text = name } } func createScanner () { // Layer Creation profileView = UIView(frame: CGRect(x: 250, y: 0, width: 100, height: holdingBox.frame.height)) profileView.backgroundColor = UIColor(red:0.54, green:1.00, blue:0.99, alpha:1.0) profileView.layer.cornerRadius = CGFloat(progressBarHeight) / 2 profileView.frame.origin.x = 0 profileView.frame.size = CGSize(width: 0, height: holdingBox.frame.height) bgBarView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: holdingBox.frame.height)) bgBarView.backgroundColor = UIColor(red:1, green:1.00, blue:1, alpha:0.3) bgBarView.layer.cornerRadius = CGFloat(progressBarHeight) / 2 bgBarView.frame.size = holdingBox.frame.size // Add to View self.holdingBox.addSubview(profileView) self.holdingBox.addSubview(bgBarView) // Animation UIView.animateKeyframes(withDuration: 1.25, delay: 0, options: [.calculationModeCubicPaced, .repeat, .autoreverse], animations:{ UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0, animations: { self.profileView.frame.origin.x = self.holdingBox.frame.width/2 self.profileView.frame.size = CGSize(width: 150, height: self.holdingBox.frame.height) }) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0, animations: { self.profileView.frame.origin.x = self.holdingBox.frame.width self.profileView.frame.size = CGSize(width: 0, height: self.holdingBox.frame.height) }) }, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func testMe() { print("SUCCESS I GUESS") //let userInfo = notification?.userInfo } func display_AR_viewController() { // Within the ViewDidLoad() method, access the main Storyboard through code. let storyboard = UIStoryboard(name: "Main", bundle: nil) // Next, instantiate each ViewController by referencing storyboard and the particular ViewController's Storyboard ID AR_viewController = storyboard.instantiateViewController(withIdentifier: "AR") // Add the new ViewController. (Calls the viewWillAppear method of the ViewController you are adding) addChildViewController(AR_viewController) // Adjust the size of the ViewController view you are adding to match the contentView of your tabBarViewController and add it as a subView of the contentView. //AR_viewController.view.frame = contentView.frame.applying(CGAffineTransform .scaledBy(x: 2, y:2)) AR_viewController.view.layer.anchorPoint = CGPoint(x: 0.5, y: 0) AR_viewController.view.frame = contentView.bounds AR_viewController.view.transform = CGAffineTransform(scaleX: 1.07, y:1.07) //AR_viewController.view.frame = contentView.bounds.CGAffineTransform(scaleX: 2.4, y:2.4) contentView.addSubview(AR_viewController.view) //contentView.center.y += 0 // Call the viewDidAppear method of the ViewController you are adding using didMove(toParentViewController: self). AR_viewController.didMove(toParentViewController: self) } func createProgressBars (numberOfVideos: Int) { for i in 0...numberOfVideos-1{ // Variables let width = CGFloat(holdingBox.frame.width) / CGFloat(numberOfVideos) - CGFloat(interVideoPadding) + CGFloat(CGFloat(interVideoPadding) / CGFloat(numberOfVideos)) let height = holdingBox.frame.height let x = Double(i) * ( Double(width) + interVideoPadding ) let y = 0 // Create let bar = UIView( frame: CGRect(x: CGFloat(x), y: CGFloat(y), width: CGFloat(width), height: CGFloat(height)) ) let bar_active = UIView( frame: CGRect(x: CGFloat(x), y: CGFloat(y), width: CGFloat(0), height: CGFloat(height)) ) // Modify bar.backgroundColor = UIColor(red:1, green:1.00, blue:1, alpha:0.3) bar_active.backgroundColor = UIColor(red:0.54, green:1.00, blue:0.99, alpha:1.0) bar.layer.cornerRadius = 3.0 bar_active.layer.cornerRadius = 3.0 // Push To Array progressBarArray.append(bar) progressBarArray_active.append(bar_active) // Add To View self.holdingBox.addSubview(bar) self.holdingBox.addSubview(bar_active) } } func destroyProgressBars () { for bar in progressBarArray { bar.removeFromSuperview() } for bar in progressBarArray_active { bar.removeFromSuperview() } progressBarArray = [] progressBarArray_active = [] } func destroyScanner () { if self.profileView != nil { self.profileView.removeFromSuperview() self.bgBarView.removeFromSuperview() } } func updateProgressBars( progress: Float, current_index: Int) { let fullWidth = Double(progressBarArray[0].frame.width) print(progressBarArray_active) for (i, bar) in self.progressBarArray_active.enumerated() { if i < current_index { // Full bar.frame.size = CGSize(width: fullWidth, height: progressBarHeight) } else if i == current_index { // Adjusted let currentWidth = Double(progress) * fullWidth bar.frame.size = CGSize(width: currentWidth, height: progressBarHeight) } else { // Empty bar.frame.size = CGSize(width: 0, height: progressBarHeight) } } } }
43.256757
185
0.624336
3a52a0003b6aab49691f706a1550b3627da3c2c1
573
// // GigyaApiRequestMock.swift // GigyaSwiftTests // // Created by Shmuel, Sagi on 26/03/2019. // Copyright © 2019 Gigya. All rights reserved. // import Foundation @testable import GigyaSwift class NetworkAdapterMock: NetworkAdapter { var data: NSData? var error: Error? init() { let model = GigyaApiReguestModel(method: "mock") let provider = GSRequestMock(forMethod: model.method) super.init(with: provider) } override func send(_ complition: @escaping GigyaResponseHandler) { complition(data, error) } }
21.222222
70
0.675393
648e4de47e3db75ff0b3a96f66f1f4d95c60c20b
72,921
// // PulleyViewController.swift // Pulley // // Created by Brendan Lee on 7/6/16. // Copyright © 2016 52inc. All rights reserved. // import UIKit /** * The base delegate protocol for Pulley delegates. */ @objc public protocol PulleyDelegate: class { /** This is called after size changes, so if you care about the bottomSafeArea property for custom UI layout, you can use this value. * NOTE: It's not called *during* the transition between sizes (such as in an animation coordinator), but rather after the resize is complete. */ @objc optional func drawerPositionDidChange(drawer: PulleyViewController, bottomSafeArea: CGFloat) /** * Make UI adjustments for when Pulley goes to 'fullscreen'. Bottom safe area is provided for your convenience. */ @objc optional func makeUIAdjustmentsForFullscreen(progress: CGFloat, bottomSafeArea: CGFloat) /** * Make UI adjustments for changes in the drawer's distance-to-bottom. Bottom safe area is provided for your convenience. */ @objc optional func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat, bottomSafeArea: CGFloat) /** * Called when the current drawer display mode changes (leftSide vs bottomDrawer). Make UI changes to account for this here. */ @objc optional func drawerDisplayModeDidChange(drawer: PulleyViewController) } /** * View controllers in the drawer can implement this to receive changes in state or provide values for the different drawer positions. */ @objc public protocol PulleyDrawerViewControllerDelegate: PulleyDelegate { /** * Provide the collapsed drawer height for Pulley. Pulley does NOT automatically handle safe areas for you, however: bottom safe area is provided for your convenience in computing a value to return. */ @objc optional func collapsedDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat /** * Provide the partialReveal drawer height for Pulley. Pulley does NOT automatically handle safe areas for you, however: bottom safe area is provided for your convenience in computing a value to return. */ @objc optional func partialRevealDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat /** * Return the support drawer positions for your drawer. */ @objc optional func supportedDrawerPositions() -> [PulleyPosition] } /** * View controllers that are the main content can implement this to receive changes in state. */ @objc public protocol PulleyPrimaryContentControllerDelegate: PulleyDelegate { // Not currently used for anything, but it's here for parity with the hopes that it'll one day be used. } /** * A completion block used for animation callbacks. */ public typealias PulleyAnimationCompletionBlock = ((_ finished: Bool) -> Void) /** Represents a Pulley drawer position. - collapsed: When the drawer is in its smallest form, at the bottom of the screen. - partiallyRevealed: When the drawer is partially revealed. - open: When the drawer is fully open. - closed: When the drawer is off-screen at the bottom of the view. Note: Users cannot close or reopen the drawer on their own. You must set this programatically */ @objc public class PulleyPosition: NSObject { @objc public static let collapsed = PulleyPosition(rawValue: 0) @objc public static let partiallyRevealed = PulleyPosition(rawValue: 1) @objc public static let open = PulleyPosition(rawValue: 2) @objc public static let closed = PulleyPosition(rawValue: 3) // @objc public static let all: [PulleyPosition] = [ // .collapsed, // .partiallyRevealed, // .open, // .closed // ] @objc public static let artsy: [PulleyPosition] = [ .partiallyRevealed, .open, .closed, .collapsed ] let rawValue: Int init(rawValue: Int) { self.rawValue = rawValue } @objc public func isEqual(toPosition position: PulleyPosition) -> Bool { return self.rawValue == position.rawValue } public static func positionFor(string: String?) -> PulleyPosition { guard let positionString = string?.lowercased() else { return .collapsed } switch positionString { case "collapsed": return .collapsed case "partiallyrevealed": return .partiallyRevealed case "open": return .open case "closed": return .closed default: print("PulleyViewController: Position for string '\(positionString)' not found. Available values are: collapsed, partiallyRevealed, open, and closed. Defaulting to collapsed.") return .collapsed } } } /// Represents the current display mode for Pulley /// /// - panel: Show as a floating panel (replaces: leftSide) /// - drawer: Show as a bottom drawer (replaces: bottomDrawer) /// - automatic: Determine it based on device / orientation / size class (like Maps.app) public enum PulleyDisplayMode { case panel case drawer case automatic } /// Represents the positioning of the drawer when the `displayMode` is set to either `PulleyDisplayMode.panel` or `PulleyDisplayMode.automatic`. /// /// - topLeft: The drawer will placed in the upper left corner /// - topRight: The drawer will placed in the upper right corner /// - bottomLeft: The drawer will placed in the bottom left corner /// - bottomRight: The drawer will placed in the bottom right corner public enum PulleyPanelCornerPlacement { case topLeft case topRight case bottomLeft case bottomRight } /// Represents the 'snap' mode for Pulley. The default is 'nearest position'. You can use 'nearestPositionUnlessExceeded' to make the drawer feel lighter or heavier. /// /// - nearestPosition: Snap to the nearest position when scroll stops /// - nearestPositionUnlessExceeded: Snap to the nearest position when scroll stops, unless the distance is greater than 'threshold', in which case advance to the next drawer position. public enum PulleySnapMode { case nearestPosition case nearestPositionUnlessExceeded(threshold: CGFloat) } private let kPulleyDefaultCollapsedHeight: CGFloat = 38.0 private let kPulleyDefaultPartialRevealHeight: CGFloat = 264.0 open class PulleyViewController: UIViewController, PulleyDrawerViewControllerDelegate { // Interface Builder /// When using with Interface Builder only! Connect a containing view to this outlet. @IBOutlet public var primaryContentContainerView: UIView! /// When using with Interface Builder only! Connect a containing view to this outlet. @IBOutlet public var drawerContentContainerView: UIView! // Internal fileprivate let primaryContentContainer: UIView = UIView() fileprivate let drawerContentContainer: UIView = UIView() fileprivate let drawerShadowView: UIView = UIView() fileprivate let drawerScrollView: PulleyPassthroughScrollView = PulleyPassthroughScrollView() fileprivate let backgroundDimmingView: UIView = UIView() fileprivate var dimmingViewTapRecognizer: UITapGestureRecognizer? // Public public let bounceOverflowMargin: CGFloat = 20.0 /// The current content view controller (shown behind the drawer). @objc public fileprivate(set) var primaryContentViewController: UIViewController! { willSet { guard let controller = primaryContentViewController else { return } controller.willMove(toParent: nil) controller.view.removeFromSuperview() controller.removeFromParent() } didSet { guard let controller = primaryContentViewController else { return } addChild(controller) primaryContentContainer.addSubview(controller.view) controller.view.constrainToParent() controller.didMove(toParent: self) if self.isViewLoaded { self.view.setNeedsLayout() self.setNeedsSupportedDrawerPositionsUpdate() } } } /// The current drawer view controller (shown in the drawer). @objc public fileprivate(set) var drawerContentViewController: UIViewController! { willSet { guard let controller = drawerContentViewController else { return } controller.willMove(toParent: nil) controller.view.removeFromSuperview() controller.removeFromParent() } didSet { guard let controller = drawerContentViewController else { return } addChild(controller) drawerContentContainer.addSubview(controller.view) controller.view.constrainToParent() controller.didMove(toParent: self) if self.isViewLoaded { self.view.setNeedsLayout() self.setNeedsSupportedDrawerPositionsUpdate() } } } /// Get the current bottom safe area for Pulley. This is a convenience accessor. Most delegate methods where you'd need it will deliver it as a parameter. public var bottomSafeSpace: CGFloat { get { return pulleySafeAreaInsets.bottom } } /// The content view controller and drawer controller can receive delegate events already. This lets another object observe the changes, if needed. @objc public weak var delegate: PulleyDelegate? /// The current position of the drawer. @objc public fileprivate(set) var drawerPosition: PulleyPosition = .collapsed { didSet { setNeedsStatusBarAppearanceUpdate() } } // The visible height of the drawer. Useful for adjusting the display of content in the main content view. @objc public var visibleDrawerHeight: CGFloat { if drawerPosition == .closed { return 0.0 } else { return drawerScrollView.bounds.height } } /// The background visual effect layer for the drawer. By default this is the extraLight effect. You can change this if you want, or assign nil to remove it. public var drawerBackgroundVisualEffectView: UIVisualEffectView? = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) { willSet { drawerBackgroundVisualEffectView?.removeFromSuperview() } didSet { if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView, self.isViewLoaded { drawerScrollView.insertSubview(drawerBackgroundVisualEffectView, aboveSubview: drawerShadowView) drawerBackgroundVisualEffectView.clipsToBounds = true drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius self.view.setNeedsLayout() } } } /// The inset from the top safe area when the drawer is fully open. This property is only for the 'drawer' displayMode. Use panelInsets to control the top/bottom/left/right insets for the panel. @IBInspectable public var drawerTopInset: CGFloat = 20.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// This replaces the previous panelInsetLeft and panelInsetTop properties. Depending on what corner placement is being used, different values from this struct will apply. For example, 'topLeft' corner placement will utilize the .top, .left, and .bottom inset properties and it will ignore the .right property (use panelWidth property to specify width) @IBInspectable public var panelInsets: UIEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The width of the panel in panel displayMode @IBInspectable public var panelWidth: CGFloat = 325.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The corner radius for the drawer. /// Note: This property is ignored if your drawerContentViewController's view.layer.mask has a custom mask applied using a CAShapeLayer. /// Note: Custom CAShapeLayer as your drawerContentViewController's view.layer mask will override Pulley's internal corner rounding and use that mask as the drawer mask. @IBInspectable public var drawerCornerRadius: CGFloat = 13.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() drawerBackgroundVisualEffectView?.layer.cornerRadius = drawerCornerRadius } } } /// The opacity of the drawer shadow. @IBInspectable public var shadowOpacity: Float = 0.1 { didSet { if oldValue != shadowOpacity { if self.isViewLoaded { drawerShadowView.layer.shadowOpacity = shadowOpacity self.view.setNeedsLayout() } } } } /// The radius of the drawer shadow. @IBInspectable public var shadowRadius: CGFloat = 3.0 { didSet { if oldValue != shadowRadius { if self.isViewLoaded { drawerShadowView.layer.shadowRadius = shadowRadius self.view.setNeedsLayout() } } } } /// The offset of the drawer shadow. @IBInspectable public var shadowOffset = CGSize(width: 0.0, height: -3.0) { didSet { if oldValue != shadowOffset { if self.isViewLoaded { drawerShadowView.layer.shadowOffset = shadowOffset self.view.setNeedsLayout() } } } } /// The opaque color of the background dimming view. @IBInspectable public var backgroundDimmingColor: UIColor = UIColor.black { didSet { if self.isViewLoaded { backgroundDimmingView.backgroundColor = backgroundDimmingColor } } } /// The maximum amount of opacity when dimming. @IBInspectable public var backgroundDimmingOpacity: CGFloat = 0.5 { didSet { if self.isViewLoaded { self.scrollViewDidScroll(drawerScrollView) } } } /// The drawer scrollview's delaysContentTouches setting @IBInspectable public var delaysContentTouches: Bool = true { didSet { if self.isViewLoaded { drawerScrollView.delaysContentTouches = delaysContentTouches } } } /// The drawer scrollview's canCancelContentTouches setting @IBInspectable public var canCancelContentTouches: Bool = true { didSet { if self.isViewLoaded { drawerScrollView.canCancelContentTouches = canCancelContentTouches } } } /// The starting position for the drawer when it first loads @objc public var initialDrawerPosition: PulleyPosition = .partiallyRevealed /// The display mode for Pulley. Default is 'drawer', which preserves the previous behavior of Pulley. If you want it to adapt automatically, choose 'automatic'. The current display mode is available by using the 'currentDisplayMode' property. public var displayMode: PulleyDisplayMode = .drawer { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The Y positioning for Pulley. This property is only oberserved when `displayMode` is set to `.automatic` or `bottom`. Default value is `.topLeft`. public var panelCornerPlacement: PulleyPanelCornerPlacement = .topLeft { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// This is here exclusively to support IBInspectable in Interface Builder because Interface Builder can't deal with enums. If you're doing this in code use the -initialDrawerPosition property instead. Available strings are: open, closed, partiallyRevealed, collapsed @IBInspectable public var initialDrawerPositionFromIB: String? { didSet { initialDrawerPosition = PulleyPosition.positionFor(string: initialDrawerPositionFromIB) } } /// Whether the drawer's position can be changed by the user. If set to `false`, the only way to move the drawer is programmatically. Defaults to `true`. @IBInspectable public var allowsUserDrawerPositionChange: Bool = true { didSet { enforceCanScrollDrawer() } } /// The animation duration for setting the drawer position @IBInspectable public var animationDuration: TimeInterval = 0.3 /// The animation delay for setting the drawer position @IBInspectable public var animationDelay: TimeInterval = 0.0 /// The spring damping for setting the drawer position @IBInspectable public var animationSpringDamping: CGFloat = 0.75 /// The spring's initial velocity for setting the drawer position @IBInspectable public var animationSpringInitialVelocity: CGFloat = 0.0 /// This setting allows you to enable/disable Pulley automatically insetting the drawer on the left/right when in 'bottomDrawer' display mode in a horizontal orientation on a device with a 'notch' or other left/right obscurement. @IBInspectable public var adjustDrawerHorizontalInsetToSafeArea: Bool = true { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The animation options for setting the drawer position public var animationOptions: UIView.AnimationOptions = [.curveEaseInOut] /// The drawer snap mode public var snapMode: PulleySnapMode = .nearestPositionUnlessExceeded(threshold: 20.0) // The feedback generator to use for drawer positon changes. Note: This is 'Any' to preserve iOS 9 compatibilty. Assign a UIFeedbackGenerator to this property. Anything else will be ignored. public var feedbackGenerator: Any? /// Access to the safe areas that Pulley is using for layout (provides compatibility for iOS < 11) public var pulleySafeAreaInsets: UIEdgeInsets { var safeAreaBottomInset: CGFloat = 0 var safeAreaLeftInset: CGFloat = 0 var safeAreaRightInset: CGFloat = 0 var safeAreaTopInset: CGFloat = 0 if #available(iOS 11.0, *) { safeAreaBottomInset = view.safeAreaInsets.bottom safeAreaLeftInset = view.safeAreaInsets.left safeAreaRightInset = view.safeAreaInsets.right safeAreaTopInset = view.safeAreaInsets.top } else { safeAreaBottomInset = self.bottomLayoutGuide.length safeAreaTopInset = self.topLayoutGuide.length } return UIEdgeInsets(top: safeAreaTopInset, left: safeAreaLeftInset, bottom: safeAreaBottomInset, right: safeAreaRightInset) } /// Get the current drawer distance. This value is equivalent in nature to the one delivered by PulleyDelegate's `drawerChangedDistanceFromBottom` callback. public var drawerDistanceFromBottom: (distance: CGFloat, bottomSafeArea: CGFloat) { if self.isViewLoaded { let lowestStop = getStopList().min() ?? 0.0 return (distance: drawerScrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom) } return (distance: 0.0, bottomSafeArea: 0.0) } /// Get all gesture recognizers in the drawer scrollview public var drawerGestureRecognizers: [UIGestureRecognizer] { get { return drawerScrollView.gestureRecognizers ?? [UIGestureRecognizer]() } } /// Get the drawer scrollview's pan gesture recognizer @objc public var drawerPanGestureRecognizer: UIPanGestureRecognizer { get { return drawerScrollView.panGestureRecognizer } } /// The drawer positions supported by the drawer fileprivate var supportedPositions: [PulleyPosition] = PulleyPosition.artsy { didSet { guard self.isViewLoaded else { return } guard oldValue != supportedPositions else { return } guard supportedPositions.count > 0 else { supportedPositions = PulleyPosition.artsy return } self.view.setNeedsLayout() if supportedPositions.contains(drawerPosition) { setDrawerPosition(position: drawerPosition, animated: true) } else { let lowestDrawerState: PulleyPosition = supportedPositions.filter({ $0 != .closed }).min { (pos1, pos2) -> Bool in return pos1.rawValue < pos2.rawValue } ?? .collapsed setDrawerPosition(position: lowestDrawerState, animated: false) } enforceCanScrollDrawer() } } /// The currently rendered display mode for Pulley. This will match displayMode unless you have it set to 'automatic'. This will provide the 'actual' display mode (never automatic). public fileprivate(set) var currentDisplayMode: PulleyDisplayMode = .automatic { didSet { if oldValue != currentDisplayMode { if self.isViewLoaded { self.view.setNeedsLayout() } delegate?.drawerDisplayModeDidChange?(drawer: self) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerDisplayModeDidChange?(drawer: self) (primaryContentContainer as? PulleyPrimaryContentControllerDelegate)?.drawerDisplayModeDidChange?(drawer: self) } } } fileprivate var isAnimatingDrawerPosition: Bool = false /// The height of the open position for the drawer private var heightOfOpenDrawer: CGFloat { let safeAreaTopInset = pulleySafeAreaInsets.top let safeAreaBottomInset = pulleySafeAreaInsets.bottom var height = self.view.bounds.height - safeAreaTopInset if currentDisplayMode == .panel { height -= (panelInsets.top + bounceOverflowMargin) height -= (panelInsets.bottom + safeAreaBottomInset) } else if currentDisplayMode == .drawer { height -= drawerTopInset } return height } /** Initialize the drawer controller programmtically. - parameter contentViewController: The content view controller. This view controller is shown behind the drawer. - parameter drawerViewController: The view controller to display inside the drawer. - note: The drawer VC is 20pts too tall in order to have some extra space for the bounce animation. Make sure your constraints / content layout take this into account. - returns: A newly created Pulley drawer. */ @objc required public init(contentViewController: UIViewController, drawerViewController: UIViewController) { super.init(nibName: nil, bundle: nil) ({ self.primaryContentViewController = contentViewController self.drawerContentViewController = drawerViewController })() } /** Initialize the drawer controller from Interface Builder. - note: Usage notes: Make 2 container views in Interface Builder and connect their outlets to -primaryContentContainerView and -drawerContentContainerView. Then use embed segues to place your content/drawer view controllers into the appropriate container. - parameter aDecoder: The NSCoder to decode from. - returns: A newly created Pulley drawer. */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func loadView() { super.loadView() // IB Support if primaryContentContainerView != nil { primaryContentContainerView.removeFromSuperview() } if drawerContentContainerView != nil { drawerContentContainerView.removeFromSuperview() } // Setup primaryContentContainer.backgroundColor = UIColor.white definesPresentationContext = true drawerScrollView.bounces = false drawerScrollView.delegate = self drawerScrollView.clipsToBounds = false drawerScrollView.showsVerticalScrollIndicator = false drawerScrollView.showsHorizontalScrollIndicator = false drawerScrollView.delaysContentTouches = delaysContentTouches drawerScrollView.canCancelContentTouches = canCancelContentTouches drawerScrollView.backgroundColor = UIColor.clear drawerScrollView.decelerationRate = UIScrollView.DecelerationRate.fast drawerScrollView.scrollsToTop = false drawerScrollView.touchDelegate = self drawerShadowView.layer.shadowOpacity = shadowOpacity drawerShadowView.layer.shadowRadius = shadowRadius drawerShadowView.layer.shadowOffset = shadowOffset drawerShadowView.backgroundColor = UIColor.clear drawerContentContainer.backgroundColor = UIColor.clear backgroundDimmingView.backgroundColor = backgroundDimmingColor backgroundDimmingView.isUserInteractionEnabled = false backgroundDimmingView.alpha = 0.0 drawerBackgroundVisualEffectView?.clipsToBounds = true dimmingViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(PulleyViewController.dimmingViewTapRecognizerAction(gestureRecognizer:))) backgroundDimmingView.addGestureRecognizer(dimmingViewTapRecognizer!) drawerScrollView.addSubview(drawerShadowView) if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView { drawerScrollView.addSubview(drawerBackgroundVisualEffectView) drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius } drawerScrollView.addSubview(drawerContentContainer) primaryContentContainer.backgroundColor = UIColor.white self.view.backgroundColor = UIColor.white self.view.addSubview(primaryContentContainer) self.view.addSubview(backgroundDimmingView) self.view.addSubview(drawerScrollView) primaryContentContainer.constrainToParent() } override open func viewDidLoad() { super.viewDidLoad() // IB Support if primaryContentViewController == nil || drawerContentViewController == nil { assert(primaryContentContainerView != nil && drawerContentContainerView != nil, "When instantiating from Interface Builder you must provide container views with an embedded view controller.") // Locate main content VC for child in self.children { if child.view == primaryContentContainerView.subviews.first { primaryContentViewController = child } if child.view == drawerContentContainerView.subviews.first { drawerContentViewController = child } } assert(primaryContentViewController != nil && drawerContentViewController != nil, "Container views must contain an embedded view controller.") } enforceCanScrollDrawer() setDrawerPosition(position: initialDrawerPosition, animated: false) scrollViewDidScroll(drawerScrollView) delegate?.drawerDisplayModeDidChange?(drawer: self) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerDisplayModeDidChange?(drawer: self) (primaryContentContainer as? PulleyPrimaryContentControllerDelegate)?.drawerDisplayModeDidChange?(drawer: self) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setNeedsSupportedDrawerPositionsUpdate() } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Make sure our view controller views are subviews of the right view (Resolves #21 issue with changing the presentation context) // May be nil during initial layout if let primary = primaryContentViewController { if primary.view.superview != nil && primary.view.superview != primaryContentContainer { primaryContentContainer.addSubview(primary.view) primaryContentContainer.sendSubviewToBack(primary.view) primary.view.constrainToParent() } } // May be nil during initial layout if let drawer = drawerContentViewController { if drawer.view.superview != nil && drawer.view.superview != drawerContentContainer { drawerContentContainer.addSubview(drawer.view) drawerContentContainer.sendSubviewToBack(drawer.view) drawer.view.constrainToParent() } } let safeAreaTopInset = pulleySafeAreaInsets.top let safeAreaBottomInset = pulleySafeAreaInsets.bottom let safeAreaLeftInset = pulleySafeAreaInsets.left let safeAreaRightInset = pulleySafeAreaInsets.right let displayModeForCurrentLayout: PulleyDisplayMode = displayMode != .automatic ? displayMode : ((self.view.bounds.width >= 600.0 || self.traitCollection.horizontalSizeClass == .regular) ? .panel : .drawer) currentDisplayMode = displayModeForCurrentLayout if displayModeForCurrentLayout == .drawer { // Bottom inset for safe area / bottomLayoutGuide if #available(iOS 11, *) { self.drawerScrollView.contentInsetAdjustmentBehavior = .scrollableAxes } else { self.automaticallyAdjustsScrollViewInsets = false self.drawerScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: self.bottomLayoutGuide.length, right: 0) self.drawerScrollView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: self.bottomLayoutGuide.length, right: 0) // (usefull if visible..) } let lowestStop = getStopList().min() ?? 0 let adjustedLeftSafeArea = adjustDrawerHorizontalInsetToSafeArea ? safeAreaLeftInset : 0.0 let adjustedRightSafeArea = adjustDrawerHorizontalInsetToSafeArea ? safeAreaRightInset : 0.0 if supportedPositions.contains(.open) { // Layout scrollview drawerScrollView.frame = CGRect(x: adjustedLeftSafeArea, y: drawerTopInset + safeAreaTopInset, width: self.view.bounds.width - adjustedLeftSafeArea - adjustedRightSafeArea, height: heightOfOpenDrawer) } else { // Layout scrollview let adjustedTopInset: CGFloat = getStopList().max() ?? 0.0 drawerScrollView.frame = CGRect(x: adjustedLeftSafeArea, y: self.view.bounds.height - adjustedTopInset, width: self.view.bounds.width - adjustedLeftSafeArea - adjustedRightSafeArea, height: adjustedTopInset) } drawerScrollView.addSubview(drawerShadowView) if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView { drawerScrollView.addSubview(drawerBackgroundVisualEffectView) drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius } drawerScrollView.addSubview(drawerContentContainer) drawerContentContainer.frame = CGRect(x: 0, y: drawerScrollView.bounds.height - lowestStop, width: drawerScrollView.bounds.width, height: drawerScrollView.bounds.height + bounceOverflowMargin) drawerBackgroundVisualEffectView?.frame = drawerContentContainer.frame drawerShadowView.frame = drawerContentContainer.frame drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: (drawerScrollView.bounds.height - lowestStop) + drawerScrollView.bounds.height - safeAreaBottomInset + (bounceOverflowMargin - 5.0)) // Update rounding mask and shadows let borderPath = drawerMaskingPath(byRoundingCorners: [.topLeft, .topRight, .bottomLeft, .bottomRight]).cgPath let cardMaskLayer = CAShapeLayer() cardMaskLayer.path = borderPath cardMaskLayer.frame = drawerContentContainer.bounds cardMaskLayer.fillColor = UIColor.white.cgColor cardMaskLayer.backgroundColor = UIColor.clear.cgColor drawerContentContainer.layer.mask = cardMaskLayer drawerShadowView.layer.shadowPath = borderPath backgroundDimmingView.frame = CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: self.view.bounds.height + drawerScrollView.contentSize.height) drawerScrollView.transform = CGAffineTransform.identity backgroundDimmingView.isHidden = false } else { // Bottom inset for safe area / bottomLayoutGuide if #available(iOS 11, *) { self.drawerScrollView.contentInsetAdjustmentBehavior = .scrollableAxes } else { self.automaticallyAdjustsScrollViewInsets = false self.drawerScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0.0, right: 0) self.drawerScrollView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0.0, right: 0) } // Layout container var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: safeAreaBottomInset) ?? kPulleyDefaultCollapsedHeight partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: safeAreaBottomInset) ?? kPulleyDefaultPartialRevealHeight } let lowestStop = [(self.view.bounds.size.height - panelInsets.bottom - safeAreaTopInset), collapsedHeight, partialRevealHeight].min() ?? 0 let xOrigin = (panelCornerPlacement == .bottomLeft || panelCornerPlacement == .topLeft) ? (safeAreaLeftInset + panelInsets.left) : (self.view.bounds.maxX - (safeAreaRightInset + panelInsets.right) - panelWidth) let yOrigin = (panelCornerPlacement == .bottomLeft || panelCornerPlacement == .bottomRight) ? (panelInsets.top + safeAreaTopInset) : (panelInsets.top + safeAreaTopInset + bounceOverflowMargin) if supportedPositions.contains(.open) { // Layout scrollview drawerScrollView.frame = CGRect(x: xOrigin, y: yOrigin, width: panelWidth, height: heightOfOpenDrawer) } else { // Layout scrollview let adjustedTopInset: CGFloat = supportedPositions.contains(.partiallyRevealed) ? partialRevealHeight : collapsedHeight drawerScrollView.frame = CGRect(x: xOrigin, y: yOrigin, width: panelWidth, height: adjustedTopInset) } syncDrawerContentViewSizeToMatchScrollPositionForSideDisplayMode() drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: self.view.bounds.height + (self.view.bounds.height - lowestStop)) switch panelCornerPlacement { case .topLeft, .topRight: drawerScrollView.transform = CGAffineTransform(scaleX: 1.0, y: -1.0) case .bottomLeft, .bottomRight: drawerScrollView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) } backgroundDimmingView.isHidden = true } drawerContentContainer.transform = drawerScrollView.transform drawerShadowView.transform = drawerScrollView.transform drawerBackgroundVisualEffectView?.transform = drawerScrollView.transform let lowestStop = getStopList().min() ?? 0 delegate?.drawerChangedDistanceFromBottom?(drawer: self, distance: drawerScrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: drawerScrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: drawerScrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom) maskDrawerVisualEffectView() maskBackgroundDimmingView() setDrawerPosition(position: drawerPosition, animated: false) } // MARK: Private State Updates private func enforceCanScrollDrawer() { guard isViewLoaded else { return } drawerScrollView.isScrollEnabled = allowsUserDrawerPositionChange && supportedPositions.count > 1 } func getStopList() -> [CGFloat] { var drawerStops = [CGFloat]() var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultCollapsedHeight partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultPartialRevealHeight } if supportedPositions.contains(.collapsed) { drawerStops.append(collapsedHeight) } if supportedPositions.contains(.partiallyRevealed) { drawerStops.append(partialRevealHeight) } if supportedPositions.contains(.open) { drawerStops.append((self.view.bounds.size.height - drawerTopInset - pulleySafeAreaInsets.top)) } return drawerStops } /** Returns a masking path appropriate for the drawer content. Either an existing user-supplied mask from the `drawerContentViewController's` view will be returned, or the default Pulley mask with the requested rounded corners will be used. - parameter corners: The corners to round if there is no custom mask already applied to the `drawerContentViewController` view. If the `drawerContentViewController` has a custom mask (supplied by the user of this library), then the corners parameter will be ignored. */ private func drawerMaskingPath(byRoundingCorners corners: UIRectCorner) -> UIBezierPath { // Only layout the drawer content view if the position is not closed. If the position is closed this view is not visable and does not need to be layout for the masking path. This is the root of iOS 14 auto layout feedback loop. if drawerPosition != .closed { drawerContentViewController.view.layoutIfNeeded() } let path: UIBezierPath if let customPath = (drawerContentViewController.view.layer.mask as? CAShapeLayer)?.path { path = UIBezierPath(cgPath: customPath) } else { path = UIBezierPath(roundedRect: drawerContentContainer.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: drawerCornerRadius, height: drawerCornerRadius)) } return path } private func maskDrawerVisualEffectView() { if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView { let path = drawerMaskingPath(byRoundingCorners: [.topLeft, .topRight]) let maskLayer = CAShapeLayer() maskLayer.path = path.cgPath drawerBackgroundVisualEffectView.layer.mask = maskLayer } } /** Mask backgroundDimmingView layer to avoid drawer background beeing darkened. */ private func maskBackgroundDimmingView() { let cutoutHeight = 2 * drawerCornerRadius let maskHeight = backgroundDimmingView.bounds.size.height - cutoutHeight - drawerScrollView.contentSize.height let borderPath = drawerMaskingPath(byRoundingCorners: [.topLeft, .topRight]) borderPath.apply(CGAffineTransform(translationX: 0.0, y: maskHeight)) let maskLayer = CAShapeLayer() // Invert mask to cut away the bottom part of the dimming view borderPath.append(UIBezierPath(rect: backgroundDimmingView.bounds)) maskLayer.fillRule = CAShapeLayerFillRule.evenOdd maskLayer.path = borderPath.cgPath backgroundDimmingView.layer.mask = maskLayer } open func prepareFeedbackGenerator() { if #available(iOS 10.0, *) { if let generator = feedbackGenerator as? UIFeedbackGenerator { generator.prepare() } } } open func triggerFeedbackGenerator() { if #available(iOS 10.0, *) { prepareFeedbackGenerator() (feedbackGenerator as? UIImpactFeedbackGenerator)?.impactOccurred() (feedbackGenerator as? UISelectionFeedbackGenerator)?.selectionChanged() (feedbackGenerator as? UINotificationFeedbackGenerator)?.notificationOccurred(.success) } } /// Add a gesture recognizer to the drawer scrollview /// /// - Parameter gestureRecognizer: The gesture recognizer to add public func addDrawerGestureRecognizer(gestureRecognizer: UIGestureRecognizer) { drawerScrollView.addGestureRecognizer(gestureRecognizer) } /// Remove a gesture recognizer from the drawer scrollview /// /// - Parameter gestureRecognizer: The gesture recognizer to remove public func removeDrawerGestureRecognizer(gestureRecognizer: UIGestureRecognizer) { drawerScrollView.removeGestureRecognizer(gestureRecognizer) } /// Bounce the drawer to get user attention. Note: Only works in .drawer display mode and when the drawer is in .collapsed or .partiallyRevealed position. /// /// - Parameters: /// - bounceHeight: The height to bounce /// - speedMultiplier: The multiplier to apply to the default speed of the animation. Note, default speed is 0.75. public func bounceDrawer(bounceHeight: CGFloat = 50.0, speedMultiplier: Double = 0.75) { guard drawerPosition == .collapsed || drawerPosition == .partiallyRevealed else { print("Pulley: Error: You can only bounce the drawer when it's in the collapsed or partially revealed position.") return } guard currentDisplayMode == .drawer else { print("Pulley: Error: You can only bounce the drawer when it's in the .drawer display mode.") return } let drawerStartingBounds = drawerScrollView.bounds // Adapted from https://www.cocoanetics.com/2012/06/lets-bounce/ let factors: [CGFloat] = [0, 32, 60, 83, 100, 114, 124, 128, 128, 124, 114, 100, 83, 60, 32, 0, 24, 42, 54, 62, 64, 62, 54, 42, 24, 0, 18, 28, 32, 28, 18, 0] var values = [CGFloat]() for factor in factors { let positionOffset = (factor / 128.0) * bounceHeight values.append(drawerStartingBounds.origin.y + positionOffset) } let animation = CAKeyframeAnimation(keyPath: "bounds.origin.y") animation.repeatCount = 1 animation.duration = (32.0/30.0) * speedMultiplier animation.fillMode = CAMediaTimingFillMode.forwards animation.values = values animation.isRemovedOnCompletion = true animation.autoreverses = false drawerScrollView.layer.add(animation, forKey: "bounceAnimation") } /** Get a frame for moving backgroundDimmingView according to drawer position. - parameter drawerPosition: drawer position in points - returns: a frame for moving backgroundDimmingView according to drawer position */ private func backgroundDimmingViewFrameForDrawerPosition(_ drawerPosition: CGFloat) -> CGRect { let cutoutHeight = (2 * drawerCornerRadius) var backgroundDimmingViewFrame = backgroundDimmingView.frame backgroundDimmingViewFrame.origin.y = 0 - drawerPosition + cutoutHeight return backgroundDimmingViewFrame } private func syncDrawerContentViewSizeToMatchScrollPositionForSideDisplayMode() { guard currentDisplayMode == .panel else { return } let lowestStop = getStopList().min() ?? 0 drawerContentContainer.frame = CGRect(x: 0.0, y: drawerScrollView.bounds.height - lowestStop , width: drawerScrollView.bounds.width, height: drawerScrollView.contentOffset.y + lowestStop + bounceOverflowMargin) drawerBackgroundVisualEffectView?.frame = drawerContentContainer.frame drawerShadowView.frame = drawerContentContainer.frame // Update rounding mask and shadows let borderPath = drawerMaskingPath(byRoundingCorners: [.topLeft, .topRight, .bottomLeft, .bottomRight]).cgPath let cardMaskLayer = CAShapeLayer() cardMaskLayer.path = borderPath cardMaskLayer.frame = drawerContentContainer.bounds cardMaskLayer.fillColor = UIColor.white.cgColor cardMaskLayer.backgroundColor = UIColor.clear.cgColor drawerContentContainer.layer.mask = cardMaskLayer maskDrawerVisualEffectView() if !isAnimatingDrawerPosition || borderPath.boundingBox.height < drawerShadowView.layer.shadowPath?.boundingBox.height ?? 0.0 { drawerShadowView.layer.shadowPath = borderPath } } // MARK: Configuration Updates /** Set the drawer position, with an option to animate. - parameter position: The position to set the drawer to. - parameter animated: Whether or not to animate the change. (Default: true) - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. (Default: nil) */ @objc public func setDrawerPosition(position: PulleyPosition, animated: Bool, completion: PulleyAnimationCompletionBlock? = nil) { guard supportedPositions.contains(position) else { print("PulleyViewController: You can't set the drawer position to something not supported by the current view controller contained in the drawer. If you haven't already, you may need to implement the PulleyDrawerViewControllerDelegate.") return } drawerPosition = position var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultCollapsedHeight partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultPartialRevealHeight } let stopToMoveTo: CGFloat switch drawerPosition { case .collapsed: stopToMoveTo = collapsedHeight case .partiallyRevealed: stopToMoveTo = partialRevealHeight case .open: stopToMoveTo = heightOfOpenDrawer case .closed: stopToMoveTo = 0 default: stopToMoveTo = 0 } let lowestStop = getStopList().min() ?? 0 triggerFeedbackGenerator() if animated && self.view.window != nil { isAnimatingDrawerPosition = true UIView.animate(withDuration: animationDuration, delay: animationDelay, usingSpringWithDamping: animationSpringDamping, initialSpringVelocity: animationSpringInitialVelocity, options: animationOptions, animations: { [weak self] () -> Void in self?.drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false) // Move backgroundDimmingView to avoid drawer background being darkened self?.backgroundDimmingView.frame = self?.backgroundDimmingViewFrameForDrawerPosition(stopToMoveTo) ?? CGRect.zero if let drawer = self { drawer.delegate?.drawerPositionDidChange?(drawer: drawer, bottomSafeArea: self?.pulleySafeAreaInsets.bottom ?? 0.0) (drawer.drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: drawer, bottomSafeArea: self?.pulleySafeAreaInsets.bottom ?? 0.0) (drawer.primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: drawer, bottomSafeArea: self?.pulleySafeAreaInsets.bottom ?? 0.0) drawer.view.layoutIfNeeded() } }, completion: { [weak self] (completed) in self?.isAnimatingDrawerPosition = false self?.syncDrawerContentViewSizeToMatchScrollPositionForSideDisplayMode() completion?(completed) }) } else { drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false) // Move backgroundDimmingView to avoid drawer background being darkened backgroundDimmingView.frame = backgroundDimmingViewFrameForDrawerPosition(stopToMoveTo) delegate?.drawerPositionDidChange?(drawer: self, bottomSafeArea: pulleySafeAreaInsets.bottom) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: self, bottomSafeArea: pulleySafeAreaInsets.bottom) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: self, bottomSafeArea: pulleySafeAreaInsets.bottom) completion?(true) } } /** Set the drawer position, by default the change will be animated. Deprecated. Recommend switching to the other setDrawerPosition method, this one will be removed in a future release. - parameter position: The position to set the drawer to. - parameter isAnimated: Whether or not to animate the change. Default: true */ @available(*, deprecated) public func setDrawerPosition(position: PulleyPosition, isAnimated: Bool = true) { setDrawerPosition(position: position, animated: isAnimated) } /** Change the current primary content view controller (The one behind the drawer) - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. Defaults to true. - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. */ public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true, completion: PulleyAnimationCompletionBlock?) { // Account for transition issue in iOS 11 controller.view.frame = primaryContentContainer.bounds controller.view.layoutIfNeeded() if animated { UIView.transition(with: primaryContentContainer, duration: 0.5, options: .transitionCrossDissolve, animations: { [weak self] () -> Void in self?.primaryContentViewController = controller }, completion: { (completed) in completion?(completed) }) } else { primaryContentViewController = controller completion?(true) } } /** Change the current primary content view controller (The one behind the drawer). This method exists for backwards compatibility. - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. Defaults to true. */ public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true) { setPrimaryContentViewController(controller: controller, animated: animated, completion: nil) } /** Change the current drawer content view controller (The one inside the drawer) - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. */ @objc public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true, completion: PulleyAnimationCompletionBlock?) { // Account for transition issue in iOS 11 controller.view.frame = drawerContentContainer.bounds controller.view.layoutIfNeeded() if animated { UIView.transition(with: drawerContentContainer, duration: 0.5, options: .transitionCrossDissolve, animations: { [weak self] () -> Void in self?.drawerContentViewController = controller self?.setDrawerPosition(position: self?.drawerPosition ?? .collapsed, animated: false) }, completion: { (completed) in completion?(completed) }) } else { drawerContentViewController = controller setDrawerPosition(position: drawerPosition, animated: false) completion?(true) } } /** Change the current drawer content view controller (The one inside the drawer). This method exists for backwards compatibility. - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. */ @objc public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true) { setDrawerContentViewController(controller: controller, animated: animated, completion: nil) } /** Update the supported drawer positions allows by the Pulley Drawer */ public func setNeedsSupportedDrawerPositionsUpdate() { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { supportedPositions = drawerVCCompliant.supportedDrawerPositions?() ?? PulleyPosition.artsy } else { supportedPositions = PulleyPosition.artsy } } // MARK: Actions @objc func dimmingViewTapRecognizerAction(gestureRecognizer: UITapGestureRecognizer) { if gestureRecognizer == dimmingViewTapRecognizer { if gestureRecognizer.state == .ended { self.setDrawerPosition(position: .collapsed, animated: true) } } } // MARK: Propogate child view controller style / status bar presentation based on drawer state override open var childForStatusBarStyle: UIViewController? { get { if drawerPosition == .open { return drawerContentViewController } return primaryContentViewController } } override open var childForStatusBarHidden: UIViewController? { get { if drawerPosition == .open { return drawerContentViewController } return primaryContentViewController } } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) if #available(iOS 10.0, *) { coordinator.notifyWhenInteractionChanges { [weak self] context in guard let currentPosition = self?.drawerPosition else { return } self?.setDrawerPosition(position: currentPosition, animated: false) } } else { coordinator.notifyWhenInteractionEnds { [weak self] context in guard let currentPosition = self?.drawerPosition else { return } self?.setDrawerPosition(position: currentPosition, animated: false) } } } // MARK: PulleyDrawerViewControllerDelegate implementation for nested Pulley view controllers in drawers. Implemented here, rather than an extension because overriding extensions in subclasses isn't good practice. Some developers want to subclass Pulley and customize these behaviors, so we'll move them here. open func collapsedDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate, let collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: bottomSafeArea) { return collapsedHeight } else { return 68.0 + bottomSafeArea } } open func partialRevealDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate, let partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: bottomSafeArea) { return partialRevealHeight } else { return 264.0 + bottomSafeArea } } open func supportedDrawerPositions() -> [PulleyPosition] { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate, let supportedPositions = drawerVCCompliant.supportedDrawerPositions?() { return supportedPositions } else { return PulleyPosition.artsy } } open func drawerPositionDidChange(drawer: PulleyViewController, bottomSafeArea: CGFloat) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.drawerPositionDidChange?(drawer: drawer, bottomSafeArea: bottomSafeArea) } } open func makeUIAdjustmentsForFullscreen(progress: CGFloat, bottomSafeArea: CGFloat) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.makeUIAdjustmentsForFullscreen?(progress: progress, bottomSafeArea: bottomSafeArea) } } open func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat, bottomSafeArea: CGFloat) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.drawerChangedDistanceFromBottom?(drawer: drawer, distance: distance, bottomSafeArea: bottomSafeArea) } } } extension PulleyViewController: PulleyPassthroughScrollViewDelegate { func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool { return !drawerContentContainer.bounds.contains(drawerContentContainer.convert(point, from: scrollView)) } func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> UIView { if currentDisplayMode == .drawer { if drawerPosition == .open { return backgroundDimmingView } return primaryContentContainer } else { if drawerContentContainer.bounds.contains(drawerContentContainer.convert(point, from: scrollView)) { return drawerContentViewController.view } return primaryContentContainer } } } extension PulleyViewController: UIScrollViewDelegate { public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if scrollView == drawerScrollView { let lastDragTargetContentOffset = targetContentOffset.pointee // Find the closest anchor point and snap there. var collapsedHeight: CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight: CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultCollapsedHeight partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultPartialRevealHeight } var drawerStops: [CGFloat] = [CGFloat]() var currentDrawerPositionStop: CGFloat = 0.0 if supportedPositions.contains(.open) { drawerStops.append(heightOfOpenDrawer) if drawerPosition == .open { currentDrawerPositionStop = drawerStops.last! } } if supportedPositions.contains(.partiallyRevealed) { drawerStops.append(partialRevealHeight) if drawerPosition == .partiallyRevealed { currentDrawerPositionStop = drawerStops.last! } } if supportedPositions.contains(.collapsed) { drawerStops.append(collapsedHeight) if drawerPosition == .collapsed { currentDrawerPositionStop = drawerStops.last! } } let lowestStop = drawerStops.min() ?? 0 let distanceFromBottomOfView = lowestStop + lastDragTargetContentOffset.y var currentClosestStop = lowestStop for currentStop in drawerStops { if abs(currentStop - distanceFromBottomOfView) < abs(currentClosestStop - distanceFromBottomOfView) { currentClosestStop = currentStop } } var closestValidDrawerPosition: PulleyPosition = drawerPosition if abs(Float(currentClosestStop - heightOfOpenDrawer)) <= Float.ulpOfOne && supportedPositions.contains(.open) { closestValidDrawerPosition = .open } else if abs(Float(currentClosestStop - collapsedHeight)) <= Float.ulpOfOne && supportedPositions.contains(.collapsed) { closestValidDrawerPosition = .collapsed } else if supportedPositions.contains(.partiallyRevealed) { closestValidDrawerPosition = .partiallyRevealed } let snapModeToUse: PulleySnapMode = closestValidDrawerPosition == drawerPosition ? snapMode : .nearestPosition if case .nearestPositionUnlessExceeded(let threshold) = snapModeToUse { let distance = currentDrawerPositionStop - distanceFromBottomOfView var positionToSnapTo: PulleyPosition = drawerPosition if abs(distance) > threshold { if distance < 0 { let orderedSupportedDrawerPositions = supportedPositions.sorted(by: { $0.rawValue < $1.rawValue }).filter({ $0 != .closed }) for position in orderedSupportedDrawerPositions { if position.rawValue > drawerPosition.rawValue { positionToSnapTo = position break } } } else { let orderedSupportedDrawerPositions = supportedPositions.sorted(by: { $0.rawValue > $1.rawValue }).filter({ $0 != .closed }) for position in orderedSupportedDrawerPositions { if position.rawValue < drawerPosition.rawValue { positionToSnapTo = position break } } } } closestValidDrawerPosition = positionToSnapTo } self.drawerPosition = closestValidDrawerPosition let stopToMoveTo: CGFloat switch drawerPosition { case .collapsed: stopToMoveTo = collapsedHeight case .partiallyRevealed: stopToMoveTo = partialRevealHeight case .open: stopToMoveTo = heightOfOpenDrawer case .closed: stopToMoveTo = 0 default: stopToMoveTo = 0 } triggerFeedbackGenerator() let desiredComputedDrawerPositionContentOffset = CGPoint(x: 0, y: stopToMoveTo - lowestStop) targetContentOffset.pointee = desiredComputedDrawerPositionContentOffset self.delegate?.drawerPositionDidChange?(drawer: self, bottomSafeArea: self.pulleySafeAreaInsets.bottom) (self.drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: self, bottomSafeArea: self.pulleySafeAreaInsets.bottom) (self.primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: self, bottomSafeArea: self.pulleySafeAreaInsets.bottom) self.view.layoutIfNeeded() } } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { // if we're going to animate to rest, disable scrolling until we are stopped. if decelerate { scrollView.isScrollEnabled = false } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollView.isScrollEnabled = true } public func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == drawerScrollView { let partialRevealHeight: CGFloat = (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.partialRevealDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultPartialRevealHeight let lowestStop = getStopList().min() ?? 0 if (scrollView.contentOffset.y - pulleySafeAreaInsets.bottom) > partialRevealHeight - lowestStop && supportedPositions.contains(.open) { // Calculate percentage between partial and full reveal let fullRevealHeight = heightOfOpenDrawer let progress: CGFloat if fullRevealHeight == partialRevealHeight { progress = 1.0 } else { progress = (scrollView.contentOffset.y - (partialRevealHeight - lowestStop)) / (fullRevealHeight - (partialRevealHeight)) } delegate?.makeUIAdjustmentsForFullscreen?(progress: progress, bottomSafeArea: pulleySafeAreaInsets.bottom) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress, bottomSafeArea: pulleySafeAreaInsets.bottom) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress, bottomSafeArea: pulleySafeAreaInsets.bottom) backgroundDimmingView.alpha = progress * backgroundDimmingOpacity backgroundDimmingView.isUserInteractionEnabled = true } else { if backgroundDimmingView.alpha >= 0.001 { backgroundDimmingView.alpha = 0.0 delegate?.makeUIAdjustmentsForFullscreen?(progress: 0.0, bottomSafeArea: pulleySafeAreaInsets.bottom) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0, bottomSafeArea: pulleySafeAreaInsets.bottom) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0, bottomSafeArea: pulleySafeAreaInsets.bottom) backgroundDimmingView.isUserInteractionEnabled = false } } delegate?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom) // Move backgroundDimmingView to avoid drawer background beeing darkened backgroundDimmingView.frame = backgroundDimmingViewFrameForDrawerPosition(scrollView.contentOffset.y + lowestStop) syncDrawerContentViewSizeToMatchScrollPositionForSideDisplayMode() } } }
42.544341
356
0.650252
d7b92b0ae1f6f8de8d53d4c53fc212e58d3ad8c0
3,621
// // PublishSubject.swift // Rx // // Created by Krunoslav Zaher on 2/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents an object that is both an observable sequence as well as an observer. Each notification is broadcasted to all subscribed observers. */ final public class PublishSubject<Element> : Observable<Element> , SubjectType , Cancelable , ObserverType , SynchronizedUnsubscribeType { public typealias SubjectObserverType = PublishSubject<Element> typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType /** Indicates whether the subject has any observers */ public var hasObservers: Bool { _lock.lock(); defer { _lock.unlock() } return _observers.count > 0 } private var _lock = NSRecursiveLock() // state private var _disposed = false private var _observers = Bag<AnyObserver<Element>>() private var _stopped = false private var _stoppedEvent = nil as Event<Element>? /** Indicates whether the subject has been disposed. */ public var disposed: Bool { return _disposed } /** Creates a subject. */ public override init() { super.init() } /** Notifies all subscribed observers about next event. - parameter event: Event to send to the observers. */ public func on(event: Event<Element>) { _lock.lock(); defer { _lock.unlock() } _synchronized_on(event) } func _synchronized_on(event: Event<E>) { switch event { case .Next(_): if _disposed || _stopped { return } _observers.on(event) case .Completed, .Error: if _stoppedEvent == nil { _stoppedEvent = event _stopped = true _observers.on(event) _observers.removeAll() } } } /** Subscribes an observer to the subject. - parameter observer: Observer to subscribe to the subject. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable { _lock.lock(); defer { _lock.unlock() } return _synchronized_subscribe(observer) } func _synchronized_subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable { if let stoppedEvent = _stoppedEvent { observer.on(stoppedEvent) return NopDisposable.instance } if _disposed { observer.on(.Error(RxError.Disposed(object: self))) return NopDisposable.instance } let key = _observers.insert(observer.asObserver()) return SubscriptionDisposable(owner: self, key: key) } func synchronizedUnsubscribe(disposeKey: DisposeKey) { _lock.lock(); defer { _lock.unlock() } _synchronized_unsubscribe(disposeKey) } func _synchronized_unsubscribe(disposeKey: DisposeKey) { _ = _observers.removeKey(disposeKey) } /** Returns observer interface for subject. */ public func asObserver() -> PublishSubject<Element> { return self } /** Unsubscribe all observers and release resources. */ public func dispose() { _lock.lock(); defer { _lock.unlock() } _synchronized_dispose() } final func _synchronized_dispose() { _disposed = true _observers.removeAll() _stoppedEvent = nil } }
26.05036
102
0.619718
67e1571e5d0a8464452a301da389181e3df5b5a2
1,117
// // Copyright © 2022 Alexander Romanov // TextBox.swift // import SwiftUI public struct TextBox: View { @Environment(\.multilineTextAlignment) var multilineTextAlignment let title: String let subtitle: String? public init(title: String, subtitle: String?) { self.title = title self.subtitle = subtitle } public init(title: String) { self.title = title subtitle = nil } public var body: some View { VStack(alignment: vStackAlignment, spacing: .medium) { Text(title) .fontStyle(.title3, color: .onSurfaceHighEmphasis) if let subtitle = subtitle { Text(subtitle) .fontStyle(.paragraph1, color: .onSurfaceHighEmphasis) } } .multilineTextAlignment(multilineTextAlignment) } var vStackAlignment: HorizontalAlignment { switch multilineTextAlignment { case .leading: return .leading case .center: return .center case .trailing: return .trailing } } }
23.270833
74
0.585497
6a76b38079b78b3e64a2aeb96e141a9fd7ff6526
338
import Foundation if let argument = CommandLine.arguments.dropFirst().first { let ext: CFString = argument as NSString if let str = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext, nil)?.takeUnretainedValue() { print(str) } else { print("fail to search UTI: \(argument)") } }
26
119
0.689349
29cb21c991d5509a84f69a257f7659da11926eb2
1,726
import SwiftQuantumComputing // for macOS let circuitFactory = MainCircuitFactory() let drawer = MainDrawerFactory().makeDrawer() func isFunctionConstant(truthTable: [String], qubitCount: Int) -> Bool { var gates = [Gate.not(target: 0)] gates += Gate.hadamard(targets: 0...qubitCount) gates += [Gate.oracle(truthTable: truthTable, controls: (1...qubitCount).reversed(), target: 0)] gates += Gate.hadamard(targets: 1...qubitCount) try! drawer.drawCircuit(gates).get() let circuit = circuitFactory.makeCircuit(gates: gates) let statevector = try! circuit.statevector().get() let probabilities = try! statevector.summarizedProbabilities(byQubits: (1...qubitCount).reversed()).get() let zeros = String(repeating: "0", count: qubitCount) let zerosProbabilities = probabilities[zeros] ?? 0.0 return (abs(1.0 - zerosProbabilities) < 0.000000001) } func makeQubitCombinations(qubitCount: Int) -> [String] { return (0..<Int.pow(2, qubitCount)).map { String($0, bitCount: qubitCount) } } func selectHalfQubitCombinations(_ combinations: [String]) -> [String] { return combinations.randomElements(count: combinations.count / 2) } let qubitCount = 3 print("Funtion: f(<Any input>) = 0") print("Is it constant? \(isFunctionConstant(truthTable: [], qubitCount: qubitCount)) \n") print("Funtion: f(<Any input>) = 1") let truthtable = makeQubitCombinations(qubitCount: qubitCount) print("Is it constant? \(isFunctionConstant(truthTable: truthtable, qubitCount: qubitCount)) \n") print("Funtion: f(<Half inputs>) = 1") let halfTruthtable = selectHalfQubitCombinations(truthtable) print("Is it constant? \(isFunctionConstant(truthTable: halfTruthtable, qubitCount: qubitCount))")
39.227273
109
0.725956
297c6bf55037e2031fcf9a5625203f5ad0b63153
9,538
// // BPBannerView.swift // BPCartoonProject // // Created by baipeng on 2019/7/9. // Copyright © 2019 Apple Inc. All rights reserved. // import UIKit class BPBannerBackView: UIView { var imageView: UIImageView? var label: UILabel? var subImgView: UIImageView? override init(frame: CGRect) { super.init(frame: frame) clipsToBounds = true imageView = UIImageView() imageView?.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: frame.size.height) self.addSubview(imageView!) let hintImgView = UIImageView() hintImgView.frame = CGRect(x: 0, y: frame.size.height - 100, width: KScreenWidth, height: 100) hintImgView.image = UIImage.init(named: "banner_back") self.addSubview(hintImgView) subImgView = UIImageView() subImgView?.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: frame.size.height) self.addSubview(subImgView!) label = UILabel() label?.textAlignment = .center label?.textColor = UIColor.white label?.font = UIFont.boldSystemFont(ofSize: 30) label?.frame = CGRect(x: 0, y: frame.size.height - KScale(70), width: KScreenWidth, height: KScale(40)) addSubview(label!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var imageOffSetX:CGFloat? { didSet{ self.imageView?.frame = CGRect(x: imageOffSetX!, y: 0, width: KScreenWidth, height: self.frame.size.height) } } var subImageOffSetX:CGFloat? { didSet{ UIView.animate(withDuration: 0.2, animations: { self.subImgView?.frame = CGRect(x: -(self.subImageOffSetX! / 5), y: 0, width: KScreenWidth, height: self.frame.size.height) }) } } } class BPBannerView: UIView,UIScrollViewDelegate{ lazy var scrollView = UIScrollView.init() lazy var pageControl = UIPageControl.init() var timer:Timer? var starCurrentOffSetX:CGFloat = 0 let AnimationOffset = KScale(100) //MARK: - life cyle 1、初始化方法 override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white createSubViewUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - 2、不同业务处理之间的方法以 var itemsArray:[GalleryItemModel]?{ didSet{ self.scrollView.subviews.forEach { (subView) in subView.removeFromSuperview() } for idx in 0..<itemsArray!.count + 2 { let bannerBackView = BPBannerBackView.init(frame: CGRect(x: CGFloat(idx)*KScreenWidth, y: 0, width: KScreenWidth, height: KScreenWidth)) self.scrollView.addSubview(bannerBackView) let tap = UITapGestureRecognizer.init(target: self, action: #selector(imageTapAction(_:))) bannerBackView.addGestureRecognizer(tap) var tag = 0; if (idx == 0) { tag = itemsArray!.count; } else if (idx == itemsArray!.count + 1) { tag = 1; } else { tag = idx; } bannerBackView.tag = idx+100; let model = itemsArray![tag - 1] bannerBackView.label?.text = model.title ?? "" //-- layer添加阴影 bannerBackView.label?.layer.shadowColor = UIColor.black.cgColor bannerBackView.label?.layer.shadowOffset = CGSize(width: 0, height: 0) bannerBackView.label?.layer.shadowRadius = 15 bannerBackView.label?.layer.shadowOpacity = 1 bannerBackView.imageView?.kf.setImage(with: URL(string: model.cover!)) bannerBackView.subImgView?.kf.setImage(with: URL(string: model.topCover!)) } self.scrollView.contentSize = CGSize(width: KScreenWidth * CGFloat(itemsArray!.count+2), height: KScreenWidth) self.scrollView.contentOffset = CGPoint(x: KScreenWidth, y: 0) self.pageControl.numberOfPages = itemsArray!.count //开启定时器 removeTimer() addTimer() } } //MARK: - Network 3、网络请求 //MARK: - Action Event 4、响应事件 ///点击图片 @objc func imageTapAction(_ tap:UITapGestureRecognizer) { print(tap.view?.tag) } //MARK: - Call back 5、回调事件 ///MARK: - Timer func addTimer() { timer = Timer.init(timeInterval: 5, repeats: true, block: { (time) in self.nextImage() }) RunLoop.current.add(timer!, forMode: RunLoop.Mode.common) } func removeTimer() { if timer != nil { timer!.invalidate() } } func nextImage() { let currentPage = self.pageControl.currentPage self.scrollView.setContentOffset(CGPoint(x: CGFloat(currentPage + 2) * KScreenWidth, y: 0), animated: true) } //MARK: - Delegate 6、代理、数据源 func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollW = self.scrollView.frame.size.width; let currentPage:CGFloat = CGFloat(self.scrollView.contentOffset.x / scrollW); if (Int(currentPage) == self.itemsArray!.count + 1) { self.pageControl.currentPage = 0; } else if (currentPage == 0) { self.pageControl.currentPage = self.itemsArray!.count; } else { self.pageControl.currentPage = Int(currentPage - 1); } let offsetX = scrollView.contentOffset.x if Int(currentPage+1) >= scrollView.subviews.count { return } //-- leftView和rightView是滚动时可见的两个视图,一个当前视图,一个将要进入的视图 let leftView:BPBannerBackView = scrollView.viewWithTag(Int(currentPage + 100)) as! BPBannerBackView let rightView:BPBannerBackView = scrollView.viewWithTag(Int(currentPage + 1 + 100)) as! BPBannerBackView //向右滑动,a为负值, 需要移动距离长度 +(偏移a值(KScreenWidth - AnimationOffset)比例上的值), 从a值开始太小,加上总移动位置=进行动画宽度 //向左滑动,a为正值, -需要移动距离长度 +(偏移a值-(KScreenWidth - AnimationOffset)比例上的值),获得负的远距离x值=进行动画宽度小值 if starCurrentOffSetX > offsetX {//向右 NSLog("向右"); let tempOffSetX = CGFloat(-(KScreenWidth - AnimationOffset)) + (offsetX - (currentPage * KScreenWidth)) / KScreenWidth * CGFloat((KScreenWidth - AnimationOffset)) rightView.imageOffSetX = tempOffSetX rightView.subImageOffSetX = tempOffSetX leftView.imageOffSetX = 0 leftView.subImageOffSetX = CGFloat((KScreenWidth - AnimationOffset)) + (offsetX - ((currentPage + 1) * KScreenWidth)) / KScreenWidth * CGFloat((KScreenWidth - AnimationOffset)) } if starCurrentOffSetX < offsetX {//向左 NSLog("向左"); let tempOffSetX: CGFloat = CGFloat((KScreenWidth - AnimationOffset)) + (offsetX - ((currentPage + 1) * KScreenWidth)) / KScreenWidth * CGFloat((KScreenWidth - AnimationOffset)) leftView.imageOffSetX = tempOffSetX leftView.subImageOffSetX = tempOffSetX rightView.imageOffSetX = 0 rightView.subImageOffSetX = CGFloat(-(KScreenWidth - AnimationOffset)) + (offsetX - (currentPage * KScreenWidth)) / KScreenWidth * CGFloat((KScreenWidth - AnimationOffset)) } } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { self.scrollViewDidEndDecelerating(scrollView) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let scrollW = self.scrollView.frame.size.width; let currentPage:Int = Int(self.scrollView.contentOffset.x / scrollW); if (currentPage == self.itemsArray!.count + 1) { self.pageControl.currentPage = 0; self.scrollView.setContentOffset(CGPoint(x: scrollW, y: 0), animated: false) } else if (currentPage == 0) { self.pageControl.currentPage = self.itemsArray!.count; self.scrollView.setContentOffset(CGPoint(x: CGFloat(self.itemsArray!.count) * scrollW, y: 0), animated: false) } else { self.pageControl.currentPage = currentPage - 1; } for view in scrollView.subviews { if view.isEqual(BPBannerBackView.self){ let v:BPBannerBackView = view as! BPBannerBackView v.imageOffSetX = 0 v.subImageOffSetX = 0 } } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeTimer() starCurrentOffSetX = self.scrollView.contentOffset.x; } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { removeTimer() self.addTimer() } //MARK: - interface 7、UI处理 func createSubViewUI() { self.scrollView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenWidth) self.scrollView.delegate = self self.scrollView.isPagingEnabled = true self.scrollView.bounces = false self.scrollView.showsHorizontalScrollIndicator = false self.addSubview(self.scrollView) self.pageControl.frame = CGRect(x: 0, y: KScreenWidth - 30, width: KScreenWidth/3, height: 30) self.pageControl.pageIndicatorTintColor = UIColor.white self.pageControl.currentPageIndicatorTintColor = UIColor.red self.addSubview(self.pageControl) } //MARK: - lazy loading 8、懒加载 }
36.40458
188
0.621409
4628393bf264edc0c4d1ac378e0fc0b400e6294f
8,090
// // AlamofireExtensionTests.swift // Serializable // // Created by Chris Combs on 18/03/16. // Copyright © 2016 Nodes. All rights reserved. // import XCTest import Serpent import Alamofire class AlamofireExtensionTests: XCTestCase { let timeoutDuration = 2.0 let manager = SessionManager() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } func urlForResource(resource: String) -> URL? { if let path = Bundle(for: type(of: self)).path(forResource: resource, ofType: "json") { return URL(fileURLWithPath: path) } return nil } func testAlamofireExtension() { let expectation = self.expectation(description: "Expected network request success") let handler:(Alamofire.DataResponse<NetworkTestModel>) -> Void = { result in switch result.result { case .success: expectation.fulfill() default: print(result) break // Fail } } if let url = urlForResource(resource: "NetworkModel") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireExtensionBadJSON() { let expectation = self.expectation(description: "Expected bad data from response") let handler:(Alamofire.DataResponse<NetworkTestModel>) -> Void = { result in switch result.result { case .failure: expectation.fulfill() default: break } } if let url = urlForResource(resource: "NetworkModelBad") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireExtensionBadJSONObject() { let expectation = self.expectation(description: "Expected bad object from response") let handler:(Alamofire.DataResponse<[NetworkTestModel]>) -> Void = { result in switch result.result { case .failure: expectation.fulfill() default: break } } if let url = urlForResource(resource: "NetworkModel") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireExtensionUnexpectedArrayJSON() { let expectation = self.expectation(description: "Expected array data to single object from response") let handler:(Alamofire.DataResponse<DecodableModel>) -> Void = { result in switch result.result { case .failure: expectation.fulfill() default: break } } if let url = urlForResource(resource: "ArrayTest") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireExtensionEmptyJSON() { let expectation = self.expectation(description: "Expected empty response") let handler:(Alamofire.DataResponse<NetworkTestModel>) -> Void = { result in switch result.result { case .failure: expectation.fulfill() default: break } } if let url = urlForResource(resource: "Empty") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireArrayUnwrapper() { let expectation = self.expectation(description: "Expected unwrapped array response") let handler:(Alamofire.DataResponse<[DecodableModel]>) -> Void = { result in switch result.result { case .success: expectation.fulfill() default: break } } let unwrapper: Parser.Unwrapper = { dict, _ in dict["data"] } if let url = urlForResource(resource: "NestedArrayTest") { manager.request(url, method: .get).responseSerializable(handler, unwrapper: unwrapper) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireArrayNotUnwrapped() { let expectation = self.expectation(description: "Expected unwrapped array response") let handler:(Alamofire.DataResponse<[DecodableModel]>) -> Void = { result in switch result.result { case .failure: expectation.fulfill() default: break } } if let url = urlForResource(resource: "NestedArrayTest") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireWrongTypeUnwrapper() { let expectation = self.expectation(description: "Expected unwrapped array response") let handler:(Alamofire.DataResponse<DecodableModel>) -> Void = { result in switch result.result { case .success: expectation.fulfill() default: break } } let unwrapper: Parser.Unwrapper = { dict, _ in ["data"] } if let url = urlForResource(resource: "NestedArrayTest") { manager.request(url, method: .get).responseSerializable(handler, unwrapper: unwrapper) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireExtensionNonSerializable() { let expectation = self.expectation(description: "Expected empty response") let handler:(Alamofire.DataResponse<NilSerializable>) -> Void = { result in switch result.result { case .failure: expectation.fulfill() default: break } } if let url = urlForResource(resource: "Empty") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireExtensionArrayRootObjectParsingToOne() { let expectation = self.expectation(description: "Expected valid object") let handler:(Alamofire.DataResponse<DecodableModel>) -> Void = { result in switch result.result { case .success(let value): XCTAssertEqual(value.id, 1) XCTAssertEqual(value.name, "Hello") expectation.fulfill() default: break } } if let url = urlForResource(resource: "ArrayTestOneObject") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireExtensionArrayRootObjectParsingToOneWithWrongUnwrapper() { let expectation = self.expectation(description: "Expected valid object") let handler:(Alamofire.DataResponse<DecodableModel>) -> Void = { result in switch result.result { case .success(let value): XCTAssertEqual(value.id, 1) XCTAssertEqual(value.name, "Hello") expectation.fulfill() default: break } } let unwrapper: Parser.Unwrapper = { dict, _ in ["nonexistent"] } if let url = urlForResource(resource: "ArrayTestOneObject") { manager.request(url, method: .get).responseSerializable(handler, unwrapper: unwrapper) } waitForExpectations(timeout: timeoutDuration, handler: nil) } func testAlamofireExtensionArrayRootObjectParsingToMultiple() { let expectation = self.expectation(description: "Expected valid array") let handler:(Alamofire.DataResponse<[DecodableModel]>) -> Void = { result in switch result.result { case .success(let values): XCTAssertEqual(values.count, 4) XCTAssertEqual(values[0].id, 1) XCTAssertEqual(values[0].name, "Hello") XCTAssertEqual(values[3].id, 4) XCTAssertEqual(values[3].name, "Hello4") expectation.fulfill() default: break } } if let url = urlForResource(resource: "ArrayTest") { manager.request(url, method: .get).responseSerializable(handler) } waitForExpectations(timeout: timeoutDuration, handler: nil) } }
33.155738
109
0.663906
d67ed2f47c45c376961f29a2ef51220c359e8809
1,546
// // SettingsProvider.swift // happyhouse // // Copyright © 2019 Depromeet. All rights reserved. // extension UserDefaults { // Basic values subscript<T>(key: String) -> T? { get { return value(forKey: key) as? T } set { set(newValue, forKey: key) } } // Enums subscript<T: RawRepresentable>(key: String) -> T? { get { if let rawValue = value(forKey: key) as? T.RawValue { return T(rawValue: rawValue) } return nil } set { set(newValue?.rawValue, forKey: key) } } } class SettingsProvider { static let shared = SettingsProvider() var isUserLoggedIn: Bool { get { return UserDefaults.standard[#function] ?? false } set { UserDefaults.standard[#function] = newValue } } var userUid: Int { get { return UserDefaults.standard[#function] ?? 0 } set { UserDefaults.standard[#function] = newValue } } var userProfileUrl: String { get { return UserDefaults.standard[#function] ?? "" } set { UserDefaults.standard[#function] = newValue } } var userNickname: String { get { return UserDefaults.standard[#function] ?? "" } set { UserDefaults.standard[#function] = newValue } } }
20.613333
65
0.489004
2fc733e330a5eff327ef5881bfac30b0e57d968f
1,334
// // Model.swift // TMModel // // Created by CaptainTeemo on 5/10/16. // Copyright © 2016 CaptainTeemo. All rights reserved. // import Foundation import TMModel final class Student: NSObject, JSONConvertible { var id = "" var name = "" var sampleDigit = "" var sampleFloat = "" var sampleArray = [Int]() var sampleDic = [String: AnyObject]() } final class User: NSObject, JSONConvertible { var id = "" var name = "" var email = "" var address = [String: AnyObject]() var phone = "" var website = "" var company = [String: AnyObject]() func printDescription() { print("id: \(id)\n name: \(name)\n email: \(email)\n address: \(address)\n phone: \(phone)\n website: \(website)\n company: \(company)") } } public final class Media: NSObject, JSONConvertible { public var type = "" public var videos = [String: AnyObject]() public var users_in_photo = [String: AnyObject]() public var filter = "" public var tags = [String]() public var comments = [String: AnyObject]() public var caption = "" public var likes = [String]() public var link = "" public var user = [String: AnyObject]() public var created_time = "" public var images = [String: AnyObject]() public var id = "" public var location = "" }
26.68
144
0.612444
d66a0284353a005402e4de82550b170c69b607e5
2,183
// // AppDelegate.swift // CustomScrollView // // Created by SaTHEEsH KaNNaN on 05/05/17. // Copyright © 2017 SKannaniOS. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.446809
285
0.756757
f40e18ab554fda09758dc07bbd5ebc4f8dd26d51
314
// // Location.swift // RainyShiny // // Created by Settar Hummetli on 7/18/17. // Copyright © 2017 Settar Hummetli. All rights reserved. // import CoreLocation class Location { static var sharedInstance = Location() private init() {} var latitude: Double! var longitude: Double! }
16.526316
58
0.652866
1a92f9a987cd51fe69f8cfa1ddcf78ca4d170573
498
// // Tree.Language.swift // SwiftySyntax // // Created by Haider Khan on 8/25/19. // Copyright © 2019 zkhaider. All rights reserved. // import Foundation public enum SyntaxLanguage { case json case swift // case python // case php // case rust internal var tsLanguage: UnsafePointer<TSLanguage>? { switch self { case .json: return tree_sitter_json() case .swift: return tree_sitter_swift() } } }
17.785714
57
0.584337
6189821938b5b0d90e1bf813bee96d8c00632bd7
168
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" func yo(name: String) -> String { return name } yo("Lucas")
14
52
0.64881
20aac01c00f5492f047d3da9224f7c71a81e3744
879
// // ComparableExtensionsTests.swift // SwifterSwift // // Created by Shai Mishali on 5/4/18. // Copyright © 2018 SwifterSwift // import XCTest @testable import SwifterSwift final class ComparableExtensionsTests: XCTestCase { func testIsBetween() { XCTAssertFalse(1.isBetween(5...7), "number range") XCTAssertTrue(7.isBetween(6...12), "number range") XCTAssertTrue(0.32.isBetween(0.31...0.33), "float range") XCTAssertTrue("c".isBetween("a"..."d"), "string range") let date = Date() XCTAssertTrue(date.isBetween(date...date.addingTimeInterval(1000)), "date range") } func testClamped() { XCTAssertEqual(1.clamped(to: 3...8), 3) XCTAssertEqual(4.clamped(to: 3...7), 4) XCTAssertEqual("c".clamped(to: "e"..."g"), "e") XCTAssertEqual(0.32.clamped(to: 0.37...0.42), 0.37) } }
27.46875
89
0.626849
1cad8d3bc34876be8505443b43c05ac69f0d2758
1,658
class Square : Hashable { static let minOrdinate = 0 static let maxOrdinate = 7 static let rankChars = ["a", "b", "c", "d", "e", "f", "g", "h"] let rank: Int // ranks are rows. let file: Int // files are columns. let color: Color var hashValue: Int { var hash = 17 hash = 19 * hash + rank hash = 23 * hash + file return hash } init(rank: Int, file: Int) { self.rank = rank self.file = file self.color = (rank - file) % 2 == 0 ? Color.black : Color.white precondition( rank >= Square.minOrdinate && rank <= Square.maxOrdinate && file >= Square.minOrdinate && file <= Square.maxOrdinate, "Rank and file should both be between 0 and 7. Given: rank: \(rank), file: \(file)") } func getPrintableColor() -> String { return self.color == Color.black ? "■" : "☐" } func getNotation() -> String { return "\(Square.rankChars[rank])\(file+1)" } static func get(notation: String) -> Square { precondition(notation.count == 2, "Invalid notation for square: \(notation)") let rank = Square.rankChars.firstIndex(of: String(notation.prefix(1)).lowercased()) let file = Int(String(notation.suffix(1))) precondition( rank != nil && file != nil, "Invalid rank: \(rank as Optional), file: \(file as Optional) in notation: \(notation)") return Square(rank: rank!, file: file! - 1) } } func == (square1: Square, square2: Square) -> Bool { return square1.rank == square2.rank && square1.file == square2.file }
33.16
100
0.562123
0eedbb7ee2ebb5818436755c77bc32c3c5591bf0
746
import XCTest @testable import SOSwift class DataFeedTests: XCTestCase { static var allTests = [ ("testSchema", testSchema), ("testDecode", testDecode), ("testEncode", testEncode), ] public static var dataFeed: DataFeed { let dataFeed = DataFeed() return dataFeed } func testSchema() throws { XCTAssertEqual(DataFeed.schemaName, "DataFeed") } func testDecode() throws { let json = """ { } """ let dataFeed = try DataFeed.make(with: json) } func testEncode() throws { let dictionary = try DataFeedTests.dataFeed.asDictionary() } }
19.128205
66
0.525469
75c786285657f3dd167ca975b80e304dce0a9152
659
// // ContentViewModel.swift // iosApp // // Created by PeterSamokhin on 22.04.2020. // Copyright © 2020 VKSDKKotlinExample. All rights reserved. // import Foundation import SharedCode class ContentViewModel: ObservableObject { private let presenter = SampleCommonPresenter() @Published var message = "Hello, VK SDK Kotlin!" /// After the view is ready, request and show some information func onAttach() { let pashka = presenter.getPashkaProfile() let pashkaFullName = "\(pashka?.firstName ?? "unknown") \(pashka?.lastName ?? "unknown")" self.message = "Pashka's full name:\n\(pashkaFullName)" } }
26.36
97
0.676783
e527f5a0728c5f40b7e3dda73725e5a29667dfce
1,488
/* * Copyright 2020 Square 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 Workflow import XCTest final class WorkflowHostTests: XCTestCase { func test_updatedInputCausesRenderPass() { let host = WorkflowHost(workflow: TestWorkflow(step: .first)) XCTAssertEqual(1, host.rendering.value) host.update(workflow: TestWorkflow(step: .second)) XCTAssertEqual(2, host.rendering.value) } fileprivate struct TestWorkflow: Workflow { var step: Step enum Step { case first case second } struct State {} func makeInitialState() -> State { return State() } typealias Rendering = Int func render(state: State, context: RenderContext<TestWorkflow>) -> Rendering { switch step { case .first: return 1 case .second: return 2 } } } }
27.054545
86
0.631048
f52f13fbaab4748fc2bd1f71a21dda565b76ec87
438
// // ContentCellControllerNavigationHandling.swift // nemo // // Created by Andyy Hope on 13/8/18. // Copyright © 2018 Andyy Hope. All rights reserved. // import Foundation protocol NavigationRequesting: class { var navigationDelegate: NavigationDelegate? { get set } func navigationWillBegin(sender: Any) } protocol NavigationDelegate: class { func navigate(to navigation: NavigationDestinationType) }
19.909091
59
0.726027
3a5909db0a91951c2d73f0f27cee6e69723e2322
9,713
// // Copyright 2019-2020 NetFoundry, 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 // // https://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 NetworkExtension import CZiti class TunnelMgr: NSObject { var tpm:NETunnelProviderManager? var tunnelRestarting = false let ipcClient = IpcAppClient() typealias TunnelStateChangedCallback = ((NEVPNStatus)->Void) var tsChangedCallbacks:[TunnelStateChangedCallback] = [] #if targetEnvironment(simulator) var _status:NEVPNStatus = .disconnected var status:NEVPNStatus { get { return _status } set { _status = newValue let zidStore = ZitiIdentityStore() let (zids, _) = zidStore.loadAll() zids?.forEach { zid in if zid.isEnabled { zid.edgeStatus = ZitiIdentity.EdgeStatus(Date().timeIntervalSince1970, status: .Available) } _ = zidStore.store(zid) } tunnelStatusDidChange(Notification(name: NSNotification.Name.NEVPNStatusDidChange)) } } #else var status:NEVPNStatus { get { if let status = tpm?.connection.status { return status } return .invalid } } #endif static let shared = TunnelMgr() private override init() {} deinit { NotificationCenter.default.removeObserver(self) } typealias LoadCompletionHandler = (NETunnelProviderManager?, Error?) -> Void func loadFromPreferences(_ bid:String, _ completionHandler: LoadCompletionHandler? = nil) { var tpm = NETunnelProviderManager() NETunnelProviderManager.loadAllFromPreferences { [weak self] savedManagers, error in if let error = error { zLog.error(error.localizedDescription) completionHandler?(nil, error) return } if let savedManagers = savedManagers, savedManagers.count > 0 { tpm = savedManagers[0] } tpm.loadFromPreferences { error in if let error = error { zLog.error(error.localizedDescription) completionHandler?(nil, error) return } // This won't happen unless first time run and no profile preference has been imported if tpm.protocolConfiguration == nil { let providerProtocol = NETunnelProviderProtocol() providerProtocol.providerBundleIdentifier = bid let defaultProviderConf = ProviderConfig() providerProtocol.providerConfiguration = defaultProviderConf.createDictionary() providerProtocol.serverAddress = defaultProviderConf.ipAddress providerProtocol.username = defaultProviderConf.username tpm.protocolConfiguration = providerProtocol tpm.localizedDescription = defaultProviderConf.localizedDescription tpm.isEnabled = true tpm.saveToPreferences { error in if let error = error { zLog.error(error.localizedDescription) } else { zLog.info("Saved successfully. Re-loading preferences") // ios hack per apple forums (else NEVPNErrorDomain Code=1) tpm.loadFromPreferences { error in zLog.error("Re-loaded preferences, error=\(error != nil)") } } } } if let tmgr = self { // Get notified when tunnel status changes NotificationCenter.default.removeObserver(tmgr) NotificationCenter.default.addObserver(tmgr, selector: #selector(TunnelMgr.tunnelStatusDidChange(_:)), name: NSNotification.Name.NEVPNStatusDidChange, object: nil) tmgr.tpm = tpm // Get our logLevel from config if let conf = (tpm.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration { if let logLevel = conf[ProviderConfig.LOG_LEVEL] as? String { let li = Int32(logLevel) ?? ZitiLog.LogLevel.INFO.rawValue let ll = ZitiLog.LogLevel(rawValue: li) ?? ZitiLog.LogLevel.INFO zLog.info("Updating log level to \(logLevel) (\(ll))") ZitiLog.setLogLevel(ll) } } else { zLog.info("No log level found. Using default") } completionHandler?(tpm, nil) tmgr.tsChangedCallbacks.forEach { cb in cb(tmgr.status) } if tmgr.status != .disconnected { tmgr.ipcClient.startPolling() } } else { completionHandler?(nil, ZitiError("Tunnel preferencecs load fail due to retain scope")) } } } } @objc func tunnelStatusDidChange(_ notification: Notification?) { if tunnelRestarting == true { if status == .disconnected { tunnelRestarting = false try? startTunnel() } tsChangedCallbacks.forEach { cb in cb(.reasserting) } } else { tsChangedCallbacks.forEach { cb in cb(status) } } if status != .disconnected { ipcClient.startPolling() } else { ipcClient.stopPolling() } } func startTunnel() throws { guard let tpm = self.tpm else { return } if tpm.isEnabled { try (tpm.connection as? NETunnelProviderSession)?.startTunnel() } else { zLog.warn("startTunnel - tunnel not enabled. Re-enabling and starting tunnel") tpm.isEnabled = true tpm.saveToPreferences { error in if let error = error { zLog.error(error.localizedDescription) } else { zLog.info("Saved successfully. Re-loading preferences") // ios hack per apple forums (else NEVPNErrorDomain Code=1 on starting tunnel) tpm.loadFromPreferences { [weak tpm] error in zLog.error("Re-loaded preferences, error=\(error != nil). Attempting to start") do { try (tpm?.connection as? NETunnelProviderSession)?.startTunnel() } catch { zLog.error("Failed starting tunnel after re-enabling. \(error.localizedDescription)") } } } } } } func stopTunnel() { (tpm?.connection as? NETunnelProviderSession)?.stopTunnel() } func restartTunnel() { #if targetEnvironment(simulator) zLog.info("Simulator ignoring tunnel restart check") #else if self.status != .disconnected { zLog.info("Restarting tunnel") tunnelRestarting = true stopTunnel() } #endif } func updateLogLevel(_ level:ZitiLog.LogLevel) { zLog.info("Updating log level to \(level)") ZitiLog.setLogLevel(level) guard let tpm = tpm else { zLog.error("Invalid tunnel provider. Tunnel logging level not updated") return } if var conf = (tpm.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration { // update logLevel conf[ProviderConfig.LOG_LEVEL] = String(level.rawValue) (tpm.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration = conf zLog.info("Updated providerConfiguration: \(String(describing: (tpm.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration))") tpm.saveToPreferences { error in if let error = error { zLog.error(error.localizedDescription) } else { // sendProviderMessage zLog.info("Sending logLevel \(level) to provider") let msg = IpcSetLogLevelMessage(level.rawValue) self.ipcClient.sendToAppex(msg) { _, zErr in guard zErr == nil else { zLog.error("Unable to send provider message to update logLevel to \(level): \(zErr!.localizedDescription)") return } } } } } else { zLog.info("No log level found. Using default") } } }
41.508547
157
0.54041
7ad6a921799b137efcba02d0a6a53a1d70c58e84
1,810
// // PieLayer.swift // PieChartView // // Created by Damon Cricket on 10.09.2019. // Copyright © 2019 DC. All rights reserved. // import UIKit // MARK: - PieLayer class PieLayer: CALayer { var startAngle: CGFloat = 0.0 var endAngle: CGFloat = 0.0 var radius: CGFloat = 0.0 var thickness: CGFloat = 0.0 var color: CGColor = UIColor.clear.cgColor // MARK: - Object LifeCycle override init() { super.init() postInitSetup() } override init(layer: Any) { super.init(layer: layer) if let pieLayer = layer as? PieLayer { startAngle = pieLayer.startAngle endAngle = pieLayer.endAngle radius = pieLayer.radius thickness = pieLayer.thickness color = pieLayer.color } postInitSetup() } required init?(coder aDecoder: NSCoder) { super.init(layer: aDecoder) postInitSetup() } func postInitSetup() { allowsEdgeAntialiasing = true contentsScale = UIScreen.main.scale needsDisplayOnBoundsChange = true } // MARK: - Draw override open func draw(in ctx: CGContext) { super.draw(in: ctx) UIGraphicsPushContext(ctx) ctx.setLineWidth(thickness) let path = CGMutablePath() path.addArc(center: CGPoint(x: bounds.maxX/2.0, y: bounds.maxY/2.0), radius: radius + thickness/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false) ctx.addPath(path) ctx.setFillColor(UIColor.clear.cgColor) ctx.setStrokeColor(color) ctx.strokePath() UIGraphicsPopContext() } }
22.073171
170
0.560221
d691496b1f400ba58dc2773b66c2af45ccddb50d
522
// // routeStop.swift // berkeleyMobileiOS // // Single bus stop location // // Created by Akilesh Bapu on 3/2/17. // Copyright © 2017 org.berkeleyMobile. All rights reserved. // import UIKit class routeStop: NSObject { var name: String var latitude: Double var longitude: Double var id: Int init(_ name: String, _ latitude: Double, _ longitude: Double, _ id: Int) { self.name = name self.latitude = latitude self.longitude = longitude self.id = id } }
19.333333
78
0.628352
08ea7643b0f5b8c1e0327a50724446ad30f817c1
839
// // NavMenu.swift // RUM Mobile Demo App // // Created by Akash Patel3 on 15/02/22. // import UIKit class NavMenu: UIView { var actionHandler : (()->Void)? override func awakeFromNib() { super.awakeFromNib() } class func showNavMenu(clickHandler : (()->Void)? = nil) { guard let menuView = Bundle.main.loadNibNamed("NavMenu", owner: self, options: nil)?[0] as? NavMenu else {return} let keyWindow = UIApplication.shared.keyWindow menuView.frame = keyWindow?.bounds ?? .zero menuView.actionHandler = clickHandler keyWindow?.addSubview(menuView) } @IBAction func btnMenuAction(_ sender : UIButton) { actionHandler?() } @IBAction func btnForDismissViewPressed(_ sender : UIButton) { self.removeFromSuperview() } }
24.676471
121
0.629321
d700ac44e8b676b2969bbc4d8966a7a0cf267d69
4,548
import Foundation import XCTest import Shared import CoreLocation import RealmSwift @testable import HomeAssistant class ZoneManagerCollectorTests: XCTestCase { private var realm: Realm! private var delegate: FakeZoneManagerCollectorDelegate! private var locationManager: FakeCLLocationManager! private var collector: ZoneManagerCollectorImpl! enum TestError: Error { case anyError } override func setUpWithError() throws { try super.setUpWithError() let executionIdentifier = UUID().uuidString realm = try Realm(configuration: .init(inMemoryIdentifier: executionIdentifier)) Current.realm = { self.realm } locationManager = FakeCLLocationManager() delegate = FakeZoneManagerCollectorDelegate() collector = ZoneManagerCollectorImpl() collector.delegate = delegate } func testDidFailDoesLog() { collector.locationManager(locationManager, didFailWithError: TestError.anyError) XCTAssertEqual(delegate.states.count, 1) guard let state = delegate.states.first else { return } switch state { case .didError(TestError.anyError): // pass break default: XCTFail("expected error, got \(state)") } } func testDidFailMonitoringDoesLog() { let region = CLCircularRegion() collector.locationManager(locationManager, monitoringDidFailFor: region, withError: TestError.anyError) XCTAssertEqual(delegate.states.count, 1) guard let state = delegate.states.first else { return } switch state { case .didFailMonitoring(region, TestError.anyError): // pass break default: XCTFail("expected error, got \(state)") } } func testDidStartMonitoringLogsAndRequestsState() { let region = CLCircularRegion() collector.locationManager(locationManager, didStartMonitoringFor: region) XCTAssertEqual(delegate.states.count, 1) guard let state = delegate.states.first else { return } switch state { case .didStartMonitoring(region): // pass break default: XCTFail("expected start, got \(state)") } XCTAssertEqual(locationManager.requestedRegions, [region]) } func testDidDetermineStateWithNoZoneInRealm() { let region = CLCircularRegion() collector.locationManager(locationManager, didDetermineState: .inside, for: region) XCTAssertEqual(delegate.events.count, 1) guard let event = delegate.events.first else { return } XCTAssertEqual(event.eventType, .region(region, .inside)) XCTAssertNil(event.associatedZone) } func testDidDetermineStateWithZoneInRealm() throws { let region = CLCircularRegion( center: .init(latitude: 1.23, longitude: 4.56), radius: 20, identifier: "zone_identifier" ) let realmZone = with(RLMZone()) { $0.ID = "zone_identifier" } try realm.write { realm.add(realmZone) } collector.locationManager(locationManager, didDetermineState: .inside, for: region) XCTAssertEqual(delegate.events.count, 1) guard let event = delegate.events.first else { return } XCTAssertEqual(event.eventType, .region(region, .inside)) XCTAssertEqual(event.associatedZone, realmZone) } func testDidUpdateLocations() { let locations = [ CLLocation(latitude: 1.23, longitude: 4.56), CLLocation(latitude: 2.34, longitude: 5.67) ] collector.locationManager(locationManager, didUpdateLocations: locations) XCTAssertEqual(delegate.events.count, 1) guard let event = delegate.events.first else { return } XCTAssertEqual(event.eventType, .locationChange(locations)) XCTAssertNil(event.associatedZone) } } private class FakeZoneManagerCollectorDelegate: ZoneManagerCollectorDelegate { var states = [ZoneManagerState]() var events = [ZoneManagerEvent]() func collector(_ collector: ZoneManagerCollector, didLog state: ZoneManagerState) { states.append(state) } func collector(_ collector: ZoneManagerCollector, didCollect event: ZoneManagerEvent) { events.append(event) } }
29.153846
111
0.643799
76d8c6af3ac3bff7b5b620fe7451c629842ac336
2,685
// // IGRCropCornerView.swift // PhotoCroper // // Created by Vitalii Parovishnyk on 2/6/17. // Copyright © 2017 IGR Software. All rights reserved. // import UIKit public class PhotoCropCornerView: UIView { init(cornerType type: CropCornerType, lineWidth: CGFloat, lineLenght: CGFloat) { super.init(frame: CGRect(x: CGFloat.zero, y: CGFloat.zero, width: lineLenght, height: lineLenght)) setup(cornerType: type, lineWidth: lineWidth, lineLenght:lineLenght) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup(cornerType: .upperRight, lineWidth: kCropViewLineWidth, lineLenght:kCropViewCornerLength) } fileprivate func setup(cornerType type: CropCornerType, lineWidth: CGFloat, lineLenght: CGFloat) { let horizontal = PhotoCropCornerLine(frame: CGRect(x: CGFloat.zero, y: CGFloat.zero, width: lineLenght, height: lineWidth)) self.addSubview(horizontal) let vertical = PhotoCropCornerLine(frame: CGRect(x: CGFloat.zero, y: CGFloat.zero, width: lineWidth, height: lineLenght)) self.addSubview(vertical) if type == .upperLeft { horizontal.center = CGPoint(x: lineLenght.half, y: lineWidth.half) vertical.center = CGPoint(x: lineWidth.half, y: lineLenght.half) self.autoresizingMask = [] } else if type == .upperRight { horizontal.center = CGPoint(x: lineLenght.half, y: lineWidth.half) vertical.center = CGPoint(x: lineLenght - lineWidth.half, y: lineLenght.half) self.autoresizingMask = [.flexibleLeftMargin] } else if type == .lowerRight { horizontal.center = CGPoint(x: lineLenght.half, y: (lineLenght - lineWidth.half)) vertical.center = CGPoint(x: lineLenght - lineWidth.half, y: (lineLenght.half)) self.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin] } else if type == .lowerLeft { horizontal.center = CGPoint(x: lineLenght.half, y: (lineLenght - lineWidth.half)) vertical.center = CGPoint(x: lineWidth.half, y: lineLenght.half) self.autoresizingMask = [.flexibleTopMargin] } } }
41.307692
106
0.553073
21988c86c8587f7f3a69f5c8999c3913ce6b924d
2,491
// ControllerModalPresenter.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) import UIKit struct ControllerModalPresenter { var rootViewController: UIViewController? { return UIApplication.shared()?.keyWindow?.rootViewController } func present(controller: UIViewController) { topViewController?.present(controller, animated: true, completion: nil) } var topViewController: UIViewController? { guard let root = self.rootViewController else { return nil } return findTopViewController(from: root) } private func findTopViewController(from root: UIViewController) -> UIViewController? { if let presented = root.presentedViewController { return findTopViewController(from: presented) } switch root { case let split as UISplitViewController: guard let last = split.viewControllers.last else { return split } return findTopViewController(from: last) case let navigation as UINavigationController: guard let top = navigation.topViewController else { return navigation } return findTopViewController(from: top) case let tab as UITabBarController: guard let selected = tab.selectedViewController else { return tab } return findTopViewController(from: selected) default: return root } } } #endif
41.516667
105
0.7222
7688baf1946c45590c004e55da265444b8c77f0a
7,996
// // AppSettingsViewController.swift // BookZone // // Created by Paianu Vlad-Valentin on 30.11.2020. // Copyright © 2020 Paianu Vlad-Valentin. All rights reserved. // import UIKit class AppSettingsViewController: UIViewController { @IBOutlet weak var navBarView: NavbarView! @IBOutlet weak var languageLabel: UILabel! @IBOutlet weak var languageDropdown: Dropdown! @IBOutlet weak var appPrefferedLanguageLabel: UILabel! @IBOutlet weak var doneToolbar: UIToolbar! @IBOutlet weak var userLanguagePicker: UIPickerView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var pickerHeight: NSLayoutConstraint! var languagesArray = [K.Languages.english, K.Languages.romana] var pickerData: PickerData? override func viewDidLoad() { super.viewDidLoad() userLanguagePicker.delegate = self userLanguagePicker.dataSource = self setUserLanguage() configureUI() } override func viewWillAppear(_ animated: Bool) { configurePickerViews() } private func configureUI() { configureNavbar() configureDropdown() configureLabels() } private func configureNavbar() { navBarView.titleLabelNavbar.text = NSLocalizedString(K.NavbarTitles.appSettingsTitle, comment: "") } private func configureLabels() { languageLabel.text = NSLocalizedString("language", comment: "") appPrefferedLanguageLabel.text = NSLocalizedString("prefLanguage", comment: "") } private func configureDropdown() { let userLanguage = UserDefaults.standard.string(forKey: K.UserKeys.userLanguage) var labelLanguage = "" switch userLanguage { case K.Languages.en: labelLanguage = K.Languages.english case K.Languages.ro: labelLanguage = K.Languages.romana default: labelLanguage = K.Languages.english } languageDropdown.dropDownView.backgroundColor = UIColor(named: "pink") languageDropdown.dropDownLabel.text = UserDefaults.standard.string(forKey: K.UserKeys.userLanguage) languageDropdown.setupShadow() let userLanguageTap = UITapGestureRecognizer(target: self, action: #selector(self.userLanguageDropdownPressed)) languageDropdown.addGestureRecognizer(userLanguageTap) } private func configurePickerViews() { let userLanguageRow = UserDefaults.standard.integer(forKey: K.UserKeys.userLanguageRow) self.userLanguagePicker.selectRow(userLanguageRow, inComponent: 0, animated: false) } //MARK: - Actions @objc func userLanguageDropdownPressed() { configurePickerViews() doneToolbar.isHidden = !doneToolbar.isHidden userLanguagePicker.isHidden = !userLanguagePicker.isHidden scrollView.scrollToBottom(animated: true) pickerHeight.constant = doneToolbar.isHidden ? 0 : 190 UIView.animate(withDuration: 0.5) { self.view.layoutIfNeeded() } } @IBAction func doneButtonPressed(_ sender: Any) { userLanguagePicker.isHidden = true doneToolbar.isHidden = true handleDonePressed() } // MARK: - Helpers func handleDonePressed() { let currentLanguage = UserDefaults.standard.string(forKey: K.UserKeys.userLanguage) var differentLanguageFlag = false if let pickerSelectedData = pickerData { setupUserValues(userLanguage: pickerSelectedData.pickerLanguage, shortLanguage: pickerSelectedData.pickerShortLanguage, rowNumber: pickerSelectedData.pickerSelectedRow) languageDropdown.dropDownLabel.text = languagesArray[UserDefaults.standard.integer(forKey: K.UserKeys.userLanguageRow)] differentLanguageFlag = currentLanguage! != pickerSelectedData.pickerLanguage ? true : false if differentLanguageFlag { switchLanguageInApp(language: UserDefaults.standard.string(forKey: K.UserKeys.userShortLanguage)!, deadline: 0.3) } } } func setUserLanguage() { let userLanguage = Bundle.main.preferredLocalizations.first! as String let selectionMade = UserDefaults.standard.bool(forKey: K.UserKeys.languageSelectionMade) if !selectionMade { switch userLanguage { case K.Languages.ro: setupDefaultUserLanguageSettings(userPhoneLanguage: languagesArray[1]) default: setupDefaultUserLanguageSettings(userPhoneLanguage: languagesArray[0]) } } } private func reloadRootVC() { let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let homeScreen = storyboard.instantiateViewController(withIdentifier: K.Identifiers.homeVC) let options = storyboard.instantiateViewController(withIdentifier: K.Identifiers.reloadSettings) options.modalPresentationStyle = .fullScreen homeScreen.modalPresentationStyle = .fullScreen UIApplication.shared.windows.first { $0.isKeyWindow }?.rootViewController = storyboard.instantiateInitialViewController() UIApplication.shared.windows.first { $0.isKeyWindow }?.rootViewController?.present( homeScreen, animated: false, completion: nil) homeScreen.present(options, animated: false, completion: nil) } private func switchLanguageInApp(language: String, deadline: Double) { Bundle.setLanguage(language) DispatchQueue.main.asyncAfter(deadline: .now() + deadline) { self.reloadRootVC() } } } //MARK: - Picker extension AppSettingsViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return languagesArray.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return languagesArray[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { var shorthandLanguage: String = "" switch languagesArray[row] { case K.Languages.romana: shorthandLanguage = K.Languages.ro default: shorthandLanguage = K.Languages.en } let pickerSelectedData = PickerData(pickerLanguage: languagesArray[row], pickerShortLanguage: shorthandLanguage, pickerSelectedRow: row) pickerData = pickerSelectedData } } //MARK: - Picker language extension AppSettingsViewController { func setupDefaultUserLanguageSettings(userPhoneLanguage: String) { UserDefaults.standard.set(userPhoneLanguage, forKey: K.UserKeys.userLanguage) let languageIndex = languagesArray.firstIndex(of: userPhoneLanguage)! as Int UserDefaults.standard.set(languageIndex, forKey: K.UserKeys.userLanguageRow) } func setupUserValues(userLanguage: String, shortLanguage: String, rowNumber: Int) { UserDefaults.standard.set(true, forKey: K.UserKeys.languageSelectionMade) UserDefaults.standard.set(userLanguage, forKey: K.UserKeys.userLanguage) UserDefaults.standard.set(shortLanguage, forKey: K.UserKeys.userShortLanguage) UserDefaults.standard.set(rowNumber, forKey: K.UserKeys.userLanguageRow) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
37.364486
119
0.662831
f89ff221b80e4fbaa56815347f28fd08a3fa85a3
1,971
// // AppDelegate.swift // TestHost // // Created by kishikawa katsumi on 7/10/16. // Copyright © 2016 kishikawa katsumi. All rights reserved. // // 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 os(OSX) import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(aNotification: NSNotification) {} } #else import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? #if swift(>=4.2) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { return true } #else func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { return true } #endif } #endif
35.196429
152
0.750381
2f89e9c1f70be25fc6bc210b9f55bd2cf3ccbfb6
460
// // HomeViewModel.swift // Project_VegeX // // Created by 천지운 on 2020/07/15. // Copyright © 2020 Doyoung Song. All rights reserved. // import Foundation enum ChallengeType: Int, CaseIterable { case processing case popular var description: String { switch self { case .processing: return "진행중" case .popular: return "인기" } } } enum TutorialStatus { case start case ongoing case finish }
16.428571
55
0.623913
dd468e4be2f5ed4d54bce93f6d7b7f2712e869b0
1,322
// Playground - noun: a place where people can play import UIKit /* 里氏替换原则 Liskov Substitution Principle (LSP) 定义1:如果对每一个类型为 T1的对象 O1,都有类型为 T2 的对象O2,使得以 T1定义的所有程序 P 在所有的对象 O1 都代换成 O2 时,程序 P 的行为没有发生变化,那么类型 T2 是类型 T1 的子类型。 定义2:所有引用基类的地方必须能透明地使用其子类的对象。 问题由来:有一功能P1,由类A完成。现需要将功能P1进行扩展,扩展后的功能为P,其中P由原有功能P1与新功能P2组成。新功能P由类A的子类B来完成,则子类B在完成新功能P2的同时,有可能会导致原有功能P1发生故障。 解决方案:当使用继承时,遵循里氏替换原则。类B继承类A时,除添加新的方法完成新增功能P2外,尽量不要重写父类A的方法,也尽量不要重载父类A的方法。 里氏替换原则通俗的来讲就是:子类可以扩展父类的功能,但不能改变父类原有的功能. 包含四层含义: 1.子类可以实现父类的抽象方法,但不能覆盖父类的非抽象方法。 2.子类中可以增加自己特有的方法。 3.当子类的方法重载父类的方法时,方法的前置条件(即方法的形参)要比父类方法的输入参数更宽松。 4.当子类的方法实现父类的抽象方法时,方法的后置条件(即方法的返回值)要比父类更严格。 */ class A { func func1(a:Int,b:Int) -> Int{ return a - b } } class B: A { //在对func1覆写的时候没有考虑原本的父类的作用 override func func1(a: Int, b: Int) -> Int { return a + b } func func2(a:Int,b:Int) -> Int { return func1(a, b: b) + 100 } } class Client { init(){ var a = A() println("100-50=\(a.func1(100, b: 50))") println("100-80=\(a.func1(100, b: 80))") var b = B() //显然,func1被破坏了 println("100-50=\(b.func1(100, b: 50))") println("100-80=\(b.func1(100, b: 80))") println("100+20+100=\(b.func2(100, b: 20))") } } var client = Client()
25.921569
113
0.633132
d54ff76facb23b9f200e650e82c16bb6434e664d
294
// 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{{struct Q{{}protocol a{class c{enum A{enum e{struct Q{struct Q{func c{enum b{func g{class A{class A{func e{func a{(_=F
49
124
0.748299
e6a62232d9ccc9e18c697247c17f0e06995e7cd9
2,889
// // AddStreamViewController.swift // RTSPViewer // // Created by mani on 2020-01-01. // Copyright © 2020 mani. All rights reserved. // import UIKit class AddStreamViewController: UITableViewController { @IBOutlet weak var urlCell: TextInputCell! var handler: ((URL) -> Void)? override func viewDidLoad() { super.viewDidLoad() title = "Add Stream" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupTextInputCell() urlCell.textField.becomeFirstResponder() } } extension AddStreamViewController { // MARK: - Setup private func setupTextInputCell() { let textField = urlCell.textField textField.delegate = self textField.addTarget(self, action: #selector(textDidChange), for: .editingChanged) textField.autocapitalizationType = .none textField.keyboardType = .URL textField.returnKeyType = .done } } extension AddStreamViewController { // MARK: - Text field validation and changes func handleTextfieldValidation(in textField: UITextField, message: String) { textField.text = "" let placeholderTextColor = UIColor(red: 236.0/255.0, green: 75.0/255.0, blue: 75.0/255.0, alpha: 1.0) textField.attributedPlaceholder = NSAttributedString(string: message, attributes: [NSAttributedString.Key.foregroundColor: placeholderTextColor]) textField.textColor = .red textField.shake() textField.becomeFirstResponder() } @objc func textDidChange(sender: UITextField) { if sender.textColor != .black { sender.textColor = .black } } } extension AddStreamViewController { // MARK: - IBAction @IBAction func done() { let textField = urlCell.textField let validator = Validator() if textField.validate([validator.isURLValid]) == false { handleTextfieldValidation(in: textField, message: "Please enter a valid URL") } else { textField.resignFirstResponder() } if let url = textField.text { if let url = URL(string: url) { dismiss(animated: true) { [weak self] in guard let weakSelf = self else { return } weakSelf.handler?(url) } } } } @IBAction func cancel(sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } } extension AddStreamViewController: UITextFieldDelegate { // MARK: - Text field delegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.returnKeyType == .done { done() return true } return false } }
27.254717
109
0.603669
11d4e4df84025856edb51fc28e759ae6836bed5c
924
// // ActivityDataSource.swift // ActivityPlusTwo // // Created by Ben Scheirman on 7/5/16. // Copyright © 2016 NSScreencast. All rights reserved. // import Foundation import HealthKit import UIKit struct ActivityDataSource { private let calendar: NSCalendar var activities: [ActivityLog]! init(calendar: NSCalendar, summaries: [HKActivitySummary]) { self.calendar = calendar self.activities = _convert(summaries) } init(calendar: NSCalendar, activities: [ActivityLog]) { self.calendar = calendar self.activities = activities } private func _convert(summaries: [HKActivitySummary]) -> [ActivityLog] { return summaries.map { summary in return ActivityLog.fromHealthKitSummary(summary, calendar: self.calendar) }.sort { (x, y) in return x.date.compare(y.date) == NSComparisonResult.OrderedDescending } } }
28.875
102
0.675325
de64ac7d2586d0651c821497a14e3624e1d4772e
806
import Foundation @testable import KsApi import Prelude import ReactiveExtensions import ReactiveSwift import Result import PlaygroundSupport func query(withSlug slug: String) -> NonEmptySet<Query> { return Query.project(slug: slug, .slug +| [ .id ] ) +| [] } struct ProjectEnvelope: Decodable { let project: Project struct Project: Decodable { let slug: String let id: String } } let client = Service() let signal: SignalProducer<ProjectEnvelope, GraphError> = client.fetchGraph(query: query(withSlug:"splatware-unique-ceramic-tableware")) let (fakeTaps, sink) = Signal<Void, NoError>.pipe() let project = fakeTaps.switchMap { signal.materialize() }.logEvents(identifier: "Project!") sink.send(value: ()) PlaygroundPage.current.needsIndefiniteExecution = true
20.666667
80
0.733251
265b3cd0c8ea9ca71d69bff1a583f00e8eb5c4ed
718
// RUN: %target-run-simple-swift-swift3 | %FileCheck %s // REQUIRES: executable_test // <rdar://problem/13986638> Missing Bool metadata when Bool is used as a generic // parameter or existential value prefix operator !! {} infix operator &&& {} protocol BooleanProtocol { var boolValue: Bool { get } } extension Bool : BooleanProtocol { var boolValue: Bool { return self } } prefix func !!<T : BooleanProtocol>(x: T) -> Bool { return x.boolValue } func &&&(x: BooleanProtocol, y: @autoclosure () -> BooleanProtocol) -> Bool { return x.boolValue ? y().boolValue : false } print(!!true) // CHECK: true print(!!false) // CHECK: false print(true &&& true) // CHECK: true print(true &&& false) // CHECK: false
25.642857
81
0.679666
2284a7ebf4b5c46923dce73a02a5d1cb338d43a2
4,494
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 public struct TMap<Key : TSerializable, Value : TSerializable> : CollectionType, DictionaryLiteralConvertible, TSerializable { public static var thriftType : TType { return .MAP } typealias Storage = Dictionary<Key, Value> public typealias Index = Storage.Index public typealias Element = Storage.Element private var storage : Storage public var startIndex : Index { return storage.startIndex } public var endIndex: Index { return storage.endIndex } public var keys: LazyMapCollection<[Key : Value], Key> { return storage.keys } public var values: LazyMapCollection<[Key : Value], Value> { return storage.values } public init() { storage = Storage() } public init(dictionaryLiteral elements: (Key, Value)...) { storage = Storage() for (key, value) in elements { storage[key] = value } } public init(minimumCapacity: Int) { storage = Storage(minimumCapacity: minimumCapacity) } public subscript (position: Index) -> Element { get { return storage[position] } } public func indexForKey(key: Key) -> Index? { return storage.indexForKey(key) } public subscript (key: Key) -> Value? { get { return storage[key] } set { storage[key] = newValue } } public mutating func updateValue(value: Value, forKey key: Key) -> Value? { return updateValue(value, forKey: key) } public mutating func removeAtIndex(index: DictionaryIndex<Key, Value>) -> (Key, Value) { return removeAtIndex(index) } public mutating func removeValueForKey(key: Key) -> Value? { return storage.removeValueForKey(key) } public mutating func removeAll(keepCapacity keepCapacity: Bool = false) { storage.removeAll(keepCapacity: keepCapacity) } public var hashValue : Int { let prime = 31 var result = 1 for (key, value) in storage { result = prime * result + key.hashValue result = prime * result + value.hashValue } return result } public static func readValueFromProtocol(proto: TProtocol) throws -> TMap { let (keyType, valueType, size) = try proto.readMapBegin() if keyType != Key.thriftType || valueType != Value.thriftType { throw NSError( domain: TProtocolErrorDomain, code: Int(TProtocolError.InvalidData.rawValue), userInfo: [TProtocolErrorExtendedErrorKey: NSNumber(int: TProtocolExtendedError.UnexpectedType.rawValue)]) } var map = TMap() for _ in 0..<size { let key = try Key.readValueFromProtocol(proto) let value = try Value.readValueFromProtocol(proto) map.storage[key] = value } try proto.readMapEnd() return map } public static func writeValue(value: TMap, toProtocol proto: TProtocol) throws { try proto.writeMapBeginWithKeyType(Key.thriftType, valueType: Value.thriftType, size: value.count) for (key, value) in value.storage { try Key.writeValue(key, toProtocol: proto) try Value.writeValue(value, toProtocol: proto) } try proto.writeMapEnd() } } extension TMap : CustomStringConvertible, CustomDebugStringConvertible { public var description : String { return storage.description } public var debugDescription : String { return storage.debugDescription } } public func ==<Key, Value>(lhs: TMap<Key,Value>, rhs: TMap<Key, Value>) -> Bool { if lhs.count != rhs.count { return false } return lhs.storage == rhs.storage }
28.264151
127
0.663106
ab8ce4a8aa9c69936e427b0983e196e0d6e90fb7
267
// // SettingStorage+CoreDataClass.swift // OpenKit-iOS // // Created by Jann on 10.08.19. // Copyright © 2019 Jann Schafranek. All rights reserved. // // import Foundation import CoreData @objc(SettingStorage) public class SettingStorage: NSManagedObject { }
15.705882
58
0.730337
9b3dd8622c738c3a2713ef464238f649b318f0ea
1,497
import Foundation import Moya let GitHubUserContentProvider = MoyaProvider<GitHubUserContent>(plugins: [NetworkLoggerPlugin(verbose: true)]) public enum GitHubUserContent { case downloadMoyaWebContent(String) } extension GitHubUserContent: TargetType { public var baseURL: URL { return URL(string: "https://raw.githubusercontent.com")! } public var path: String { switch self { case .downloadMoyaWebContent(let contentPath): return "/Moya/Moya/master/web/\(contentPath)" } } public var method: Moya.Method { switch self { case .downloadMoyaWebContent: return .GET } } public var parameters: [String: Any]? { switch self { case .downloadMoyaWebContent: return nil } } public var task: Task { switch self { case .downloadMoyaWebContent: return .download(.request(DefaultDownloadDestination)) } } public var sampleData: Data { switch self { case .downloadMoyaWebContent: return animatedBirdData() as Data } } } private let DefaultDownloadDestination: DownloadDestination = { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) if !directoryURLs.isEmpty { return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) } return (temporaryURL, []) }
27.218182
110
0.646627
f8c731d8c216c1802671bd13b948fd80d510eaf5
2,111
import SwiftUI struct SwiftUI_ViewsAndModifiersView: View { var body: some View { VStack(spacing: 20) { Text("Views & Modifiers") .font(.largeTitle) Text("Concepts") .font(.title) .foregroundColor(.gray) Text("Building a UI... Building a UI... Building a UI... Building a UI... Building a UI... Building a UI...") .frame(maxWidth: .infinity) .font(.title) .background(Color.orange) Button(action: { // Your code here print("Button pressed") }) { Text("Button With Shadow") .font(.title) .padding() .foregroundColor(.white) .background(Color.orange) .cornerRadius(20) .shadow(color: Color.gray, radius: 20, y: 5) } Image(systemName: "hand.thumbsup.fill") .font(.largeTitle) } } } struct ViewsAndModifiersView_Previews: PreviewProvider { static var previews: some View { let devices = [ "iPhone 13 mini", "iPad (9th generation)" ] let viewToPreview = SwiftUI_ViewsAndModifiersView() viewToPreview .preferredColorScheme(.light) .previewDisplayName("light Mode") viewToPreview .preferredColorScheme(.dark) .previewDisplayName("dark Mode") if #available(iOS 15.0, *) { viewToPreview .previewInterfaceOrientation(.landscapeRight) .previewDisplayName("landscapeRight") } ForEach(devices, id: \.self) { device in viewToPreview .previewDevice(PreviewDevice(rawValue: device)) .previewDisplayName(device) } } }
28.527027
121
0.463761
8a027c0ade51c5d4f2c568b34ea5e7df5d6b878b
311
import Foundation protocol NewAddIngredientAmountTypeProtocol { var name:String { get } func createIngredient( ingredientIdentifier:String, name:String, amount:String, build:Build, database:Database, completion:@escaping((BuildIngredient) -> ())) }
20.733333
54
0.646302
485b872a2f6c864a69560424b4ab3c297ec4ae06
1,302
// // main.swift // JYMT-MISTool // // Created by Jerry Yan on 11/18/19. // import Foundation import JYMTBasicKit import JYMTAdvancedKit printWelcomeBanner("MIS Tool") let abcPM = ABCTuple(6709.080887*1e6, 4121.532619*1e6, 3387.851702*1e6, totalAtomicMass: 76.0944) let abcA = ABCTuple(5296.279016*1e6, 3642.216781*1e6, 3125.767619*1e6, totalAtomicMass: 76.0944, substitutedIsotopes: [(ChemElement.carbon, 13)]) let abcB = ABCTuple(4775.040608*1e6, 3569.764660*1e6, 2866.559174*1e6, totalAtomicMass: 76.0944, substitutedIsotopes: [(ChemElement.carbon, 13)]) let abcAB = ABCTuple(4305.255076*1e6, 3214.296089*1e6, 2574.740027*1e6, totalAtomicMass: 76.0944, substitutedIsotopes: [(ChemElement.carbon, 13), (ChemElement.carbon, 13)]) var atoms = fromSISToAtoms(original: abcPM, substituted: [abcA, abcB]) for atom in atoms { atom.massNumber = 13 } var atomBs = atoms[1].possibles var rABCs = [([Atom], ABCTuple)]() for atomB in atomBs { let rABC = MISFromSubstitutedAtoms(depth: 2, original: abcPM, substitutedAtoms: [atoms[0], atomB]) rABCs.append(rABC[0]) } let abcABRVec = Vector3D(abcAB.arrayForm) rABCs.sort(by: { (Vector3D($0.1.arrayForm) - abcABRVec).magnitude < (Vector3D($1.1.arrayForm) - abcABRVec).magnitude }) print(rABCs[0].1.arrayForm) //print(rABCs[0].0[0].rvec!)
33.384615
172
0.731951
ff64b8646a591d1ffc3e305be16d9f777c1f9d3f
3,220
// // VerifyServiceTests.swift // VerifyIosSdk // // Created by Dorian Peake on 02/09/2015. // Copyright (c) 2015 Nexmo Inc. All rights reserved. // import Foundation import XCTest @testable import NexmoVerify class VerifyServiceTests : XCTestCase { func testVerifyServiceCallsServiceExecutorWithCorrectParams() { let deviceProperties = DevicePropertiesMock() let params = [ServiceExecutor.PARAM_NUMBER : VerifyIosSdkTests.TEST_NUMBER, ServiceExecutor.PARAM_COUNTRY_CODE : VerifyIosSdkTests.TEST_COUNTRY_CODE, ServiceExecutor.PARAM_SOURCE_IP : deviceProperties.getIpAddress()!, ServiceExecutor.PARAM_DEVICE_ID : deviceProperties.getUniqueDeviceIdentifierAsString()!] let serviceExecutor = ServiceExecutorMock(expectedParams: params, httpRequest: HttpRequest(request: URLRequest(url: Config.ENDPOINT_PRODUCTION_URL), encoding: String.Encoding.utf8)) let verifyService = SDKVerifyService(nexmoClient: VerifyIosSdkTests.nexmoClient, serviceExecutor: serviceExecutor, deviceProperties: deviceProperties) let verifyRequest = VerifyRequest(countryCode: VerifyIosSdkTests.TEST_COUNTRY_CODE, phoneNumber: VerifyIosSdkTests.TEST_NUMBER, standalone: false) let verifyExpectation = expectation(description: "verify response received") verifyService.start(request: verifyRequest) { response, error in verifyExpectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssert(serviceExecutor.performHttpRequestForServiceCalled, "Generate Http Request not called correctly!") } func testVerifyServiceCallsServiceExecutorWithCorrectParamsWithPushToken() { let deviceProperties = DevicePropertiesMock() let params = [ServiceExecutor.PARAM_COUNTRY_CODE : VerifyIosSdkTests.TEST_COUNTRY_CODE, ServiceExecutor.PARAM_NUMBER : VerifyIosSdkTests.TEST_NUMBER, ServiceExecutor.PARAM_PUSH_TOKEN : VerifyIosSdkTests.TEST_PUSH_TOKEN, ServiceExecutor.PARAM_DEVICE_ID : deviceProperties.getUniqueDeviceIdentifierAsString()!, ServiceExecutor.PARAM_SOURCE_IP : deviceProperties.getIpAddress()!] let serviceExecutor = ServiceExecutorMock(expectedParams: params, httpRequest: HttpRequest(request: URLRequest(url: Config.ENDPOINT_PRODUCTION_URL), encoding: String.Encoding.utf8)) let verifyService = SDKVerifyService(nexmoClient: VerifyIosSdkTests.nexmoClient, serviceExecutor: serviceExecutor, deviceProperties: deviceProperties) let verifyRequest = VerifyRequest(countryCode: VerifyIosSdkTests.TEST_COUNTRY_CODE, phoneNumber: VerifyIosSdkTests.TEST_NUMBER, standalone: false , pushToken: VerifyIosSdkTests.TEST_PUSH_TOKEN) let verifyExpectation = expectation(description: "verify response received") verifyService.start(request: verifyRequest) { response, error in verifyExpectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssert(serviceExecutor.performHttpRequestForServiceCalled, "Generate Http Request not called correctly!") } }
61.923077
201
0.75
69db69a9f0bcd5e77dd7b7a62258adbf8a3f317d
397
// // Aliases.swift // ALUtils // // Created by Aleksey Lobanov on 08/08/2017. // Copyright © 2017 ALUtils. All rights reserved. // import Foundation /// Data dictionaries public typealias JSONDictionary = [String: Any] public typealias JSONArrayDictionary = [[String: Any]] public typealias DictionaryAnyObject = [String: AnyObject] public typealias DictionaryArray = [[String: AnyObject]]
24.8125
58
0.745592
dec616d4190b688960a771a8b52193a7d7b2c2c3
3,515
// // NowPlayingViewController.swift // Flix // // Created by Danny on 9/11/18. // Copyright © 2018 Danny Rivera. All rights reserved. // import UIKit import AlamofireImage class NowPlayingViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var movies: [Movie] = [] var activityIndicator: UIActivityIndicatorView! var refreshControl: UIRefreshControl! override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self self.tableView.delegate = self DispatchQueue.global(qos: .userInteractive).async { self.fetchNowPlayingMovies() DispatchQueue.main.async { self.createCustomActivityIndicator() self.createPullToRefreshControl() } } } func createCustomActivityIndicator() { let rect = CGRect(origin: CGPoint(x: self.tableView.contentSize.width/2.0, y: self.tableView.contentSize.height/2.0), size: CGSize(width: 5000, height: 5000)) self.activityIndicator = UIActivityIndicatorView(frame: rect) as UIActivityIndicatorView self.activityIndicator.center = self.view.center self.activityIndicator.hidesWhenStopped = true self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge self.activityIndicator.color = UIColor.red self.activityIndicator.startAnimating() self.view.addSubview(activityIndicator) } func createPullToRefreshControl() { refreshControl = UIRefreshControl() refreshControl.tintColor = UIColor.red refreshControl.addTarget(self, action: #selector(NowPlayingViewController.didPullToRefresh(_ :)), for: .valueChanged) tableView.insertSubview(refreshControl, at: 0) } @objc func didPullToRefresh(_ refreshControl: UIRefreshControl) { self.activityIndicator.startAnimating() fetchNowPlayingMovies() } func fetchNowPlayingMovies() { MovieApiManager().nowPlayingMovies { (movies: [Movie]?, error: Error?) in if let movies = movies { self.movies = movies self.tableView.reloadData() self.refreshControl.endRefreshing() self.activityIndicator.stopAnimating() } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCell cell.movie = self.movies[indexPath.row] return cell } 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?) { if segue.identifier == "detailView" { let detailViewController = segue.destination as! DetailViewController let row = tableView.indexPathForSelectedRow!.row detailViewController.movies = self.movies[row] } } }
37.393617
125
0.662589
d6078ef57f7c974490b13a9a5799ba82e8221200
12,512
// // BarChart.swift // ModuleKit // // Created by Serhiy Mytrovtsiy on 26/04/2020. // Using Swift 5.0. // Running on macOS 10.15. // // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // import Cocoa import StatsKit public class BarChart: Widget { private var labelState: Bool = true private var boxState: Bool = true private var frameState: Bool = false private var colorState: widget_c = .systemAccent private let store: UnsafePointer<Store>? private var colors: [widget_c] = widget_c.allCases private var value: [Double] = [] private var pressureLevel: Int = 0 private var boxSettingsView: NSView? = nil private var frameSettingsView: NSView? = nil public init(preview: Bool, title: String, config: NSDictionary?, store: UnsafePointer<Store>?) { var widgetTitle: String = title self.store = store if config != nil { var configuration = config! if let titleFromConfig = config!["Title"] as? String { widgetTitle = titleFromConfig } if preview { if let previewConfig = config!["Preview"] as? NSDictionary { configuration = previewConfig if let value = configuration["Value"] as? String { self.value = value.split(separator: ",").map{ (Double($0) ?? 0) } } } } if let label = configuration["Label"] as? Bool { self.labelState = label } if let box = configuration["Box"] as? Bool { self.boxState = box } if let colorsToDisable = configuration["Unsupported colors"] as? [String] { self.colors = self.colors.filter { (color: widget_c) -> Bool in return !colorsToDisable.contains("\(color.self)") } } if let color = configuration["Color"] as? String { if let defaultColor = colors.first(where: { "\($0.self)" == color }) { self.colorState = defaultColor } } } super.init(frame: CGRect(x: 0, y: Constants.Widget.margin, width: Constants.Widget.width, height: Constants.Widget.height - (2*Constants.Widget.margin))) self.preview = preview self.title = widgetTitle self.type = .barChart self.canDrawConcurrently = true if self.store != nil && !preview { self.boxState = store!.pointee.bool(key: "\(self.title)_\(self.type.rawValue)_box", defaultValue: self.boxState) self.frameState = store!.pointee.bool(key: "\(self.title)_\(self.type.rawValue)_frame", defaultValue: self.frameState) self.labelState = store!.pointee.bool(key: "\(self.title)_\(self.type.rawValue)_label", defaultValue: self.labelState) self.colorState = widget_c(rawValue: store!.pointee.string(key: "\(self.title)_\(self.type.rawValue)_color", defaultValue: self.colorState.rawValue)) ?? self.colorState } if preview { if self.value.count == 0 { self.value = [0.72, 0.38] } self.setFrameSize(NSSize(width: 36, height: self.frame.size.height)) self.invalidateIntrinsicContentSize() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) let ctx = NSGraphicsContext.current!.cgContext ctx.saveGState() var width: CGFloat = 0 var x: CGFloat = Constants.Widget.margin var chartPadding: CGFloat = 0 if self.labelState { let style = NSMutableParagraphStyle() style.alignment = .center let stringAttributes = [ NSAttributedString.Key.font: NSFont.systemFont(ofSize: 7, weight: .regular), NSAttributedString.Key.foregroundColor: NSColor.textColor, NSAttributedString.Key.paragraphStyle: style ] let letterHeight = self.frame.height / 3 let letterWidth: CGFloat = 6.0 var yMargin: CGFloat = 0 for char in String(self.title.prefix(3)).uppercased().reversed() { let rect = CGRect(x: x, y: yMargin, width: letterWidth, height: letterHeight) let str = NSAttributedString.init(string: "\(char)", attributes: stringAttributes) str.draw(with: rect) yMargin += letterHeight } width = width + letterWidth + (Constants.Widget.margin*2) x = letterWidth + (Constants.Widget.margin*3) } switch self.value.count { case 0, 1: width += 14 break case 2: width += 26 break case 3...4: // 3,4 width += 32 break case 5...8: // 5,6,7,8 width += 42 break case 9...12: // 9..12 width += 52 break case 13...16: // 13..16 width += 78 break case 17...32: // 17..32 width += 86 break default: // > 32 width += 120 break } let box = NSBezierPath(roundedRect: NSRect(x: x, y: 0, width: width - x - Constants.Widget.margin, height: self.frame.size.height), xRadius: 2, yRadius: 2) if self.boxState { (isDarkMode ? NSColor.white : NSColor.black).set() box.stroke() box.fill() chartPadding = 1 x += 0.5 } let widthForBarChart = box.bounds.width - chartPadding let partitionMargin: CGFloat = 0.5 let partitionsMargin: CGFloat = (CGFloat(self.value.count - 1)) * partitionMargin / CGFloat(self.value.count - 1) let partitionWidth: CGFloat = (widthForBarChart / CGFloat(self.value.count)) - CGFloat(partitionsMargin.isNaN ? 0 : partitionsMargin) let maxPartitionHeight: CGFloat = box.bounds.height - (chartPadding*2) for i in 0..<self.value.count { let partitionValue = self.value[i] let partitonHeight = maxPartitionHeight * CGFloat(partitionValue) let partition = NSBezierPath(rect: NSRect(x: x, y: chartPadding, width: partitionWidth, height: partitonHeight)) switch self.colorState { case .systemAccent: NSColor.controlAccentColor.set() case .utilization: partitionValue.usageColor().setFill() case .pressure: self.pressureLevel.pressureColor().setFill() case .monochrome: if self.boxState { (isDarkMode ? NSColor.black : NSColor.white).set() } else { (isDarkMode ? NSColor.white : NSColor.black).set() } default: colorFromString("\(self.colorState.self)").set() } partition.fill() partition.close() x += partitionWidth + partitionMargin } if self.boxState || self.frameState { (isDarkMode ? NSColor.white : NSColor.black).set() box.lineWidth = 1 box.stroke() } ctx.restoreGState() self.setWidth(width) } public func setValue(_ value: [Double]) { self.value = value DispatchQueue.main.async(execute: { self.display() }) } public func setPressure(_ level: Int) { guard self.pressureLevel != level else { return } self.pressureLevel = level DispatchQueue.main.async(execute: { self.display() }) } public override func settings(superview: NSView) { let rowHeight: CGFloat = 30 let settingsNumber: CGFloat = 4 let height: CGFloat = ((rowHeight + Constants.Settings.margin) * settingsNumber) + Constants.Settings.margin superview.setFrameSize(NSSize(width: superview.frame.width, height: height)) let view: NSView = NSView(frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin, width: superview.frame.width - (Constants.Settings.margin*2), height: superview.frame.height - (Constants.Settings.margin*2))) view.addSubview(ToggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 3, width: view.frame.width, height: rowHeight), title: LocalizedString("Label"), action: #selector(toggleLabel), state: self.labelState )) self.boxSettingsView = ToggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 2, width: view.frame.width, height: rowHeight), title: LocalizedString("Box"), action: #selector(toggleBox), state: self.boxState ) view.addSubview(self.boxSettingsView!) self.frameSettingsView = ToggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 1, width: view.frame.width, height: rowHeight), title: LocalizedString("Frame"), action: #selector(toggleFrame), state: self.frameState ) view.addSubview(self.frameSettingsView!) view.addSubview(SelectColorRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight), title: LocalizedString("Color"), action: #selector(toggleColor), items: self.colors.map{ $0.rawValue }, selected: self.colorState.rawValue )) superview.addSubview(view) } @objc private func toggleLabel(_ sender: NSControl) { var state: NSControl.StateValue? = nil if #available(OSX 10.15, *) { state = sender is NSSwitch ? (sender as! NSSwitch).state: nil } else { state = sender is NSButton ? (sender as! NSButton).state: nil } self.labelState = state! == .on ? true : false self.store?.pointee.set(key: "\(self.title)_\(self.type.rawValue)_label", value: self.labelState) self.display() } @objc private func toggleBox(_ sender: NSControl) { var state: NSControl.StateValue? = nil if #available(OSX 10.15, *) { state = sender is NSSwitch ? (sender as! NSSwitch).state: nil } else { state = sender is NSButton ? (sender as! NSButton).state: nil } self.boxState = state! == .on ? true : false self.store?.pointee.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) if self.frameState { FindAndToggleNSControlState(self.frameSettingsView, state: .off) self.frameState = false self.store?.pointee.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) } self.display() } @objc private func toggleFrame(_ sender: NSControl) { var state: NSControl.StateValue? = nil if #available(OSX 10.15, *) { state = sender is NSSwitch ? (sender as! NSSwitch).state: nil } else { state = sender is NSButton ? (sender as! NSButton).state: nil } self.frameState = state! == .on ? true : false self.store?.pointee.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) if self.boxState { FindAndToggleNSControlState(self.boxSettingsView, state: .off) self.boxState = false self.store?.pointee.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) } self.display() } @objc private func toggleColor(_ sender: NSMenuItem) { if let newColor = widget_c.allCases.first(where: { $0.rawValue == sender.title }) { self.colorState = newColor self.store?.pointee.set(key: "\(self.title)_\(self.type.rawValue)_color", value: self.colorState.rawValue) self.display() } } }
39.470032
234
0.564178
5d04d73bb85b991e12606018c26fdd4c9a182fc1
2,503
// // CertificateViewController.swift // // // © Copyright IBM Deutschland GmbH 2021 // SPDX-License-Identifier: Apache-2.0 // import CovPassUI import UIKit private enum Constants { enum Accessibility { static let close = VoiceOverOptions.Settings(label: "accessibility_popup_label_close".localized) } } class CertificateViewController: UIViewController { // MARK: - IBOutlet @IBOutlet var headline: InfoHeaderView! @IBOutlet var imageView: UIImageView! @IBOutlet var toolbarView: CustomToolbarView! // MARK: - Properties private(set) var viewModel: CertificateViewModel // MARK: - Lifecycle @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init?(coder: NSCoder) not implemented yet") } init(viewModel: CertificateViewModel) { self.viewModel = viewModel super.init(nibName: String(describing: Self.self), bundle: .main) } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() configureImageView() configureHeadline() configureToolbarView() } // MARK: - Private private func configureImageView() { imageView.image = viewModel.image imageView.pinHeightToScaleAspectFit() } private func configureHeadline() { headline.attributedTitleText = nil headline.action = { [weak self] in self?.viewModel.cancel() } headline.image = .close headline.actionButton.enableAccessibility(label: Constants.Accessibility.close.label) } private func configureToolbarView() { toolbarView.state = .confirm("vaccination_certificate_detail_view_qrcode_screen_action_button_title".localized) toolbarView.setUpLeftButton(leftButtonItem: .disabledTextButton) toolbarView.layoutMargins.top = .space_24 toolbarView.delegate = self } } // MARK: - CustomToolbarViewDelegate extension CertificateViewController: CustomToolbarViewDelegate { func customToolbarView(_: CustomToolbarView, didTap buttonType: ButtonItemType) { switch buttonType { case .navigationArrow: viewModel.cancel() case .textButton: viewModel.done() default: return } } } // MARK: - ModalInteractiveDismissibleProtocol extension CertificateViewController: ModalInteractiveDismissibleProtocol { func modalViewControllerDidDismiss() { viewModel.cancel() } }
26.62766
119
0.684778
484a9cdd1c538d0aea7ff29a9d978eb64f7ebaf0
5,991
import Foundation import UIKit import KsApi import Library import ReactiveCocoa import Result import Prelude internal final class CommentsViewController: UITableViewController { private let viewModel: CommentsViewModelType = CommentsViewModel() private let dataSource = CommentsDataSource() // This button needs to store a strong reference so as to not get wiped when setting hidden state. @IBOutlet private var commentBarButton: UIBarButtonItem! private weak var loginToutViewController: UIViewController? = nil internal static func configuredWith(project project: Project? = nil, update: Update? = nil) -> CommentsViewController { let vc = Storyboard.Comments.instantiate(CommentsViewController) vc.viewModel.inputs.configureWith(project: project, update: update) return vc } internal override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self.dataSource NSNotificationCenter.defaultCenter() .addObserverForName(CurrentUserNotifications.sessionStarted, object: nil, queue: nil) { [weak self] _ in self?.viewModel.inputs.userSessionStarted() } self.viewModel.inputs.viewDidLoad() self.navigationItem.title = Strings.project_menu_buttons_comments() if self.traitCollection.userInterfaceIdiom == .Pad { self.navigationItem.leftBarButtonItem = .close(self, selector: #selector(closeButtonTapped)) } } internal override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: animated) } internal override func bindStyles() { super.bindStyles() self |> baseTableControllerStyle(estimatedRowHeight: 200.0) |> CommentsViewController.lens.view.backgroundColor .~ .whiteColor() self.commentBarButton |> UIBarButtonItem.lens.title %~ { _ in Strings.general_navigation_buttons_comment() } |> UIBarButtonItem.lens.accessibilityHint %~ { _ in Strings.accessibility_dashboard_buttons_post_update_hint() } } // swiftlint:disable function_body_length internal override func bindViewModel() { self.viewModel.outputs.closeLoginTout .observeForControllerAction() .observeNext { [weak self] in self?.loginToutViewController?.dismissViewControllerAnimated(true, completion: nil) } self.viewModel.outputs.commentBarButtonVisible .observeForUI() .observeNext { [weak self] visible in self?.navigationItem.rightBarButtonItem = visible ? self?.commentBarButton : nil } self.viewModel.outputs.commentsAreLoading .observeForUI() .observeNext { [weak self] in $0 ? self?.refreshControl?.beginRefreshing() : self?.refreshControl?.endRefreshing() } self.viewModel.outputs.dataSource .observeForUI() .observeNext { [weak self] comments, project, user in self?.dataSource.load(comments: comments, project: project, loggedInUser: user) self?.tableView.reloadData() } self.viewModel.outputs.emptyStateVisible .observeForControllerAction() .observeNext { [weak self] project, update in self?.dataSource.load(project: project, update: update) self?.tableView.reloadData() } self.viewModel.outputs.openLoginTout .observeForControllerAction() .observeNext { [weak self] in self?.presentLoginTout() } self.viewModel.outputs.presentPostCommentDialog .observeForControllerAction() .observeNext { [weak self] project, update in self?.presentCommentDialog(project: project, update: update) } } // swiftlint:enable function_body_length override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let emptyCell = cell as? CommentsEmptyStateCell { emptyCell.delegate = self } self.viewModel.inputs.willDisplayRow(self.dataSource.itemIndexAt(indexPath), outOf: self.dataSource.numberOfItems()) } internal func presentCommentDialog(project project: Project, update: Update?) { let dialog = CommentDialogViewController .configuredWith(project: project, update: update, recipient: nil, context: update == nil ? .projectComments : .updateComments) dialog.delegate = self let nav = UINavigationController(rootViewController: dialog) nav.modalPresentationStyle = .FormSheet self.presentViewController(nav, animated: true, completion: nil) } internal func presentLoginTout() { let login = LoginToutViewController.configuredWith(loginIntent: .generic) let nav = UINavigationController(rootViewController: login) nav.modalPresentationStyle = .FormSheet self.presentViewController(nav, animated: true, completion: nil) } @IBAction func commentButtonPressed() { self.viewModel.inputs.commentButtonPressed() } @IBAction internal func refresh() { self.viewModel.inputs.refresh() } @objc private func closeButtonTapped() { self.dismissViewControllerAnimated(true, completion: nil) } } extension CommentsViewController: CommentDialogDelegate { internal func commentDialogWantsDismissal(dialog: CommentDialogViewController) { dialog.dismissViewControllerAnimated(true, completion: nil) } internal func commentDialog(dialog: CommentDialogViewController, postedComment comment: Comment) { self.viewModel.inputs.commentPosted(comment) } } extension CommentsViewController: CommentsEmptyStateCellDelegate { internal func commentEmptyStateCellGoBackToProject() { self.navigationController?.popViewControllerAnimated(true) } internal func commentEmptyStateCellGoToCommentDialog() { self.viewModel.inputs.commentButtonPressed() } internal func commentEmptyStateCellGoToLoginTout() { self.viewModel.inputs.loginButtonPressed() } }
34.039773
110
0.7331
20e67e50b4939158c21ff6d30a8d9d10616ff9c5
2,734
// This is a super-simple 'hello world' app that demonstrates how to control // a Nova Bluetooth flash. // // See https://www.novaphotos.com/ // And https://github.com/novaphotos/nova-ios-sdk // // To keep things simple, this iOS app has no UI or camera. It simply connects // to the closest flash and toggles the light every second. // // -Joe Walnes import UIKit @UIApplicationMain class AppDelegate: NSObject, UIApplicationDelegate, NVFlashServiceDelegate { var flashService: NVFlashService! var timer: NSTimer! func applicationDidFinishLaunching(application: UIApplication) { NSLog("init") // Initialize flash service flashService = NVFlashService() // Optional: receive callbacks when flashes come into range or are connected/disconnected flashService.delegate = self // Auto connect to closest flash flashService.autoConnect = true // Uncomment to auto connect to more than one flash // flashService.autoConnectMaxFlashes = 4 // Set a timer to toggle flash every second. timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("toggleFlash"), userInfo: nil, repeats: true) } // When app is active enable bluetooth scanning func applicationDidBecomeActive(application: UIApplication) { NSLog("enable") flashService.enable() } // When app is not active, shut down bluetooth to conserve battery life func applicationWillResignActive(application: UIApplication) { NSLog("disable") flashService.disable() } // Called every second by timer func toggleFlash() { // choose the brightness and color temperature // warm/gentle/neutral/bright/custom/... let flashSettings = NVFlashSettings.warm() // loop through all connected flashes // typically just 1, but change autoConnectMaxFlashes above for more for flash in flashService.connectedFlashes as [NVFlash] { // toggle flash if (!flash.lit) { NSLog("activate flash %@", flash.identifier) flash.beginFlash(flashSettings) } else { NSLog("deactivate flash %@", flash.identifier) flash.endFlash() } } } // Optional NVFlashServiceDelegate callbacks to monitor connections func flashServiceConnectedFlash(flash: NVFlash) { NSLog("connected flash %@", flash.identifier) } func flashServiceDisconnectedFlash(flash: NVFlash) { NSLog("disconnect flash %@", flash.identifier) } }
30.719101
97
0.640454
c1adda09dc3d58b478b06a062f1874bd78a724a5
3,863
// // UnitTests.swift // CodeEdit // // Created by Lukas Pistrol on 19.04.22. // @testable import CodeEditUI import Foundation import SnapshotTesting import SwiftUI import XCTest final class CodeEditUIUnitTests: XCTestCase { // MARK: Help Button func testHelpButtonLight() throws { let view = HelpButton(action: {}) let hosting = NSHostingView(rootView: view) hosting.frame = CGRect(origin: .zero, size: .init(width: 40, height: 40)) hosting.appearance = .init(named: .aqua) assertSnapshot(matching: hosting, as: .image(size: .init(width: 40, height: 40))) } func testHelpButtonDark() throws { let view = HelpButton(action: {}) let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .darkAqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 40, height: 40)) assertSnapshot(matching: hosting, as: .image) } // MARK: Segmented Control func testSegmentedControlLight() throws { let view = SegmentedControl(.constant(0), options: ["Opt1", "Opt2"]) let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .aqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 100, height: 30)) assertSnapshot(matching: hosting, as: .image) } func testSegmentedControlDark() throws { let view = SegmentedControl(.constant(0), options: ["Opt1", "Opt2"]) let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .darkAqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 100, height: 30)) assertSnapshot(matching: hosting, as: .image) } // MARK: FontPickerView func testFontPickerViewLight() throws { let view = FontPicker("Font", name: .constant("SF-Mono"), size: .constant(13)) let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .aqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 120, height: 30)) assertSnapshot(matching: hosting, as: .image) } func testFontPickerViewDark() throws { let view = FontPicker("Font", name: .constant("SF-Mono"), size: .constant(13)) let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .darkAqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 120, height: 30)) assertSnapshot(matching: hosting, as: .image) } // MARK: EffectView func testEffectViewLight() throws { let view = EffectView() let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .aqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 20, height: 20)) assertSnapshot(matching: hosting, as: .image) } func testEffectViewDark() throws { let view = EffectView() let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .darkAqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 20, height: 20)) assertSnapshot(matching: hosting, as: .image) } // MARK: ToolbarBranchPicker func testBranchPickerLight() throws { let view = ToolbarBranchPicker(nil) let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .aqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 100, height: 50)) assertSnapshot(matching: hosting, as: .image) } func testBranchPickerDark() throws { let view = ToolbarBranchPicker(nil) let hosting = NSHostingView(rootView: view) hosting.appearance = .init(named: .darkAqua) hosting.frame = CGRect(origin: .zero, size: .init(width: 100, height: 50)) assertSnapshot(matching: hosting, as: .image) } }
36.443396
89
0.642247
1ed8b4307bef3c27efd48e5bae241018fb6b77d1
10,610
// // WatchCustom.swift // watchClock // // Created by [email protected] on 2018/11/9. // Copyright © 2018 [email protected]. All rights reserved. // import Foundation import SpriteKit class WatchSettings: NSObject, CnWeatherProtocol { static var GFaceNameList: [String] = ["empty", "Hermes_watch_face_original", "Hermes_watch_face_original_orange", "Hermes_watch_face_classic", "Hermes_watch_face_classic_orange", "Hermes_watch_face_roma", "Hermes_watch_face_roma_orange", "Hermes_watch_face_standard", "Hermes_watch_face_standard_orange", "Nike_watch_face_black", "Nike_watch_face_blue", "Nike_watch_face_green", "Nike_watch_face_greenblue", "Nike_watch_face_grey", "Nike_watch_face_night", "Nike_watch_face_pink", "Nike_watch_face_red", "Rolex_watch_face_black_gold", "Rolex_watch_face_black_silver", "Rolex_watch_face_black_white", "Rolex_watch_face_green", "Rolex_watch_face_luminous", "S4Numbers"] static var GHourImageList: [String] = ["Hermes_hours", "Hermes_hours_white", "HermesDoubleclour_H", "HermesDoubleclour_H_Orange", "HermesDoubleclour_H_Pink", "Nike_hours", "Nike_hours_red", "Rolex_hours_gold", "Rolex_hours_luminous", "Rolex_hours_write"] static var GMinuteImageList: [String] = ["Hermes_minutes", "Hermes_minutes_white", "HermesDoubleclour_M_Orange", "HermesDoubleclour_M_Pink", "Nike_minutes", "Nike_minutes_red", "Rolex_minutes_gold", "Rolex_minutes_luminous", "Rolex_minutes_write"] static var GMinutesAnchorFromBottoms: [CGFloat] = [16, 16, 18, 18, 17, 17, 17, 17, 17] static var GSecondImageList: [String] = ["empty", "Hermes_seconds", "Hermes_seconds_orange", "Nike_seconds", "Nike_seconds_orange", "Rolex_seconds_gold", "Rolex_seconds_luminous", "Rolex_seconds_write"] static var GSecondsAnchorFromBottoms: [CGFloat] = [0, 27, 27, 26, 26, 67, 67, 67] static var GLogoImageList: [String] = ["empty", "hermes_logo_white", "hermes_logo_2", "gucci_log", "constantin_logo", "Patek_Philippe_logo", "rolex_logo_gold", "apple_logo_color", "apple_logo_white"] static var GInfoBackgroud: [String] = ["empty", "info_back_1_52x46", "info_back_2_52x46", "info_back_3_36x32", "info_back_4_36x32" ] private var cnWeather: CnWeather? var weatherData: CnWeatherData? private override init() { super.init() self.loadSettings() // cnWeather = CnWeather() // cnWeather?.delegate = self // cnWeather?.beginTimer() // self._weekStyle = UserDefaults.standard.integer(forKey: "WeekStyle") // self._WeatherDrawColorAQI = UserDefaults.standard.bool(forKey: "DrawColorAQI") // self._weather_location = UserDefaults.standard.string(forKey: "WeatherLocation") ?? "" // self._weather_city = UserDefaults.standard.string(forKey: "WeatherCity") ?? "" // self._weatherIconSize = CGFloat(UserDefaults.standard.float(forKey: "WeatherIconSize")) // if (self._weatherIconSize == 0) { // self._weatherIconSize = 20 // } } static let sharedInstance = WatchSettings() static var WeekStyle1: [String] = ["日", "一", "二", "三", "四", "五", "六"] static var WeekStyle2: [String] = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"] static var WeekStyle3: [String] = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] private var _weekStyle: Int = 0 static var WeekStyle: Int { get { return sharedInstance._weekStyle } set { sharedInstance._weekStyle = newValue UserDefaults.standard.set(newValue, forKey: "WeekStyle") } } private var _weatherIconSize: CGFloat = 20 static var WeatherIconSize: CGFloat { get { return sharedInstance._weatherIconSize } set { sharedInstance._weatherIconSize = newValue UserDefaults.standard.set(newValue, forKey: "WeatherIconSize") } } private var _WeatherDrawColorAQI: Bool = true static var WeatherDrawColorAQI: Bool { get { return sharedInstance._WeatherDrawColorAQI } set { sharedInstance._WeatherDrawColorAQI = newValue UserDefaults.standard.set(newValue, forKey: "DrawColorAQI") } } private var _weather_city: String = "" static var WeatherCity: String { get { return sharedInstance._weather_city } set { sharedInstance._weather_city = newValue UserDefaults.standard.set(newValue, forKey: "WeatherCity") } } private var _weather_location: String = "" static var WeatherLocation: String { get { return sharedInstance._weather_location } set { sharedInstance._weather_location = newValue UserDefaults.standard.set(newValue, forKey: "WeatherLocation") sharedInstance.cnWeather?.beginTimer() } } private func loadSettings() { self._weekStyle = UserDefaults.standard.integer(forKey: "WeekStyle") self._WeatherDrawColorAQI = UserDefaults.standard.bool(forKey: "DrawColorAQI") self._weather_location = UserDefaults.standard.string(forKey: "WeatherLocation") ?? "" self._weather_city = UserDefaults.standard.string(forKey: "WeatherCity") ?? "" self._weatherIconSize = CGFloat(UserDefaults.standard.float(forKey: "WeatherIconSize")) if (self._weatherIconSize == 0) { self._weatherIconSize = 20 } } static var WeatherData: CnWeatherData? { get { return sharedInstance.weatherData } } static func reloadSettings() { sharedInstance.loadSettings() } func showWeather(_ data: CnWeatherData) { self.weatherData = data NotificationCenter.default.post(name: Notification.Name("WeatherDataUpdate"), object: self) // NotificationCenter.default.post(Notification.init(name: Notification.Name("WeatherDataUpdate"))) // self.currentWatch?.setWeatherData(data: data) } private func _loadWeatherData() { if (self.cnWeather == nil) { self.cnWeather = CnWeather() cnWeather?.delegate = self cnWeather?.beginTimer() } } static func LoadWeatherData() { sharedInstance._loadWeatherData() } } enum NumeralStyle: Int, Codable { case NumeralStyleAll, NumeralStyleCardinal, NumeralStyleNone } enum TickmarkStyle: Int, Codable { case TickmarkStyleAll, TickmarkStyleMajor, TickmarkStyleMinor, TickmarkStyleNone } enum WatchFaceStyle: Int, Codable { case WatchFaceStyleRound, WatchFaceStyleRectangle } extension UIFont { func SmallCaps() -> UIFont { let settings = [UIFontDescriptor.FeatureKey.featureIdentifier: kUpperCaseType, UIFontDescriptor.FeatureKey.typeIdentifier: kUpperCaseSmallCapsSelector] return UIFont.init(descriptor: UIFontDescriptor.init(fontAttributes: [UIFontDescriptor.AttributeName.featureSettings: settings, UIFontDescriptor.AttributeName.name: self.fontName]), size: self.pointSize) } } extension UIImage { public class func imageWithColor(color: UIColor, size: CGSize) -> UIImage? { UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(UIColor.white.cgColor) context?.fill(CGRect.init(x: 0, y: 0, width: size.width, height: size.height)) context?.setFillColor(color.cgColor) context?.fill(CGRect.init(x: 1, y: 1, width: size.width - 2, height: size.height - 2)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public class func imageWithPureColor(color: UIColor, size: CGSize) -> UIImage? { UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(CGRect.init(x: 0, y: 0, width: size.width, height: size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
38.581818
211
0.523186
67777f9f00014a79e305166a17bf8cf33431591d
1,947
// // TextRecognitionResultsViewTests.swift // VisionCameraDemoTests // // Created by David Steppenbeck on 2020/05/13. // Copyright © 2020 David Steppenbeck. All rights reserved. // import XCTest @testable import VisionCameraDemo final class TextRecognitionResultsViewTests: XCTestCase { var sut: TextRecognitionResultsView! override func setUp() { super.setUp() sut = TextRecognitionResultsView() } override func tearDown() { sut = nil super.tearDown() } func testAllTextBoundingBoxes() { // The text bounding boxes collection should be empty following initialization. let allTextBoundingBoxes = sut.allTextBoundingBoxes // Check the actual value against the expected result. XCTAssertTrue(allTextBoundingBoxes.isEmpty) } func testSublayers() { // There should be no sublayers following initialization. let sublayers = sut.layer.sublayers // Check the actual value against the expected result. XCTAssertNil(sublayers) } func testAddBoxes() throws { // Create a "box" to add to the view. let box = CAShapeLayer() let boxes: Set<TextBoundingBox> = [box] // Should add the boxes in the collection to the view as sublayers. sut.add(boxes) // Check the actual value against the expected result. let sublayers = try XCTUnwrap(sut.layer.sublayers) XCTAssertEqual(sublayers.count, 1) XCTAssertEqual(sublayers.first, box) XCTAssertEqual(sut.allTextBoundingBoxes.count, 1) XCTAssertEqual(sut.allTextBoundingBoxes.first, box) // Adding an empty set should then clear all the "boxes" from the collection and the view. sut.add([]) // Check the actual value against the expected result. XCTAssertNil(sut.layer.sublayers) XCTAssertTrue(sut.allTextBoundingBoxes.isEmpty) } }
29.5
98
0.675912