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
d71d54014e6feb3a69914b8f5f7316252a8960f3
7,565
// // OperatorUsageWhitespaceRule.swift // SwiftLint // // Created by Marcelo Fabri on 12/13/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct OperatorUsageWhitespaceRule: OptInRule, CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "operator_usage_whitespace", name: "Operator Usage Whitespace", description: "Operators should be surrounded by a single whitespace " + "when they are being used.", nonTriggeringExamples: [ "let foo = 1 + 2\n", "let foo = 1 > 2\n", "let foo = !false\n", "let foo: Int?\n", "let foo: Array<String>\n", "let foo: [String]\n", "let foo = 1 + \n 2\n", "let range = 1...3\n", "let range = 1 ... 3\n", "let range = 1..<3\n", "#if swift(>=3.0)\n", "array.removeAtIndex(-200)\n", "let name = \"image-1\"\n", "button.setImage(#imageLiteral(resourceName: \"image-1\"), for: .normal)\n", "let doubleValue = -9e-11\n" ], triggeringExamples: [ "let foo = 1↓+2\n", "let foo = 1↓ + 2\n", "let foo = 1↓ + 2\n", "let foo = 1↓ + 2\n", "let foo↓=1↓+2\n", "let foo↓=1 + 2\n", "let foo↓=bar\n", "let range = 1↓ ..< 3\n", "let foo = bar↓ ?? 0\n", "let foo = bar↓??0\n", "let foo = bar↓ != 0\n", "let foo = bar↓ !== bar2\n", "let v8 = Int8(1)↓ << 6\n", "let v8 = 1↓ << (6)\n", "let v8 = 1↓ << (6)\n let foo = 1 > 2\n" ], corrections: [ "let foo = 1↓+2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo↓=1↓+2\n": "let foo = 1 + 2\n", "let foo↓=1 + 2\n": "let foo = 1 + 2\n", "let foo↓=bar\n": "let foo = bar\n", "let range = 1↓ ..< 3\n": "let range = 1..<3\n", "let foo = bar↓ ?? 0\n": "let foo = bar ?? 0\n", "let foo = bar↓??0\n": "let foo = bar ?? 0\n", "let foo = bar↓ != 0\n": "let foo = bar != 0\n", "let foo = bar↓ !== bar2\n": "let foo = bar !== bar2\n", "let v8 = Int8(1)↓ << 6\n": "let v8 = Int8(1) << 6\n", "let v8 = 1↓ << (6)\n": "let v8 = 1 << (6)\n", "let v8 = 1↓ << (6)\n let foo = 1 > 2\n": "let v8 = 1 << (6)\n let foo = 1 > 2\n" ] ) public func validate(file: File) -> [StyleViolation] { return violationRanges(file: file).map { range, _ in StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: range.location)) } } private func violationRanges(file: File) -> [(NSRange, String)] { let escapedOperators = ["/", "=", "-", "+", "*", "|", "^", "~"].map({ "\\\($0)" }).joined() let rangePattern = "\\.\\.(?:\\.|<)" // ... or ..< let notEqualsPattern = "\\!\\=\\=?" // != or !== let coalescingPattern = "\\?{2}" let operators = "(?:[\(escapedOperators)%<>&]+|\(rangePattern)|\(coalescingPattern)|" + "\(notEqualsPattern))" let oneSpace = "[^\\S\\r\\n]" // to allow lines ending with operators to be valid let zeroSpaces = oneSpace + "{0}" let manySpaces = oneSpace + "{2,}" let leadingVariableOrNumber = "(?:\\b|\\))" let trailingVariableOrNumber = "(?:\\b|\\()" let spaces = [(zeroSpaces, zeroSpaces), (oneSpace, manySpaces), (manySpaces, oneSpace), (manySpaces, manySpaces)] let patterns = spaces.map { first, second in leadingVariableOrNumber + first + operators + second + trailingVariableOrNumber } let pattern = "(?:\(patterns.joined(separator: "|")))" let genericPattern = "<(?:\(oneSpace)|\\S)+?>" // not using dot to avoid matching new line let validRangePattern = leadingVariableOrNumber + zeroSpaces + rangePattern + zeroSpaces + trailingVariableOrNumber let excludingPattern = "(?:\(genericPattern)|\(validRangePattern))" let excludingKinds = SyntaxKind.commentAndStringKinds() + [.objectLiteral] return file.match(pattern: pattern, excludingSyntaxKinds: excludingKinds, excludingPattern: excludingPattern).flatMap { range in // if it's only a number (i.e. -9e-11), it shouldn't trigger guard kinds(in: range, file: file) != [.number] else { return nil } let spacesPattern = oneSpace + "*" let rangeRegex = regex(spacesPattern + rangePattern + spacesPattern) // if it's a range operator, the correction shouldn't have spaces if let matchRange = rangeRegex.firstMatch(in: file.contents, options: [], range: range)?.range { let correction = operatorInRange(file: file, range: matchRange) return (matchRange, correction) } let pattern = spacesPattern + operators + spacesPattern let operatorsRegex = regex(pattern) guard let matchRange = operatorsRegex.firstMatch(in: file.contents, options: [], range: range)?.range else { return nil } let operatorContent = operatorInRange(file: file, range: matchRange) let correction = " " + operatorContent + " " return (matchRange, correction) } } private func kinds(in range: NSRange, file: File) -> [SyntaxKind] { let contents = file.contents.bridge() guard let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length) else { return [] } return file.syntaxMap.tokens(inByteRange: byteRange).flatMap { SyntaxKind(rawValue: $0.type) } } private func operatorInRange(file: File, range: NSRange) -> String { return file.contents.bridge().substring(with: range).trimmingCharacters(in: .whitespaces) } public func correct(file: File) -> [Correction] { let violatingRanges = violationRanges(file: file).filter { range, _ in return !file.ruleEnabled(violatingRanges: [range], for: self).isEmpty } var correctedContents = file.contents var adjustedLocations = [Int]() for (violatingRange, correction) in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents .replacingCharacters(in: indexRange, with: correction) adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } }
41.565934
109
0.527032
5daae425466695b63279ce2f9cbcb22f6258db50
2,324
// APIs.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class bombbomb-swift-openapiAPI { public static var basePath = "https://api.bombbomb.com/v2" public static var credential: NSURLCredential? public static var customHeaders: [String:String] = [:] static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() } public class APIBase { func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { let encoded: AnyObject? = encodable?.encodeToJSON() if encoded! is [AnyObject] { var dictionary = [String:AnyObject]() for (index, item) in (encoded as! [AnyObject]).enumerate() { dictionary["\(index)"] = item } return dictionary } else { return encoded as? [String:AnyObject] } } } public class RequestBuilder<T> { var credential: NSURLCredential? var headers: [String:String] let parameters: [String:AnyObject]? let isBody: Bool let method: String let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((NSProgress) -> ())? required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody self.headers = headers addHeaders(bombbomb-swift-openapiAPI.customHeaders) } public func addHeaders(aHeaders:[String:String]) { for (header, value) in aHeaders { headers[header] = value } } public func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) { } public func addHeader(name name: String, value: String) -> Self { if !value.isEmpty { headers[name] = value } return self } public func addCredential() -> Self { self.credential = bombbomb-swift-openapiAPI.credential return self } } protocol RequestBuilderFactory { func getBuilder<T>() -> RequestBuilder<T>.Type }
29.794872
140
0.633821
2199748632f80f05a0aaaff234ab4033b703af79
685
import Foundation enum Endpoint { struct Overview: Codable { let active_subscribers_count: Int let active_trials_count: Int let active_users_count: Int let installs_count: Int let mrr: Double let revenue: Double } struct Transaction: Codable, Hashable { let store_transaction_identifier: String } struct Transactions: Codable, Hashable { let transactions: [Transaction] } struct Error: Decodable { let code: Int let message: String } struct Response { let transactions: Set<Endpoint.Transaction> let overview: Endpoint.Overview } }
22.096774
51
0.624818
f972f12103db176eb94b166c3da0f6eb79af8881
621
// // KitchenMapper.swift // FoodieApp-iOS // // Created by omrobbie on 20/11/20. // struct KitchenMapper { static func mapResponseToDomain(response: [KitchenResponse]) -> [KitchenModel] { response.map { result in KitchenModel( kitchenId: result.kitchenId ?? "", name: result.name ?? "", category: result.category ?? "", rating: result.rating ?? 0, longitude: result.longitude ?? 0, latitude: result.latitude ?? 0, imageName: result.imageName ?? "" ) } } }
27
84
0.515298
5be7f8b08ca18a335aedccc47bbdc4ff164b984d
619
// // DogAllOf.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif public struct DogAllOf: Codable { public var breed: String? public init(breed: String? = nil) { self.breed = breed } public enum CodingKeys: String, CodingKey, CaseIterable { case breed } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } }
19.34375
67
0.675283
624700a97c12796a98a72708673af64207cfe258
620
import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! let mainWindowController = MainWindowController() func applicationDidFinishLaunching(aNotification: NSNotification) { mainWindowController.showWindow(self) } func applicationDidBecomeActive(notification: NSNotification) { println("applicationDidBecomeActive") } func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { mainWindowController.showWindow(self) return true } }
24.8
101
0.730645
567004a872f56441ea958275eb1123b9b8160167
3,297
// Copyright 2018-2019 Yubico AB // // 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. protocol KeySessionObserverDelegate: NSObjectProtocol { func keySessionObserver(_ observer: KeySessionObserver, sessionStateChangedTo state: YKFKeySessionState) } /* The KeySessionObserver is an example on how to wrap the KVO observation of the Key Session into a separate class and use a delegate to notify about state changes. This example can be used to mask the KVO code when the target application prefers a delegate pattern. */ class KeySessionObserver: NSObject { private weak var delegate: KeySessionObserverDelegate? private var queue: DispatchQueue? private static var observationContext = 0 private var isObservingSessionStateUpdates = false init(delegate: KeySessionObserverDelegate, queue: DispatchQueue? = nil) { self.delegate = delegate self.queue = queue super.init() observeSessionState = true } deinit { observeSessionState = false } var observeSessionState: Bool { get { return isObservingSessionStateUpdates } set { guard newValue != isObservingSessionStateUpdates else { return } isObservingSessionStateUpdates = newValue let keySession = YubiKitManager.shared.keySession as AnyObject let keyPath = #keyPath(YKFKeySession.sessionState) if isObservingSessionStateUpdates { keySession.addObserver(self, forKeyPath: keyPath, options: [], context: &KeySessionObserver.observationContext) } else { keySession.removeObserver(self, forKeyPath: keyPath) } } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &KeySessionObserver.observationContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } switch keyPath { case #keyPath(YKFKeySession.sessionState): keySessionStateDidChange() default: fatalError() } } func keySessionStateDidChange() { let queue = self.queue ?? DispatchQueue.main queue.async { [weak self] in guard let self = self else { return } guard let delegate = self.delegate else { return } let state = YubiKitManager.shared.keySession.sessionState delegate.keySessionObserver(self, sessionStateChangedTo: state) } } }
35.451613
151
0.653321
145bd0c836f422895c298be62f25060ec314166e
3,770
// // RouteComposer // SingleContainerStep.swift // https://github.com/ekazaev/route-composer // // Created by Eugene Kazaev in 2018-2022. // Distributed under the MIT license. // import Foundation import UIKit /// A simple class that produces an intermediate `ActionToStepIntegrator` describing a container view controller. public class SingleContainerStep<F: Finder, FC: ContainerFactory>: ActionToStepIntegrator<F.ViewController, F.Context> where F.ViewController == FC.ViewController, F.Context == FC.Context { // MARK: Internal entities final class UnsafeWrapper<VC: UIViewController, C, F: Finder, FC: ContainerFactory>: ActionToStepIntegrator<VC, C> where F.ViewController == FC.ViewController, F.Context == FC.Context { final let step: SingleContainerStep<F, FC> init(step: SingleContainerStep<F, FC>) { self.step = step super.init(taskCollector: step.taskCollector) } final override func routingStep<A: Action>(with action: A) -> RoutingStep? { step.routingStep(with: action) } final override func embeddableRoutingStep<A: ContainerAction>(with action: A) -> RoutingStep? { step.embeddableRoutingStep(with: action) } } // MARK: Properties final let finder: F final let factory: FC // MARK: Methods /// Creates an instance of the `ActionToStepIntegrator` describing a container view controller. /// /// - Parameters: /// - finder: The `UIViewController` `Finder`. /// - factory: The `UIViewController` `ContainerFactory`. public init(finder: F, factory: FC) { self.finder = finder self.factory = factory } final override func routingStep<A: Action>(with action: A) -> RoutingStep { let entitiesCollector = BaseEntitiesCollector<ContainerFactoryBox<FC>, ActionBox>(finder: finder, factory: factory, action: action) return BaseStep(entitiesProvider: entitiesCollector, taskProvider: taskCollector) } final override func embeddableRoutingStep<A: ContainerAction>(with action: A) -> RoutingStep { let entitiesCollector = BaseEntitiesCollector<ContainerFactoryBox<FC>, ContainerActionBox>(finder: finder, factory: factory, action: action) return BaseStep(entitiesProvider: entitiesCollector, taskProvider: taskCollector) } /// Adapts context and view controller type dependencies. /// /// *NB:* Developer guaranties that this types will compliment in runtime. public final func unsafelyRewrapped<VC: UIViewController, C>() -> ActionToStepIntegrator<VC, C> { UnsafeWrapper(step: self) } /// Allows to avoid container view controller check. /// /// *NB:* Developer guaranties that it will be there in the runtime. public final func expectingContainer<VC: ContainerViewController>() -> ActionToStepIntegrator<VC, F.Context> { UnsafeWrapper(step: self) } } // MARK: Helper methods where the Context is Any? public extension SingleContainerStep where FC.Context == Any? { /// Allows to avoid container view controller check. This method is available only for the steps that are /// able to accept any type of context. /// /// *NB:* Developer guaranties that it will be there in the runtime. final func expectingContainer<VC: ContainerViewController, C>() -> ActionToStepIntegrator<VC, C> { UnsafeWrapper(step: self) } /// Allows to compliment to the type check. A step that has context equal to Optional(Any) can be build /// with any type of context passed to the router. final func adaptingContext<C>() -> ActionToStepIntegrator<F.ViewController, C> { UnsafeWrapper(step: self) } }
36.25
148
0.692573
d90465885ac5a674038ced8a6516f5ea1f4aa844
711
// // UIView+ViewController.swift // MMBaseFramework // // Created by soft7 on 2018/5/10. // #if os(iOS) || os(tvOS) import Foundation import UIKit extension UIView { public func mm_viewController() -> MMViewController? { return mm_UIViewController() as? MMViewController } public func mm_UIViewController() -> UIViewController? { var nextResponder: UIResponder? = self repeat { nextResponder = nextResponder?.next if let viewController = nextResponder as? UIViewController { return viewController } } while nextResponder != nil return nil } } #endif
22.935484
72
0.592124
21be4dc83817530a654965a4e3a197d904bbd74b
196
// // AppDelegate.swift // SPMExample // // Copyright © 2020 Giftbot. All rights reserved. // import UIKit @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate { }
14
61
0.734694
4649298a058005da535735ba1b50ffa00badb560
850
import XCTest @testable import CDecNumber final class CDecNumberTests: XCTestCase { func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. // XCTAssertEqual(CDecNumber().text, "Hello, World!") var c = decContext() var s = [CChar](repeating: 0, count: 32) decContextDefault(&c, DEC_INIT_BASE) c.traps = 0 c.round = DEC_ROUND_HALF_UP var a = decNumber(), b = decNumber(), d = decNumber() c.digits = 15 decNumberFromString(&a, "111111111111", &c) decNumberFromString(&b, "111111111", &c) c.digits = 9 decNumberXor(&d, &a, &b, &c) decNumberToString(&d, &s) print(String(cString: s)) } }
32.692308
87
0.595294
efb0de838ec8dfef1e621415b21bde0400326c01
1,779
// // MediaItemMultipleBadgeView.swift // Neebla // // Created by Christopher G Prince on 6/25/21. // import Foundation import SwiftUI struct MediaItemMultipleBadgeView: View { @ObservedObject var model:MediaItemMultipleBadgeViewModel let size: CGSize // size of each badge view init(object: ServerObjectModel, maxNumberOthersBadges: Int, size: CGSize) { model = MediaItemMultipleBadgeViewModel(object: object, maxNumberOthersBadges: maxNumberOthersBadges) self.size = size } var body: some View { VStack { // Not showing a .hide badge because we show a special image for this. And because it seems a little confusing to have both the special image and a hide badge. if let badges = model.mediaItemBadges, badges.selfBadge != .hide { if let selfBadge = model.mediaItemBadges?.selfBadge { MediaItemSingleBadgeView(badge: selfBadge, size: size) } if badges.othersBadges.count > 0 { VStack(spacing: 0) { Text("Others") .foregroundColor(Color(UIColor.darkGray)) .font(Font.system(size: 14)) // If there is no self-badge, the gray border around these (if any) should make it clear that they are not self badges. ForEach(badges.othersBadges, id: \.userId) { userBadge in MediaItemSingleBadgeView(badge: userBadge.badge, size: size) } } .padding(5) .border(Color.gray, width: 2) } } } } }
38.673913
171
0.554806
ff2bb88905290d2f0cc1cb544442a379b48dd8b0
1,319
// // Address.swift // restaurant // // Created by love on 6/23/19. // Copyright © 2019 love. All rights reserved. // import Foundation import MapKit import Realm import RealmSwift class Address: Object, Codable { @objc dynamic var id = Int() @objc dynamic var title = String() @objc dynamic var fullName = String() @objc dynamic var phoneNumber = String() @objc dynamic var address = String() @objc dynamic var longitude = Double() @objc dynamic var latitude = Double() @objc dynamic var createdDate = Date() @objc dynamic var isDefault = true override static func primaryKey() -> String? { return "id" } convenience init(title: String, fullName: String, phoneNumber: String, address: String, longitude: Double, latitude: Double) { self.init() self.title = title self.fullName = fullName self.phoneNumber = phoneNumber self.address = address self.longitude = longitude self.latitude = latitude } required init() { super.init() } required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } required init(value: Any, schema: RLMSchema) { super.init(value: value, schema: schema) } }
25.365385
130
0.630781
2f3f6505c70aa328186c7d6d14c35b2d99cec23e
488
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -emit-silgen enum e<b> : d { func c<b>() -> b { } } protocol d { func c<b>()(_: b) -> b }
30.5
78
0.680328
0a286cc60a418c6323e05f3bb8ce9bf4a4f820aa
2,436
import Advent import Year2019 import XCTest final class Day05Tests: XCTestCase { func testPart1Puzzle() throws { let day = Day05() let input = try Bundle.module.input(named: "Day05") let result = try day.part1(input: input) XCTAssertEqual(result, 9006673) } private func run(code: [Int], input: Int) throws -> Int { var computer = IntcodeComputer(code: code) computer.input(input) try computer.run() return computer.output.first ?? .min } func testPart2Example1() throws { let code = [3,9,8,9,10,9,4,9,99,-1,8] XCTAssertEqual(try run(code: code, input: 8), 1) XCTAssertEqual(try run(code: code, input: 7), 0) } func testPart2Example2() throws { let code = [3,9,7,9,10,9,4,9,99,-1,8] XCTAssertEqual(try run(code: code, input: 7), 1) XCTAssertEqual(try run(code: code, input: 8), 0) } func testPart2Example3() throws { let code = [3,3,1108,-1,8,3,4,3,99] XCTAssertEqual(try run(code: code, input: 8), 1) XCTAssertEqual(try run(code: code, input: 9), 0) } func testPart2Example4() throws { let code = [3,3,1107,-1,8,3,4,3,99] XCTAssertEqual(try run(code: code, input: 7), 1) XCTAssertEqual(try run(code: code, input: 8), 0) } func testPart2Example5() throws { let code = [3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9] XCTAssertEqual(try run(code: code, input: 0), 0) XCTAssertEqual(try run(code: code, input: 8), 1) } func testPart2Example6() throws { let code = [3,3,1105,-1,9,1101,0,0,12,4,12,99,1] XCTAssertEqual(try run(code: code, input: 0), 0) XCTAssertEqual(try run(code: code, input: 8), 1) } func testPart2Example7() throws { let code = [3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31, 1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104, 999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99] XCTAssertEqual(try run(code: code, input: 7), 999) XCTAssertEqual(try run(code: code, input: 8), 1000) XCTAssertEqual(try run(code: code, input: 9), 1001) } func testPart2Puzzle() throws { let day = Day05() let input = try Bundle.module.input(named: "Day05") let result = try day.part2(input: input) XCTAssertEqual(result, 3629692) } }
32.918919
72
0.589901
f8b1484c263374036ca58a3e1f5368a9fe0a20ba
898
// // NetworkTests.swift // SourceryExampleTests // // Created by Gabriel Marson on 13/06/20. // Copyright © 2020 Gabriel Marson. All rights reserved. // import XCTest @testable import SourceryExample class ViewModelTests: XCTestCase { func testIfRequestWasCalled() { // given let networkLayer = NetworkDispatcherMock(baseUrl: "") let someViewModel = SomeViewModel(network: networkLayer) // when someViewModel.requestWhatViewModelNeeds() // then XCTAssert(networkLayer.requestMethodHeadersOnCompletionCalled) } } private class SomeViewModel { var network: NetworkDispatcher init(network: NetworkDispatcher) { self.network = network } func requestWhatViewModelNeeds() { network.request(method: .get, headers: ["someHeaders":"someValues"], onCompletion: nil) } }
23.025641
95
0.668151
21c250ab1c363c1af11ddac01a301f28c2253d70
1,068
// // AppDelegate.swift // BenchMark // // Created by didi on 2021/3/3. // import UIKit import Hummer @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. Hummer.startEngine(nil); // let path = Bundle.main.path(forResource: "/dist/scroller", ofType: "js") let path = Bundle.main.path(forResource: "/tenon-dist/scroller", ofType: "js") let file = URL.init(fileURLWithPath: path!); self.window = UIWindow.init(frame: UIScreen.main.bounds) let vc = ViewController.init(url: file.absoluteString, params: nil) let nav = UINavigationController.init(rootViewController: vc!); nav.navigationBar.isTranslucent = false; self.window?.rootViewController = nav self.window?.makeKeyAndVisible() return true } }
28.864865
145
0.675094
500401ed67a4d7a82b1948758374eeb1fd4c3d4e
8,661
// // CategoriesTable.swift // MySampleApp // // // Copyright 2017 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.10 // import Foundation import UIKit import AWSDynamoDB import AWSMobileHubHelper class CategoriesTable: NSObject, Table { var tableName: String var partitionKeyName: String var partitionKeyType: String var sortKeyName: String? var sortKeyType: String? var model: AWSDynamoDBObjectModel var indexes: [Index] var orderedAttributeKeys: [String] { return produceOrderedAttributeKeys(model) } var tableDisplayName: String { return "categories" } override init() { model = Categories() tableName = model.classForCoder.dynamoDBTableName() partitionKeyName = model.classForCoder.hashKeyAttribute() partitionKeyType = "String" indexes = [ ] if let sortKeyNamePossible = model.classForCoder.rangeKeyAttribute?() { sortKeyName = sortKeyNamePossible } super.init() } /** * Converts the attribute name from data object format to table format. * * - parameter dataObjectAttributeName: data object attribute name * - returns: table attribute name */ func tableAttributeName(_ dataObjectAttributeName: String) -> String { return Categories.jsonKeyPathsByPropertyKey()[dataObjectAttributeName] as! String } func getItemDescription() -> String { let hashKeyValue = AWSIdentityManager.default().identityId! return "Find Item with userId = \(hashKeyValue)." } func getItemWithCompletionHandler(_ completionHandler: @escaping (_ response: AWSDynamoDBObjectModel?, _ error: NSError?) -> Void) { let objectMapper = AWSDynamoDBObjectMapper.default() objectMapper.load(Categories.self, hashKey: AWSIdentityManager.default().identityId!, rangeKey: nil) { (response: AWSDynamoDBObjectModel?, error: Error?) in DispatchQueue.main.async(execute: { completionHandler(response, error as NSError?) }) } } func scanDescription() -> String { return "Show all items in the table." } func scanWithCompletionHandler(_ completionHandler: @escaping (_ response: AWSDynamoDBPaginatedOutput?, _ error: NSError?) -> Void) { let objectMapper = AWSDynamoDBObjectMapper.default() let scanExpression = AWSDynamoDBScanExpression() scanExpression.limit = 5 objectMapper.scan(Categories.self, expression: scanExpression) { (response: AWSDynamoDBPaginatedOutput?, error: Error?) in DispatchQueue.main.async(execute: { completionHandler(response, error as NSError?) }) } } func scanWithFilterDescription() -> String { let scanFilterValue = 1111500000 return "Find all items with idCategory < \(scanFilterValue)." } func scanWithFilterWithCompletionHandler(_ completionHandler: @escaping (_ response: AWSDynamoDBPaginatedOutput?, _ error: NSError?) -> Void) { let objectMapper = AWSDynamoDBObjectMapper.default() let scanExpression = AWSDynamoDBScanExpression() scanExpression.filterExpression = "#idCategory < :idCategory" scanExpression.expressionAttributeNames = ["#idCategory": "idCategory" ,] scanExpression.expressionAttributeValues = [":idCategory": 1111500000 ,] objectMapper.scan(Categories.self, expression: scanExpression) { (response: AWSDynamoDBPaginatedOutput?, error: Error?) in DispatchQueue.main.async(execute: { completionHandler(response, error as? NSError) }) } } func insertSampleDataWithCompletionHandler(_ completionHandler: @escaping (_ errors: [NSError]?) -> Void) { let objectMapper = AWSDynamoDBObjectMapper.default() var errors: [NSError] = [] let group: DispatchGroup = DispatchGroup() let numberOfObjects = 20 let itemForGet: Categories! = Categories() itemForGet._userId = AWSIdentityManager.default().identityId! itemForGet._idCategory = NoSQLSampleDataGenerator.randomSampleNumber() itemForGet._nmCategory = NoSQLSampleDataGenerator.randomSampleStringWithAttributeName("nmCategory") group.enter() objectMapper.save(itemForGet, completionHandler: {(error: Error?) -> Void in if let error = error as? NSError { DispatchQueue.main.async(execute: { errors.append(error) }) } group.leave() }) for _ in 1..<numberOfObjects { let item: Categories = Categories() item._userId = AWSIdentityManager.default().identityId! item._idCategory = NoSQLSampleDataGenerator.randomSampleNumber() item._nmCategory = NoSQLSampleDataGenerator.randomSampleStringWithAttributeName("nmCategory") group.enter() objectMapper.save(item, completionHandler: {(error: Error?) -> Void in if error != nil { DispatchQueue.main.async(execute: { errors.append(error! as NSError) }) } group.leave() }) } group.notify(queue: DispatchQueue.main, execute: { if errors.count > 0 { completionHandler(errors) } else { completionHandler(nil) } }) } func removeSampleDataWithCompletionHandler(_ completionHandler: @escaping ([NSError]?) -> Void) { let objectMapper = AWSDynamoDBObjectMapper.default() let queryExpression = AWSDynamoDBQueryExpression() queryExpression.keyConditionExpression = "#userId = :userId" queryExpression.expressionAttributeNames = ["#userId": "userId"] queryExpression.expressionAttributeValues = [":userId": AWSIdentityManager.default().identityId!,] objectMapper.query(Categories.self, expression: queryExpression) { (response: AWSDynamoDBPaginatedOutput?, error: Error?) in if let error = error as? NSError { DispatchQueue.main.async(execute: { completionHandler([error]); }) } else { var errors: [NSError] = [] let group: DispatchGroup = DispatchGroup() for item in response!.items { group.enter() objectMapper.remove(item, completionHandler: {(error: Error?) in if let error = error as? NSError { DispatchQueue.main.async(execute: { errors.append(error) }) } group.leave() }) } group.notify(queue: DispatchQueue.main, execute: { if errors.count > 0 { completionHandler(errors) } else { completionHandler(nil) } }) } } } func updateItem(_ item: AWSDynamoDBObjectModel, completionHandler: @escaping (_ error: NSError?) -> Void) { let objectMapper = AWSDynamoDBObjectMapper.default() let itemToUpdate: Categories = item as! Categories itemToUpdate._idCategory = NoSQLSampleDataGenerator.randomSampleNumber() itemToUpdate._nmCategory = NoSQLSampleDataGenerator.randomSampleStringWithAttributeName("nmCategory") objectMapper.save(itemToUpdate, completionHandler: {(error: Error?) in DispatchQueue.main.async(execute: { completionHandler(error as? NSError) }) }) } func removeItem(_ item: AWSDynamoDBObjectModel, completionHandler: @escaping (_ error: NSError?) -> Void) { let objectMapper = AWSDynamoDBObjectMapper.default() objectMapper.remove(item, completionHandler: {(error: Error?) in DispatchQueue.main.async(execute: { completionHandler(error as? NSError) }) }) } }
37.493506
164
0.605126
3a9227e54512718621a659b25e62be3a21478fcc
13,515
// // SeeAll.swift // appdb // // Created by ned on 21/04/2018. // Copyright © 2018 ned. All rights reserved. // import UIKit import ObjectMapper class SeeAll: LoadingTableView { var type: ItemType = .ios var categoryId: String = "" var devId: String = "" var price: Price = .all var order: Order = .added var query: String = "" private var currentPage: Int = 1 private var allLoaded: Bool = false var items: [Item] = [] private var filteredItems: [Item] = [] private let searchController = UISearchController(searchResultsController: nil) // Store the result from registerForPreviewing(with:sourceView:) var previewingContext: UIViewControllerPreviewing? // Called when 'See All' button is clicked convenience init(title: String, type: ItemType, category: String, price: Price, order: Order) { self.init(style: .plain) self.title = title self.type = type self.categoryId = category self.price = price self.order = order } // Called when 'See more from this dev/author' is clicked convenience init(title: String, type: ItemType, devId: String) { self.init(style: .plain) self.title = title self.type = type self.devId = devId } override func viewDidLoad() { super.viewDidLoad() tableView.register(SeeAllCell.self, forCellReuseIdentifier: "seeallcell") tableView.register(SeeAllCell.self, forCellReuseIdentifier: "seeallcell_book") tableView.register(SeeAllCellWithStars.self, forCellReuseIdentifier: "seeallcellwithstars") tableView.register(SeeAllCellWithStars.self, forCellReuseIdentifier: "seeallcellwithstars_book") tableView.rowHeight = type == .books ? (130 ~~ 110) : (105 ~~ 85) tableView.theme_separatorColor = Color.borderColor tableView.theme_backgroundColor = Color.tableViewBackgroundColor view.theme_backgroundColor = Color.tableViewBackgroundColor animated = false showsErrorButton = false showsSpinner = false if #available(iOS 9.0, *), traitCollection.forceTouchCapability == .available { previewingContext = registerForPreviewing(with: self, sourceView: tableView) } // Hide the 'Back' text on back button let backItem = UIBarButtonItem(title: "", style: .done, target: nil, action: nil) navigationItem.backBarButtonItem = backItem // Hide last separator tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1)) // Search Controller navigationItem.hidesSearchBarWhenScrolling = false searchController.searchResultsUpdater = self searchController.delegate = self if #available(iOS 9.1, *) { searchController.obscuresBackgroundDuringPresentation = false } switch type { case .ios: searchController.searchBar.placeholder = "Search iOS Apps".localized() case .cydia: searchController.searchBar.placeholder = "Search Cydia Apps".localized() case .books: searchController.searchBar.placeholder = "Search Books".localized() default: break } searchController.searchBar.textField?.theme_textColor = Color.title searchController.searchBar.textField?.theme_keyboardAppearance = [.light, .dark, .dark] definesPresentationContext = true if #available(iOS 11.0, *) { navigationItem.searchController = searchController } else { searchController.searchBar.barStyle = .default searchController.searchBar.searchBarStyle = .minimal searchController.searchBar.showsScopeBar = false searchController.hidesNavigationBarDuringPresentation = false navigationItem.titleView = searchController.searchBar } if Global.isIpad { // Add 'Dismiss' button for iPad let dismissButton = UIBarButtonItem(title: "Dismiss".localized(), style: .done, target: self, action: #selector(self.dismissAnimated)) self.navigationItem.rightBarButtonItems = [dismissButton] } // Refresh action tableView.spr_setIndicatorHeader { [weak self] in self?.currentPage = 1 self?.items = [] self?.loadContent() } setFooter() // Begin refresh tableView.spr_beginRefreshing() } // Called when user reaches bottom, loads 25 more private func setFooter() { tableView.spr_setIndicatorFooter { [weak self] in self?.currentPage += 1 self?.loadContent() } } private func loadContent() { // If the data is all loaded, the footer has been removed (spr_endRefreshingWithNoMoreData) // But if this func gets called via indicator header refresh, only the first 25 items will be shown // so we need to readd the footer, as well as setting 'allLoaded' to false if self.allLoaded { allLoaded = false setFooter() } switch self.type { case .ios: loadItems(type: App.self) case .cydia: loadItems(type: CydiaApp.self) case .books: loadItems(type: Book.self) default: break } } private func loadItems<T>(type: T.Type) where T: Item { API.search(type: type, order: order, price: price, genre: categoryId, dev: devId, page: currentPage, success: { [weak self] array in guard let self = self else { return } if array.isEmpty { self.tableView.spr_endRefreshingWithNoMoreData() self.allLoaded = true } else { self.items += array if self.items.count < 25 { self.tableView.spr_endRefreshingWithNoMoreData() } else { self.tableView.spr_endRefreshing() } } self.state = .done }, fail: { error in self.tableView.spr_endRefreshing() self.items = [] self.tableView.reloadData() self.showErrorMessage(text: "Cannot connect".localized(), secondaryText: error, animated: false) }) } @objc func dismissAnimated() { dismiss(animated: true) } override func numberOfSections(in tableView: UITableView) -> Int { 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { isFiltering() ? filteredItems.count : items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard (isFiltering() ? filteredItems : items).indices.contains(indexPath.row) else { return UITableViewCell() } let item = isFiltering() ? filteredItems[indexPath.row] : items[indexPath.row] if let app = item as? App { if app.itemHasStars { guard let cell = tableView.dequeueReusableCell(withIdentifier: "seeallcellwithstars", for: indexPath) as? SeeAllCellWithStars else { return UITableViewCell() } cell.configure(name: app.name, category: app.category?.name ?? "", version: app.version, iconUrl: app.image, size: app.size, rating: app.numberOfStars, num: app.numberOfRating) return cell } else { guard let cell = tableView.dequeueReusableCell(withIdentifier: "seeallcell", for: indexPath) as? SeeAllCell else { return UITableViewCell() } cell.configure(name: app.name, category: app.category?.name ?? "", version: app.version, iconUrl: app.image, size: app.size) return cell } } else if let book = item as? Book { if book.itemHasStars { guard let cell = tableView.dequeueReusableCell(withIdentifier: "seeallcellwithstars_book", for: indexPath) as? SeeAllCellWithStars else { return UITableViewCell() } cell.configure(name: book.name, author: book.author, language: book.language, categoryId: book.categoryId, coverUrl: book.image, rating: book.numberOfStars, num: book.numberOfRating) return cell } else { guard let cell = tableView.dequeueReusableCell(withIdentifier: "seeallcell_book", for: indexPath) as? SeeAllCell else { return UITableViewCell() } cell.configure(name: book.name, author: book.author, language: book.language, categoryId: book.categoryId, coverUrl: book.image) return cell } } else if let cydiaApp = item as? CydiaApp { guard let cell = tableView.dequeueReusableCell(withIdentifier: "seeallcell", for: indexPath) as? SeeAllCell else { return UITableViewCell() } cell.configure(name: cydiaApp.name, categoryId: cydiaApp.categoryId, version: cydiaApp.version, iconUrl: cydiaApp.image, tweaked: cydiaApp.isTweaked) return cell } return UITableViewCell() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = isFiltering() ? filteredItems[indexPath.row] : items[indexPath.row] let vc = Details(content: item) navigationController?.pushViewController(vc, animated: true) } } // MARK: - UISearchResultsUpdating Delegate extension SeeAll: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { filterContentForSearchText(searchController.searchBar.text!) } func searchBarIsEmpty() -> Bool { searchController.searchBar.text?.isEmpty ?? true } func filterContentForSearchText(_ searchText: String) { if searchText.count <= 1 { filteredItems = items.filter({( item: Item) -> Bool in item.itemName.lowercased().contains(searchText.lowercased()) }) self.tableView.reloadData() } else { query = searchText switch type { case .ios: quickSearch(type: App.self) case .cydia: quickSearch(type: CydiaApp.self) case .books: quickSearch(type: Book.self) default: break } } } func quickSearch<T>(type: T.Type) where T: Item { API.search(type: type, q: query, success: { [weak self] results in guard let self = self else { return } self.filteredItems = results self.tableView.reloadData() }, fail: { _ in }) } func isFiltering() -> Bool { searchController.isActive && !searchBarIsEmpty() } } // MARK: - iOS 13 Context Menus @available(iOS 13.0, *) extension SeeAll { override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { let item = isFiltering() ? filteredItems[indexPath.row] : items[indexPath.row] return UIContextMenuConfiguration(identifier: nil, previewProvider: { Details(content: item) }) } override func tableView(_ tableView: UITableView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) { animator.addCompletion { if let viewController = animator.previewViewController { self.show(viewController, sender: self) } } } } // MARK: - 3D Touch Peek and Pop extension SeeAll: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let tableView = previewingContext.sourceView as? UITableView else { return nil } guard let indexPath = tableView.indexPathForRow(at: location) else { return nil } previewingContext.sourceRect = tableView.rectForRow(at: indexPath) let item = isFiltering() ? filteredItems[indexPath.row] : items[indexPath.row] let vc = Details(content: item) return vc } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: self) } } // Allow 3D touch on search results when search controller is active extension SeeAll: UISearchControllerDelegate { func willPresentSearchController(_ searchController: UISearchController) { if let context = previewingContext { unregisterForPreviewing(withContext: context) previewingContext = searchController.registerForPreviewing(with: self, sourceView: tableView) } } func willDismissSearchController(_ searchController: UISearchController) { if let context = previewingContext { searchController.unregisterForPreviewing(withContext: context) previewingContext = registerForPreviewing(with: self, sourceView: tableView) } } }
41.457055
185
0.634258
214d83118a10bb80515a1ebe819a50080466f722
4,062
// // Networking.swift // Obedar // // Created by Marek Pridal on 21.03.18. // Copyright © 2018 Marek Pridal. All rights reserved. // import Combine import Foundation import SwiftyJSON enum Networking { static let storage = RestaurantsStorage() private enum Constants { static let rootURL = URL(string: "http://obedar.fit.cvut.cz/api/v1/restaurants")! } private static func getRestaurants(completionHandler: @escaping ([String]?, Error?) -> Void) { var request = URLRequest(url: Constants.rootURL) request.httpMethod = "GET" let dataTask = URLSession.shared.dataTask(with: request) { data, _, error in guard let data = data, let jsonData = try? JSON(data: data) else { completionHandler(nil, error) return } completionHandler(jsonData.compactMap { $1.string }, error) } dataTask.resume() } static func getMenu(for restaurant: RestaurantTO) { var request = URLRequest(url: Constants.rootURL.appendingPathComponent(restaurant.id).appendingPathComponent("menu")) request.httpMethod = "GET" // swiftlint:disable closure_body_length let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, let jsonData = try? JSON(data: data), (response as? HTTPURLResponse)?.statusCode == 200 else { // print(error?.localizedDescription ?? "error \(restaurant.id)") if let error = error { Networking.storage.restaurants.send(completion: Subscribers.Completion<Error>.failure(error)) } return } let type = jsonData["data"]["type"].string let title = jsonData["data"]["attributes"]["title"].string let soupsData = jsonData["data"]["attributes"]["content"]["Polévky"].array let mealsData = jsonData["data"]["attributes"]["content"]["Hlavní jídla"].array let menuData = jsonData["data"]["attributes"]["content"]["Menu"].array let cached = jsonData["data"]["attributes"]["cached"].string ?? "" let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" let date = formatter.date(from: cached) var soups: [SoupTO] = [] soupsData?.forEach({ json in soups.append(SoupTO(name: json[0].string ?? "", price: json[1].double)) }) var meals: [MealTO] = [] mealsData?.forEach({ json in meals.append(MealTO(name: json[0].string ?? "", price: json[1].double)) }) var menu: [MenuTO] = [] menuData?.forEach({ json in menu.append(MenuTO(name: json[0].string ?? "", price: json[1].double, description: json[1].string)) }) Networking.storage.add(restaurant: RestaurantTO(type: type, id: restaurant.id, title: title, cached: date, web: nil, soups: soups, meals: meals, menu: menu, GPS: restaurant.GPS)) } // swiftlint:enable closure_body_length dataTask.resume() } private static func getRestaurantDetail(for restaurant: RestaurantTO, completionHandler: @escaping (RestaurantTO?, Error?) -> Void) { var request = URLRequest(url: Constants.rootURL.appendingPathComponent(restaurant.id)) request.httpMethod = "GET" let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, let jsonData = try? JSON(data: data), (response as? HTTPURLResponse)?.statusCode == 200 else { // print(error?.localizedDescription ?? "error \(restaurant)") completionHandler(restaurant, error) return } var restaurant = restaurant restaurant.web = jsonData["data"]["attributes"]["url"].url completionHandler(restaurant, error) } dataTask.resume() } }
41.44898
190
0.601428
0e2e48a192077ec96e451c74bf5f924286f2735f
644
// // UITextField+Rx.swift // Wei // // Created by Ryosuke Fukuda on 2018/05/23. // Copyright © 2018 popshoot All rights reserved. // import UIKit import RxSwift import RxCocoa extension Reactive where Base: UITextField { var trimmedText: ControlProperty<String?> { let value = text.map { $0?.trimmingCharacters(in: .whitespaces) } let bindingObserver = Binder(base) { (textView, text: String?) in if textView.text != text { textView.text = text?.trimmingCharacters(in: .whitespaces) } } return ControlProperty(values: value, valueSink: bindingObserver) } }
26.833333
74
0.645963
d94abce41fe87a800c6f1d105759aef92fda48cf
43,981
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: service.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ // Copyright (c) 2019-2020 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php . import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// A BlockID message contains identifiers to select a block: a height or a /// hash. Specification by hash is not implemented, but may be in the future. struct BlockID { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var height: UInt64 = 0 var hash: Data = Data() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// BlockRange specifies a series of blocks from start to end inclusive. /// Both BlockIDs must be heights; specification by hash is not yet supported. struct BlockRange { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var start: BlockID { get {return _start ?? BlockID()} set {_start = newValue} } /// Returns true if `start` has been explicitly set. var hasStart: Bool {return self._start != nil} /// Clears the value of `start`. Subsequent reads from it will return its default value. mutating func clearStart() {self._start = nil} var end: BlockID { get {return _end ?? BlockID()} set {_end = newValue} } /// Returns true if `end` has been explicitly set. var hasEnd: Bool {return self._end != nil} /// Clears the value of `end`. Subsequent reads from it will return its default value. mutating func clearEnd() {self._end = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _start: BlockID? = nil fileprivate var _end: BlockID? = nil } /// A TxFilter contains the information needed to identify a particular /// transaction: either a block and an index, or a direct transaction hash. /// Currently, only specification by hash is supported. struct TxFilter { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// block identifier, height or hash var block: BlockID { get {return _block ?? BlockID()} set {_block = newValue} } /// Returns true if `block` has been explicitly set. var hasBlock: Bool {return self._block != nil} /// Clears the value of `block`. Subsequent reads from it will return its default value. mutating func clearBlock() {self._block = nil} /// index within the block var index: UInt64 = 0 /// transaction ID (hash, txid) var hash: Data = Data() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _block: BlockID? = nil } /// RawTransaction contains the complete transaction data. It also optionally includes /// the block height in which the transaction was included. struct RawTransaction { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// exact data returned by Zcash 'getrawtransaction' var data: Data = Data() /// height that the transaction was mined (or -1) var height: UInt64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// A SendResponse encodes an error code and a string. It is currently used /// only by SendTransaction(). If error code is zero, the operation was /// successful; if non-zero, it and the message specify the failure. struct SendResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var errorCode: Int32 = 0 var errorMessage: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// Chainspec is a placeholder to allow specification of a particular chain fork. struct ChainSpec { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// Empty is for gRPCs that take no arguments, currently only GetLightdInfo. struct Empty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// LightdInfo returns various information about this lightwalletd instance /// and the state of the blockchain. struct LightdInfo { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var version: String = String() var vendor: String = String() /// true var taddrSupport: Bool = false /// either "main" or "test" var chainName: String = String() /// depends on mainnet or testnet var saplingActivationHeight: UInt64 = 0 /// protocol identifier, see consensus/upgrades.cpp var consensusBranchID: String = String() /// latest block on the best chain var blockHeight: UInt64 = 0 var gitCommit: String = String() var branch: String = String() var buildDate: String = String() var buildUser: String = String() /// less than tip height if zcashd is syncing var estimatedHeight: UInt64 = 0 /// example: "v4.1.1-877212414" var zcashdBuild: String = String() /// example: "/MagicBean:4.1.1/" var zcashdSubversion: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// TransparentAddressBlockFilter restricts the results to the given address /// or block range. struct TransparentAddressBlockFilter { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// t-address var address: String = String() /// start, end heights var range: BlockRange { get {return _range ?? BlockRange()} set {_range = newValue} } /// Returns true if `range` has been explicitly set. var hasRange: Bool {return self._range != nil} /// Clears the value of `range`. Subsequent reads from it will return its default value. mutating func clearRange() {self._range = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _range: BlockRange? = nil } /// Duration is currently used only for testing, so that the Ping rpc /// can simulate a delay, to create many simultaneous connections. Units /// are microseconds. struct Duration { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var intervalUs: Int64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// PingResponse is used to indicate concurrency, how many Ping rpcs /// are executing upon entry and upon exit (after the delay). /// This rpc is used for testing only. struct PingResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var entry: Int64 = 0 var exit: Int64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Address { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var address: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct AddressList { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var addresses: [String] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Balance { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var valueZat: Int64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Exclude { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var txid: [Data] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// The TreeState is derived from the Zcash z_gettreestate rpc. struct TreeState { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// "main" or "test" var network: String = String() var height: UInt64 = 0 /// block id var hash: String = String() /// Unix epoch time when the block was mined var time: UInt32 = 0 /// sapling commitment tree state var tree: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// Results are sorted by height, which makes it easy to issue another /// request that picks up from where the previous left off. struct GetAddressUtxosArg { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var addresses: [String] = [] var startHeight: UInt64 = 0 /// zero means unlimited var maxEntries: UInt32 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct GetAddressUtxosReply { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var address: String = String() var txid: Data = Data() var index: Int32 = 0 var script: Data = Data() var valueZat: Int64 = 0 var height: UInt64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct GetAddressUtxosReplyList { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var addressUtxos: [GetAddressUtxosReply] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "cash.z.wallet.sdk.rpc" extension BlockID: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".BlockID" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "height"), 2: .same(proto: "hash"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt64Field(value: &self.height) }() case 2: try { try decoder.decodeSingularBytesField(value: &self.hash) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.height != 0 { try visitor.visitSingularUInt64Field(value: self.height, fieldNumber: 1) } if !self.hash.isEmpty { try visitor.visitSingularBytesField(value: self.hash, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: BlockID, rhs: BlockID) -> Bool { if lhs.height != rhs.height {return false} if lhs.hash != rhs.hash {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension BlockRange: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".BlockRange" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "start"), 2: .same(proto: "end"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._start) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._end) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._start { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } if let v = self._end { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: BlockRange, rhs: BlockRange) -> Bool { if lhs._start != rhs._start {return false} if lhs._end != rhs._end {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension TxFilter: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".TxFilter" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "block"), 2: .same(proto: "index"), 3: .same(proto: "hash"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._block) }() case 2: try { try decoder.decodeSingularUInt64Field(value: &self.index) }() case 3: try { try decoder.decodeSingularBytesField(value: &self.hash) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._block { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } if self.index != 0 { try visitor.visitSingularUInt64Field(value: self.index, fieldNumber: 2) } if !self.hash.isEmpty { try visitor.visitSingularBytesField(value: self.hash, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: TxFilter, rhs: TxFilter) -> Bool { if lhs._block != rhs._block {return false} if lhs.index != rhs.index {return false} if lhs.hash != rhs.hash {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension RawTransaction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".RawTransaction" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "data"), 2: .same(proto: "height"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBytesField(value: &self.data) }() case 2: try { try decoder.decodeSingularUInt64Field(value: &self.height) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.data.isEmpty { try visitor.visitSingularBytesField(value: self.data, fieldNumber: 1) } if self.height != 0 { try visitor.visitSingularUInt64Field(value: self.height, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: RawTransaction, rhs: RawTransaction) -> Bool { if lhs.data != rhs.data {return false} if lhs.height != rhs.height {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension SendResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".SendResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "errorCode"), 2: .same(proto: "errorMessage"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt32Field(value: &self.errorCode) }() case 2: try { try decoder.decodeSingularStringField(value: &self.errorMessage) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.errorCode != 0 { try visitor.visitSingularInt32Field(value: self.errorCode, fieldNumber: 1) } if !self.errorMessage.isEmpty { try visitor.visitSingularStringField(value: self.errorMessage, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: SendResponse, rhs: SendResponse) -> Bool { if lhs.errorCode != rhs.errorCode {return false} if lhs.errorMessage != rhs.errorMessage {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension ChainSpec: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ChainSpec" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: ChainSpec, rhs: ChainSpec) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Empty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Empty" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Empty, rhs: Empty) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension LightdInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".LightdInfo" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "version"), 2: .same(proto: "vendor"), 3: .same(proto: "taddrSupport"), 4: .same(proto: "chainName"), 5: .same(proto: "saplingActivationHeight"), 6: .same(proto: "consensusBranchId"), 7: .same(proto: "blockHeight"), 8: .same(proto: "gitCommit"), 9: .same(proto: "branch"), 10: .same(proto: "buildDate"), 11: .same(proto: "buildUser"), 12: .same(proto: "estimatedHeight"), 13: .same(proto: "zcashdBuild"), 14: .same(proto: "zcashdSubversion"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.version) }() case 2: try { try decoder.decodeSingularStringField(value: &self.vendor) }() case 3: try { try decoder.decodeSingularBoolField(value: &self.taddrSupport) }() case 4: try { try decoder.decodeSingularStringField(value: &self.chainName) }() case 5: try { try decoder.decodeSingularUInt64Field(value: &self.saplingActivationHeight) }() case 6: try { try decoder.decodeSingularStringField(value: &self.consensusBranchID) }() case 7: try { try decoder.decodeSingularUInt64Field(value: &self.blockHeight) }() case 8: try { try decoder.decodeSingularStringField(value: &self.gitCommit) }() case 9: try { try decoder.decodeSingularStringField(value: &self.branch) }() case 10: try { try decoder.decodeSingularStringField(value: &self.buildDate) }() case 11: try { try decoder.decodeSingularStringField(value: &self.buildUser) }() case 12: try { try decoder.decodeSingularUInt64Field(value: &self.estimatedHeight) }() case 13: try { try decoder.decodeSingularStringField(value: &self.zcashdBuild) }() case 14: try { try decoder.decodeSingularStringField(value: &self.zcashdSubversion) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.version.isEmpty { try visitor.visitSingularStringField(value: self.version, fieldNumber: 1) } if !self.vendor.isEmpty { try visitor.visitSingularStringField(value: self.vendor, fieldNumber: 2) } if self.taddrSupport != false { try visitor.visitSingularBoolField(value: self.taddrSupport, fieldNumber: 3) } if !self.chainName.isEmpty { try visitor.visitSingularStringField(value: self.chainName, fieldNumber: 4) } if self.saplingActivationHeight != 0 { try visitor.visitSingularUInt64Field(value: self.saplingActivationHeight, fieldNumber: 5) } if !self.consensusBranchID.isEmpty { try visitor.visitSingularStringField(value: self.consensusBranchID, fieldNumber: 6) } if self.blockHeight != 0 { try visitor.visitSingularUInt64Field(value: self.blockHeight, fieldNumber: 7) } if !self.gitCommit.isEmpty { try visitor.visitSingularStringField(value: self.gitCommit, fieldNumber: 8) } if !self.branch.isEmpty { try visitor.visitSingularStringField(value: self.branch, fieldNumber: 9) } if !self.buildDate.isEmpty { try visitor.visitSingularStringField(value: self.buildDate, fieldNumber: 10) } if !self.buildUser.isEmpty { try visitor.visitSingularStringField(value: self.buildUser, fieldNumber: 11) } if self.estimatedHeight != 0 { try visitor.visitSingularUInt64Field(value: self.estimatedHeight, fieldNumber: 12) } if !self.zcashdBuild.isEmpty { try visitor.visitSingularStringField(value: self.zcashdBuild, fieldNumber: 13) } if !self.zcashdSubversion.isEmpty { try visitor.visitSingularStringField(value: self.zcashdSubversion, fieldNumber: 14) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: LightdInfo, rhs: LightdInfo) -> Bool { if lhs.version != rhs.version {return false} if lhs.vendor != rhs.vendor {return false} if lhs.taddrSupport != rhs.taddrSupport {return false} if lhs.chainName != rhs.chainName {return false} if lhs.saplingActivationHeight != rhs.saplingActivationHeight {return false} if lhs.consensusBranchID != rhs.consensusBranchID {return false} if lhs.blockHeight != rhs.blockHeight {return false} if lhs.gitCommit != rhs.gitCommit {return false} if lhs.branch != rhs.branch {return false} if lhs.buildDate != rhs.buildDate {return false} if lhs.buildUser != rhs.buildUser {return false} if lhs.estimatedHeight != rhs.estimatedHeight {return false} if lhs.zcashdBuild != rhs.zcashdBuild {return false} if lhs.zcashdSubversion != rhs.zcashdSubversion {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension TransparentAddressBlockFilter: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".TransparentAddressBlockFilter" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "address"), 2: .same(proto: "range"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.address) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._range) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.address.isEmpty { try visitor.visitSingularStringField(value: self.address, fieldNumber: 1) } if let v = self._range { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: TransparentAddressBlockFilter, rhs: TransparentAddressBlockFilter) -> Bool { if lhs.address != rhs.address {return false} if lhs._range != rhs._range {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Duration: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Duration" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "intervalUs"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.intervalUs) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.intervalUs != 0 { try visitor.visitSingularInt64Field(value: self.intervalUs, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Duration, rhs: Duration) -> Bool { if lhs.intervalUs != rhs.intervalUs {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PingResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".PingResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "entry"), 2: .same(proto: "exit"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.entry) }() case 2: try { try decoder.decodeSingularInt64Field(value: &self.exit) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.entry != 0 { try visitor.visitSingularInt64Field(value: self.entry, fieldNumber: 1) } if self.exit != 0 { try visitor.visitSingularInt64Field(value: self.exit, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: PingResponse, rhs: PingResponse) -> Bool { if lhs.entry != rhs.entry {return false} if lhs.exit != rhs.exit {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Address: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Address" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "address"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.address) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.address.isEmpty { try visitor.visitSingularStringField(value: self.address, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Address, rhs: Address) -> Bool { if lhs.address != rhs.address {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension AddressList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".AddressList" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "addresses"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedStringField(value: &self.addresses) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.addresses.isEmpty { try visitor.visitRepeatedStringField(value: self.addresses, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: AddressList, rhs: AddressList) -> Bool { if lhs.addresses != rhs.addresses {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Balance: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Balance" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "valueZat"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.valueZat) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.valueZat != 0 { try visitor.visitSingularInt64Field(value: self.valueZat, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Balance, rhs: Balance) -> Bool { if lhs.valueZat != rhs.valueZat {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Exclude: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Exclude" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "txid"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedBytesField(value: &self.txid) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.txid.isEmpty { try visitor.visitRepeatedBytesField(value: self.txid, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Exclude, rhs: Exclude) -> Bool { if lhs.txid != rhs.txid {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension TreeState: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".TreeState" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "network"), 2: .same(proto: "height"), 3: .same(proto: "hash"), 4: .same(proto: "time"), 5: .same(proto: "tree"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.network) }() case 2: try { try decoder.decodeSingularUInt64Field(value: &self.height) }() case 3: try { try decoder.decodeSingularStringField(value: &self.hash) }() case 4: try { try decoder.decodeSingularUInt32Field(value: &self.time) }() case 5: try { try decoder.decodeSingularStringField(value: &self.tree) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.network.isEmpty { try visitor.visitSingularStringField(value: self.network, fieldNumber: 1) } if self.height != 0 { try visitor.visitSingularUInt64Field(value: self.height, fieldNumber: 2) } if !self.hash.isEmpty { try visitor.visitSingularStringField(value: self.hash, fieldNumber: 3) } if self.time != 0 { try visitor.visitSingularUInt32Field(value: self.time, fieldNumber: 4) } if !self.tree.isEmpty { try visitor.visitSingularStringField(value: self.tree, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: TreeState, rhs: TreeState) -> Bool { if lhs.network != rhs.network {return false} if lhs.height != rhs.height {return false} if lhs.hash != rhs.hash {return false} if lhs.time != rhs.time {return false} if lhs.tree != rhs.tree {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension GetAddressUtxosArg: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetAddressUtxosArg" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "addresses"), 2: .same(proto: "startHeight"), 3: .same(proto: "maxEntries"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedStringField(value: &self.addresses) }() case 2: try { try decoder.decodeSingularUInt64Field(value: &self.startHeight) }() case 3: try { try decoder.decodeSingularUInt32Field(value: &self.maxEntries) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.addresses.isEmpty { try visitor.visitRepeatedStringField(value: self.addresses, fieldNumber: 1) } if self.startHeight != 0 { try visitor.visitSingularUInt64Field(value: self.startHeight, fieldNumber: 2) } if self.maxEntries != 0 { try visitor.visitSingularUInt32Field(value: self.maxEntries, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: GetAddressUtxosArg, rhs: GetAddressUtxosArg) -> Bool { if lhs.addresses != rhs.addresses {return false} if lhs.startHeight != rhs.startHeight {return false} if lhs.maxEntries != rhs.maxEntries {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension GetAddressUtxosReply: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetAddressUtxosReply" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 6: .same(proto: "address"), 1: .same(proto: "txid"), 2: .same(proto: "index"), 3: .same(proto: "script"), 4: .same(proto: "valueZat"), 5: .same(proto: "height"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBytesField(value: &self.txid) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self.index) }() case 3: try { try decoder.decodeSingularBytesField(value: &self.script) }() case 4: try { try decoder.decodeSingularInt64Field(value: &self.valueZat) }() case 5: try { try decoder.decodeSingularUInt64Field(value: &self.height) }() case 6: try { try decoder.decodeSingularStringField(value: &self.address) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.txid.isEmpty { try visitor.visitSingularBytesField(value: self.txid, fieldNumber: 1) } if self.index != 0 { try visitor.visitSingularInt32Field(value: self.index, fieldNumber: 2) } if !self.script.isEmpty { try visitor.visitSingularBytesField(value: self.script, fieldNumber: 3) } if self.valueZat != 0 { try visitor.visitSingularInt64Field(value: self.valueZat, fieldNumber: 4) } if self.height != 0 { try visitor.visitSingularUInt64Field(value: self.height, fieldNumber: 5) } if !self.address.isEmpty { try visitor.visitSingularStringField(value: self.address, fieldNumber: 6) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: GetAddressUtxosReply, rhs: GetAddressUtxosReply) -> Bool { if lhs.address != rhs.address {return false} if lhs.txid != rhs.txid {return false} if lhs.index != rhs.index {return false} if lhs.script != rhs.script {return false} if lhs.valueZat != rhs.valueZat {return false} if lhs.height != rhs.height {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension GetAddressUtxosReplyList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetAddressUtxosReplyList" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "addressUtxos"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.addressUtxos) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.addressUtxos.isEmpty { try visitor.visitRepeatedMessageField(value: self.addressUtxos, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: GetAddressUtxosReplyList, rhs: GetAddressUtxosReplyList) -> Bool { if lhs.addressUtxos != rhs.addressUtxos {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
37.462521
141
0.711898
38d531d55468a3d4921bdc6e54edea621690ca69
2,647
// // BackgroundViewController.swift // Curtain_Example // // Created by Igor Squadra on 06/07/2020. // Copyright © 2020 CocoaPods. All rights reserved. // import Foundation import UIKit import Curtain // MARK: - Instance vars and IBOutlets class BackgroundViewController: UIViewController { var backgroundProgressView: BackgroundProgressView! // Background animation direction type: .vertical or .horizontal var direction: DirectionType! } // MARK: - Essentials extension BackgroundViewController { // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() // Create and add progress view backgroundProgressView = BackgroundProgressView.init(frame: CGRect.init( x: 0, y: 0, width: 0, height: 0 )) view.addSubview(backgroundProgressView) // Setup your progress view here backgroundProgressView.setup( withDirection: direction, withTime: 3, view: view.frame, color: UIColor.init(red: 109/255, green: 212/255, blue: 0/255, alpha: 1.0), initialSize: 0, autoreset: true, resetType: .linear ) // backgroundProgressView.setup(withDirection: direction, withTime: 3, view: view.frame, color: UIColor.init(red: 30/255, green: 150/255, blue: 182/255, alpha: 1.0)) // Hide navigation bar navigationController?.navigationBar.topItem?.titleView = UIView.init() navigationController?.navigationBar.setBackgroundImage(UIImage.init(), for: .default) navigationController?.navigationBar.shadowImage = UIImage.init() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Start progress view backgroundProgressView.start() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } // MARK: Memory warning override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Layout subviews override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } }
24.509259
172
0.596524
e66009e985325f98676642d6a7886731ee4c33dd
1,216
import SwiftUI public extension ViewType { struct VStack: KnownViewType { public static let typePrefix: String = "VStack" } } public extension VStack { func inspect() throws -> InspectableView<ViewType.VStack> { return try InspectableView<ViewType.VStack>(self) } } // MARK: - Content Extraction extension ViewType.VStack: MultipleViewContent { public static func content(view: Any, envObject: Any) throws -> LazyGroup<Any> { return try ViewType.HStack.content(view: view, envObject: envObject) } } // MARK: - Extraction from SingleViewContent parent public extension InspectableView where View: SingleViewContent { func vStack() throws -> InspectableView<ViewType.VStack> { let content = try View.content(view: view, envObject: envObject) return try InspectableView<ViewType.VStack>(content) } } // MARK: - Extraction from MultipleViewContent parent public extension InspectableView where View: MultipleViewContent { func vStack(_ index: Int) throws -> InspectableView<ViewType.VStack> { let content = try contentView(at: index) return try InspectableView<ViewType.VStack>(content) } }
27.022222
84
0.702303
87939294c42a6eee597daa05409e88ea2e159e96
2,463
// // Created by martin on 21.04.18. // Copyright © 2018 Martin Hartl. All rights reserved. // import Foundation import AcknowList import MessageUI final class SettingsNavigator: NSObject { private let navigationController: UINavigationController private let appNavigator: AppNavigator init(navigationController: UINavigationController, appNavigator: AppNavigator) { self.navigationController = navigationController self.appNavigator = appNavigator } func openAcknowledgements() { let viewController = AcknowListViewController() viewController.view.backgroundColor = Color.accentSuperLight navigationController.pushViewController(viewController, animated: true) } func openHartlCoOnMicroBlog() { let viewModel = ListViewModel(type: .username(username: "hartlco")) let itemNavigator = ItemNavigator(navigationController: navigationController) let viewController = ListViewController(viewModel: viewModel, itemNavigator: itemNavigator) navigationController.pushViewController(viewController, animated: true) } func openSupportMail() { guard MFMailComposeViewController.canSendMail() else { return } let viewController = MFMailComposeViewController() viewController.mailComposeDelegate = self viewController.setToRecipients(["[email protected]"]) viewController.setSubject("Icro support") navigationController.present(viewController, animated: true, completion: nil) } func openMicroBlog() { let itemNavigator = ItemNavigator(navigationController: navigationController) itemNavigator.openMicroBlog() } func openBlacklist() { let viewModel = BlacklistViewModel(userSettings: UserSettings.shared) let itemNavigator = ItemNavigator(navigationController: navigationController) let viewController = BlacklistViewController(viewModel: viewModel, itemNavigator: itemNavigator) navigationController.pushViewController(viewController, animated: true) } func logout() { appNavigator.logout() } } extension SettingsNavigator: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } }
37.318182
133
0.72635
fe717cf442c86cda2dca9525ee38110fc2154cfa
851
// // BlurView.swift // POSE // // Created by Ethan on 2022/4/2. // import SwiftUI struct BlurView: UIViewRepresentable { let style: UIBlurEffect.Style func makeUIView(context: UIViewRepresentableContext<BlurView>) -> UIView { let view = UIView(frame: .zero) view.backgroundColor = .clear let blurEffect = UIBlurEffect(style: style) let blurView = UIVisualEffectView(effect: blurEffect) blurView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(blurView, at: 0) NSLayoutConstraint.activate([ blurView.heightAnchor.constraint(equalTo: view.heightAnchor), blurView.widthAnchor.constraint(equalTo: view.widthAnchor), ]) return view } func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<BlurView>) {} }
28.366667
77
0.692127
14ab232548c3a1cc3aaa5b7d36254a4223e22029
3,429
import Foundation import azureSwiftRuntime public protocol WebAppsGetInstanceProcessModule { var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var name : String { get set } var processId : String { get set } var baseAddress : String { get set } var instanceId : String { get set } var subscriptionId : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (ProcessModuleInfoProtocol?, Error?) -> Void) -> Void ; } extension Commands.WebApps { // GetInstanceProcessModule get process information by its ID for a specific scaled-out instance in a web site. internal class GetInstanceProcessModuleCommand : BaseCommand, WebAppsGetInstanceProcessModule { public var resourceGroupName : String public var name : String public var processId : String public var baseAddress : String public var instanceId : String public var subscriptionId : String public var apiVersion = "2016-08-01" public init(resourceGroupName: String, name: String, processId: String, baseAddress: String, instanceId: String, subscriptionId: String) { self.resourceGroupName = resourceGroupName self.name = name self.processId = processId self.baseAddress = baseAddress self.instanceId = instanceId self.subscriptionId = subscriptionId super.init() self.method = "Get" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/instances/{instanceId}/processes/{processId}/modules/{baseAddress}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{name}"] = String(describing: self.name) self.pathParameters["{processId}"] = String(describing: self.processId) self.pathParameters["{baseAddress}"] = String(describing: self.baseAddress) self.pathParameters["{instanceId}"] = String(describing: self.instanceId) self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(ProcessModuleInfoData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (ProcessModuleInfoProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: ProcessModuleInfoData?, error: Error?) in completionHandler(result, error) } } } }
48.985714
197
0.644211
8a12be510ab832a2ea33cd13a4bfc0a9d85f9636
782
// // SpecialModelName.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif public struct SpecialModelName: Codable, Hashable { public private(set) var specialPropertyName: Int64? public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } }
24.4375
88
0.725064
48124b97a4c3262fbc118ae2e0bf74193250effe
2,140
// // NSLayoutConstraint+Extension.swift // AutoLayoutFormula // // Created by ParkHyunsoo on 2019/10/13. // import UIKit public extension NSLayoutConstraint { func updateMultiply(_ newValue: CGFloat, shouldUpdate: Bool = false) -> NSLayoutConstraint { if self.isActive { NSLayoutConstraint.deactivate([self]) } let newConstraint = NSLayoutConstraint(item: firstItem, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: newValue, constant: constant) newConstraint.priority = priority newConstraint.shouldBeArchived = shouldBeArchived newConstraint.identifier = identifier if shouldUpdate { NSLayoutConstraint.activate([newConstraint]) } return newConstraint } func updateConstant(_ newValue: CGFloat, shouldUpdate: Bool = false) -> NSLayoutConstraint { if self.isActive { NSLayoutConstraint.deactivate([self]) } let newConstraint = NSLayoutConstraint(item: firstItem, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: newValue) newConstraint.priority = priority newConstraint.shouldBeArchived = shouldBeArchived newConstraint.identifier = identifier if shouldUpdate { NSLayoutConstraint.activate([newConstraint]) } return newConstraint } }
35.081967
96
0.487383
4ba5a05a92a906c0bf2936c0b2ad4bdaf15c526c
2,227
////===----------------------------------------------------------------------===// //// //// This source file is part of the Swift.org open source project //// //// Copyright (c) 2020 Apple Inc. and the Swift project authors //// Licensed under Apache License v2.0 with Runtime Library Exception //// //// See https://swift.org/LICENSE.txt for license information //// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors //// ////===----------------------------------------------------------------------===// import Swift @_implementationOnly import _SwiftConcurrencyShims // FIXME: This file and all "time types" defined here are temporary until we decide what types to use. // It was suggested to avoid Dispatch types in public API of Swift Concurrency, // so for now we use "bare minimum" types just to be able to continue prototyping. extension Task { /// Represents a time interval, i.e. a number of seconds. /// /// It can be used to express deadlines, in the form of time interval from "now." /// /// - Note: This is equivalent to `DispatchTimeInterval` if we were to use it. public struct _TimeInterval: Equatable, Comparable { let nanoseconds: UInt64 private init(nanoseconds: UInt64) { self.nanoseconds = nanoseconds } public static func seconds(_ s: UInt64) -> Self { .init(nanoseconds: clampedInt64Product(s, 1_000_000_000)) } public static func milliseconds(_ ms: UInt64) -> Self { .init(nanoseconds: clampedInt64Product(ms, 1_000_000)) } public static func microseconds(_ us: UInt64) -> Self { .init(nanoseconds: clampedInt64Product(us, 1_000)) } public static func nanoseconds(_ ns: UInt64) -> Self { .init(nanoseconds: ns) } public static var never: Self { .init(nanoseconds: .max) } public static func < (lhs: Self, rhs: Self) -> Bool { lhs.nanoseconds < rhs.nanoseconds } } } // Returns m1 * m2, clamped to the range [UInt64.min, UInt64.max]. private func clampedInt64Product(_ m1: UInt64, _ m2: UInt64) -> UInt64 { let (result, overflow) = m1.multipliedReportingOverflow(by: m2) if overflow { return UInt64.max } return result }
33.238806
102
0.633139
0e64f95c3c47920ce9a620caef39144e295a7498
9,009
// // YPAssetViewContainer.swift // YPImagePicker // // Created by Sacha Durand Saint Omer on 15/11/2016. // Copyright © 2016 Yummypets. All rights reserved. // import Foundation import UIKit import Stevia import AVFoundation /// The container for asset (video or image). It containts the YPGridView and YPAssetZoomableView. class YPAssetViewContainer: UIView { public var zoomableView: YPAssetZoomableView? public let grid = YPGridView() public let curtain = UIView() public let spinnerView = UIView() public let squareCropButton = UIButton() public let multipleSelectionButton = UIButton() public var onlySquare = YPConfig.library.onlySquare public var isShown = true private let spinner = UIActivityIndicatorView(activityIndicatorStyle: .white) private var shouldCropToSquare = false private var isMultipleSelection = false public let bottomView = UIView() public let cameraButton = UIButton() public let cameraCircle = UIView() public let useButton = UIButton.init(type: UIButtonType.system) public let countLabel = UILabel() override func awakeFromNib() { super.awakeFromNib() addSubview(grid) grid.frame = frame clipsToBounds = true for sv in subviews { if let cv = sv as? YPAssetZoomableView { zoomableView = cv zoomableView?.myDelegate = self } } grid.alpha = 0 let touchDownGR = UILongPressGestureRecognizer(target: self, action: #selector(handleTouchDown)) touchDownGR.minimumPressDuration = 0 touchDownGR.delegate = self addGestureRecognizer(touchDownGR) // TODO: Add tap gesture to play/pause. Add double tap gesture to square/unsquare sv( spinnerView.sv( spinner ), curtain ) spinner.centerInContainer() spinnerView.fillContainer() curtain.fillContainer() spinner.startAnimating() spinnerView.backgroundColor = UIColor.black.withAlphaComponent(0.3) curtain.backgroundColor = UIColor.black.withAlphaComponent(0.5) curtain.alpha = 0 if !onlySquare { // Crop Button squareCropButton.setImage(YPConfig.icons.cropIcon, for: .normal) sv(squareCropButton) squareCropButton.size(42) |-15-squareCropButton squareCropButton.Top == zoomableView!.Top + 15 } // Multiple selection button sv(multipleSelectionButton) multipleSelectionButton.size(42) multipleSelectionButton-15-| multipleSelectionButton.setImage(YPConfig.icons.multipleSelectionOffIcon, for: .normal) multipleSelectionButton.Top == zoomableView!.Top + 15 let color = UIColor(red: 48.0 / 255.0, green: 66.0 / 255.0, blue: 87.0 / 255.0, alpha: 0.8) let bottomHeight: CGFloat = 55 let outerCircleHeight: CGFloat = 67 sv(bottomView) // bottomView.backgroundColor = UIColor(white: 0, alpha: 0.1) bottomView.Bottom == zoomableView!.Bottom - 25 bottomView.height(bottomHeight) |bottomView| bottomView.sv(cameraCircle) cameraCircle.backgroundColor = UIColor.white.withAlphaComponent(0.5) cameraCircle.layer.cornerRadius = outerCircleHeight/2 cameraCircle.clipsToBounds = true |-13-cameraCircle cameraCircle.size(outerCircleHeight) cameraCircle.centerVertically() bottomView.sv(cameraButton) cameraButton.size(bottomHeight) cameraButton.CenterX == cameraCircle.CenterX cameraButton.CenterY == cameraCircle.CenterY cameraButton.setImage(YPConfig.icons.cameraImage, for: .normal) cameraButton.backgroundColor = color cameraButton.layer.cornerRadius = bottomHeight/2 cameraButton.clipsToBounds = true let useCircle = UIView() bottomView.sv(useCircle) useCircle.backgroundColor = UIColor.white.withAlphaComponent(0.5) useCircle.layer.cornerRadius = outerCircleHeight/2 useCircle.clipsToBounds = true useCircle-13-| useCircle.size(outerCircleHeight) useCircle.centerVertically() bottomView.sv(useButton) useButton.size(bottomHeight) useButton.CenterX == useCircle.CenterX useButton.CenterY == useCircle.CenterY useButton.setTitle(YPConfig.wordings.add, for: .normal) useButton.setTitleColor(.white, for: .normal) useButton.titleLabel?.font = UIFont.systemFont(ofSize: 20) useButton.backgroundColor = color useButton.layer.cornerRadius = bottomHeight/2 useButton.clipsToBounds = true bottomView.sv(countLabel) countLabel.textAlignment = .center countLabel.size(bottomHeight) countLabel.CenterX == useCircle.CenterX countLabel.CenterY == useCircle.CenterY countLabel.font = UIFont.systemFont(ofSize: 20) countLabel.textColor = .white countLabel.backgroundColor = color countLabel.layer.cornerRadius = bottomHeight/2 countLabel.clipsToBounds = true countLabel.isHidden = true bottomView.isHidden = !YPConfig.library.allowMultipleItems } func showUseButton() { countLabel.isHidden = true useButton.isHidden = false } // MARK: - Square button @objc public func squareCropButtonTapped() { if let zoomableView = zoomableView { let z = zoomableView.zoomScale if z >= 1 && z < zoomableView.squaredZoomScale { shouldCropToSquare = true } else { shouldCropToSquare = false } } zoomableView?.fitImage(shouldCropToSquare, animated: true) } public func refreshSquareCropButton() { if onlySquare { squareCropButton.isHidden = true } else { if let image = zoomableView?.assetImageView.image { let isImageASquare = image.size.width == image.size.height squareCropButton.isHidden = isImageASquare } } } // MARK: - Multiple selection /// Use this to update the multiple selection mode UI state for the YPAssetViewContainer public func setMultipleSelectionMode(on: Bool) { isMultipleSelection = on let image = on ? YPConfig.icons.multipleSelectionOnIcon : YPConfig.icons.multipleSelectionOffIcon multipleSelectionButton.setImage(image, for: .normal) refreshSquareCropButton() } } // MARK: - ZoomableViewDelegate extension YPAssetViewContainer: YPAssetZoomableViewDelegate { public func ypAssetZoomableViewDidLayoutSubviews(_ zoomableView: YPAssetZoomableView) { let newFrame = zoomableView.assetImageView.convert(zoomableView.assetImageView.bounds, to: self) // update grid position grid.frame = frame.intersection(newFrame) grid.layoutIfNeeded() // Update play imageView position - bringing the playImageView from the videoView to assetViewContainer, // but the controll for appearing it still in videoView. if zoomableView.videoView.playImageView.isDescendant(of: self) == false { self.addSubview(zoomableView.videoView.playImageView) zoomableView.videoView.playImageView.centerInContainer() } } public func ypAssetZoomableViewScrollViewDidZoom() { if isShown { UIView.animate(withDuration: 0.1) { self.grid.alpha = 1 } } } public func ypAssetZoomableViewScrollViewDidEndZooming() { UIView.animate(withDuration: 0.3) { self.grid.alpha = 0 } } } // MARK: - Gesture recognizer Delegate extension YPAssetViewContainer: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return !(touch.view is UIButton) } @objc private func handleTouchDown(sender: UILongPressGestureRecognizer) { switch sender.state { case .began: if isShown { UIView.animate(withDuration: 0.1) { self.grid.alpha = 1 } } case .ended: UIView.animate(withDuration: 0.3) { self.grid.alpha = 0 } default: () } } }
34.783784
115
0.633811
0ee06c32bb131d9f495d2c496dfc9c63d6d0d97b
6,253
// // MNkTabBarController.swift // lottie-ios // // Created by Malith Nadeeshan on 8/4/18. // // |\/\ /\/| // |\/\/\ /\/\| // |\/\/\/\ /\/\/\/| // |\/\/\/\/\_/\/\/\/\| // |\/\ /\/\_/\/ \/\| // |\/\ \/\_/\ /\| import UIKit public var animatedTabBar:MNkTabBar? public var animatedTabBarController:MNkTabBarController? protocol MNkTabbarDelegate{ var isTabbarHidden:Bool{get set} } open class MNkTabBarController: UIViewController { ///Check tab bar currently hide or not public var isTabBarHide:Bool{ return _isTabBarHide } private var _isTabBarHide:Bool = false ///User can scroll between tabs just swiping. public var isScrollableTabs:Bool = false{ didSet{ let delegate = isScrollableTabs ? tabPageController : nil let dataSource = isScrollableTabs ? tabPageController : nil tabPageController.delegate = delegate tabPageController.dataSource = dataSource } } ///Animate changing tabs when user tapped tab bar menu item public var isSwitchBetweenTabsAnimatable:Bool = false ///Frame of tab bar public var tabbarHeight:CGFloat{ return statusBarHeight == 20 ? 55 : 80 } ///Frame of tab view controllers container public var containerFrame:CGRect{ return CGRect(origin: .zero, size: CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height - tabbarHeight)) } private var tabBarFrame:CGRect{ let origin = CGPoint(x: 0, y: containerFrame.size.height) return CGRect(origin: origin, size: CGSize(width: self.view.bounds.size.width, height: tabbarHeight)) } private var statusBarHeight:CGFloat{ return UIApplication.shared.statusBarFrame.size.height } public var selectedVCIndex:Int = 0{ willSet{ guard selectedVCIndex != newValue else{return} removeAllChilds() } } ///Set view controllers to show in tabs public var mnkTabBarViewControllers:[UIViewController] = [] private lazy var container:TabPageContainer = { let con = TabPageContainer(frame: containerFrame) return con }() ///Tab bar view public lazy var tabBar:MNkTabBar = { let con = MNkTabBar(frame: tabBarFrame) return con }() private lazy var tabPageController:MenuTabsViewController = { let tvc = MenuTabsViewController(transitionStyle: .scroll, navigationOrientation: .horizontal) tvc.tabPageViewControllers = self.mnkTabBarViewControllers tvc.tabControllerDelegate = self return tvc }() public init(){ super.init(nibName: nil, bundle: nil) doInitialWork() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) doInitialWork() } ///Set subview controllers and add animated or still images to tab bar open func setSubViewControllers(){} private func doInitialWork(){ view.backgroundColor = .white insertAndLayoutSubviews() setSubViewControllers() addControllerComp(tabPageController, to: container) animatedTabBar = tabBar animatedTabBarController = self } //MARK:- LAYOUT SUBVIEWS OF VIEW CONTROLLER private func insertAndLayoutSubviews(){ view.addSubview(container) view.addSubview(tabBar) } // /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\//\\/\/\/\/\/\/\\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\/\/\/\ //MARK:- FUNCTIONS THAT MADE FOR WORK USER TO CONFIGURE TAB BAR public func insertMnkTabbar(itemAt tag:Int,titleResouse resouse:Any,for title:String,_ type:MNkTabBarButton.Types = .image){ let button = MNkTabBarButton() button.tag = tag button.type = type button.titleResource = resouse button.title = title button.delegate = self tabBar.insertNew(tabbarButton: button) } private func setSelectedVC(at index:Int){ guard mnkTabBarViewControllers.count > index else{return} let navigationDirection:UIPageViewControllerNavigationDirection = tabPageController.beforeSelectedIndex > index ? UIPageViewControllerNavigationDirection.reverse : .forward tabPageController.setViewControllers([tabPageController.tabPageViewControllers[index]], direction: navigationDirection, animated: isSwitchBetweenTabsAnimatable, completion: nil) tabPageController.beforeSelectedIndex = index tabBar.setActivateTabButton(at: index) } ///Set tab bar show or hide. public func setTabBar(hide isHide:Bool,animated isAnimated:Bool){ guard _isTabBarHide != isHide else {return} _isTabBarHide = isHide let _tabBarAnimatedOriginY = isHide ? (tabBarFrame.origin.y + tabBarFrame.size.height) : tabBarFrame.origin.y let _containerFrame = isHide ? CGRect(origin: .zero, size: CGSize(width: containerFrame.size.width, height: (containerFrame.size.height + tabBarFrame.size.height) - self.view.safeAreaInsets.bottom)) : containerFrame let animateTime:Double = isAnimated ? 0.4 : 0.0 UIView.animate(withDuration: animateTime, delay: 0, options: .curveEaseOut, animations: { self.tabBar.frame.origin.y = _tabBarAnimatedOriginY self.container.frame = _containerFrame }, completion: nil) } } extension MNkTabBarController:MNkButtonDelegate{ func userDidChagedTap(buttonAt index: Int) { setSelectedVC(at: index) } } extension MNkTabBarController:MenuTabsViewControllerDelegate{ func userScroll(to viewController: UIViewController, at index: Int) { tabBar.setActivateTabButton(at: index) } }
31.903061
223
0.610267
2908d9e092ae62b49dd32acc5c0d4183c73ecc4f
4,247
// // Copyright © FINN.no AS, Inc. All rights reserved. // import UIKit public final class BottomSheetTransitioningDelegate: NSObject { public private(set) var contentHeights: [CGFloat] private let startTargetIndex: Int private let handleBackground: BottomSheetView.HandleBackground private let draggableHeight: CGFloat? private let useSafeAreaInsets: Bool private let stretchOnResize: Bool private var weakPresentationController: WeakRef<BottomSheetPresentationController>? private weak var presentationDelegate: BottomSheetPresentationControllerDelegate? private weak var animationDelegate: BottomSheetViewAnimationDelegate? private var presentationController: BottomSheetPresentationController? { return weakPresentationController?.value } // MARK: - Init public init( contentHeights: [CGFloat], startTargetIndex: Int = 0, handleBackground: BottomSheetView.HandleBackground = .color(.clear), draggableHeight: CGFloat? = nil, presentationDelegate: BottomSheetPresentationControllerDelegate? = nil, animationDelegate: BottomSheetViewAnimationDelegate? = nil, useSafeAreaInsets: Bool = false, stretchOnResize: Bool = false ) { self.contentHeights = contentHeights self.startTargetIndex = startTargetIndex self.handleBackground = handleBackground self.draggableHeight = draggableHeight self.presentationDelegate = presentationDelegate self.animationDelegate = animationDelegate self.useSafeAreaInsets = useSafeAreaInsets self.stretchOnResize = stretchOnResize } // MARK: - Public /// Animates bottom sheet view to the given height. /// /// - Parameters: /// - index: the index of the target height public func transition(to index: Int) { presentationController?.transition(to: index) } /// Recalculates target offsets and animates to the minimum one. /// Call this method e.g. when orientation change is detected. public func reset() { presentationController?.reset() } public func reload(with contentHeights: [CGFloat]) { self.contentHeights = contentHeights presentationController?.reload(with: contentHeights) } } // MARK: - UIViewControllerTransitioningDelegate extension BottomSheetTransitioningDelegate: UIViewControllerTransitioningDelegate { public func presentationController( forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController ) -> UIPresentationController? { let presentationController = BottomSheetPresentationController( presentedViewController: presented, presenting: presenting, contentHeights: contentHeights, startTargetIndex: startTargetIndex, presentationDelegate: presentationDelegate, animationDelegate: animationDelegate, handleBackground: handleBackground, draggableHeight: draggableHeight, useSafeAreaInsets: useSafeAreaInsets, stretchOnResize: stretchOnResize ) self.weakPresentationController = WeakRef(value: presentationController) return presentationController } public func animationController( forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController ) -> UIViewControllerAnimatedTransitioning? { presentationController?.transitionState = .presenting return presentationController } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { presentationController?.transitionState = .dismissing return presentationController } public func interactionControllerForPresentation( using animator: UIViewControllerAnimatedTransitioning ) -> UIViewControllerInteractiveTransitioning? { return presentationController } } // MARK: - Private types private class WeakRef<T> where T: AnyObject { private(set) weak var value: T? init(value: T?) { self.value = value } }
35.391667
121
0.71627
397fee42f9ed3ceaeacf49a545314e491f8d134e
10,329
// // RouteComposer // ShortUITests.swift // https://github.com/ekazaev/route-composer // // Created by Eugene Kazaev in 2018-2021. // Distributed under the MIT license. // #if os(iOS) import XCTest class ShortUITests: XCTestCase { var app: XCUIApplication! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false app = XCUIApplication() // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. // 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. // We send a command line argument to our app, // to enable it to reset its state app.launchArguments.append("--uitesting") } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testPromptScreenAndBack() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Welcome"].tap() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.terminate() } func testGoToSquareFromModalInTab() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Routing control"].tap() XCTAssertTrue(app.otherElements["routingRuleViewController"].exists) app.buttons["Go to Square Tab"].tap() XCTAssertTrue(app.otherElements["squareViewController"].exists) } func testCollectionsAndReturnHome() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Square Tab"].tap() XCTAssertTrue(app.otherElements["squareViewController"].exists) app.buttons["Go to Collections*"].tap() XCTAssertTrue(app.otherElements["loginViewController"].exists) app.textFields["loginTextField"].tap() app.textFields["loginTextField"].typeText("abc") app.textFields["passwordTextField"].tap() app.textFields["passwordTextField"].typeText("abc") app.buttons["Login"].tap() XCTAssertTrue(app.tables["collectionsViewController"].waitForExistence(timeout: 5)) app.buttons["Done"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.terminate() } func testCancelLoginScreenAndReturnHome() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Second modal"].tap() XCTAssertTrue(app.otherElements["secondLevelViewController"].waitForExistence(timeout: 3)) app.buttons["Go to Minsk*"].tap() XCTAssertTrue(app.otherElements["loginViewController"].exists) app.buttons["Close"].tap() XCTAssertTrue(app.otherElements["secondLevelViewController"].exists) app.buttons["Go to Home"].tap() XCTAssertTrue(app.otherElements["circleViewController"].exists) app.terminate() } func testImagesModule() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Images"].tap() XCTAssertTrue(app.tables["imagesViewController"].exists) app.tables.cells.element(boundBy: 2).tap() XCTAssertTrue(app.otherElements["imagestarViewController"].waitForExistence(timeout: 1)) app.buttons["Dismiss"].tap() XCTAssertTrue(app.tables["imagesViewController"].waitForExistence(timeout: 1)) app.buttons["Done"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Images (No Library)"].tap() XCTAssertTrue(app.tables["imagesViewController"].exists) app.tables.cells.element(boundBy: 1).tap() XCTAssertTrue(app.otherElements["imagesecondViewController"].waitForExistence(timeout: 1)) app.buttons["Dismiss"].tap() XCTAssertTrue(app.tables["imagesViewController"].waitForExistence(timeout: 1)) app.buttons["Done"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.terminate() } func testAlternativeStarRoute() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Square Tab"].tap() XCTAssertTrue(app.otherElements["squareViewController"].exists) var switcher = app.switches["routeSwitchControl"] switcher.tap() XCTAssertTrue(app.otherElements["squareViewController"].exists) app.buttons["Go to Star Screen*"].tap() XCTAssertTrue(app.otherElements["loginViewController"].exists) app.textFields["loginTextField"].tap() app.textFields["loginTextField"].typeText("abc") app.textFields["passwordTextField"].tap() app.textFields["passwordTextField"].typeText("abc") app.buttons["Login"].tap() XCTAssertTrue(app.otherElements["starViewController"].waitForExistence(timeout: 4)) app.buttons["Go to Product 02"].tap() XCTAssertTrue(app.otherElements["productViewController+02"].exists) app.buttons["Go to Circle Tab"].tap() XCTAssertTrue(app.otherElements["circleViewController"].exists) app.buttons["Go to Square Tab"].tap() XCTAssertTrue(app.otherElements["squareViewController"].exists) app.buttons["Go to Star Screen*"].tap() XCTAssertTrue(app.otherElements["starViewController"].exists) app.buttons["Dismiss Star Tab*"].tap() XCTAssertTrue(app.otherElements["circleViewController"].exists) app.buttons["Go to Square Tab"].tap() XCTAssertTrue(app.otherElements["squareViewController"].exists) switcher = app.switches["routeSwitchControl"] switcher.tap() XCTAssertTrue(app.otherElements["squareViewController"].exists) app.buttons["Go to Star Screen*"].tap() XCTAssertTrue(app.otherElements["starViewController"].exists) app.buttons["Dismiss Star Tab*"].tap() XCTAssertTrue(app.otherElements["circleViewController"].exists) app.terminate() } func testLastProductRoute() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Square Tab"].tap() XCTAssertTrue(app.otherElements["squareViewController"].exists) app.buttons["Go to Split*"].tap() XCTAssertTrue(app.otherElements["loginViewController"].exists) app.textFields["loginTextField"].tap() app.textFields["loginTextField"].typeText("abc") app.textFields["passwordTextField"].tap() app.textFields["passwordTextField"].typeText("abc") app.buttons["Login"].tap() XCTAssertTrue(app.otherElements["citiesSplitViewController"].waitForExistence(timeout: 3)) app.buttons["Product"].tap() XCTAssertTrue(app.otherElements["productViewController+123"].waitForExistence(timeout: 3)) } func testUnexpectedAnimation() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Routing control"].tap() XCTAssertTrue(app.otherElements["routingRuleViewController"].exists) app.buttons["Go to New York*"].tap() XCTAssertTrue(app.otherElements["loginViewController"].waitForExistence(timeout: 3)) app.textFields["loginTextField"].tap() app.textFields["loginTextField"].typeText("abc") app.textFields["passwordTextField"].tap() app.textFields["passwordTextField"].typeText("abc") app.buttons["Login"].tap() // We have to wait for login service to succeed // Apple uses same technique http://cleanswifter.com/asynchronous-xcode-ui-testing/ XCTAssertTrue(app.otherElements["cityDetailsViewController+3"].waitForExistence(timeout: 7)) } func testGoProductFromCircle() { app.launch() XCTAssertTrue(app.otherElements["promptViewController"].exists) app.buttons["Continue"].tap() XCTAssertTrue(app.otherElements["homeViewController"].exists) app.buttons["Go to Product 00"].tap() XCTAssertTrue(app.otherElements["productViewController+00"].exists) app.buttons["Go to next Product from Circle"].tap() XCTAssertTrue(app.otherElements["productViewController+01"].waitForExistence(timeout: 3)) app.buttons["Go to next Product from Circle"].tap() XCTAssertTrue(app.otherElements["productViewController+02"].waitForExistence(timeout: 3)) app.buttons["Go to Product 01"].tap() XCTAssertTrue(app.otherElements["productViewController+01"].exists) app.buttons["Go to next Product from Circle"].tap() XCTAssertTrue(app.otherElements["productViewController+02"].waitForExistence(timeout: 3)) app.buttons["Go to Circle Tab"].tap() XCTAssertTrue(app.otherElements["circleViewController"].waitForExistence(timeout: 1)) } } #endif
35.864583
131
0.678962
18732e2c79d77d02eeee8367c83bdf2ae7768642
533
// // RoundedShadowImageView.swift // Vision-App // // Created by Johnny Perdomo on 4/26/18. // Copyright © 2018 Johnny Perdomo. All rights reserved. // import UIKit class RoundedShadowImageView: UIImageView { override func awakeFromNib() { self.layer.shadowColor = #colorLiteral(red: 0.3333333433, green: 0.3333333433, blue: 0.3333333433, alpha: 1) self.layer.shadowRadius = 15 //blurs shadow self.layer.shadowOpacity = 0.75 //opaque self.layer.cornerRadius = 15 //rounds corners } }
25.380952
116
0.684803
33db9fd14ccce78cc806e728b20a3bbed1cdaff2
2,335
import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! var center: CLLocationCoordinate2D var region: MKCoordinateRegion var overlay: WMSTileOverlay override func viewDidLoad() { super.viewDidLoad() self.getCardfromGeoserver() self.recentreMap() mapView.mapType = MKMapType.Hybrid mapView.setRegion(region, animated: false) self.mapView.delegate = self } required init?(coder aDecoder: NSCoder) { self.center = CLLocationCoordinate2D(latitude: 51.0000000, longitude: 10.0000000) self.region = MKCoordinateRegion(center: self.center, span: MKCoordinateSpan(latitudeDelta: 10.01, longitudeDelta: 10.01)) self.overlay = WMSTileOverlay(urlArg: "", useMercatorArg: true) super.init(coder: aDecoder) } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKTileOverlay { let renderer = MKTileOverlayRenderer(overlay:overlay) renderer.alpha = (overlay as! WMSTileOverlay).alpha return renderer } return MKPolylineRenderer() } // Warnung ueber Geoserver holen func getCardfromGeoserver() { let url = "https://__GEOSERVER__?LAYERS=__LAYER__&STYLES=&SERVICE=WMS&VERSION=1.3&REQUEST=GetMap&SRS=EPSG:900913&width=256&height=256&format=image/png8&transparent=true" self.recentreMap() self.mapView.removeOverlay(overlay) overlay = WMSTileOverlay(urlArg: url, useMercatorArg: true) overlay.canReplaceMapContent = false //Set the overlay transparency overlay.alpha = 0.7 //Add the overlay self.mapView.addOverlay(overlay) } func recentreMap() { let centre = CLLocationCoordinate2D(latitude: 51.0000000, longitude: 10.0000000) let span = MKCoordinateSpan(latitudeDelta: 10.01, longitudeDelta: 10.01) let region = MKCoordinateRegion(center: centre, span: span) self.mapView.setRegion(region, animated: false) self.mapView.regionThatFits(region) } }
31.554054
177
0.641542
67ffcc1cc47940440fd9033187e8466302be4a08
411
import Cocoa /// A view that will never return self for a hitTest /// /// Useful for makeFirstResponder passthough to superviews due /// to mouseDown events. open class NoSelfHitTestingView: NSView { open override func hitTest(_ point: NSPoint) -> NSView? { let resultView = super.hitTest(point) if resultView === self { return nil } return resultView } }
22.833333
62
0.649635
1efc67421610f54d0bada55d3bd7aa5db32f3790
970
// // WorldTrotterTests.swift // WorldTrotterTests // // Created by SB on 8/15/17. // Copyright © 2017 SB. All rights reserved. // import XCTest @testable import WorldTrotter class WorldTrotterTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.216216
111
0.634021
89f98625721b86625899217ca988f7bbf578bd7a
858
// // LamarA.swift // NoPlaceToGo // // Created by Bryan Costanza on 8/27/20. // import SwiftUI struct LamarB: View { @State private var installIndex = 0 private var numInstallsAtSite = 3 var body: some View { VStack { if installIndex == 0 { StevenFrost() NextInstallationButton( installIndex: $installIndex, numInstallsAtSite: numInstallsAtSite, messageNext: "Liberace is\nfinished with me") } else if installIndex == 1 { ChrissyGrace(installIndex: $installIndex, numInstallsAtSite: numInstallsAtSite) } else { ReadyForNextSiteView() } } } } struct LamarA_Previews: PreviewProvider { static var previews: some View { LamarA() } }
23.833333
95
0.558275
eb4f39277e9572ae9b31b4b8f73274bf3333c0eb
951
import AppAudioLibrary import AppClipAudioLibrary import DictionarySqliteClient import OnboardingFeature import Styleguide import SwiftUI @main struct OnboardingPreviewApp: App { init() { Styleguide.registerFonts() } var body: some Scene { WindowGroup { OnboardingView( store: .init( initialState: .init(presentationStyle: .firstLaunch), reducer: onboardingReducer, environment: OnboardingEnvironment( audioPlayer: .live( bundles: [ AppClipAudioLibrary.bundle, AppAudioLibrary.bundle, ] ), backgroundQueue: DispatchQueue.global().eraseToAnyScheduler(), dictionary: .sqlite(), feedbackGenerator: .live, lowPowerMode: .live, mainQueue: .main, mainRunLoop: .main, userDefaults: .noop ) ) ) } } }
23.775
74
0.582545
f8c0a309b576b713965e0d651b7da89d7c451b33
1,017
import UIKit let githubURL: URL = URL(string: "https://github.com/chadaustin/is-it-snappy")! let twitterURL: URL = URL(string: "https://twitter.com/chadaustin")! class AboutViewController: UIViewController { @IBAction func handleBack() { dismiss(animated: true, completion: nil) } @IBAction func handleTapGitHub() { UIApplication.shared.open(githubURL, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil) } @IBAction func handleTapTwitter() { UIApplication.shared.open(twitterURL, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) }
42.375
150
0.763029
21ea41d6ea21e5328a2b020dcd19693205214bc9
2,116
import UIKit enum ColorWellArrowDirection: Int { case down = 0, up var opposite: ColorWellArrowDirection { switch self { case .down: return .up case .up: return .down } } } final class ColorWellArrowViewControl: UIControl { override var intrinsicContentSize: CGSize { return CGSize(width: 60, height: 44) } private let arrowImageView = UIImageView(image: UIImage(named: "icon_nav-carat")?.withRenderingMode(.alwaysTemplate)) private let colorWellView = ColorWellView() private(set) var arrowDirection: ColorWellArrowDirection = .up var color: UIColor? { didSet { colorWellView.color = color arrowImageView.tintColor = color?.blackOrWhiteTintColorForLuminosity } } override init(frame: CGRect) { super.init(frame: frame) arrowImageView.sizeToFit() arrowImageView.transform = transform(for: arrowDirection) addSubview(colorWellView) addSubview(arrowImageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() colorWellView.frame = bounds arrowImageView.center = CGPoint(x: bounds.width/2, y: bounds.height/2) } func setArrowDirection(_ arrowDirection: ColorWellArrowDirection, animated: Bool = false) { guard arrowDirection != self.arrowDirection else { return } let duration = animated ? 0.2 : 0.0 self.arrowDirection = arrowDirection UIView.animate(withDuration: duration, animations: { self.arrowImageView.transform = self.transform(for: arrowDirection) }) } private func transform(for direction: ColorWellArrowDirection) -> CGAffineTransform { switch direction { case .up: return CGAffineTransform(rotationAngle: CGFloat(180.0 * .pi) / CGFloat(180.0)) case .down: return CGAffineTransform.identity } } }
27.480519
121
0.638941
4642a8584871d72f737ac71b26cc3b2d003af8e4
424
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -emit-ir if{enum a{private extension
42.4
79
0.757075
75ffbd22d02679bb5c053c61b01136d23bb81d4e
1,112
import Flexbox /// Virtual tree node without `PropsReflectable`. /// This is a basic generic class that has type-unsafe `props` only, /// and relies on KVC to create a new view. public final class VGeneric<V: View, Msg: Message>: VTree { public let key: Key? public let props: [String: Any] public let flexbox: Flexbox.Node? public let handlers: HandlerMapping<Msg> public let gestures: [GestureEvent<Msg>] public let children: [AnyVTree<Msg>] public init( key: Key? = nil, props: [String: Any] = [:], flexbox: Flexbox.Node? = nil, handlers: HandlerMapping<Msg> = [:], gestures: [GestureEvent<Msg>] = [], children: [AnyVTree<Msg>] = [] ) { self.key = key self.props = props self.flexbox = flexbox self.handlers = handlers self.gestures = gestures self.children = children } public func createView<Msg2: Message>(_ msgMapper: @escaping (Msg) -> Msg2) -> V { let view = V() self._setupView(view, msgMapper: msgMapper) return view } }
27.8
84
0.600719
09e08c177565d2f67cd9cd6d621b81824f36c8bc
708
// // Calculator.swift // TipCalculator // // Created by Jasmin Ramirez on 10/2/19. // Copyright © 2019 Jasmin Ramirez . All rights reserved. // import UIKit class Calculator: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
21.454545
106
0.64548
09f3e9ab4c356eff816f56f0d805366fe0b3a025
2,571
// // MainCircuitStatevectorFactoryTests.swift // SwiftQuantumComputing // // Created by Enrique de la Torre on 08/06/2020. // Copyright © 2020 Enrique de la Torre. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest @testable import SwiftQuantumComputing // MARK: - Main body class MainCircuitStatevectorFactoryTests: XCTestCase { // MARK: - Properties let factory = MainCircuitStatevectorFactory() let nonPowerOfTwoVector = try! Vector([.zero, .zero, .one]) let squareModulusNotEqualToOneVector = try! Vector([.zero, .zero, .one, .one]) let validVector = try! Vector([.zero, .zero, .one, .zero]) // MARK: - Tests func testNonPowerOfTwoVector_makeStatevector_throwException() { // Then var error: MakeStatevectorError? if case .failure(let e) = factory.makeStatevector(vector: nonPowerOfTwoVector) { error = e } XCTAssertEqual(error, .vectorCountHasToBeAPowerOfTwo) } func testSquareModulusNotEqualToOneVector_makeStatevector_throwException() { // Then var error: MakeStatevectorError? if case .failure(let e) = factory.makeStatevector(vector: squareModulusNotEqualToOneVector) { error = e } XCTAssertEqual(error, .vectorAdditionOfSquareModulusIsNotEqualToOne) } func testValidVector_makeStatevector_returnValue() { // Then var result: CircuitStatevector? if case .success(let r) = factory.makeStatevector(vector: validVector) { result = r } XCTAssertNotNil(result) } static var allTests = [ ("testNonPowerOfTwoVector_makeStatevector_throwException", testNonPowerOfTwoVector_makeStatevector_throwException), ("testSquareModulusNotEqualToOneVector_makeStatevector_throwException", testSquareModulusNotEqualToOneVector_makeStatevector_throwException), ("testValidVector_makeStatevector_returnValue", testValidVector_makeStatevector_returnValue) ] }
34.28
101
0.711396
5ddda4a8a55d16bee3d6bcf89bfb06b693ab884c
1,785
// // Copyright (c) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Firebase import GoogleSignIn @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate { var window: UIWindow? @available(iOS 9.0, *) func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { return self.application(application, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: "") } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation) } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) { if let error = error { print("Error \(error)") return } } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { GIDSignIn.sharedInstance().clientID = "" GIDSignIn.sharedInstance().delegate = self return true } }
34.326923
158
0.728852
efd13d238b3bf7d5a0934fc22cea97952fc85746
14,667
/* This source file is part of the Swift.org open source project Copyright (c) 2020 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation import TSCBasic import TSCUtility /// Represents a message output by xcbuild. public enum XCBuildMessage { public struct BuildDiagnosticInfo { public let message: String } public struct BuildCompletedInfo { public enum Result: String { case ok case failed case cancelled case aborted } public let result: Result } public struct BuildOutputInfo { let data: String } public struct DidUpdateProgressInfo { public let message: String public let percentComplete: Double public let showInLog: Bool } public struct TargetUpToDateInfo { public let guid: PIF.GUID } public struct TargetStartedInfo { public enum Kind: String { case native = "Native" case aggregate = "Aggregate" case external = "External" case packageProduct = "Package Product" } public let targetID: Int public let targetGUID: PIF.GUID public let targetName: String public let type: Kind } public struct TargetCompleteInfo { public let targetID: Int } public struct TaskUpToDateInfo { let targetID: Int? let taskSignature: String let parentTaskID: Int? } public struct TaskStartedInfo { let taskID: Int let targetID: Int? let taskSignature: String let parentTaskID: Int? let ruleInfo: String let interestingPath: AbsolutePath? let commandLineDisplayString: String? let executionDescription: String } public struct TaskDiagnosticInfo { let taskID: Int let targetID: Int? let message: String } public struct TaskOutputInfo { let taskID: Int let data: String } public struct TaskCompleteInfo { public enum Result: String { case success case failed case cancelled } let taskID: Int let result: Result let signalled: Bool } public struct TargetDiagnosticInfo { let targetID: Int let message: String } case buildStarted case buildDiagnostic(BuildDiagnosticInfo) case buildCompleted(BuildCompletedInfo) case buildOutput(BuildOutputInfo) case preparationComplete case didUpdateProgress(DidUpdateProgressInfo) case targetUpToDate(TargetUpToDateInfo) case targetStarted(TargetStartedInfo) case targetComplete(TargetCompleteInfo) case taskUpToDate(TaskUpToDateInfo) case taskStarted(TaskStartedInfo) case taskDiagnostic(TaskDiagnosticInfo) case taskOutput(TaskOutputInfo) case taskComplete(TaskCompleteInfo) case targetDiagnostic(TargetDiagnosticInfo) } /// Protocol for the parser delegate to get notified of parsing events. public protocol XCBuildOutputParserDelegate: AnyObject { /// Called for each message parsed. func xcBuildOutputParser(_ parser: XCBuildOutputParser, didParse message: XCBuildMessage) /// Called on an un-expected parsing error. No more events will be received after that. func xcBuildOutputParser(_ parser: XCBuildOutputParser, didFailWith error: Error) } /// Parser for XCBuild output. public final class XCBuildOutputParser { /// The underlying JSON message parser. private var jsonParser: JSONMessageStreamingParser<XCBuildOutputParser>! /// Whether the parser is in a failing state. private var hasFailed: Bool /// Delegate to notify of parsing events. public weak var delegate: XCBuildOutputParserDelegate? = nil /// Initializes the parser with a delegate to notify of parsing events. /// - Parameters: /// - delegate: Delegate to notify of parsing events. public init(delegate: XCBuildOutputParserDelegate) { self.hasFailed = false self.delegate = delegate self.jsonParser = JSONMessageStreamingParser<XCBuildOutputParser>(delegate: self) } /// Parse the next bytes of the Swift compiler JSON output. /// - Note: If a parsing error is encountered, the delegate will be notified and the parser won't accept any further /// input. public func parse<C>(bytes: C) where C: Collection, C.Element == UInt8 { guard !hasFailed else { return } jsonParser.parse(bytes: bytes) } } extension XCBuildOutputParser: JSONMessageStreamingParserDelegate { public func jsonMessageStreamingParser( _ parser: JSONMessageStreamingParser<XCBuildOutputParser>, didParse message: XCBuildMessage ) { guard !hasFailed else { return } delegate?.xcBuildOutputParser(self, didParse: message) } public func jsonMessageStreamingParser( _ parser: JSONMessageStreamingParser<XCBuildOutputParser>, didParseRawText text: String ) { // Don't do anything with raw text. } public func jsonMessageStreamingParser( _ parser: JSONMessageStreamingParser<XCBuildOutputParser>, didFailWith error: Error ) { delegate?.xcBuildOutputParser(self, didFailWith: error) } } extension XCBuildMessage.BuildDiagnosticInfo: Decodable, Equatable {} extension XCBuildMessage.BuildCompletedInfo.Result: Decodable, Equatable {} extension XCBuildMessage.BuildCompletedInfo: Decodable, Equatable {} extension XCBuildMessage.BuildOutputInfo: Decodable, Equatable {} extension XCBuildMessage.TargetUpToDateInfo: Decodable, Equatable {} extension XCBuildMessage.TaskDiagnosticInfo: Decodable, Equatable {} extension XCBuildMessage.TargetDiagnosticInfo: Decodable, Equatable {} extension XCBuildMessage.DidUpdateProgressInfo: Decodable, Equatable { enum CodingKeys: String, CodingKey { case message case percentComplete case showInLog } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) message = try container.decode(String.self, forKey: .message) percentComplete = try container.decodeDoubleOrString(forKey: .percentComplete) showInLog = try container.decodeBoolOrString(forKey: .showInLog) } } extension XCBuildMessage.TargetStartedInfo.Kind: Decodable, Equatable {} extension XCBuildMessage.TargetStartedInfo: Decodable, Equatable { enum CodingKeys: String, CodingKey { case targetID = "id" case targetGUID = "guid" case targetName = "name" case type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) targetID = try container.decodeIntOrString(forKey: .targetID) targetGUID = try container.decode(PIF.GUID.self, forKey: .targetGUID) targetName = try container.decode(String.self, forKey: .targetName) type = try container.decode(Kind.self, forKey: .type) } } extension XCBuildMessage.TargetCompleteInfo: Decodable, Equatable { enum CodingKeys: String, CodingKey { case targetID = "id" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) targetID = try container.decodeIntOrString(forKey: .targetID) } } extension XCBuildMessage.TaskUpToDateInfo: Decodable, Equatable { enum CodingKeys: String, CodingKey { case targetID case taskSignature = "signature" case parentTaskID = "parentID" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) targetID = try container.decodeIntOrStringIfPresent(forKey: .targetID) taskSignature = try container.decode(String.self, forKey: .taskSignature) parentTaskID = try container.decodeIntOrStringIfPresent(forKey: .parentTaskID) } } extension XCBuildMessage.TaskStartedInfo: Decodable, Equatable { enum CodingKeys: String, CodingKey { case taskID = "id" case targetID case taskSignature = "signature" case parentTaskID = "parentID" case ruleInfo case interestingPath case commandLineDisplayString case executionDescription } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) taskID = try container.decodeIntOrString(forKey: .taskID) targetID = try container.decodeIntOrStringIfPresent(forKey: .targetID) taskSignature = try container.decode(String.self, forKey: .taskSignature) parentTaskID = try container.decodeIntOrStringIfPresent(forKey: .parentTaskID) ruleInfo = try container.decode(String.self, forKey: .ruleInfo) interestingPath = try AbsolutePath(validatingOrNilIfEmpty: container.decodeIfPresent(String.self, forKey: .interestingPath)) commandLineDisplayString = try container.decode(String.self, forKey: .commandLineDisplayString) executionDescription = try container.decode(String.self, forKey: .executionDescription) } } extension XCBuildMessage.TaskOutputInfo: Decodable, Equatable { enum CodingKeys: String, CodingKey { case taskID case data } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) taskID = try container.decodeIntOrString(forKey: .taskID) data = try container.decode(String.self, forKey: .data) } } extension XCBuildMessage.TaskCompleteInfo.Result: Decodable, Equatable {} extension XCBuildMessage.TaskCompleteInfo: Decodable, Equatable { enum CodingKeys: String, CodingKey { case taskID = "id" case result case signalled } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) taskID = try container.decodeIntOrString(forKey: .taskID) result = try container.decode(Result.self, forKey: .result) signalled = try container.decode(Bool.self, forKey: .signalled) } } extension XCBuildMessage: Decodable, Equatable { enum CodingKeys: CodingKey { case kind } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let kind = try container.decode(String.self, forKey: .kind) switch kind { case "buildStarted": self = .buildStarted case "buildDiagnostic": self = try .buildDiagnostic(BuildDiagnosticInfo(from: decoder)) case "buildCompleted": self = try .buildCompleted(BuildCompletedInfo(from: decoder)) case "buildOutput": self = try .buildOutput(BuildOutputInfo(from: decoder)) case "preparationComplete": self = .preparationComplete case "didUpdateProgress": self = try .didUpdateProgress(DidUpdateProgressInfo(from: decoder)) case "targetUpToDate": self = try .targetUpToDate(TargetUpToDateInfo(from: decoder)) case "targetStarted": self = try .targetStarted(TargetStartedInfo(from: decoder)) case "targetComplete": self = try .targetComplete(TargetCompleteInfo(from: decoder)) case "taskUpToDate": self = try .taskUpToDate(TaskUpToDateInfo(from: decoder)) case "taskStarted": self = try .taskStarted(TaskStartedInfo(from: decoder)) case "taskDiagnostic": self = try .taskDiagnostic(TaskDiagnosticInfo(from: decoder)) case "taskOutput": self = try .taskOutput(TaskOutputInfo(from: decoder)) case "taskComplete": self = try .taskComplete(TaskCompleteInfo(from: decoder)) case "targetDiagnostic": self = try .targetDiagnostic(TargetDiagnosticInfo(from: decoder)) default: throw DecodingError.dataCorruptedError(forKey: .kind, in: container, debugDescription: "invalid kind \(kind)") } } } fileprivate extension KeyedDecodingContainer { func decodeBoolOrString(forKey key: Key) throws -> Bool { do { return try decode(Bool.self, forKey: key) } catch { let string = try decode(String.self, forKey: key) guard let value = Bool(string) else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Could not parse '\(string)' as Bool for key \(key)") } return value } } func decodeDoubleOrString(forKey key: Key) throws -> Double { do { return try decode(Double.self, forKey: key) } catch { let string = try decode(String.self, forKey: key) guard let value = Double(string) else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Could not parse '\(string)' as Double for key \(key)") } return value } } func decodeIntOrString(forKey key: Key) throws -> Int { do { return try decode(Int.self, forKey: key) } catch { let string = try decode(String.self, forKey: key) guard let value = Int(string) else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Could not parse '\(string)' as Int for key \(key)") } return value } } func decodeIntOrStringIfPresent(forKey key: Key) throws -> Int? { do { return try decodeIfPresent(Int.self, forKey: key) } catch { guard let string = try decodeIfPresent(String.self, forKey: key), !string.isEmpty else { return nil } guard let value = Int(string) else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Could not parse '\(string)' as Int for key \(key)") } return value } } } fileprivate extension AbsolutePath { init?(validatingOrNilIfEmpty path: String?) throws { guard let path = path, !path.isEmpty else { return nil } try self.init(validating: path) } }
34.755924
151
0.668439
eff25bc1c62644de876469704c487e36af06d46e
1,174
// // MostCommonCharacter.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func mostCommonCharacter(inventory: [UDItem]) -> Character? { var char = Character("i") var dictionarys = [Character:Int]() var max = 0 if(inventory.count != 0){ for uditem in inventory { if let name = uditem.name.lowercased() as? String{ for character in name.characters { if(dictionarys[character] == nil) { dictionarys[character] = 1 }else{ dictionarys[character]! += 1 if(dictionarys[character]!>max){ max=dictionarys[character]! char=character } } } } } //print(dictionarys) return char }else{ return nil } } }
27.302326
66
0.413969
b93632f579e1e5e3d5b584042855e8224e48f9fd
74,816
import Flutter import UIKit import ImSDK import HandyJSON public class SwiftTencentImPlugin: NSObject, FlutterPlugin, TIMUserStatusListener, TIMConnListener, TIMGroupEventListener, TIMRefreshListener, TIMMessageRevokeListener, TIMMessageReceiptListener, TIMMessageListener, TIMUploadProgressListener { public static var channel: FlutterMethodChannel?; /** * 监听器回调的方法名 */ private static let LISTENER_FUNC_NAME = "onListener"; public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "tencent_im_plugin", binaryMessenger: registrar.messenger()) let instance = SwiftTencentImPlugin() SwiftTencentImPlugin.channel = channel; registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "init": self.`init`(call: call, result: result) break case "login": self.login(call: call, result: result) break case "logout": self.logout(call: call, result: result) break case "getLoginUser": self.getLoginUser(call: call, result: result) break case "initStorage": self.initStorage(call: call, result: result) break case "getConversationList": getConversationList(call: call, result: result) break case "getConversation": getConversation(call: call, result: result) break case "getGroupInfo": self.getGroupInfo(call: call, result: result); break; case "getUserInfo": self.getUserInfo(call: call, result: result); break; case "getMessages": self.getMessages(call: call, result: result); break; case "getLocalMessages": self.getLocalMessages(call: call, result: result); break; case "setRead": self.setRead(call: call, result: result); break; case "sendMessage": self.sendMessage(call: call, result: result); break; case "saveMessage": self.saveMessage(call: call, result: result); break; case "getFriendList": self.getFriendList(call: call, result: result); break; case "getGroupList": self.getGroupList(call: call, result: result); break; case "addFriend": self.addFriend(call: call, result: result); break; case "checkSingleFriends": self.checkSingleFriends(call: call, result: result); break; case "getPendencyList": self.getPendencyList(call: call, result: result); break; case "pendencyReport": self.pendencyReport(call: call, result: result); break; case "deletePendency": self.deletePendency(call: call, result: result); break; case "examinePendency": self.examinePendency(call: call, result: result); break; case "deleteConversation": self.deleteConversation(call: call, result: result); break; case "deleteLocalMessage": self.deleteLocalMessage(call: call, result: result); break; case "createGroup": self.createGroup(call: call, result: result); break; case "inviteGroupMember": self.inviteGroupMember(call: call, result: result); break; case "applyJoinGroup": self.applyJoinGroup(call: call, result: result); break; case "quitGroup": self.quitGroup(call: call, result: result); break; case "deleteGroupMember": self.deleteGroupMember(call: call, result: result); break; case "getGroupMembers": self.getGroupMembers(call: call, result: result); break; case "deleteGroup": self.deleteGroup(call: call, result: result); break; case "modifyGroupOwner": self.modifyGroupOwner(call: call, result: result); break; case "modifyGroupInfo": self.modifyGroupInfo(call: call, result: result); break; case "modifyMemberInfo": self.modifyMemberInfo(call: call, result: result); break; case "getGroupPendencyList": self.getGroupPendencyList(call: call, result: result); break; case "reportGroupPendency": self.reportGroupPendency(call: call, result: result); break; case "groupPendencyAccept": self.groupPendencyAccept(call: call, result: result); break; case "groupPendencyRefuse": self.groupPendencyRefuse(call: call, result: result); break; case "getSelfProfile": self.getSelfProfile(call: call, result: result); break; case "modifySelfProfile": self.modifySelfProfile(call: call, result: result); break; case "modifyFriend": self.modifyFriend(call: call, result: result); break; case "deleteFriends": self.deleteFriends(call: call, result: result); break; case "addBlackList": self.addBlackList(call: call, result: result); break; case "deleteBlackList": self.deleteBlackList(call: call, result: result); break; case "getBlackList": self.getBlackList(call: call, result: result); break; case "createFriendGroup": self.createFriendGroup(call: call, result: result); break; case "deleteFriendGroup": self.deleteFriendGroup(call: call, result: result); break; case "addFriendsToFriendGroup": self.addFriendsToFriendGroup(call: call, result: result); break; case "deleteFriendsFromFriendGroup": self.deleteFriendsFromFriendGroup(call: call, result: result); break; case "renameFriendGroup": self.renameFriendGroup(call: call, result: result); break; case "getFriendGroups": self.getFriendGroups(call: call, result: result); break; case "revokeMessage": self.revokeMessage(call: call, result: result); break; case "removeMessage": self.removeMessage(call: call, result: result); break; case "setMessageCustomInt": self.setMessageCustomInt(call: call, result: result); break; case "setMessageCustomStr": self.setMessageCustomStr(call: call, result: result); break; case "downloadVideoImage": self.downloadVideoImage(call: call, result: result); break; case "downloadVideo": self.downloadVideo(call: call, result: result); break; case "downloadSound": self.downloadSound(call: call, result: result); break; case "findMessage": self.findMessage(call: call, result: result); break; case "setOfflinePushSettings": self.setOfflinePushSettings(call: call, result: result); break; case "setOfflinePushToken": self.setOfflinePushToken(call: call, result: result); break; default: result(FlutterMethodNotImplemented); } } /** * 初始化腾讯云IM */ public func `init`(call: FlutterMethodCall, result: @escaping FlutterResult) { if let appid = CommonUtils.getParam(call: call, result: result, param: "appid") as? String, let enabledLogPrint = CommonUtils.getParam(call: call, result: result, param: "enabledLogPrint") as? Bool, let logPrintLevel = CommonUtils.getParam(call: call, result: result, param: "logPrintLevel") as? Int { // 初始化SDK配置 let sdkConfig = TIMSdkConfig(); sdkConfig.disableLogPrint = enabledLogPrint; sdkConfig.sdkAppId = (appid as NSString).intValue; sdkConfig.logLevel = TIMLogLevel.init(rawValue: logPrintLevel)!; sdkConfig.connListener = self; TIMManager.sharedInstance()?.initSdk(sdkConfig); // 初始化用户配置 let userConfig = TIMUserConfig(); userConfig.enableReadReceipt = true; userConfig.userStatusListener = self; userConfig.groupEventListener = self; userConfig.refreshListener = self; userConfig.messageRevokeListener = self; userConfig.messageReceiptListener = self; userConfig.uploadProgressListener = self; TIMManager.sharedInstance()?.setUserConfig(userConfig); // 添加新消息监听器 TIMManager.sharedInstance()?.add(self); result(nil); } } /** * 登录 */ public func login(call: FlutterMethodCall, result: @escaping FlutterResult) { if let identifier = CommonUtils.getParam(call: call, result: result, param: "identifier") as? String, let userSig = CommonUtils.getParam(call: call, result: result, param: "userSig") as? String { // 如果已经登录,则不允许重复登录 if TIMManager.sharedInstance()?.getLoginUser() != nil { result( FlutterError(code: "login failed.", message: "user is login", details: "user is already login ,you should login out first") ); } else { // 登录操作 let loginParam = TIMLoginParam(); loginParam.identifier = identifier; loginParam.userSig = userSig; TIMManager.sharedInstance()?.login(loginParam, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } } /** * 登出 */ public func logout(call: FlutterMethodCall, result: @escaping FlutterResult) { TIMManager.sharedInstance()?.logout({ result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } /** * 获得当前登录用户 */ public func getLoginUser(call: FlutterMethodCall, result: @escaping FlutterResult) { result(TIMManager.sharedInstance()?.getLoginUser()); } /** * 初始化本地存储 */ public func initStorage(call: FlutterMethodCall, result: @escaping FlutterResult) { if let identifier = CommonUtils.getParam(call: call, result: result, param: "identifier") as? String { TIMManager.sharedInstance()?.initStorage(identifier, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 获得当前登录用户会话列表 */ public func getConversationList(call: FlutterMethodCall, result: @escaping FlutterResult) { TencentImUtils.getConversationInfo(conversations: (TIMManager.sharedInstance()?.getConversationList())!, onSuccess: { (array) -> Void in result(JsonUtil.toJson(array)); }, onFail: TencentImUtils.returnErrorClosures(result: result)); } /** * 根据ID获得会话 */ public func getConversation(call: FlutterMethodCall, result: @escaping FlutterResult) { if let sessionId = CommonUtils.getParam(call: call, result: result, param: "sessionId") as? String, let sessionTypeStr = CommonUtils.getParam(call: call, result: result, param: "sessionType") as? String { if let session = TencentImUtils.getSession(sessionId: sessionId, sessionTypeStr: sessionTypeStr, result: result) { TencentImUtils.getConversationInfo(conversations: ([session]), onSuccess: { (array) -> Void in if array.count >= 1 { result(JsonUtil.toJson(array[0])); } else { result(nil); } }, onFail: TencentImUtils.returnErrorClosures(result: result)); } } } /** * 获得群信息 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getGroupInfo(call: FlutterMethodCall, result: @escaping FlutterResult) { if let id = CommonUtils.getParam(call: call, result: result, param: "id") { TIMGroupManager.sharedInstance()?.getGroupInfo([id], succ: { (array) -> Void in if array!.count >= 1 { result(JsonUtil.toJson(GroupInfoEntity(groupInfo: array![0] as! TIMGroupInfoResult))); } else { result(nil); } }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 获得用户信息 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getUserInfo(call: FlutterMethodCall, result: @escaping FlutterResult) { if let id = CommonUtils.getParam(call: call, result: result, param: "id") as? String, let forceUpdate = CommonUtils.getParam(call: call, result: result, param: "forceUpdate") as? Bool { TIMFriendshipManager.sharedInstance()?.getUsersProfile([id], forceUpdate: forceUpdate, succ: { (array) -> Void in if array!.count >= 1 { result(JsonUtil.toJson(UserInfoEntity(userProfile: array![0]))); } else { result(nil); } }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 设置会话消息为已读 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func setRead(call: FlutterMethodCall, result: @escaping FlutterResult) { if let sessionId = CommonUtils.getParam(call: call, result: result, param: "sessionId") as? String, let sessionTypeStr = CommonUtils.getParam(call: call, result: result, param: "sessionType") as? String { if let session = TencentImUtils.getSession(sessionId: sessionId, sessionTypeStr: sessionTypeStr, result: result) { session.setRead(nil, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } } /** * 获得消息列表 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getMessages(call: FlutterMethodCall, result: @escaping FlutterResult) { self.getMessages(call: call, result: result, local: false); } /** * 获得本地消息列表 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getLocalMessages(call: FlutterMethodCall, result: @escaping FlutterResult) { self.getMessages(call: call, result: result, local: true); } /** * 获得消息列表 * * @param methodCall 方法调用对象 * @param result 返回结果对象 * @param local 是否是获取本地消息 */ private func getMessages(call: FlutterMethodCall, result: @escaping FlutterResult, local: Bool) { if let sessionId = CommonUtils.getParam(call: call, result: result, param: "sessionId") as? String, let sessionTypeStr = CommonUtils.getParam(call: call, result: result, param: "sessionType") as? String, let number = CommonUtils.getParam(call: call, result: result, param: "number") as? Int32 { if let session = TencentImUtils.getSession(sessionId: sessionId, sessionTypeStr: sessionTypeStr, result: result) { TencentImUtils.getTimMessage(call: call, result: result, name: "lastMessage", onCallback: { (message) -> Void in // 成功回调 let successCallback = { (array: Any) -> Void in TencentImUtils.getMessageInfo(timMessages: array as! [TIMMessage], onSuccess: { (array) -> Void in result(JsonUtil.toJson(array)); }, onFail: TencentImUtils.returnErrorClosures(result: result)); }; // 获取本地消息记录或云端消息记录 if local { session.getLocalMessage(number, last: message, succ: successCallback, fail: TencentImUtils.returnErrorClosures(result: result)) } else { session.getMessage(number, last: message, succ: successCallback, fail: TencentImUtils.returnErrorClosures(result: result)) } }); } } } /** * 发送消息 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func sendMessage(call: FlutterMethodCall, result: @escaping FlutterResult) { if let sessionId = CommonUtils.getParam(call: call, result: result, param: "sessionId") as? String, let sessionType = CommonUtils.getParam(call: call, result: result, param: "sessionType") as? String, let nodeStr = CommonUtils.getParam(call: call, result: result, param: "node") as? String, let ol = CommonUtils.getParam(call: call, result: result, param: "ol") as? Bool { // 将节点信息解析 let node = JsonUtil.getDictionaryFromJSONString(jsonString: nodeStr); // 通过多态发送消息 MessageNodeType.valueOf(name: node["nodeType"] as! String)?.messageNodeInterface().send(conversation: TencentImUtils.getSession(sessionId: sessionId, sessionTypeStr: sessionType, result: result)!, params: node, ol: ol, onCallback: { (message) -> Void in // 处理消息结果并返回 TencentImUtils.getMessageInfo(timMessages: [message], onSuccess: { (array) -> Void in result(JsonUtil.toJson(array[0])); }, onFail: TencentImUtils.returnErrorClosures(result: result)); }, onFailCalback: TencentImUtils.returnErrorClosures(result: result)); } } /** * 发送消息 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func saveMessage(call: FlutterMethodCall, result: @escaping FlutterResult) { if let sessionId = CommonUtils.getParam(call: call, result: result, param: "sessionId") as? String, let sessionType = CommonUtils.getParam(call: call, result: result, param: "sessionType") as? String, let nodeStr = CommonUtils.getParam(call: call, result: result, param: "node") as? String, let sender = CommonUtils.getParam(call: call, result: result, param: "sender") as? String, let isReaded = CommonUtils.getParam(call: call, result: result, param: "isReaded") as? Bool { // 将节点信息解析 let node = JsonUtil.getDictionaryFromJSONString(jsonString: nodeStr); // 通过多态发送消息 let message = MessageNodeType.valueOf(name: node["nodeType"] as! String)?.messageNodeInterface().save(conversation: TencentImUtils.getSession(sessionId: sessionId, sessionTypeStr: sessionType, result: result)!, params: node, sender: sender, isReaded: isReaded); TencentImUtils.getMessageInfo(timMessages: [message!], onSuccess: { (array) -> Void in result(JsonUtil.toJson(array[0])); }, onFail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 获得好友列表 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getFriendList(call: FlutterMethodCall, result: @escaping FlutterResult) { TIMFriendshipManager.sharedInstance()?.getFriendList({ (array) -> Void in var resultData: [FriendEntity] = [] for item in array! { resultData.append(FriendEntity(friend: item)); } result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } /** * 获得群组列表 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getGroupList(call: FlutterMethodCall, result: @escaping FlutterResult) { TIMGroupManager.sharedInstance()?.getGroupList({ (array) -> Void in var ids: [String] = []; for item in array! { ids.append((item as! TIMGroupInfo).group) } if (ids.count == 0) { result(JsonUtil.toJson([])); return; } // 获得群资料 TIMGroupManager.sharedInstance()?.getGroupInfo(ids, succ: { (array) -> Void in var resultData: [GroupInfoEntity] = [] for item in array! { resultData.append(GroupInfoEntity(groupInfo: item as! TIMGroupInfoResult)); } result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } /** * 添加好友 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func addFriend(call: FlutterMethodCall, result: @escaping FlutterResult) { let remark = ((call.arguments as! [String: Any])["remark"]) as? String; let addWording = ((call.arguments as! [String: Any])["addWording"]) as? String; let addSource = ((call.arguments as! [String: Any])["addSource"]) as? String; let friendGroup = ((call.arguments as! [String: Any])["friendGroup"]) as? String; if let id = CommonUtils.getParam(call: call, result: result, param: "id") as? String, let addType = CommonUtils.getParam(call: call, result: result, param: "addType") as? Int { let request = TIMFriendRequest(); request.identifier = id; request.addType = TIMFriendAddType(rawValue: addType)!; if remark != nil { request.remark = remark!; } if addWording != nil { request.addWording = addWording!; } if addSource != nil { request.addSource = addSource!; } if friendGroup != nil { request.group = friendGroup; } TIMFriendshipManager.sharedInstance()?.addFriend(request, succ: { (data) -> Void in result(JsonUtil.toJson(FriendResultEntity(result: data!))); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 检测单个好友关系 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func checkSingleFriends(call: FlutterMethodCall, result: @escaping FlutterResult) { let type = ((call.arguments as! [String: Any])["type"]) as? Int; if let id = CommonUtils.getParam(call: call, result: result, param: "id") as? String { let checkInfo = TIMFriendCheckInfo(); if type != nil { checkInfo.checkType = TIMFriendCheckType(rawValue: type!)!; } checkInfo.users = [id]; TIMFriendshipManager.sharedInstance()?.checkFriends(checkInfo, succ: { (array) -> Void in result(JsonUtil.toJson(FriendCheckResultEntity(result: (array!)[0]))); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 获得未决好友列表(申请中) * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getPendencyList(call: FlutterMethodCall, result: @escaping FlutterResult) { let seq = ((call.arguments as! [String: Any])["seq"]) as? UInt64; let timestamp = ((call.arguments as! [String: Any])["timestamp"]) as? UInt64; let numPerPage = ((call.arguments as! [String: Any])["numPerPage"]) as? UInt64; if let type = CommonUtils.getParam(call: call, result: result, param: "type") as? Int { let request = TIMFriendPendencyRequest(); request.type = TIMPendencyType(rawValue: type)!; if seq != nil { request.seq = seq!; } if timestamp != nil { request.timestamp = timestamp!; } if numPerPage != nil { request.numPerPage = numPerPage!; } TIMFriendshipManager.sharedInstance()?.getPendencyList(request, succ: { (data) -> Void in if data?.pendencies.count == 0 { result("{}"); return; } // 返回结果 var resultData = [PendencyEntity](); // 用户ID对应用户对象 var map: [String: PendencyEntity] = [:]; // 循环获得的列表,进行对象封装 for item in data!.pendencies { map[item.identifier] = PendencyEntity(item: item); } // 获得用户信息 TIMFriendshipManager.sharedInstance()?.getUsersProfile(Array(map.keys), forceUpdate: true, succ: { (array) -> Void in // 填充用户对象 for item in array! { if let data = map[item.identifier] { data.userProfile = UserInfoEntity(userProfile: item); resultData.append(data); } } // 返回结果 result(JsonUtil.toJson(PendencyPageEntity(res: data!, items: resultData))); }, fail: TencentImUtils.returnErrorClosures(result: result)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 未决已读上报 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func pendencyReport(call: FlutterMethodCall, result: @escaping FlutterResult) { if let timestamp = CommonUtils.getParam(call: call, result: result, param: "timestamp") as? UInt64 { TIMFriendshipManager.sharedInstance()?.pendencyReport(timestamp, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 未决删除 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deletePendency(call: FlutterMethodCall, result: @escaping FlutterResult) { if let type = CommonUtils.getParam(call: call, result: result, param: "type") as? Int, let id = CommonUtils.getParam(call: call, result: result, param: "id") as? String { TIMFriendshipManager.sharedInstance()?.delete(TIMPendencyType(rawValue: type)!, users: [id], succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 未决审核 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func examinePendency(call: FlutterMethodCall, result: @escaping FlutterResult) { let remark = ((call.arguments as! [String: Any])["remark"]) as? String; if let type = CommonUtils.getParam(call: call, result: result, param: "type") as? Int, let id = CommonUtils.getParam(call: call, result: result, param: "id") as? String { let response = TIMFriendResponse(); if remark != nil { response.remark = remark!; } response.responseType = TIMFriendResponseType(rawValue: type)!; response.identifier = id; TIMFriendshipManager.sharedInstance()?.do(response, succ: { (data) -> Void in result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 删除会话 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deleteConversation(call: FlutterMethodCall, result: @escaping FlutterResult) { if let sessionId = CommonUtils.getParam(call: call, result: result, param: "sessionId") as? String, let sessionTypeStr = CommonUtils.getParam(call: call, result: result, param: "sessionType") as? String, let removeCache = CommonUtils.getParam(call: call, result: result, param: "removeCache") as? Bool { if removeCache { TIMManager.sharedInstance()?.deleteConversationAndMessages(TIMConversationType(rawValue: SessionType.getEnumByName(name: sessionTypeStr)!.rawValue)!, receiver: sessionId); } else { TIMManager.sharedInstance()?.delete(TIMConversationType(rawValue: SessionType.getEnumByName(name: sessionTypeStr)!.rawValue)!, receiver: sessionId); } result(nil); } } /** * 删除会话内的本地聊天记录 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deleteLocalMessage(call: FlutterMethodCall, result: @escaping FlutterResult) { if let sessionId = CommonUtils.getParam(call: call, result: result, param: "sessionId") as? String, let sessionTypeStr = CommonUtils.getParam(call: call, result: result, param: "sessionType") as? String { TIMManager.sharedInstance()?.deleteConversationAndMessages(TIMConversationType(rawValue: SessionType.getEnumByName(name: sessionTypeStr)!.rawValue)!, receiver: sessionId); result(nil); } } /** * 创建群组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func createGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { let groupId = ((call.arguments as! [String: Any])["groupId"]) as? String; let notification = ((call.arguments as! [String: Any])["notification"]) as? String; let introduction = ((call.arguments as! [String: Any])["introduction"]) as? String; let faceUrl = ((call.arguments as! [String: Any])["faceUrl"]) as? String; let addOption = ((call.arguments as! [String: Any])["addOption"]) as? String; let maxMemberNum = ((call.arguments as! [String: Any])["maxMemberNum"]) as? UInt32; let members = ((call.arguments as! [String: Any])["members"]) as? String; if let type = CommonUtils.getParam(call: call, result: result, param: "type") as? String, let name = CommonUtils.getParam(call: call, result: result, param: "name") as? String { // 封装群对象 let groupInfo = TIMCreateGroupInfo(); if groupId != nil { groupInfo.group = groupId!; } if notification != nil { groupInfo.notification = notification!; } if introduction != nil { groupInfo.introduction = introduction!; } if faceUrl != nil { groupInfo.faceURL = faceUrl!; } if addOption != nil { groupInfo.addOpt = TIMGroupAddOpt(rawValue: GroupAddOptType.getEnumByName(name: addOption!)!.rawValue)!; } if maxMemberNum != nil { groupInfo.maxMemberNum = maxMemberNum!; } if members != nil { var memberInfo: [TIMCreateGroupMemberInfo] = []; if let ms = [GroupMemberEntity].deserialize(from: members) { for item in ms { memberInfo.append(item!.toTIMCreateGroupMemberInfo()); } } groupInfo.membersInfo = memberInfo; } groupInfo.groupType = type; groupInfo.groupName = name; // 创建群 TIMGroupManager.sharedInstance()?.createGroup(groupInfo, succ: { (id) -> Void in result(id); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 邀请加入群组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func inviteGroupMember(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String, let ids = CommonUtils.getParam(call: call, result: result, param: "ids") as? String { TIMGroupManager.sharedInstance()?.inviteGroupMember(groupId, members: ids.components(separatedBy: ","), succ: { (array) -> Void in var resultData: [GroupMemberResult] = []; for item in array! { resultData.append(GroupMemberResult(result: item as! TIMGroupMemberResult)); } result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 申请加入群组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func applyJoinGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String, let reason = CommonUtils.getParam(call: call, result: result, param: "ids") as? String { TIMGroupManager.sharedInstance()?.joinGroup(groupId, msg: reason, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 退出群组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func quitGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String { TIMGroupManager.sharedInstance()?.quitGroup(groupId, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 删除群组成员 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deleteGroupMember(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String, let reason = CommonUtils.getParam(call: call, result: result, param: "reason") as? String, let ids = CommonUtils.getParam(call: call, result: result, param: "ids") as? String { TIMGroupManager.sharedInstance()?.deleteGroupMember(withReason: groupId, reason: reason, members: ids.components(separatedBy: ","), succ: { (array) -> Void in var resultData: [GroupMemberResult] = []; for item in array! { resultData.append(GroupMemberResult(result: item as! TIMGroupMemberResult)); } result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 获取群成员列表 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getGroupMembers(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String { TIMGroupManager.sharedInstance()?.getGroupMembers(groupId, succ: { (array) -> Void in var userInfo: [String: GroupMemberEntity] = [:]; for item in array! { let member = item as! TIMGroupMemberInfo; let item = GroupMemberEntity(info: member); userInfo[member.member] = item; } // 获得用户信息 TIMFriendshipManager.sharedInstance()?.getUsersProfile(Array(userInfo.keys), forceUpdate: true, succ: { (array) -> Void in var resultData: [GroupMemberEntity] = []; // 填充用户对象 for item in array! { if let data = userInfo[item.identifier] { data.userProfile = UserInfoEntity(userProfile: item); resultData.append(data); } } // 返回结果 result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 解散群组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deleteGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String { TIMGroupManager.sharedInstance()?.deleteGroup(groupId, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 转让群组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func modifyGroupOwner(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String, let identifier = CommonUtils.getParam(call: call, result: result, param: "identifier") as? String { TIMGroupManager.sharedInstance()?.modifyGroupOwner(groupId, user: identifier, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 修改群资料 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func modifyGroupInfo(call: FlutterMethodCall, result: @escaping FlutterResult) { let notification = ((call.arguments as! [String: Any])["notification"]) as? String; let introduction = ((call.arguments as! [String: Any])["introduction"]) as? String; let faceUrl = ((call.arguments as! [String: Any])["faceUrl"]) as? String; let addOption = ((call.arguments as! [String: Any])["addOption"]) as? String; let groupName = ((call.arguments as! [String: Any])["groupName"]) as? String; let visable = ((call.arguments as! [String: Any])["visable"]) as? Bool; let silenceAll = ((call.arguments as! [String: Any])["silenceAll"]) as? Bool; let customInfo = ((call.arguments as! [String: Any])["customInfo"]) as? String; if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String { if silenceAll != nil { TIMGroupManager.sharedInstance()?.modifyGroupAllShutup(groupId, shutup: silenceAll!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if visable != nil { TIMGroupManager.sharedInstance()?.modifyGroupSearchable(groupId, searchable: visable!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } if groupName != nil { TIMGroupManager.sharedInstance()?.modifyGroupName(groupId, groupName: groupName!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if addOption != nil { TIMGroupManager.sharedInstance()?.modifyGroupAddOpt(groupId, opt: TIMGroupAddOpt(rawValue: GroupAddOptType.getEnumByName(name: addOption!)!.hashValue)!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if faceUrl != nil { TIMGroupManager.sharedInstance()?.modifyGroupFaceUrl(groupId, url: faceUrl!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if introduction != nil { TIMGroupManager.sharedInstance()?.modifyGroupIntroduction(groupId, introduction: introduction!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if notification != nil { TIMGroupManager.sharedInstance()?.modifyGroupNotification(groupId, notification: notification!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if customInfo != nil { let ci = JsonUtil.getDictionaryFromJSONString(jsonString: customInfo!); var customInfoData: [String: Data] = [:]; for (key, value) in ci { customInfoData[key] = "\(value)".data(using: String.Encoding.utf8); } TIMGroupManager.sharedInstance()?.modifyGroupCustomInfo(groupId, customInfo: customInfoData, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } } /** * 修改群成员资料 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func modifyMemberInfo(call: FlutterMethodCall, result: @escaping FlutterResult) { let nameCard = ((call.arguments as! [String: Any])["nameCard"]) as? String; let silence = ((call.arguments as! [String: Any])["silence"]) as? UInt32; let role = ((call.arguments as! [String: Any])["role"]) as? Int; let customInfo = ((call.arguments as! [String: Any])["customInfo"]) as? String; if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String, let identifier = CommonUtils.getParam(call: call, result: result, param: "identifier") as? String { if nameCard != nil { TIMGroupManager.sharedInstance()?.modifyGroupMemberInfoSetNameCard(groupId, user: identifier, nameCard: nameCard!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if silence != nil { TIMGroupManager.sharedInstance()?.modifyGroupMemberInfoSetSilence(groupId, user: identifier, stime: silence!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if role != nil { TIMGroupManager.sharedInstance()?.modifyGroupMemberInfoSetRole(groupId, user: identifier, role: TIMGroupMemberRole(rawValue: role!)!, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } if customInfo != nil { let ci = JsonUtil.getDictionaryFromJSONString(jsonString: customInfo!); var customInfoData: [String: Data] = [:]; for (key, value) in ci { customInfoData[key] = "\(value)".data(using: String.Encoding.utf8); } TIMGroupManager.sharedInstance()?.modifyGroupMemberInfoSetCustomInfo(groupId, user: identifier, customInfo: customInfoData, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } } /** * 获得未决群列表 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getGroupPendencyList(call: FlutterMethodCall, result: @escaping FlutterResult) { let timestamp = ((call.arguments as! [String: Any])["timestamp"]) as? UInt64; let numPerPage = ((call.arguments as! [String: Any])["numPerPage"]) as? UInt32; let option = TIMGroupPendencyOption(); if timestamp != nil { option.timestamp = timestamp!; } if numPerPage != nil { option.numPerPage = numPerPage!; } TIMGroupManager.sharedInstance()?.getPendencyFromServer(option, succ: { (meta, array) -> Void in // 如果没有数据就直接返回 if array?.count == 0 { result("[]"); return; } // 存储ID的集合 var groupIds = Set<String>(); var userIds = Set<String>(); var resultData: [GroupPendencyEntity] = []; for item in array! { resultData.append(GroupPendencyEntity(item: item)); groupIds.insert(item.groupId); userIds.insert(item.selfIdentifier); userIds.insert(item.toUser); } // 当前步骤 和 最大步骤 var current = 0; let maxIndex = (groupIds.count > 1 ? 1 : 0) + (userIds.count > 1 ? 1 : 0); // 获得群信息 if groupIds.count >= 1 { TIMGroupManager.sharedInstance()?.getGroupInfo(Array(groupIds), succ: { (array) -> Void in // 循环赋值 for resultDatum in resultData { for item in array! { let group = item as! TIMGroupInfoResult; if group.group == resultDatum.groupId { resultDatum.groupInfo = GroupInfoEntity(groupInfo: group); } } } current += 1; if (current >= maxIndex) { result(JsonUtil.toJson(GroupPendencyPageEntiity(meta: meta!, list: resultData))) } }, fail: TencentImUtils.returnErrorClosures(result: result)); } if userIds.count >= 1 { TIMFriendshipManager.sharedInstance()?.getUsersProfile((Array(userIds)), forceUpdate: true, succ: { (array) -> Void in // 循环赋值 for resultDatum in resultData { for item in array! { let userInfo = item; if userInfo.identifier == resultDatum.identifier { resultDatum.applyUserInfo = UserInfoEntity(userProfile: item); } if userInfo.identifier == resultDatum.toUser { resultDatum.handlerUserInfo = UserInfoEntity(userProfile: item); } } } current += 1; if (current >= maxIndex) { result(JsonUtil.toJson(GroupPendencyPageEntiity(meta: meta!, list: resultData))) } }, fail: TencentImUtils.returnErrorClosures(result: result)) } }, fail: TencentImUtils.returnErrorClosures(result: result)) } /** * 上报未决已读 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func reportGroupPendency(call: FlutterMethodCall, result: @escaping FlutterResult) { if let timestamp = ((call.arguments as! [String: Any])["timestamp"]) as? UInt64 { TIMGroupManager.sharedInstance()?.pendencyReport(timestamp, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 同意申请 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func groupPendencyAccept(call: FlutterMethodCall, result: @escaping FlutterResult) { let msg = ((call.arguments as! [String: Any])["msg"]) as? String; if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String, let identifier = CommonUtils.getParam(call: call, result: result, param: "identifier") as? String, let addTime = CommonUtils.getParam(call: call, result: result, param: "addTime") as? UInt64 { TIMGroupManager.sharedInstance()?.getPendencyFromServer(TIMGroupPendencyOption(), succ: { (_, array) -> Void in for item in array! { if item.groupId == groupId && item.selfIdentifier == identifier && item.addTime == addTime { item.accept(msg, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 拒绝申请 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func groupPendencyRefuse(call: FlutterMethodCall, result: @escaping FlutterResult) { let msg = ((call.arguments as! [String: Any])["msg"]) as? String; if let groupId = CommonUtils.getParam(call: call, result: result, param: "groupId") as? String, let identifier = CommonUtils.getParam(call: call, result: result, param: "identifier") as? String, let addTime = CommonUtils.getParam(call: call, result: result, param: "addTime") as? UInt64 { TIMGroupManager.sharedInstance()?.getPendencyFromServer(TIMGroupPendencyOption(), succ: { (_, array) -> Void in for item in array! { if item.groupId == groupId && item.selfIdentifier == identifier && item.addTime == addTime { item.refuse(msg, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 获取自己的资料 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getSelfProfile(call: FlutterMethodCall, result: @escaping FlutterResult) { // 强制走后台拉取 let forceUpdate = ((call.arguments as! [String: Any])["forceUpdate"]) as? Bool; if forceUpdate != nil && forceUpdate! { TIMFriendshipManager.sharedInstance()?.getSelfProfile({ (data) -> Void in result(JsonUtil.toJson(UserInfoEntity(userProfile: data!))); }, fail: TencentImUtils.returnErrorClosures(result: result)) } else { if let data = TIMFriendshipManager.sharedInstance()?.querySelfProfile() { result(JsonUtil.toJson(UserInfoEntity(userProfile: data))); } else { TIMFriendshipManager.sharedInstance()?.getSelfProfile({ (data) -> Void in result(JsonUtil.toJson(UserInfoEntity(userProfile: data!))); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } } /** * 修改自己的资料 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func modifySelfProfile(call: FlutterMethodCall, result: @escaping FlutterResult) { if let params = CommonUtils.getParam(call: call, result: result, param: "params") as? String { TIMFriendshipManager.sharedInstance()?.modifySelfProfile(JsonUtil.getDictionaryFromJSONString(jsonString: params), succ: { () -> Void in result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 修改好友的资料 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func modifyFriend(call: FlutterMethodCall, result: @escaping FlutterResult) { if let identifier = CommonUtils.getParam(call: call, result: result, param: "identifier") as? String, let params = CommonUtils.getParam(call: call, result: result, param: "params") as? String { TIMFriendshipManager.sharedInstance()?.modifyFriend(identifier, values: JsonUtil.getDictionaryFromJSONString(jsonString: params), succ: { () -> Void in result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 删除好友 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deleteFriends(call: FlutterMethodCall, result: @escaping FlutterResult) { if let ids = CommonUtils.getParam(call: call, result: result, param: "ids") as? String, let delFriendType = CommonUtils.getParam(call: call, result: result, param: "delFriendType") as? Int { TIMFriendshipManager.sharedInstance()?.deleteFriends(ids.components(separatedBy: ","), delType: TIMDelFriendType(rawValue: delFriendType)!, succ: { (array) -> Void in var resultData: [FriendResultEntity] = []; // 填充对象 for item in array! { resultData.append(FriendResultEntity(result: item)); } // 返回结果 result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 添加到黑名单 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func addBlackList(call: FlutterMethodCall, result: @escaping FlutterResult) { if let ids = CommonUtils.getParam(call: call, result: result, param: "ids") as? String { TIMFriendshipManager.sharedInstance()?.addBlackList(ids.components(separatedBy: ","), succ: { (array) -> Void in var resultData: [FriendResultEntity] = []; // 填充对象 for item in array! { resultData.append(FriendResultEntity(result: item)); } // 返回结果 result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 从黑名单删除 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deleteBlackList(call: FlutterMethodCall, result: @escaping FlutterResult) { if let ids = CommonUtils.getParam(call: call, result: result, param: "ids") as? String { TIMFriendshipManager.sharedInstance()?.deleteBlackList(ids.components(separatedBy: ","), succ: { (array) -> Void in var resultData: [FriendResultEntity] = []; // 填充对象 for item in array! { resultData.append(FriendResultEntity(result: item)); } // 返回结果 result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } } /** * 获得黑名单列表 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getBlackList(call: FlutterMethodCall, result: @escaping FlutterResult) { TIMFriendshipManager.sharedInstance()?.getBlackList({ (array) -> Void in var resultData: [FriendEntity] = [] for item in array! { resultData.append(FriendEntity(friend: item)); } result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)) } /** * 创建好友分组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func createFriendGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupNames = CommonUtils.getParam(call: call, result: result, param: "groupNames") as? String, let ids = CommonUtils.getParam(call: call, result: result, param: "ids") as? String { TIMFriendshipManager.sharedInstance()?.createFriendGroup(groupNames.components(separatedBy: ","), users: ids.components(separatedBy: ","), succ: { (array) -> Void in var resultData: [FriendResultEntity] = []; // 填充对象 for item in array! { resultData.append(FriendResultEntity(result: item)); } // 返回结果 result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 删除好友分组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deleteFriendGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupNames = CommonUtils.getParam(call: call, result: result, param: "groupNames") as? String { TIMFriendshipManager.sharedInstance()?.deleteFriendGroup(groupNames.components(separatedBy: ","), succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 添加好友到某个分组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func addFriendsToFriendGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupName = CommonUtils.getParam(call: call, result: result, param: "groupName") as? String, let ids = CommonUtils.getParam(call: call, result: result, param: "ids") as? String { TIMFriendshipManager.sharedInstance()?.addFriends(toFriendGroup: groupName, users: ids.components(separatedBy: ","), succ: { (array) -> Void in var resultData: [FriendResultEntity] = []; // 填充对象 for item in array! { resultData.append(FriendResultEntity(result: item)); } // 返回结果 result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 从分组删除好友 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func deleteFriendsFromFriendGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { if let groupName = CommonUtils.getParam(call: call, result: result, param: "groupName") as? String, let ids = CommonUtils.getParam(call: call, result: result, param: "ids") as? String { TIMFriendshipManager.sharedInstance()?.deleteFriends(fromFriendGroup: groupName, users: ids.components(separatedBy: ","), succ: { (array) -> Void in var resultData: [FriendResultEntity] = []; // 填充对象 for item in array! { resultData.append(FriendResultEntity(result: item)); } // 返回结果 result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 重命名分组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func renameFriendGroup(call: FlutterMethodCall, result: @escaping FlutterResult) { if let oldGroupName = CommonUtils.getParam(call: call, result: result, param: "oldGroupName") as? String, let newGroupName = CommonUtils.getParam(call: call, result: result, param: "newGroupName") as? String { TIMFriendshipManager.sharedInstance()?.renameFriendGroup(oldGroupName, newName: newGroupName, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 获得好友分组 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func getFriendGroups(call: FlutterMethodCall, result: @escaping FlutterResult) { // 组名 let groupNames = ((call.arguments as! [String: Any])["groupNames"]) as? String; var groups: [String] = []; if groupNames != nil { groups = groupNames!.components(separatedBy: ","); } TIMFriendshipManager.sharedInstance()?.getFriendGroups(groups, succ: { (array) -> Void in var resultData: [FriendGroupEntity] = []; // 填充对象 for item in array! { resultData.append(FriendGroupEntity(group: item)); } // 返回结果 result(JsonUtil.toJson(resultData)); }, fail: TencentImUtils.returnErrorClosures(result: result)); } /** * 消息撤回 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func revokeMessage(call: FlutterMethodCall, result: @escaping FlutterResult) { TencentImUtils.getTimMessage(call: call, result: result, onCallback: { (message) -> Void in message!.getConversation()!.revokeMessage(message, succ: { result(nil); // 一对一才发送撤回通知(群聊会自动进入撤回监听器) if message?.getConversation()!.getType() == TIMConversationType.C2C { self.invokeListener(type: ListenerType.MessageRevoked, params: MessageLocatorEntity(locator: message!.locator())); } }, fail: TencentImUtils.returnErrorClosures(result: result)); }); } /** * 消息删除 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func removeMessage(call: FlutterMethodCall, result: @escaping FlutterResult) { TencentImUtils.getTimMessage(call: call, result: result, onCallback: { (message) -> Void in result(message!.remove()); }); } /** * 设置消息自定义整型 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func setMessageCustomInt(call: FlutterMethodCall, result: @escaping FlutterResult) { if let value = CommonUtils.getParam(call: call, result: result, param: "value") as? Int32 { TencentImUtils.getTimMessage(call: call, result: result, onCallback: { (message) -> Void in message!.setCustomInt(value); result(nil); }); } } /** * 设置消息自定义字符串 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func setMessageCustomStr(call: FlutterMethodCall, result: @escaping FlutterResult) { if let value = CommonUtils.getParam(call: call, result: result, param: "value") as? String { TencentImUtils.getTimMessage(call: call, result: result, onCallback: { (message) -> Void in message!.setCustomData(value.data(using: String.Encoding.utf8)); result(nil); }); } } /** * 下载视频图片 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func downloadVideoImage(call: FlutterMethodCall, result: @escaping FlutterResult) { let path = ((call.arguments as! [String: Any])["path"]) as? String; if path != nil && FileManager.default.fileExists(atPath: path!) { result(path); return; } TencentImUtils.getTimMessage(call: call, result: result, onCallback: { (message) -> Void in let elem: TIMElem = message!.getElem(0); if elem is TIMVideoElem { let videoElem: TIMVideoElem = elem as! TIMVideoElem; var finalPath: String? = path; if finalPath == nil || finalPath! == "" { finalPath = NSTemporaryDirectory() + "/" + videoElem.snapshot.uuid; } // 如果文件存在则不进行下载 if (FileManager.default.fileExists(atPath: finalPath!)) { result(finalPath); return; } TencentImUtils.getMessageInfo(timMessages: [message!], onSuccess: { (array) -> Void in videoElem.snapshot!.getImage(finalPath!, progress: { (current, total) -> Void in self.invokeListener(type: ListenerType.DownloadProgress, params: [ "message": array[0], "path": finalPath!, "currentSize": current, "totalSize": total ]); }, succ: { () -> Void in result(finalPath!); }, fail: TencentImUtils.returnErrorClosures(result: result)) }, onFail: TencentImUtils.returnErrorClosures(result: result)); } }); } /** * 下载视频 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func downloadVideo(call: FlutterMethodCall, result: @escaping FlutterResult) { let path = ((call.arguments as! [String: Any])["path"]) as? String; if path != nil && FileManager.default.fileExists(atPath: path!) { result(path!); return; } TencentImUtils.getTimMessage(call: call, result: result, onCallback: { (message) -> Void in let elem: TIMElem = message!.getElem(0); if elem is TIMVideoElem { let videoElem: TIMVideoElem = elem as! TIMVideoElem; var finalPath: String? = path; if finalPath == nil || finalPath! == "" { finalPath = NSTemporaryDirectory() + "/" + videoElem.video.uuid; } // 如果文件存在则不进行下载 if (FileManager.default.fileExists(atPath: finalPath!)) { result(finalPath!); return; } TencentImUtils.getMessageInfo(timMessages: [message!], onSuccess: { (array) -> Void in videoElem.video!.getVideo(finalPath!, progress: { (current, total) -> Void in self.invokeListener(type: ListenerType.DownloadProgress, params: [ "message": array[0], "path": finalPath!, "currentSize": current, "totalSize": total ]); }, succ: { () -> Void in result(finalPath!); }, fail: TencentImUtils.returnErrorClosures(result: result)) }, onFail: TencentImUtils.returnErrorClosures(result: result)); } }); } /** * 下载语音 * * @param methodCall 方法调用对象 * @param result 返回结果对象 */ private func downloadSound(call: FlutterMethodCall, result: @escaping FlutterResult) { let path = ((call.arguments as! [String: Any])["path"]) as? String; if path != nil && FileManager.default.fileExists(atPath: path!) { result(path!); return; } TencentImUtils.getTimMessage(call: call, result: result, onCallback: { (message) -> Void in let elem: TIMElem = message!.getElem(0); if elem is TIMSoundElem { let soundElem: TIMSoundElem = elem as! TIMSoundElem; var finalPath: String? = path; if finalPath == nil || finalPath! == "" { finalPath = NSTemporaryDirectory() + "/" + soundElem.uuid; } // 如果文件存在则不进行下载 if (FileManager.default.fileExists(atPath: finalPath!)) { result(finalPath!); return; } TencentImUtils.getMessageInfo(timMessages: [message!], onSuccess: { (array) -> Void in soundElem.getSound(finalPath!, progress: { (current, total) -> Void in self.invokeListener(type: ListenerType.DownloadProgress, params: [ "message": array[0], "path": finalPath!, "currentSize": current, "totalSize": total ]); }, succ: { () -> Void in result(finalPath!); }, fail: TencentImUtils.returnErrorClosures(result: result)) }, onFail: TencentImUtils.returnErrorClosures(result: result)); } }); } /** * 查找一条消息 */ private func findMessage(call: FlutterMethodCall, result: @escaping FlutterResult) { TencentImUtils.getTimMessage(call: call, result: result, onCallback: { (message) -> Void in TencentImUtils.getMessageInfo(timMessages: [message!], onSuccess: { (array) -> Void in result(JsonUtil.toJson(array[0] as! MessageEntity)); }, onFail: TencentImUtils.returnErrorClosures(result: result)); }); } /** * 设置离线推送配置 */ private func setOfflinePushSettings(call: FlutterMethodCall, result: @escaping FlutterResult) { let enabled = ((call.arguments as! [String: Any])["enabled"]) as? Bool; let c2cSound = ((call.arguments as! [String: Any])["c2cSound"]) as? String; let groupSound = ((call.arguments as! [String: Any])["groupSound"]) as? String; let videoSound = ((call.arguments as! [String: Any])["videoSound"]) as? String; let config = TIMAPNSConfig(); if enabled != nil { config.openPush = enabled! == true ? 1 : 2; } if c2cSound != nil { config.c2cSound = c2cSound!; } if groupSound != nil { config.groupSound = groupSound!; } if videoSound != nil { config.videoSound = videoSound!; } TIMManager.sharedInstance().setAPNS(config, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } /** * 设置离线推送Token */ private func setOfflinePushToken(call: FlutterMethodCall, result: @escaping FlutterResult) { if let token = CommonUtils.getParam(call: call, result: result, param: "token") as? String, let bussid = CommonUtils.getParam(call: call, result: result, param: "bussid") as? UInt32 { let config = TIMTokenParam(); config.token = token.data(using: String.Encoding.utf8); config.busiId = bussid; TIMManager.sharedInstance().setToken(config, succ: { result(nil); }, fail: TencentImUtils.returnErrorClosures(result: result)) } } /** * 调用监听器 * * @param type 类型 * @param params 参数 */ private func invokeListener(type: ListenerType, params: Any?) { var resultParams: [String: Any] = [:]; resultParams["type"] = type; if let p = params { resultParams["params"] = JsonUtil.toJson(p); } SwiftTencentImPlugin.channel!.invokeMethod(SwiftTencentImPlugin.LISTENER_FUNC_NAME, arguments: JsonUtil.toJson(resultParams)); } /** * 踢下线通知 */ public func onForceOffline() { self.invokeListener(type: ListenerType.ForceOffline, params: nil); } /** * 断线重连失败【IOS独享】 */ public func onReConnFailed(_ code: Int32, err: String!) { self.invokeListener(type: ListenerType.Disconnected, params: ["code": code, "msg": err as Any]); } /** * 用户登录的 userSig 过期(用户需要重新获取 userSig 后登录) */ public func onUserSigExpired() { self.invokeListener(type: ListenerType.UserSigExpired, params: nil); } /** * 网络连接成功 */ public func onConnSucc() { self.invokeListener(type: ListenerType.Connected, params: nil); } /** * 网络连接失败【IOS独享】 */ public func onConnFailed(_ code: Int32, err: String!) { self.invokeListener(type: ListenerType.ConnFailed, params: ["code": code, "msg": err as Any]); } /** * 网络连接断开(断线只是通知用户,不需要重新登录,重连以后会自动上线) */ public func onDisconnect(_ code: Int32, err: String!) { self.invokeListener(type: ListenerType.Disconnected, params: ["code": code, "msg": err as Any]); } /** * 连接中【IOS独享】 */ public func onConnecting() { self.invokeListener(type: ListenerType.Connecting, params: nil); } /** * 群Tips回调 */ public func onGroupTipsEvent(_ elem: TIMGroupTipsElem!) { self.invokeListener(type: ListenerType.GroupTips, params: GroupTipsMessageEntity(elem: elem)); } /** * 刷新会话 */ public func onRefresh() { self.invokeListener(type: ListenerType.Refresh, params: nil); } /** * 刷新部分会话 */ public func onRefreshConversations(_ conversations: [TIMConversation]!) { // 获取资料后调用回调 TencentImUtils.getConversationInfo(conversations: conversations, onSuccess: { (array) -> Void in self.invokeListener(type: ListenerType.RefreshConversation, params: array); }, onFail: { _, _ in }); } /** * 消息撤回通知 */ public func onRevokeMessage(_ locator: TIMMessageLocator!) { self.invokeListener(type: ListenerType.MessageRevoked, params: MessageLocatorEntity(locator: locator)); } /** * 收到了已读回执 */ public func onRecvMessageReceipts(_ receipts: [Any]!) { var rs: [String] = []; for item in receipts { rs.append((item as! TIMMessageReceipt).conversation.getReceiver()); } self.invokeListener(type: ListenerType.RecvReceipt, params: rs); } /** * 新消息回调通知 */ public func onNewMessage(_ msgs: [Any]!) { TencentImUtils.getMessageInfo(timMessages: msgs as! [TIMMessage], onSuccess: { (array) -> Void in self.invokeListener(type: ListenerType.NewMessages, params: array); }, onFail: { _, _ in }) } /** * 上传进度改变回调 */ public func onUploadProgressCallback(_ msg: TIMMessage!, elemidx: UInt32, taskid: UInt32, progress: UInt32) { TencentImUtils.getMessageInfo(timMessages: [msg] as! [TIMMessage], onSuccess: { (array) -> Void in self.invokeListener(type: ListenerType.UploadProgress, params: [ "message": array[0], "elemId": elemidx, "taskId": taskid, "progress": progress ]); }, onFail: { _, _ in }) } }
39.732342
273
0.563877
1a73d8b5213214d979bfebe1973e0c23562d23a9
3,378
import Foundation import SwiftProtobuf import NIO import NIOHTTP1 /// Abstract base class exposing a method that exposes a promise for the RPC response. /// /// - When `responsePromise` is fulfilled, the call is closed and the provided response transmitted with status `responseStatus` (`.ok` by default). /// - If `statusPromise` is failed and the error is of type `GRPCStatus`, that error will be returned to the client. /// - For other errors, `GRPCStatus.processingError` is returned to the client. /// /// For unary calls, the response is not actually provided by fulfilling `responsePromise`, but instead by completing /// the future returned by `UnaryCallHandler.EventObserver`. open class UnaryResponseCallContext<ResponseMessage: Message>: ServerCallContextBase, StatusOnlyCallContext { public typealias WrappedResponse = GRPCServerResponsePart<ResponseMessage> public let responsePromise: EventLoopPromise<ResponseMessage> public var responseStatus: GRPCStatus = .ok public override init(eventLoop: EventLoop, request: HTTPRequestHead) { self.responsePromise = eventLoop.newPromise() super.init(eventLoop: eventLoop, request: request) } } /// Protocol variant of `UnaryResponseCallContext` that only exposes the `responseStatus` field, but not /// `responsePromise`. /// /// Motivation: `UnaryCallHandler` already asks the call handler return an `EventLoopFuture<ResponseMessage>` which /// is automatically cascaded into `UnaryResponseCallContext.responsePromise`, so that promise does not (and should not) /// be fulfilled by the user. /// /// We can use a protocol (instead of an abstract base class) here because removing the generic `responsePromise` field /// lets us avoid associated-type requirements on the protocol. public protocol StatusOnlyCallContext: ServerCallContext { var responseStatus: GRPCStatus { get set } } /// Concrete implementation of `UnaryResponseCallContext` used by our generated code. open class UnaryResponseCallContextImpl<ResponseMessage: Message>: UnaryResponseCallContext<ResponseMessage> { public let channel: Channel public init(channel: Channel, request: HTTPRequestHead) { self.channel = channel super.init(eventLoop: channel.eventLoop, request: request) responsePromise.futureResult .map { responseMessage in // Send the response provided to the promise. //! FIXME: It would be nicer to chain sending the status onto a successful write, but for some reason the // "write message" future doesn't seem to get fulfilled? self.channel.writeAndFlush(NIOAny(WrappedResponse.message(responseMessage)), promise: nil) return self.responseStatus } // Ensure that any error provided is of type `GRPCStatus`, using "internal server error" as a fallback. .mapIfError { error in (error as? GRPCStatus) ?? .processingError } // Finish the call by returning the final status. .whenSuccess { status in self.channel.writeAndFlush(NIOAny(WrappedResponse.status(status)), promise: nil) } } } /// Concrete implementation of `UnaryResponseCallContext` used for testing. /// /// Only provided to make it clear in tests that no "real" implementation is used. open class UnaryResponseCallContextTestStub<ResponseMessage: Message>: UnaryResponseCallContext<ResponseMessage> { }
46.916667
148
0.753404
87e117030ba0ed71c130b043a4c8ec7edae89418
232
import Foundation public final class SessionManager: Session { public static let shared: SessionManager = { return SessionManager() }() public var accessToken: String { return Config.accessKey } }
17.846154
48
0.668103
de6cb2afd10220b4f3ef7a7e47c0663f7b3c7a44
12,656
// // KRETaskWidgetView.swift // KoreBotSDK // // Created by Srinivas Vasadi on 13/03/19. // Copyright © 2019 Srinivas Vasadi. All rights reserved. // import UIKit public enum KRETemplateType: Int { case none = 0, calendarEvent = 1, fileSearch = 2, taskList = 3, button = 4, announcement = 5, knowledge = 6, hashTag = 7, skill = 8, customWidget = 9, customWidgetCircle = 10, loginWidget = 11 } public enum WidgetId: String { case upcomingTasksWidgetId = "upcomingTasks" case overdueTasksWidgetId = "overdueTasks" case files = "cloudFiles" case upcomingMeetings = "upcomingMeetings" case article = "Article" case announcement = "Announcement" } // MARK: - KRETaskWidgetView public class KRETaskWidgetView: KREWidgetView { // MARK: - properites public lazy var stackView: KREStackView = { let stackView = KREStackView(frame: .zero) stackView.axis = .vertical stackView.separatorColor = .paleLilacFour stackView.translatesAutoresizingMaskIntoConstraints = false stackView.automaticallyHidesLastSeparator = true return stackView }() public var updateSubviews:(() -> Void)? var elements: [KRETaskListItem]? public weak var widgetViewDelegate: KREWidgetViewDelegate? public var actionHandler:((KREAction) -> Void)? lazy var titleStrikeThroughAttributes: [NSAttributedString.Key: Any] = { return [.font: UIFont.textFont(ofSize: 14.0, weight: .bold), .foregroundColor: UIColor.blueyGrey] }() lazy var taskTitleAttributes: [NSAttributedString.Key: Any] = { return [.font: UIFont.textFont(ofSize: 14.0, weight: .bold), .foregroundColor: UIColor.gunmetal] }() // MARK: - init override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { addSubview(stackView) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options:[], metrics: nil, views: ["stackView": stackView])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options:[], metrics: nil, views: ["stackView": stackView])) } func populateWidget() { stackView.removeAllRows() switch widget?.widgetState { case .loading?: let cell = KRECustomWidgetView(frame: .zero) cell.translatesAutoresizingMaskIntoConstraints = false cell.loadingDataState() stackView.addRow(cell) case .loaded?, .refreshed?, .refreshing?: let numberOfRows = min(MAX_ELEMENTS + 1, elements?.count ?? 1) for index in 0..<numberOfRows { switch index { case 0..<MAX_ELEMENTS: let element = elements?[index] let listItemView = KRETaskListItemView(frame: .zero) listItemView.translatesAutoresizingMaskIntoConstraints = false if let taskListItem = element as? KRETaskListItem { configureTaskListItemView(listItemView, taskListItem: taskListItem) listItemView.layoutSubviews() stackView.addRow(listItemView) stackView.setTapHandler(forRow: listItemView) { [weak self] (listItemView) in self?.viewDelegate?.elementAction(for: taskListItem, in: self?.widget) } } default: let buttonView = KREButtonView() buttonView.translatesAutoresizingMaskIntoConstraints = false buttonView.title = NSLocalizedString("View more", comment: "Widgets") stackView.addRow(buttonView) stackView.setTapHandler(forRow: buttonView) { [weak self] (view) in self?.viewDelegate?.viewMoreElements(for: self?.widgetComponent, in: self?.widget) } } } default: break } layoutSubviews() invalidateIntrinsicContentSize() updateSubviews?() } // MARK: - KREWidgetView methods override public var widget: KREWidget? { didSet { populateWidget() } } override public var widgetComponent: KREWidgetComponent? { didSet { if let taskElements = widgetComponent?.elements as? [KRETaskListItem] { elements = taskElements } populateWidget() invalidateIntrinsicContentSize() } } override public func startShimmering() { } override public func stopShimmering() { } override public func prepareForReuse() { super.prepareForReuse() widgetComponent = nil widget = nil populateWidget() layoutIfNeeded() invalidateIntrinsicContentSize() } // MARK: - helpers func compareDates(_ lastSeenDate : Date?, _ updateDate: Date?) -> ComparisonResult { // Compare them guard let updateDate = updateDate else { return .orderedSame } switch lastSeenDate?.compare(updateDate) { case .orderedAscending?: return .orderedAscending case .orderedDescending?: return .orderedDescending case .orderedSame?: return .orderedSame case .none: return .orderedSame } } public func formatAsDateWithTime(using date: NSDate) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE, LLL d', 'h:mm a" dateFormatter.amSymbol = "AM" dateFormatter.pmSymbol = "PM" return dateFormatter.string(from: date as Date) } func convertUTCToDate(_ utcDate: Int64) -> String { let timeInSeconds = Double(truncating: NSNumber(value: utcDate)) / 1000 let dateTime = Date(timeIntervalSince1970: timeInSeconds) let dateStr = formatAsDateWithTime(using: dateTime as NSDate) return dateStr } } // MARK: - extension KRETaskWidgetView { func configureTaskListItemView(_ view: KRETaskListItemView, taskListItem: KRETaskListItem) { var utcDate: Date? view.loadedDataState() if let dueDate = taskListItem.dueDate { view.dateTimeLabel.text = convertUTCToDate(dueDate) utcDate = Date(milliseconds: Int64(truncating: NSNumber(value: dueDate))) } view.itemSelectionHandler = { [weak self] (taskListItemCell) in } view.moreSelectionHandler = { [weak self] (taskListItemCell) in self?.viewDelegate?.elementAction(for: taskListItem, in: self?.widget) } let assigneeMatching = KREWidgetManager.shared.user?.userId == taskListItem.assignee?.id let ownerMatching = KREWidgetManager.shared.user?.userId == taskListItem.owner?.id if assigneeMatching { view.assigneeLabel.text = "You" } else { view.assigneeLabel.text = taskListItem.assignee?.fullName } if ownerMatching { view.ownerLabel.text = "You" } else { view.ownerLabel.text = taskListItem.owner?.fullName } if ownerMatching && assigneeMatching { view.ownerLabel.text = "You" view.assigneeLabel.isHidden = true view.triangle.isHidden = true } else { view.assigneeLabel.isHidden = false view.triangle.isHidden = false } view.selectionView.isHidden = true view.selectionViewWidthConstraint.constant = 0.0 view.selectionViewLeadingConstraint.constant = 0.0 if let status = taskListItem.status, let taskTitle = taskListItem.title { switch status.lowercased() { case "close": let attributeString = NSMutableAttributedString(string: taskTitle, attributes: titleStrikeThroughAttributes) attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attributeString.length)) view.titleLabel.attributedText = attributeString view.ownerLabel.textColor = UIColor.blueyGrey view.assigneeLabel.textColor = UIColor.blueyGrey view.dateTimeLabel.textColor = UIColor.blueyGrey view.selectionView.isSelected = taskListItem.isSelected if taskListItem.isSelected { view.backgroundColor = UIColor(red: 252/255, green: 234/255, blue: 236/255, alpha: 1) } else { view.backgroundColor = UIColor.white } default: view.titleLabel.attributedText = NSAttributedString(string: taskTitle, attributes: taskTitleAttributes) view.ownerLabel.textColor = UIColor.gunmetal view.assigneeLabel.textColor = UIColor.gunmetal let comparasionResult = compareDates(Date(), utcDate) if comparasionResult == .orderedAscending { view.dateTimeLabel.textColor = UIColor.gunmetal } else { view.dateTimeLabel.textColor = UIColor.red } view.selectionView.isSelected = taskListItem.isSelected if taskListItem.isSelected { view.backgroundColor = UIColor(red: 252/255, green: 234/255, blue: 236/255, alpha: 1) } else { view.backgroundColor = UIColor.white } } } } func getInitialsFromNameOne(name1: String, name2: String) -> String { let firstName = name1.first ?? Character(" ") let lastName = name2.first ?? Character(" ") return "\(firstName)\(lastName)".trimmingCharacters(in: .whitespaces) } } // MARK: - KREWidgetHeaderFooterView public class KREWidgetHeaderFooterView: UITableViewHeaderFooterView { // MARK: - properties public lazy var bubbleView: KREWidgetBubbleView = { let bubbleView = KREWidgetBubbleView() bubbleView.translatesAutoresizingMaskIntoConstraints = false return bubbleView }() public lazy var sepratorLine: UIView = { let view = UIView(frame: .zero) view.isHidden = true view.translatesAutoresizingMaskIntoConstraints = false return view }() // MARK: - override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override func prepareForReuse() { super.prepareForReuse() bubbleView.prepareForReuse() } // MARK: - func setup() { contentView.addSubview(bubbleView) contentView.addSubview(sepratorLine) let bubbleViews: [String: UIView] = ["bubbleView": bubbleView, "sepratorLine": sepratorLine] contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[bubbleView]-1-|", options: [], metrics: nil, views: bubbleViews)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[sepratorLine(1)]-|", options: [], metrics: nil, views: bubbleViews)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[bubbleView]|", options: [], metrics: nil, views: bubbleViews)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[sepratorLine]|", options: [], metrics: nil, views: bubbleViews)) } } extension Date { public func formatTimeAsHours() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mm a" dateFormatter.amSymbol = "am" dateFormatter.pmSymbol = "pm" return dateFormatter.string(from: self) } //Fri, Mar 30 2018 public func formatTimeAsFullDate() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "d LLL, yyyy, h:mm a" dateFormatter.amSymbol = "am" dateFormatter.pmSymbol = "pm" return dateFormatter.string(from: self) } }
38.351515
196
0.612279
644b6138665a69e04fcd8afb412e9b8f832589e8
596
// // ViewController.swift // TestSQLite // // Created by Javier A. Junca Barreto on 26/10/19. // Copyright © 2019 SICyA Software SAS. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let fnS3 = fnSICyA() fnS3.initDBSQLite(strFileName: "TestDB") let dataSQLite = fnS3.executeQueryResultDBSQLite(pQuery: "select * from Usuarios") print("Resultado: ", dataSQLite.count) } }
23.84
90
0.634228
0105ae4e76d7fd54dcfdf062027cdd034d0a275d
377
// // ListWorker.swift // Containment // // Created by Raymond Law on 8/28/17. // Copyright (c) 2017 Clean Swift LLC. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit class ListWorker { func doSomeWork() { } }
17.952381
66
0.68435
181e5431f00c3cc6953ebf3c7b341f7021c40755
4,232
// // Webservice.swift // Repository // // Created by Fernando Moya de Rivas on 10/07/2019. // Copyright © 2019 fmoyader. All rights reserved. // import Foundation import Alamofire import Domain import UseCases typealias HttpDataResult = Swift.Result<Data, WebserviceError> public typealias HttpAcknowledgementResult = Swift.Result<Bool, WebserviceError> public typealias AthletesResult = Swift.Result<[Domain.Athlete], WebserviceError> public enum WebserviceError: Error, Equatable { case unknown(String) case badRequest case unauthorized case forbidden case notFound case internalServerError case badGateway case unavailable } public class Webservice { public init() { } public func login(email: String, password: String, completion: @escaping (HttpAcknowledgementResult) -> Void) { let endpoint: Endpoint = .login(email: email, password: password) post(to: endpoint) { (result) in switch result { case .success: return completion(.success(true)) case .failure(let error): return completion(.failure(error)) } } } public func fetchAthletes(completion: @escaping (AthletesResult) -> Void) { let endpoint: Endpoint = .athletesAndSquads get(from: endpoint) { (result) in switch result { case .success(let data): let response = try! JSONDecoder().decode(AthletesAndSquadsResponse.self, from: data) let assembler = AthletesSquadsAssembler() let athletes = assembler.assemble(athletes: response.athletes, squads: response.squads) return completion(.success(athletes)) case .failure(let error): return completion(.failure(error)) } } } private func post(to endpoint: Endpoint, completion: @escaping (HttpDataResult) -> Void) { var urlRequest = URLRequest(url: URL(string: endpoint.url)!) urlRequest.httpMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = endpoint.body.data(using: .utf8) request(urlRequest) .responseJSON { [weak self] (dataResponse) in guard let self = self else { return } let result = self.processHttpResponse(dataResponse) completion(result) } } private func get(from endpoint: Endpoint, completion: @escaping (HttpDataResult) -> Void) { request(endpoint.url) .responseJSON { [weak self] (dataResponse) in guard let self = self else { return } let result = self.processHttpResponse(dataResponse) completion(result) } } private func processHttpResponse<T>(_ dataResponse: DataResponse<T>) -> HttpDataResult { let error = self.findErrors(in: dataResponse) guard error == nil else { return .failure(error!) } guard let data = dataResponse.data else { return .failure(.unknown("Empty response")) } return .success(data) } private func findErrors<T>(in dataResponse: DataResponse<T>) -> WebserviceError? { guard let error = dataResponse.error else { return nil } if let httpCode = dataResponse.response?.statusCode { return processHttpErrorResponse(with: httpCode) } else { return .unknown(error.localizedDescription) } } private func processHttpErrorResponse(with code: Int) -> WebserviceError { let error: WebserviceError switch code { case 400: error = .badRequest case 401: error = .unauthorized case 403: error = .forbidden case 404: error = .notFound case 500: error = .internalServerError case 502: error = .badGateway case 503: error = .unavailable default: error = .unknown("HTTP code \(code)") } return error } }
32.806202
115
0.601607
290287f8a9b857641a8916e2d5eeebcac8c70fcb
3,151
// // MyViewControllerExtension.swift // SwiftExtension // // Created by 东正 on 15/12/7. // Copyright © 2015年 东正. All rights reserved. // import UIKit // MARK: - 模态 var commonParametersBind = "commonParametersBind" extension UIViewController{ ///是否模态 public var isModal: Bool { return self.presentingViewController?.presentedViewController == self || (self.navigationController != nil && self.navigationController?.presentingViewController?.presentedViewController == self.navigationController) || self.tabBarController?.presentingViewController is UITabBarController } /// 传输的属性 public var commonParameters:[String:Any] { get{ if(objc_getAssociatedObject(self, &commonParametersBind) == nil){ objc_setAssociatedObject(self, &commonParametersBind, 0,.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return [:] }else{ return objc_getAssociatedObject(self,&commonParametersBind) as! [String:Any] } } set{ objc_setAssociatedObject(self, &commonParametersBind, newValue,.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - RunTime //extension UIViewController{ // public override class func initialize(){ // struct Static{ // static var token:dispatch_once_t = 0 // } // if self != UIViewController.self{ // return // } // dispatch_once(&Static.token, { // _ in // let viewDidLoad = class_getInstanceMethod(self, Selector("viewDidLoad")) // let viewDidLoaded = class_getInstanceMethod(self, Selector("myViewDidLoad")) // method_exchangeImplementations(viewDidLoad,viewDidLoaded) // }) // } // func myViewDidLoad(){ // self.myViewDidLoad() // print("\(self)在viewDidLoad创建了😄") // } //} // MARK: - 用block实现RunTime //typealias _IMP = @convention(c)(id:AnyObject,sel:UnsafeMutablePointer<Selector>)->AnyObject //typealias _VIMP = @convention(c)(id:AnyObject,sel:UnsafeMutablePointer<Selector>)->Void // //extension UIViewController{ // public override class func initialize(){ // struct Static{ // static var token:dispatch_once_t = 0 // } // if self != UIViewController.self{ // return // } // // dispatch_once(&Static.token, { // _ in // let viewDidLoad:Method = class_getInstanceMethod(self, Selector("viewDidLoad")) // let viewDidLoad_VIMP:_VIMP = unsafeBitCast(method_getImplementation(viewDidLoad),_VIMP.self) // let block:@convention(block)(UnsafeMutablePointer<AnyObject>,UnsafeMutablePointer<Selector>)->Void = { // (id,sel) in // viewDidLoad_VIMP(id: id.memory, sel: sel) // print("viewDidLoad func execu over id ---> \(id.memory)"); // } // let imp:COpaquePointer = imp_implementationWithBlock(unsafeBitCast(block, AnyObject.self)) // method_setImplementation(viewDidLoad,imp) // }) // } //}
35.011111
158
0.618851
20fc414f928fc96bbc7eb281f04e06efb1af0087
1,032
// // DateDataElement.swift // AAMVA Barcode Paser // // Created by Jakub Dolejs on 20/12/2019. // Copyright © 2019 Applied Recognition Inc. All rights reserved. // import Foundation struct DateDataElement: DataElement { let mandatory: Bool let cardType: CardType let id: String let description: String let params: ElementParams let dateFormatter: ISO8601DateFormatter = ISO8601DateFormatter() let dateParser: DateFormatter = DateFormatter() init(mandatory: Bool, cardType: CardType, id: String, description: String, params: ElementParams) { self.mandatory = mandatory self.cardType = cardType self.id = id self.description = description self.params = params dateParser.timeStyle = .none dateParser.dateFormat = "MMddyyyy" } func formatValue(_ value: String) -> String { if let date = dateParser.date(from: value) { return dateFormatter.string(from: date) } return value } }
27.157895
103
0.656977
e9790155e60ba6c3057fcbf169d861c03dafaccd
8,307
// // ClipView.swift // CollectionView // // Created by Wesley Byrne on 3/30/16. // Copyright © 2016 Noun Project. All rights reserved. // //import Foundation import AppKit //typealias DisplayLinkCallback = @convention(block) ( CVDisplayLink!, UnsafePointer<CVTimeStamp>, UnsafePointer<CVTimeStamp>, CVOptionFlags, UnsafeMutablePointer<CVOptionFlags>, UnsafeMutablePointer<Void>)->Void open class ClipView : NSClipView { static let DefaultDecelerationRate : CGFloat = 0.78 var shouldAnimateOriginChange = false var destinationOrigin = CGPoint.zero var scrollView : NSScrollView? { return self.enclosingScrollView ?? self.superview as? NSScrollView } var scrollEnabled : Bool = true /** The rate of deceleration for animated scrolls. Higher is slower. default is 0.78 */ public var decelerationRate = DefaultDecelerationRate { didSet { if decelerationRate > 1 { self.decelerationRate = 1 } else if decelerationRate < 0 { self.decelerationRate = 0 } } } var completionBlock : AnimationCompletion? init(clipView: NSClipView) { super.init(frame: clipView.frame) self.backgroundColor = clipView.backgroundColor self.drawsBackground = clipView.drawsBackground self.setup() } deinit { NotificationCenter.default.removeObserver(self) } override init(frame frameRect: NSRect) { super.init(frame: frameRect) self.setup() } required public init?(coder: NSCoder) { super.init(coder: coder) self.setup() } func setup() { self.wantsLayer = true } override open func viewWillMove(toWindow newWindow: NSWindow?) { if (self.window != nil) { NotificationCenter.default.removeObserver(self, name: NSWindow.didChangeScreenNotification, object: self.window) } super.viewWillMove(toWindow: newWindow) if (newWindow != nil) { NotificationCenter.default.addObserver(self, selector: #selector(ClipView.updateCVDisplay(_:)), name: NSWindow.didChangeScreenNotification, object: newWindow) } } // open override func constrainBoundsRect(_ proposedBounds: NSRect) -> NSRect { // var rect = proposedBounds // rect.origin.x = 50 // return rect // } var _displayLink : CVDisplayLink? var displayLink : CVDisplayLink { if let link = _displayLink { return link } let linkCallback : CVDisplayLinkOutputCallback = {( displayLink, _, _, _, _, displayLinkContext) -> CVReturn in unsafeBitCast(displayLinkContext, to: ClipView.self).updateOrigin() return kCVReturnSuccess } var link : CVDisplayLink? CVDisplayLinkCreateWithActiveCGDisplays(&link) CVDisplayLinkSetOutputCallback(link!, linkCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())) self._displayLink = link return link! } open override func mouseDown(with event: NSEvent) { self.cancelScrollAnimation() super.mouseDown(with: event) } @objc func updateCVDisplay(_ note: Notification) { guard self._displayLink != nil else { return } if let screen = self.window?.screen { let screenDictionary = screen.deviceDescription let screenID = screenDictionary[NSDeviceDescriptionKey("NSScreenNumber")] as! NSNumber let displayID = screenID.uint32Value CVDisplayLinkSetCurrentCGDisplay(displayLink, displayID) } else { CVDisplayLinkSetCurrentCGDisplay(displayLink, CGMainDisplayID()) } } var manualScroll = false @discardableResult open func scrollRectToVisible(_ rect: CGRect, animated: Bool, completion: AnimationCompletion? = nil) -> Bool { manualScroll = false shouldAnimateOriginChange = animated if animated == false { // Calculate the point to scroll to to get make the rect visible var o = rect.origin o.y -= self.contentInsets.top self.scroll(to: o) completion?(true) return true } self.completionBlock = completion let success = super.scrollToVisible(rect) if !success { self.finishedScrolling(success) } return success } func finishedScrolling(_ success: Bool) { self.completionBlock?(success) self.completionBlock = nil; } open override func scroll(to newOrigin: NSPoint) { if self.shouldAnimateOriginChange { self.shouldAnimateOriginChange = false if CVDisplayLinkIsRunning(self.displayLink) { self.destinationOrigin = newOrigin return } self.destinationOrigin = newOrigin self.beginScrolling() } else if self.scrollEnabled || manualScroll { // Otherwise, we stop any scrolling that is currently occurring (if needed) and let // super's implementation handle a normal scroll. super.scroll(to: newOrigin) self.cancelScrollAnimation() // Can't remember why this is here, it may be to cleanup if needed // if self._displayLink != nil && !manualScroll { // self.endScrolling() // } } } func cancelScrollAnimation() { self.destinationOrigin = self.bounds.origin } func updateOrigin() { var o = CGPoint.zero var integral = false var cancel = false DispatchQueue.main.sync { if self.window == nil { cancel = true } o = self.bounds.origin; integral = self.window?.backingScaleFactor == 1 } if cancel { self.endScrolling() return } let lastOrigin = o; let deceleration = self.decelerationRate; // Calculate the next origin on a basic ease-out curve. o.x = o.x * deceleration + self.destinationOrigin.x * (1 - self.decelerationRate); o.y = o.y * deceleration + self.destinationOrigin.y * (1 - self.decelerationRate); if integral { o = o.integral } // Calling -scrollToPoint: instead of manually adjusting the bounds lets us get the expected // overlay scroller behavior for free. DispatchQueue.main.async { super.scroll(to: o) // Make this call so that we can force an update of the scroller positions. self.scrollView?.reflectScrolledClipView(self) NotificationCenter.default.post(name: NSScrollView.didLiveScrollNotification, object: self.scrollView) } //.postNotificationName(NSScrollViewDidLiveScrollNotification, object: self, userInfo: nil) if ((fabs(o.x - lastOrigin.x) < 0.1 && fabs(o.y - lastOrigin.y) < 0.1)) { self.endScrolling() // Make sure we always finish out the animation with the actual coordinates DispatchQueue.main.async(execute: { super.scroll(to: self.destinationOrigin) self.finishedScrolling(true) if let cv = self.scrollView as? CollectionView { cv.delegate?.collectionViewDidEndScrolling?(cv, animated: true) } }) } } func beginScrolling() { if CVDisplayLinkIsRunning(self.displayLink) { return } DispatchQueue.main.async { (self.scrollView as? CollectionView)?.isScrolling = true } CVDisplayLinkStart(self.displayLink) } func endScrolling() { manualScroll = false if !CVDisplayLinkIsRunning(self.displayLink) { return } DispatchQueue.main.async { (self.scrollView as? CollectionView)?.isScrolling = false } CVDisplayLinkStop(self.displayLink) } }
32.704724
212
0.603467
8aaede99a964205b1cfaac94b752185898cf732f
846
import UIKit class MGridMapDetailItemTitle:MGridMapDetailItem { init?(annotation:MGridMapAnnotation) { guard let rawTitle:String = annotation.algo?.algoTitle else { return nil } let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.center let attributesTitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:18), NSForegroundColorAttributeName:UIColor.black, NSParagraphStyleAttributeName:paragraphStyle] let stringTitle:NSAttributedString = NSAttributedString( string:rawTitle, attributes:attributesTitle) super.init(attributedString:stringTitle) } }
27.290323
78
0.628842
e21ea0eb559999344267af5fc87283f4df1f47aa
2,412
// // Seaglass, a native macOS Matrix client // Copyright © 2018, Neil Alexander // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // import Cocoa class MenuController: NSMenu { @IBAction func focusOnRoomSearchField(_ sender: NSMenuItem) { sender.target = self let mainWindow = NSApplication.shared.mainWindow let splitViewController = mainWindow?.contentViewController as? NSSplitViewController let mainRoomsViewController = splitViewController?.splitViewItems.first?.viewController as? MainViewRoomsController if let searchField = mainRoomsViewController?.RoomSearch { searchField.selectText(sender) let lengthOfInput = NSString(string: searchField.stringValue).length searchField.currentEditor()?.selectedRange = NSMakeRange(lengthOfInput, 0) } } @IBAction func inviteButtonClicked(_ sender: NSMenuItem) { MatrixServices.inst.mainController?.channelDelegate?.uiRoomStartInvite() } @IBAction func gotoOldestLoaded(_ sender: NSMenuItem) { let mainWindow = NSApplication.shared.mainWindow let splitViewController = mainWindow?.contentViewController as? NSSplitViewController let mainRoomViewController = splitViewController?.splitViewItems.last?.viewController as? MainViewRoomController mainRoomViewController?.RoomMessageTableView.scrollToBeginningOfDocument(self) } @IBAction func gotoNewest(_ sender: NSMenuItem) { let mainWindow = NSApplication.shared.mainWindow let splitViewController = mainWindow?.contentViewController as? NSSplitViewController let mainRoomViewController = splitViewController?.splitViewItems.last?.viewController as? MainViewRoomController mainRoomViewController?.RoomMessageTableView.scrollToEndOfDocument(self) } }
40.881356
120
0.761609
8a45a95662b2327c54d8e7148237fc3fce280793
1,643
// // main.swift // // // Created by Christian Treffs on 14.11.20. // import SwiftMiniaudio func dataCallback(_ pDevice: UnsafeMutablePointer<ma_device>?, _ pOutput: UnsafeMutableRawPointer?, _ pInput: UnsafeRawPointer?, _ frameCount: ma_uint32) { guard let pDevice = pDevice else { return } let pDecoder = pDevice.pointee.pUserData.assumingMemoryBound(to: ma_decoder.self) ma_decoder_read_pcm_frames(pDecoder, pOutput, ma_uint64(frameCount)) } if CommandLine.arguments.count < 2 { print("No input file.") exit(-1) } var decoder = ma_decoder() let result = ma_decoder_init_file(CommandLine.unsafeArgv[1], nil, &decoder) if result != MA_SUCCESS { exit(-2) } var deviceConfig: ma_device_config = ma_device_config_init(ma_device_type_playback) deviceConfig.playback.format = decoder.outputFormat deviceConfig.playback.channels = decoder.outputChannels deviceConfig.sampleRate = decoder.outputSampleRate deviceConfig.dataCallback = dataCallback deviceConfig.pUserData = UnsafeMutableRawPointer(&decoder) // Can be accessed from the device object (device.pUserData). var device = ma_device() if ma_device_init(nil, &deviceConfig, &device) != MA_SUCCESS { print("Failed to open playback device.") ma_decoder_uninit(&decoder) exit(-3) } if ma_device_start(&device) != MA_SUCCESS { print("Failed to start playback device.") ma_device_uninit(&device) ma_decoder_uninit(&decoder) exit(-4) } print("Press Enter to quit...") getchar() ma_device_uninit(&device) ma_decoder_uninit(&decoder) exit(0)
25.671875
130
0.712112
d5a4cb678cb783f7f0aac148195603be1782278f
1,254
// The MIT License (MIT) // // Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean). import XCTest @testable import Nuke class ImageDecompressionTests: XCTestCase { func testDecompressionNotNeededFlagSet() throws { // Given let input = Test.image ImageDecompression.setDecompressionNeeded(true, for: input) // When let output = ImageDecompression.decompress(image: input) // Then XCTAssertFalse(try XCTUnwrap(ImageDecompression.isDecompressionNeeded(for: output))) } func testGrayscalePreserved() throws { // Given let input = Test.image(named: "grayscale", extension: "jpeg") XCTAssertEqual(input.cgImage?.bitsPerComponent, 8) XCTAssertEqual(input.cgImage?.bitsPerPixel, 8) // When let output = ImageDecompression.decompress(image: input) // Then // The original image doesn't have an alpha channel (kCGImageAlphaNone), // but this parameter combination (8 bbc and kCGImageAlphaNone) is not // supported by CGContext. Thus we are switching to a different format. XCTAssertEqual(output.cgImage?.bitsPerPixel, 16) XCTAssertEqual(output.cgImage?.bitsPerComponent, 8) } }
32.153846
92
0.678628
9b222968bc0b0ddef1bcd441c5347b9fc354f9a9
8,490
// // M13CheckboxAnimationGenerator.swift // M13Checkbox // // Created by McQuilkin, Brandon on 3/27/16. // Copyright © 2016 Brandon McQuilkin. 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. import UIKit //extension CGFloat { // static var zero: CGFloat { // return CGFloat(0) // } // static var one: CGFloat { // return CGFloat(1) // } //} extension NSNumber { static var zero: NSNumber { return NSNumber(integerLiteral: 1) } static var one: NSNumber { return NSNumber(integerLiteral: 0) } } internal class M13CheckboxAnimationGenerator { //---------------------------- // MARK: - Properties //---------------------------- // The duration of animations that are generated by the animation manager. var animationDuration: TimeInterval = 0.3 // The frame rate for certian keyframe animations. fileprivate var frameRate: CGFloat = 60.0 //---------------------------- // MARK: - Quick Animations //---------------------------- final func quickAnimation(_ key: String, reverse: Bool) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: key) // Set the start and end. if !reverse { animation.fromValue = NSNumber.zero animation.toValue = NSNumber.one animation.timingFunction = CAMediaTimingFunction(name: .easeIn) } else { animation.fromValue = NSNumber.one animation.toValue = NSNumber.zero animation.beginTime = CACurrentMediaTime() + (animationDuration * 0.9) animation.timingFunction = CAMediaTimingFunction(name: .easeOut) } // Set animation properties. animation.duration = animationDuration / 10.0 animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.forwards return animation } /** Creates an animation that either quickly fades a layer in or out. - note: Mainly used to smooth out the start and end of various animations. - parameter reverse: The direction of the animation. - returns: A `CABasicAnimation` that animates the opacity property. */ final func quickOpacityAnimation(_ reverse: Bool) -> CABasicAnimation { return quickAnimation("opacity", reverse: reverse) } /** Creates an animation that either quickly changes the line width of a layer from 0% to 100%. - note: Mainly used to smooth out the start and end of various animations. - parameter reverse: The direction of the animation. - returns: A `CABasicAnimation` that animates the opacity property. */ final func quickLineWidthAnimation(_ width: CGFloat, reverse: Bool) -> CABasicAnimation { let animation = quickAnimation("lineWidth", reverse: reverse) // Set the start and end. if !reverse { animation.toValue = width } else { animation.fromValue = width } return animation } //---------------------------- // MARK: - Animation Component Generation //---------------------------- final func animation(_ key: String, reverse: Bool) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: key) // Set the start and end. if !reverse { animation.fromValue = NSNumber.zero animation.toValue = NSNumber.one } else { animation.fromValue = NSNumber.one animation.toValue = NSNumber.zero } // Set animation properties. animation.duration = animationDuration animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.forwards animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) return animation } /** Creates an animation that animates the stroke property. - parameter reverse: The direction of the animation. - returns: A `CABasicAnimation` that animates the stroke property. */ final func strokeAnimation(_ reverse: Bool) -> CABasicAnimation { return animation("strokeEnd", reverse: reverse) } /** Creates an animation that animates the opacity property. - parameter reverse: The direction of the animation. - returns: A `CABasicAnimation` that animates the opacity property. */ final func opacityAnimation(_ reverse: Bool) -> CABasicAnimation { return animation("opacity", reverse: reverse) } /** Creates an animation that animates between two `UIBezierPath`s. - parameter fromPath: The start path. - parameter toPath: The end path. - returns: A `CABasicAnimation` that animates a path between the `fromPath` and `toPath`. */ final func morphAnimation(_ fromPath: UIBezierPath?, toPath: UIBezierPath?) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "path") // Set the start and end. animation.fromValue = fromPath?.cgPath animation.toValue = toPath?.cgPath // Set animation properties. animation.duration = animationDuration animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) animation.fillMode = CAMediaTimingFillMode.forwards animation.isRemovedOnCompletion = false return animation } /** Creates an animation that animates between a filled an unfilled box. - parameter numberOfBounces: The number of bounces in the animation. - parameter amplitude: The distance of the bounce. - parameter reverse: The direction of the animation. - returns: A `CAKeyframeAnimation` that animates a change in fill. */ final func fillAnimation(_ numberOfBounces: Int, amplitude: CGFloat, reverse: Bool) -> CAKeyframeAnimation { var values = [CATransform3D]() var keyTimes = [Float]() // Add the start scale if !reverse { values.append(CATransform3DMakeScale(0.0, 0.0, 0.0)) } else { values.append(CATransform3DMakeScale(1.0, 1.0, 1.0)) } keyTimes.append(0.0) // Add the bounces. if numberOfBounces > 0 { for i in 1...numberOfBounces { let scale = i % 2 == 1 ? (1.0 + (amplitude / CGFloat(i))) : (1.0 - (amplitude / CGFloat(i))) let time = (Float(i) * 1.0) / Float(numberOfBounces + 1) values.append(CATransform3DMakeScale(scale, scale, scale)) keyTimes.append(time) } } // Add the end scale. if !reverse { values.append(CATransform3DMakeScale(1.0, 1.0, 1.0)) } else { values.append(CATransform3DMakeScale(0.0001, 0.0001, 0.0001)) } keyTimes.append(1.0) // Create the animation. let animation = CAKeyframeAnimation(keyPath: "transform") animation.values = values.map({ NSValue(caTransform3D: $0) }) animation.keyTimes = keyTimes.map({ NSNumber(value: $0 as Float) }) animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.forwards animation.duration = animationDuration animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) return animation } }
40.428571
464
0.638045
1c7d248d9e58b139ac6cabccdc1ef7640e7284f5
1,488
// // AVCaptureDevice+Resolution.swift // VisionCam // // Created by Steve on 8/22/20. // import Foundation import AVFoundation extension AVCaptureDevice { /** Helper method to find the highest resolution 420 format for the current capture device - Returns: Tuple that holds both the device format and resolution calculated */ public func highestRes420Format() -> (format: AVCaptureDevice.Format, resolution: CGSize)? { var highFormat: AVCaptureDevice.Format? = nil var highDimensions = CMVideoDimensions(width: 0, height: 0) for format in formats { let deviceFormat = format as AVCaptureDevice.Format let deviceFormatDescription = deviceFormat.formatDescription if CMFormatDescriptionGetMediaSubType(deviceFormatDescription) == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange { let candidateDimensions = CMVideoFormatDescriptionGetDimensions(deviceFormatDescription) if (highFormat == nil) || (candidateDimensions.width > highDimensions.width) { highFormat = deviceFormat highDimensions = candidateDimensions } } } if highFormat != nil { let resolution = CGSize(width: CGFloat(highDimensions.width), height: CGFloat(highDimensions.height)) return (highFormat!, resolution) } return nil } }
33.818182
126
0.645161
1821cc447b657a3118f6e58b2921fccacadb202e
266
// // Formatter.swift // Logger // import Foundation public protocol Formatter: class { var name: String { get } func format(details: inout LogDetails) } extension Formatter { public var name: String { String(describing: Self.self) } }
14
42
0.650376
e0b7cd273a80404cd6978cfea23db90f602072c9
15,859
/* Copyright Airship and Contributors */ /** * This class is responsible for runtime-persisting actions and associating * them with names and predicates. */ @objc(UAActionRegistry) public class ActionRegistry : NSObject { private static let actionKey = "action" private static let namesKey = "names" private static let predicateKey = "predicate" private var _entries: [ActionRegistryEntry] = [] private var lock = Lock() /** * A set of the current registered entries */ @objc public var registeredEntries: Set<ActionRegistryEntry> { get { return Set(self._entries) } } /** * Factory method to create an action registry with the default action entries. * - Returns: An action registry with the default action entries. */ @objc public class func defaultRegistry() -> ActionRegistry { let registry = ActionRegistry() registry.registerDefaultActions() return registry } /** * Registers an action. * * If another entry is registered under specified name, it will be removed from that * entry and used for the new action. * * - Parameters: * - action: The action. * - names: The action's names. * - Returns: true if the action was able to be registered, otherwise false. */ @objc(registerAction:names:) @discardableResult public func register(_ action: Action, names: [String]) -> Bool { return register(action, names: names, predicate: nil) } /** * Registers an action. * * If another entry is registered under specified name, it will be removed from that * entry and used for the new action. * * - Parameters: * - action: The action. * - name: The action's name. * - Returns: true if the action was able to be registered, otherwise false. */ @objc(registerAction:name:) @discardableResult public func register(_ action: Action, name: String) -> Bool { return register(action, name: name, predicate: nil) } /** * Registers an action. * * If another entry is registered under specified name, it will be removed from that * entry and used for the new action. * * - Parameters: * - action: The action. * - name: The action's name. * - predicate: The action's predicate. * - Returns: true if the action was able to be registered, otherwise false. */ @objc(registerAction:name:predicate:) @discardableResult public func register(_ action: Action, name: String, predicate: UAActionPredicate?) -> Bool { return register(action, names: [name], predicate: predicate) } /** * Registers an action. * * If another entry is registered under specified name, it will be removed from that * entry and used for the new action. * * - Parameters: * - action: The action. * - names: The action's names. * - predicate: The action's predicate. * - Returns: true if the action was able to be registered, otherwise false. */ @objc(registerAction:names:predicate:) @discardableResult public func register(_ action: Action, names: [String], predicate: UAActionPredicate?) -> Bool { let entry = ActionRegistryEntry(action: action) return register(entry, names: names, predicate: predicate) } /** * Registers an action by class name.. * * If another entry is registered under specified name, it will be removed from that * entry and used for the new action. * * - Parameters: * - actionClass: The action's class. * - names: The action's names. * - Returns: true if the action was able to be registered, otherwise false. */ @objc(registerActionClass:names:) @discardableResult public func register(_ actionClass: AnyClass, names: [String]) -> Bool { return register(actionClass, names: names, predicate: nil) } /** * Registers an action by class name.. * * If another entry is registered under specified name, it will be removed from that * entry and used for the new action. * * - Parameters: * - actionClass: The action's class. * - name: The action's name. * - Returns: true if the action was able to be registered, otherwise false. */ @objc(registerActionClass:name:) @discardableResult public func register(_ actionClass: AnyClass, name: String) -> Bool { return register(actionClass, name: name, predicate: nil) } /** * Registers an action by class name.. * * If another entry is registered under specified name, it will be removed from that * entry and used for the new action. * * - Parameters: * - actionClass: The action's class. * - name: The action's name. * - predicate: The action's predicate. * - Returns: true if the action was able to be registered, otherwise false. */ @objc(registerActionClass:name:predicate:) @discardableResult public func register(_ actionClass: AnyClass, name: String, predicate: UAActionPredicate?) -> Bool { return register(actionClass, names: [name], predicate: predicate) } /** * Registers an action by class name.. * * If another entry is registered under specified name, it will be removed from that * entry and used for the new action. * * - Parameters: * - actionClass: The action's class. * - names: The action's names. * - predicate:The action's predicate. * - Returns: true if the action was able to be registered, otherwise false. */ @objc(registerActionClass:names:predicate:) @discardableResult public func register(_ actionClass: AnyClass, names: [String], predicate: UAActionPredicate?) -> Bool { guard actionClass is Action.Type else { AirshipLogger.error("Unable to register an action class that isn't a subclass of UAAction.") return false } guard let actionClass = actionClass as? NSObject.Type else { AirshipLogger.error("Unable to register an action class that isn't a subclass of NSObject.") return false } let entry = ActionRegistryEntry(actionClass: actionClass) return register(entry, names: names, predicate: predicate) } /** * Removes an entry by name. * - Parameters: * - name: The name of the entry to remove. */ @objc(removeEntryWithName:) public func removeEntry(_ name: String) { lock.sync { self._entries.removeAll(where: { $0.names.contains(name) }) } } /** * Removes a name for a registered entry. * - Parameters: * - name: The name to remove. */ @objc(removeName:) public func removeName(_ name: String) { self.removeNames([name]) } func removeNames(_ names: [String]) { lock.sync { names.forEach { name in if let entry = registryEntry(name) { entry._names.removeAll(where: { $0 == name }) } } self._entries.removeAll(where: { $0.names.isEmpty }) } } /** * Adds a name to a registered entry. * - Parameters: * - name: The name to add * - entryName:The name of the entry. * - Returns: true if the entry was found, othewrise false.. */ @objc @discardableResult public func addName(_ name: String, forEntryWithName entryName: String) -> Bool { var result = false lock.sync { if let entry = registryEntry(entryName) { removeNames([name]) entry._names.append(name) result = true } } return result } /** * Adds a situation override for the entry. * - Parameters: * - situation: The situation to override. * - name: The name of the entry. * - action: The action. */ @objc @discardableResult public func addSituationOverride(_ situation: Situation, forEntryWithName name: String, action: Action?) -> Bool { var result = false lock.sync { if let entry = registryEntry(name) { entry._situationOverrides[situation] = action result = true } } return result } /** * Gets an entry by name. * - Parameters: * - name: The name of the entry. * - Returns: The entry if found, otherwise null. */ @objc(registryEntryWithName:) public func registryEntry(_ name: String) -> ActionRegistryEntry? { var result: ActionRegistryEntry? = nil lock.sync { result = self._entries.first(where: {$0.names.contains(name) }) } return result } /** * Updates an entry's predicate. * - Parameters: * - predicate: The predicate. * - name: The name of the entry. * - Returns: The entry if found, otherwise null. */ @objc(updatePredicate:forEntryWithName:) @discardableResult public func update(_ predicate: UAActionPredicate?, forEntryWithName name: String) -> Bool { var result = false lock.sync { if let entry = registryEntry(name) { entry._predicate = predicate result = true } } return result } /** * Updates an entry's action. * - Parameters: * - action: The action. * - name: The name of the entry. * - Returns: The entry if found, otherwise null. */ @objc(updateAction:forEntryWithName:) @discardableResult public func update(_ action: Action, forEntryWithName name: String) -> Bool { var result = false lock.sync { if let entry = registryEntry(name) { entry._action = action result = true } } return result } /** * Updates an entry's action. * - Parameters: * - actionClass: The action class. * - name: The name of the entry. * - Returns: The entry if found, otherwise null. */ @objc(updateActionClass:forEntryWithName:) @discardableResult public func update(_ actionClass: AnyClass, forEntryWithName name: String) -> Bool { guard actionClass is Action.Type else { AirshipLogger.error("Unable to register an action class that isn't a subclass of UAAction.") return false } guard let actionClass = actionClass as? NSObject.Type else { AirshipLogger.error("Unable to register an action class that isn't a subclass of NSObject.") return false } var result = false lock.sync { if let entry = registryEntry(name) { entry._action = nil entry._actionClass = actionClass result = true } } return result } /** * Registers actions from a plist file. * - Parameters: * - path: The path to the plist. */ @objc(registerActionsFromFile:) public func registerActions(_ path: String) { AirshipLogger.debug("Loading actions from \(path)") guard let actions = NSArray(contentsOfFile: path) as? [[AnyHashable : Any]] else { AirshipLogger.error("Unable to load actions from: \(path)") return } for actionEntry in actions { guard let names = actionEntry[ActionRegistry.namesKey] as? [String], !names.isEmpty else { AirshipLogger.error("Missing action names for entry \(actionEntry)") continue } guard let actionClassName = actionEntry[ActionRegistry.actionKey] as? String else { AirshipLogger.error("Missing action class name for entry \(actionEntry)") continue } guard let actionClass = NSClassFromString(actionClassName) else { AirshipLogger.error("Unable to find class for name \(actionClassName)") continue } var predicateBlock: ((ActionArguments) -> Bool)? = nil if let predicateClassName = actionEntry[ActionRegistry.predicateKey] as? String { guard let predicateClass = NSClassFromString(predicateClassName) as? NSObject.Type else { AirshipLogger.error("Unable to find class for name \(predicateClassName)") continue } guard predicateClass is ActionPredicateProtocol.Type else { AirshipLogger.error("Invalid predicate for class \(predicateClassName)") continue } if let predicate = predicateClass.init() as? ActionPredicateProtocol { predicateBlock = { args in return predicate.apply(args) } } } _ = self.register(actionClass, names: names, predicate: predicateBlock) } } private func register(_ entry: ActionRegistryEntry, names: [String], predicate: UAActionPredicate?) -> Bool { guard !names.isEmpty else { AirshipLogger.error("Unable to register action class. A name must be specified.") return false } lock.sync { self.removeNames(names) entry._names = names entry._predicate = predicate _entries.append(entry) } return true } func registerDefaultActions() { #if os(tvOS) let path = AirshipCoreResources.bundle.path(forResource: "UADefaultActionsTVOS", ofType: "plist") #else let path = AirshipCoreResources.bundle.path(forResource: "UADefaultActions", ofType: "plist") #endif if let path = path { registerActions(path) } } } /** * An action registry entry. */ @objc(UAActionRegistryEntry) public class ActionRegistryEntry : NSObject { internal var _actionClass: NSObject.Type? internal var _situationOverrides: [Situation : Action] = [:] internal var _action : Action? internal var _names: [String] = [] /** * The entry's names. */ @objc public var names: [String] { get { return self._names } } internal var _predicate: UAActionPredicate? /** * The entry's predicate. */ @objc public var predicate : UAActionPredicate? { get { return self._predicate } } /** * The entry's default action.. */ @objc public var action: Action { get { if (self._action == nil) { self._action = self._actionClass?.init() as? Action ?? EmptyAction() } return self._action! } } init(actionClass: NSObject.Type) { self._actionClass = actionClass } init(action: Action) { self._action = action } /** * Gets the action for the situation. * - Parameters: * - situation: The situation. * - Returns: The action. */ @objc(actionForSituation:) public func action(situation: Situation) -> Action { return self._situationOverrides[situation] ?? self.action } }
31.591633
113
0.581436
5b03e2ed70ec558ea90a28d22e909d5625e44ce2
5,260
import Foundation import Utility struct FileContentsChecker { let checkInfo: CheckInfo let regex: Regex let filePathsToCheck: [String] let autoCorrectReplacement: String? let repeatIfAutoCorrected: Bool } extension FileContentsChecker: Checker { func performCheck() throws -> [Violation] { // swiftlint:disable:this function_body_length log.message("Start checking \(checkInfo) ...", level: .debug) var violations: [Violation] = [] for filePath in filePathsToCheck.reversed() { log.message("Start reading contents of file at \(filePath) ...", level: .debug) if let fileData = fileManager.contents(atPath: filePath), let fileContents = String(data: fileData, encoding: .utf8) { var newFileContents: String = fileContents let linesInFile: [String] = fileContents.components(separatedBy: .newlines) // skip check in file if contains `AnyLint.skipInFile: <All or CheckInfo.ID>` let skipInFileRegex = try Regex(#"AnyLint\.skipInFile:[^\n]*([, ]All[,\s]|[, ]\#(checkInfo.id)[,\s])"#) guard !skipInFileRegex.matches(fileContents) else { log.message("Skipping \(checkInfo) in file \(filePath) due to 'AnyLint.skipInFile' instruction ...", level: .debug) continue } let skipHereRegex = try Regex(#"AnyLint\.skipHere:[^\n]*[, ]\#(checkInfo.id)"#) for match in regex.matches(in: fileContents).reversed() { let locationInfo = fileContents.locationInfo(of: match.range.lowerBound) log.message("Found violating match at \(locationInfo) ...", level: .debug) // skip found match if contains `AnyLint.skipHere: <CheckInfo.ID>` in same line or one line before guard !linesInFile.containsLine(at: [locationInfo.line - 2, locationInfo.line - 1], matchingRegex: skipHereRegex) else { log.message("Skip reporting last match due to 'AnyLint.skipHere' instruction ...", level: .debug) continue } let autoCorrection: AutoCorrection? = { guard let autoCorrectReplacement = autoCorrectReplacement else { return nil } let newMatchString = regex.replaceAllCaptures(in: match.string, with: autoCorrectReplacement) return AutoCorrection(before: match.string, after: newMatchString) }() if let autoCorrection = autoCorrection { guard match.string != autoCorrection.after else { // can skip auto-correction & violation reporting because auto-correct replacement is equal to matched string continue } // apply auto correction newFileContents.replaceSubrange(match.range, with: autoCorrection.after) log.message("Applied autocorrection for last match ...", level: .debug) } log.message("Reporting violation for \(checkInfo) in file \(filePath) at \(locationInfo) ...", level: .debug) violations.append( Violation( checkInfo: checkInfo, filePath: filePath, matchedString: match.string, locationInfo: locationInfo, appliedAutoCorrection: autoCorrection ) ) } if newFileContents != fileContents { log.message("Rewriting contents of file \(filePath) due to autocorrection changes ...", level: .debug) try newFileContents.write(toFile: filePath, atomically: true, encoding: .utf8) } } else { log.message( "Could not read contents of file at \(filePath). Make sure it is a text file and is formatted as UTF8.", level: .warning ) } Statistics.shared.checkedFiles(at: [filePath]) } violations = violations.reversed() if repeatIfAutoCorrected && violations.contains(where: { $0.appliedAutoCorrection != nil }) { log.message("Repeating check \(checkInfo) because auto-corrections were applied on last run.", level: .debug) // only paths where auto-corrections were applied need to be re-checked let filePathsToReCheck = Array(Set(violations.filter { $0.appliedAutoCorrection != nil }.map { $0.filePath! })).sorted() let violationsOnRechecks = try FileContentsChecker( checkInfo: checkInfo, regex: regex, filePathsToCheck: filePathsToReCheck, autoCorrectReplacement: autoCorrectReplacement, repeatIfAutoCorrected: repeatIfAutoCorrected ).performCheck() violations.append(contentsOf: violationsOnRechecks) } return violations } }
48.256881
140
0.569772
c1cdf7c6c160c37dcca82bc02ade9fe6cb6644eb
1,239
// // RealmDemoUITests.swift // RealmDemoUITests // // Created by angcyo on 16/08/20. // Copyright © 2016年 angcyo. All rights reserved. // import XCTest class RealmDemoUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.486486
182
0.662631
238743d53fcebaf154aa216f1823776cc3ca2a3e
1,764
// // NSDate+Extension.swift // Floral // // Created by ALin on 16/4/12. // Copyright © 2016年 ALin. All rights reserved. // import UIKit extension NSDate { class func dateWithstr(dateStr: String) -> NSDate? { let formatter = NSDateFormatter() // 2016-04-24 15:10:24.0 formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // 有的时候, 有的服务器生成的时间是采用的其他地区或者语音,这种情况, 一定要设置本地化, 比如这儿的Aug, 如果你不设置成en, 那么鬼才知道你要解析成什么样的. // formatter.locale = NSLocale(localeIdentifier: "en") return formatter.dateFromString(dateStr) } // 分类中可以直接添加计算型属性, 因为他不需要分配存储空间 var dateDesc : String{ let formatter = NSDateFormatter() var formatterStr : String? let calendar = NSCalendar.currentCalendar() if calendar.isDateInToday(self){ let seconds = (Int)(NSDate().timeIntervalSinceDate(self)) if seconds < 60{ return "刚刚" }else if seconds < 60 * 60{ return "\(seconds/60)分钟前" }else{ return "\(seconds/60/60)小时前" } }else if calendar.isDateInYesterday(self){ // 昨天: 昨天 17:xx formatterStr = "昨天 HH:mm" }else{ // 很多年前: 2014-12-14 17:xx // 如果枚举可以选择多个, 就用数组[]包起来, 如果为空, 就直接一个空数组 let components = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: []) // 今年: 03-15 17:xx if components.year < 1 { formatterStr = "MM-dd HH:mm" }else{ formatterStr = "yyyy-MM-dd HH:mm" } } formatter.dateFormat = formatterStr return formatter.stringFromDate(self) } }
30.947368
116
0.551587
48a9133d65cd9334ad5753d4a3e889d7078fdcf2
267
public enum AttributeError: Swift.Error { case badInput(Any?) case badAttribute(Context) // MARK: Public public struct Context { public let name: String public let entity: String public let originalError: Swift.Error } }
20.538462
45
0.64794
465d1eac98148fbcb8bf3424453beaaf624b8c3c
2,464
// // KayacClockContainerView.swift // MustangClock // // Created by ryu-ushin on 4/14/15. // Copyright (c) 2015 rain. All rights reserved. // import UIKit @IBDesignable public class SmileClockContainerView: UIView { @IBInspectable public var bgColor: UIColor = .black @IBInspectable public var graduationColor: UIColor = .white @IBInspectable public var fontColor: UIColor = .white @IBInspectable public var handColor: UIColor = .white @IBInspectable public var secHandColor: UIColor = .yellow @IBInspectable public var clockStyleNum: Int = 3 @IBInspectable public var hour: Int = 9 @IBInspectable public var minute: Int = 30 @IBInspectable public var second: Int = 7 public var bgImage: UIImage? public var hourHandImage: UIImage? public var minHandImage: UIImage? public var secHandImage: UIImage? public var centerImage: UIImage? public var clockView: SmileClockView! #if TARGET_INTERFACE_BUILDER public override func willMove(toSuperview newSuperview: UIView?) { addClockView() } #else override public func awakeFromNib() { super.awakeFromNib() addClockView() } #endif public func updateClockView() { clockView.removeFromSuperview() addClockView() } private func addClockView() { self.backgroundColor = UIColor.clear clockView = SmileClockView(frame: self.bounds) clockView.clockStyle = safeSetClockStyle(styleNum: clockStyleNum) clockView.bgColor = bgColor clockView.graduationColor = graduationColor clockView.handColor = handColor clockView.secHandColor = secHandColor clockView.fontColor = fontColor clockView.hour = hour clockView.minute = minute clockView.second = second clockView.bgImage = bgImage clockView.centerImage = centerImage clockView.hourHandImage = hourHandImage clockView.minHandImage = minHandImage clockView.secHandImage = secHandImage clockView.updateClockViewLayers() self.addSubview(clockView) } func safeSetClockStyle(styleNum: Int) -> ClockStyle { if clockStyleNum > ClockStyle.count() || clockStyleNum < 0 { clockStyleNum = 0 } else { clockStyleNum = styleNum } return ClockStyle(rawValue: clockStyleNum)! } }
30.04878
73
0.665179
381d8aa48a26238d082d666238df634faabe71be
390
// // PlayNowProtocol.swift // QBKalturaPlayer // // Created by Anton Kononenko on 12/15/20. // Copyright © 2020 Applicaster. All rights reserved. // import Foundation @objc protocol PlayNowProtocol: AnyObject { func preparePlayNowService() func releasePlayNowService() func setNewPlayNowRateDescription(newRate: Float) func applicationWillTerminateReleasePlayNow() }
22.941176
54
0.75641
2f65ff18e7a9a27319737cbb8ae088fb057bdb8c
11,973
// // main.swift // jailbreakd // // Created by Linus Henze. // Copyright © 2021 Linus Henze. All rights reserved. // import Foundation import KernelExploit import externalCStuff import asmAndC // AltStore builds should have this option set to true // This will cause a message to be shown after installing the untether let altStoreBuild = false var pe: PostExploitation! @_cdecl("init_libkrw_support") func init_libkrw_support() -> Int32 { guard pe != nil else { return 999 } return pe!.initKrwSupport() } @discardableResult func run(prog: String, args: [String]) -> Bool { var argv = [strdup(prog)] for a in args { argv.append(strdup(a)) } argv.append(nil) defer { for a in argv { if a != nil { free(a) } } } typealias fType = @convention(c) () -> pid_t let fork = unsafeBitCast(dlsym(dlopen(nil, 0), "fork"), to: fType.self) let child: pid_t = fork() if child == 0 { execv(prog, &argv) puts("Failed to exec: \(String(cString: strerror(errno)))") exit(-1) } waitpid(child, nil, 0) return true } @discardableResult func runWithKCreds(pe: PostExploitation, prog: String, args: [String]) -> Bool { var argv = [strdup(prog)] for a in args { argv.append(strdup(a)) } argv.append(nil) defer { for a in argv { if a != nil { free(a) } } } var spawnattr: posix_spawnattr_t? posix_spawnattr_init(&spawnattr) posix_spawnattr_setflags(&spawnattr, Int16(POSIX_SPAWN_START_SUSPENDED)) var child: pid_t = 0 let res = posix_spawn(&child, prog, nil, &spawnattr, argv, environ) if res != 0 { return false } usleep(10000) var cur = Proc.getFirstProc(pe: pe) while cur != nil { if cur.unsafelyUnwrapped.pid == child { Logger.print("Found child, giving creds") let res = (try? pe.giveKernelCreds(toProc: cur.unsafelyUnwrapped)) == nil ? false : true Logger.print("Status: \(res)") break } cur = cur.unsafelyUnwrapped.next } kill(child, SIGCONT) waitpid(child, nil, 0) return true } @discardableResult func showMessage(withOptions options: [CFString: NSObject]) -> CFOptionFlags { while true { var err: Int32 = 0 let notif = CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &err, options as CFDictionary) guard notif != nil && err == 0 else { sleep(1) continue } var response: CFOptionFlags = 0 CFUserNotificationReceiveResponse(notif, 0, &response) guard (response & 0x3) != kCFUserNotificationCancelResponse else { sleep(1) continue } return response & 0x3 } } func showSimpleMessage(withTitle title: String, andMessage message: String) { showMessage(withOptions: [ kCFUserNotificationAlertTopMostKey: 1 as NSNumber, kCFUserNotificationAlertHeaderKey: title as NSString, kCFUserNotificationAlertMessageKey: message as NSString ]) } func doInstall(pe: PostExploitation) { let result = pe.install() switch result { case .rebootRequired: showMessage(withOptions: [ kCFUserNotificationAlertTopMostKey: 1 as NSNumber, kCFUserNotificationAlertHeaderKey: "Reboot required" as NSString, kCFUserNotificationAlertMessageKey: "Fugu14 successfully installed the untether. To complete the installation, your device needs to be rebooted." as NSString, kCFUserNotificationDefaultButtonTitleKey: "Reboot now" as NSString ]) reboot(0) exit(0) case .ok: showSimpleMessage(withTitle: "Already installed", andMessage: "Fugu14 has already been installed. Please restore the root fs if you're experienceing any problems.") exit(0) case .otaAlreadyMounted: showSimpleMessage(withTitle: "OTA already mounted", andMessage: "Fugu14 could not be installed because an OTA update is already mounted. Please remove the update, reboot and run the installer again.") exit(0) case .failed(reason: let reason): showSimpleMessage(withTitle: "Failed to install untether", andMessage: "The untether failed to install. Error: \(reason)") exit(0) } } func doUninstall() { let result = PostExploitation.uninstall() switch result { case .rebootRequired: showMessage(withOptions: [ kCFUserNotificationAlertTopMostKey: 1 as NSNumber, kCFUserNotificationAlertHeaderKey: "Reboot required" as NSString, kCFUserNotificationAlertMessageKey: "To complete the uninstallation of Fugu14, your device needs to be rebooted." as NSString, kCFUserNotificationDefaultButtonTitleKey: "Reboot now" as NSString ]) reboot(0) exit(0) case .noRestoreRequired: showSimpleMessage(withTitle: "Not installed", andMessage: "Fugu14 could not be uninstalled because it is not installed.") exit(0) case .failed(reason: let reason): showSimpleMessage(withTitle: "Failed to uninstall", andMessage: "Fugu14 could not be uninstalled. Error: \(reason)") exit(0) } } func doSilentUninstall() { let result = PostExploitation.uninstall() switch result { case .rebootRequired: reboot(0) default: break } } func serverMain(pe: PostExploitation) -> Never { let controlIn = FileHandle(fileDescriptor: Int32(CommandLine.arguments[2])!, closeOnDealloc: true) let controlOut = FileHandle(fileDescriptor: Int32(CommandLine.arguments[3])!, closeOnDealloc: true) let comm = ProcessCommunication(read: controlIn, write: controlOut) while true { guard let cmd = comm.receiveArg() else { // Probably broken pipe exit(-1) } switch cmd { case "ping": comm.sendArg("pong") case "install": Logger.print("Received install request!") doInstall(pe: pe) case "uninstall": Logger.print("Received uninstall request!") doUninstall() default: Logger.print("Received unknown command \(cmd)!") } } } if getuid() != 0 { // Not root, UI Process // Do UI stuff // Remove old closures first let cacheDir = String(cString: getenv("HOME")) + "/Library/Caches/com.apple.dyld" if let closures = try? FileManager.default.contentsOfDirectory(atPath: cacheDir) { for c in closures { if c != "." && c != ".." && !c.hasSuffix(".closure") { try? FileManager.default.removeItem(at: URL(fileURLWithPath: c, relativeTo: URL(fileURLWithPath: cacheDir))) } } } JailbreakdApp.main() fatalError("AppDelegate.main() returned!") } if CommandLine.arguments.count < 2 { Logger.print("Didn't receive any arguments, I don't know what to do!") fatalError("Didn't receive any arguments, I don't know what to do!") } var action = CommandLine.arguments[1] if action == "ping" { // Launched from App only to attach signature // Do nothing Logger.print("pong") exit(0) } else if action == "uninstall" { doUninstall() exit(0) } else if action == "doNothing" { dispatchMain() } else if action != "server" { setsid() } else { let logOut = FileHandle(fileDescriptor: Int32(CommandLine.arguments[4])!, closeOnDealloc: true) Logger.logFileHandle = logOut } if action == "untether" { if access("/", W_OK) == 0 { // Untether already ran, sleep forever // Try to replace service to prevent us from being launched again run(prog: "/.Fugu14Untether/bin/launchctl", args: ["unload", "/System/Library/LaunchDaemons/com.apple.analyticsd.plist"]) run(prog: "/.Fugu14Untether/bin/launchctl", args: ["load", "/Library/LaunchDaemons/com.apple.analyticsd.plist"]) dispatchMain() } let state = getUntetherState() if state == .disabled { // Sleep forever dispatchMain() } else if state == .forceRestore { action = "silent_uninstall" } } do { pe = try PostExploitation() } catch MemoryAccessError.failedToInitialize { execv(Bundle.main.executablePath, CommandLine.unsafeArgv) fatalError("Failed to re-exec myself!") } catch let e { Logger.print("Failed to initialize a PostExploitation object") Logger.print("Error: \(e)") fatalError("Error: \(e)") } switch action { case "untether": // First of all, inject trust cache pe.unsafelyUnwrapped.injectTC(path: "/.Fugu14Untether/trustcache") // Now replace service run(prog: "/.Fugu14Untether/bin/launchctl", args: ["unload", "/System/Library/LaunchDaemons/com.apple.analyticsd.plist"]) run(prog: "/.Fugu14Untether/bin/launchctl", args: ["load", "/Library/LaunchDaemons/com.apple.analyticsd.plist"]) // Attempt to mount, then launch jailbreak server if case .ok = pe.unsafelyUnwrapped.untether() { do { // See if we should load custom trust caches if let autorun = try? FileManager.default.contentsOfDirectory(atPath: "/.Fugu14Untether/trustcaches/") { for exe in autorun { let path = "/.Fugu14Untether/trustcaches/" + exe if access(path, R_OK) == 0 { // Inject it pe.unsafelyUnwrapped.injectTC(path: path) } } } // See if we have any autorun executables if let autorun = try? FileManager.default.contentsOfDirectory(atPath: "/.Fugu14Untether/autorun/") { for exe in autorun { let path = "/.Fugu14Untether/autorun/" + exe if access(path, X_OK) == 0 { // Execute it var child: pid_t = 0 _ = path.withCString { cPath in posix_spawn(&child, path, nil, nil, [UnsafeMutablePointer<CChar>(mutating: cPath), nil], environ) } } } } // Deinit kernel call, not required anymore pe.unsafelyUnwrapped.deinitKernelCall() // Check if we should show AltStore message if access("/.Fugu14Untether/.AltStoreInstall", F_OK) == 0 { showSimpleMessage(withTitle: "Untether installed", andMessage: "To continue installing your jailbreak, please open AltStore and follow the instructions.") unlink("/.Fugu14Untether/.AltStoreInstall") } // Also launch iDownload launchCServer() dispatchMain() } /*catch let e { Logger.print("Failed to start server: \(e)") }*/ } else { Logger.print("Remount failed!") } case "uninstall": // Restore RootFS and remove other stuff doUninstall() case "silent_uninstall": doSilentUninstall() dispatchMain() case "server": serverMain(pe: pe.unsafelyUnwrapped) // Stuff below is useful on the SRD case "install": doInstall(pe: pe.unsafelyUnwrapped) case "remount": pe.unsafelyUnwrapped.mountOnly() case "loadTC": if CommandLine.arguments.count < 3 { Logger.print("Usage: jailbreakd loadTC <path_to_trust_cache>") exit(-1) } pe.unsafelyUnwrapped.injectTC(path: CommandLine.arguments[2]) pe.unsafelyUnwrapped.deinitKernelCall() default: Logger.print("Unknown action \(action)!") } pe.unsafelyUnwrapped.killMe()
31.758621
208
0.611042
893e0e29f79711ab78fe1e732803c9b056ae28d0
679
// // Banner.swift // ETV // // Created by Heisenbean on 16/9/30. // Copyright © 2016年 Heisenbean. All rights reserved. // import UIKit class Banner: NSObject { var title : String? var smallimg : String? var bigimg : String? init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } class func banners(_ dictArray: [[String: AnyObject]]) -> [Banner]? { if dictArray.count == 0{ return nil } var banners = [Banner]() for d in dictArray { banners.append(Banner(dict: d)) } return banners } }
17.410256
73
0.515464
64c6aea3c82eaa32e6784e514e9d7984360963dd
18,030
// // Fraction.swift // Fraction // // Created by Noah Wilder on 2018-11-27. // Copyright © 2018 Noah Wilder. All rights reserved. // import Foundation // Precedence of exponent operator precedencegroup ExponentPrecedence { associativity: left higherThan: MultiplicationPrecedence lowerThan: BitwiseShiftPrecedence assignment: false } // Declaration of exponent operators infix operator **: ExponentPrecedence infix operator **=: AssignmentPrecedence /// A fraction consisting of a `numerator` and a `denominator` public struct Fraction { // Private stored properties private var _numerator: Int private var _denominator: Int // Stored property accessors public var numerator: Int { get { return _numerator } set { _numerator = newValue _adjustFraction() } } public var denominator: Int { get { return _denominator } set { precondition(denominator != 0, "Cannot divide by 0") _denominator = newValue _adjustFraction() } } public private(set) var signum: Int = 1 // Initializers public init(num: Int, den: Int) { precondition(den != 0, "Cannot divide by 0") self._numerator = num self._denominator = den _adjustFraction() } public init(_ numerator: Int, _ denominator: Int) { self.init(num: numerator, den: denominator) } public init(_ n: Int) { self.init(num: n, den: 1) } public init(_ n: Double) { var nArr = "\(n)".split(separator: ".") let decimal = (pre: Int(nArr[0])!, post: Int(nArr[1])!) let sign = n < 0.0 ? -1 : 1 guard decimal.post != 0 else { self.init(num: sign * decimal.pre, den: 1) return } let den = Int(pow(10.0, Double(nArr[1].count))) self.init(num: sign * (decimal.post + abs(decimal.pre) * den), den: den) } public init(_ n: Float) { self.init(Double(n)) } // Constants public static let max = Int.max public static let min = Int.min public static let zero = Fraction(num: 0, den: 1) // Computed properties public var decimal: Double { return Double(numerator) / Double(denominator) } public var isWholeNumber: Bool { return denominator == 1 || numerator == 0 } // Binary arithmetic operators // Private functions private mutating func _adjustFraction() { self._setSignum() self._simplifyFraction() } private mutating func _simplifyFraction() { guard self._numerator != 0 && abs(self._numerator) != 1 && self._denominator != 1 else { return } for n in (2...Swift.min(abs(self._numerator), abs(self._denominator))).reversed() { if self._numerator % n == 0 && self._denominator % n == 0 { self._numerator /= n self._denominator /= n return } } } private mutating func _setSignum() { guard _numerator != 0 else { signum = 0 return } switch _denominator.signum() + _numerator.signum() { case -2: _denominator = abs(_denominator) _numerator = abs(_numerator) signum = 1 case 0: signum = -1 if _numerator.signum() == 1 { _numerator *= -1 _denominator *= -1 } case 2: signum = 1 default: break } } } // Protocol Conformances extension Fraction: CustomStringConvertible { public var description: String { guard denominator != 1 && numerator != 0 else { return "\(numerator)" } return "\(numerator)/\(denominator)" } } extension Fraction: Equatable { public static func == (lhs: Fraction, rhs: Fraction) -> Bool { return lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator } } extension Fraction: Comparable { public static func < (lhs: Fraction, rhs: Fraction) -> Bool { return Double(lhs.numerator) / Double(lhs.denominator) < Double(rhs.numerator) / Double(rhs.denominator) } } extension Fraction: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = Int public init(integerLiteral value: Int) { self.init(num: value, den: 1) } } extension Fraction: ExpressibleByFloatLiteral { public typealias FloatLiteralType = Double public init(floatLiteral value: Double) { self.init(value) } } extension Fraction: Numeric { public var magnitude: Fraction { return self * self.signum } public typealias Magnitude = Fraction public init?<T>(exactly source: T) where T : BinaryInteger { guard let n = Int(exactly: source) else { return nil } self.init(num: n, den: 1) } // Binary arithmetic operators public static func + (lhs: Fraction, rhs: Fraction) -> Fraction { return Fraction(num: (lhs.numerator * rhs.denominator) + (rhs.numerator * lhs.denominator), den: lhs.denominator * rhs.denominator) } public static func - (lhs: Fraction, rhs: Fraction) -> Fraction { return Fraction(num: lhs.numerator * rhs.denominator - rhs.numerator * lhs.denominator, den: lhs.denominator * rhs.denominator) } public static func * (lhs: Fraction, rhs: Fraction) -> Fraction { return Fraction(num: lhs.numerator * rhs.numerator, den: lhs.denominator * rhs.denominator) } public static func / (lhs: Fraction, rhs: Fraction) -> Fraction { precondition(rhs.numerator != 0, "Cannot divide by 0") return Fraction(num: lhs.numerator * rhs.denominator, den: lhs.denominator * rhs.numerator) } public static func ** (lhs: Fraction, rhs: Fraction) -> Fraction { return Fraction(num: Int(pow(Double(lhs.numerator), rhs.decimal)), den: Int(pow(Double(lhs.denominator), rhs.decimal))) } // Compound assignment operators public static func += (lhs: inout Fraction, rhs: Fraction) { lhs = lhs + rhs } public static func -= (lhs: inout Fraction, rhs: Fraction) { lhs = lhs - rhs } public static func *= (lhs: inout Fraction, rhs: Fraction) { lhs = lhs * rhs } public static func /= (lhs: inout Fraction, rhs: Fraction) { lhs = lhs / rhs } public static func **= (lhs: inout Fraction, rhs: Fraction) { lhs = lhs ** rhs } } extension Fraction: SignedNumeric { public mutating func negate() { self.numerator = -self.numerator } } extension Fraction: Strideable { public typealias Stride = Fraction public func distance(to other: Fraction) -> Fraction { return other - self } public func advanced(by n: Fraction) -> Fraction { return self + n } } // Additional Operators (equality, comparison, arithmetic) extension Fraction { // Equality operators with Int, Double, and Float public static func == (lhs: Fraction, rhs: Double) -> Bool { return lhs.decimal == rhs } public static func == (lhs: Fraction, rhs: Float) -> Bool { return Float(lhs.decimal) == rhs } public static func == (lhs: Fraction, rhs: Int) -> Bool { return (lhs.numerator == 0 && rhs == 0) || (lhs.denominator == 1 && lhs.numerator == rhs) } public static func == (lhs: Double, rhs: Fraction) -> Bool { return lhs == rhs.decimal } public static func == (lhs: Float, rhs: Fraction) -> Bool { return lhs == Float(rhs.decimal) } public static func == (lhs: Int, rhs: Fraction) -> Bool { return (rhs.numerator == 0 && lhs == 0) || (rhs.denominator == 1 && rhs.numerator == lhs) } // Comparison operators with Double public static func < (lhs: Fraction, rhs: Double) -> Bool { return lhs.decimal < rhs } public static func > (lhs: Fraction, rhs: Double) -> Bool { return !(lhs <= rhs) } public static func <= (lhs: Fraction, rhs: Double) -> Bool { return lhs < rhs || lhs == rhs } public static func >= (lhs: Fraction, rhs: Double) -> Bool { return !(lhs < rhs) } public static func < (lhs: Double, rhs: Fraction) -> Bool { return lhs < rhs.decimal } public static func > (lhs: Double, rhs: Fraction) -> Bool { return !(lhs <= rhs) } public static func <= (lhs: Double, rhs: Fraction) -> Bool { return lhs < rhs || lhs == rhs } public static func >= (lhs: Double, rhs: Fraction) -> Bool { return !(lhs < rhs) } // Comparison operators with Int public static func < (lhs: Fraction, rhs: Int) -> Bool { return lhs.decimal < Double(rhs) } public static func > (lhs: Fraction, rhs: Int) -> Bool { return !(lhs <= rhs) } public static func <= (lhs: Fraction, rhs: Int) -> Bool { return lhs < rhs || lhs == rhs } public static func >= (lhs: Fraction, rhs: Int) -> Bool { return !(lhs < rhs) } public static func < (lhs: Int, rhs: Fraction) -> Bool { return Double(lhs) < rhs.decimal } public static func > (lhs: Int, rhs: Fraction) -> Bool { return !(lhs <= rhs) } public static func <= (lhs: Int, rhs: Fraction) -> Bool { return lhs < rhs || lhs == rhs } public static func >= (lhs: Int, rhs: Fraction) -> Bool { return !(lhs < rhs) } // Comparison operators with Float public static func < (lhs: Fraction, rhs: Float) -> Bool { return Float(lhs.decimal) < rhs } public static func > (lhs: Fraction, rhs: Float) -> Bool { return !(lhs <= rhs) } public static func <= (lhs: Fraction, rhs: Float) -> Bool { return lhs < rhs || lhs == rhs } public static func >= (lhs: Fraction, rhs: Float) -> Bool { return !(lhs < rhs) } public static func < (lhs: Float, rhs: Fraction) -> Bool { return lhs < Float(rhs.decimal) } public static func > (lhs: Float, rhs: Fraction) -> Bool { return !(lhs <= rhs) } public static func <= (lhs: Float, rhs: Fraction) -> Bool { return lhs < rhs || lhs == rhs } public static func >= (lhs: Float, rhs: Fraction) -> Bool { return !(lhs < rhs) } // Arithmetic operators with Int public static func + (lhs: Fraction, rhs: Int) -> Fraction { return Fraction(num: lhs.numerator + (rhs * lhs.denominator), den: lhs.denominator) } public static func - (lhs: Fraction, rhs: Int) -> Fraction { return Fraction(num: lhs.numerator - rhs * lhs.denominator, den: lhs.denominator) } public static func * (lhs: Fraction, rhs: Int) -> Fraction { return Fraction(num: lhs.numerator * rhs, den: lhs.denominator) } public static func / (lhs: Fraction, rhs: Int) -> Fraction { precondition(rhs != 0, "Cannot divide by 0") return Fraction(num: lhs.numerator, den: lhs.denominator * rhs) } public static func ** (lhs: Fraction, rhs: Int) -> Fraction { return Fraction(num: Int(pow(Double(lhs.numerator), Double(rhs))), den: Int(pow(Double(lhs.denominator), Double(rhs)))) } public static func + (lhs: Int, rhs: Fraction) -> Fraction { return Fraction(num: lhs * rhs.denominator + rhs.numerator, den: rhs.denominator) } public static func - (lhs: Int, rhs: Fraction) -> Fraction { return Fraction(num: lhs * rhs.denominator - rhs.numerator, den: rhs.denominator) } public static func * (lhs: Int, rhs: Fraction) -> Fraction { return Fraction(num: lhs * rhs.numerator, den: rhs.denominator) } public static func / (lhs: Int, rhs: Fraction) -> Fraction { precondition(rhs.numerator != 0, "Cannot divide by 0") return Fraction(num: lhs * rhs.denominator, den: rhs.numerator) } public static func += (lhs: inout Fraction, rhs: Int) { lhs = lhs + rhs } public static func -= (lhs: inout Fraction, rhs: Int) { lhs = lhs - rhs } public static func *= (lhs: inout Fraction, rhs: Int) { lhs = lhs * rhs } public static func /= (lhs: inout Fraction, rhs: Int) { lhs = lhs / rhs } public static func **= (lhs: inout Fraction, rhs: Int) { return lhs = lhs ** rhs } // Arithmetic operators with Double public static func + (lhs: Fraction, rhs: Double) -> Fraction { return lhs + Fraction(rhs) } public static func - (lhs: Fraction, rhs: Double) -> Fraction { return lhs - Fraction(rhs) } public static func * (lhs: Fraction, rhs: Double) -> Fraction { return lhs * Fraction(rhs) } public static func / (lhs: Fraction, rhs: Double) -> Fraction { precondition(rhs != 0.0, "Cannot divide by 0") return lhs / Fraction(rhs) } public static func ** (lhs: Fraction, rhs: Double) -> Fraction { return Fraction(num: Int(pow(Double(lhs.numerator), rhs)), den: Int(pow(Double(lhs.denominator), rhs))) } public static func + (lhs: Double, rhs: Fraction) -> Fraction { return Fraction(lhs) + rhs } public static func - (lhs: Double, rhs: Fraction) -> Fraction { return Fraction(lhs) - rhs } public static func * (lhs: Double, rhs: Fraction) -> Fraction { return Fraction(lhs) * rhs } public static func / (lhs: Double, rhs: Fraction) -> Fraction { precondition(rhs.numerator != 0, "Cannot divide by 0") return Fraction(lhs) / rhs } public static func += (lhs: inout Fraction, rhs: Double) { lhs = lhs + rhs } public static func -= (lhs: inout Fraction, rhs: Double) { lhs = lhs - rhs } public static func *= (lhs: inout Fraction, rhs: Double) { lhs = lhs * rhs } public static func /= (lhs: inout Fraction, rhs: Double) { lhs = lhs / rhs } public static func **= (lhs: inout Fraction, rhs: Double) { return lhs = lhs ** rhs } // Arithmetic operators with Float public static func + (lhs: Fraction, rhs: Float) -> Fraction { return lhs + Fraction(rhs) } public static func - (lhs: Fraction, rhs: Float) -> Fraction { return lhs - Fraction(rhs) } public static func * (lhs: Fraction, rhs: Float) -> Fraction { return lhs * Fraction(rhs) } public static func / (lhs: Fraction, rhs: Float) -> Fraction { precondition(rhs != 0.0, "Cannot divide by 0") return lhs / Fraction(rhs) } public static func ** (lhs: Fraction, rhs: Float) -> Fraction { return Fraction(num: Int(pow(Double(lhs.numerator), Double(rhs))), den: Int(pow(Double(lhs.denominator), Double(rhs)))) } public static func + (lhs: Float, rhs: Fraction) -> Fraction { return Fraction(lhs) + rhs } public static func - (lhs: Float, rhs: Fraction) -> Fraction { return Fraction(lhs) - rhs } public static func * (lhs: Float, rhs: Fraction) -> Fraction { return Fraction(lhs) * rhs } public static func / (lhs: Float, rhs: Fraction) -> Fraction { precondition(rhs.numerator != 0, "Cannot divide by 0") return Fraction(lhs) / rhs } public static func += (lhs: inout Fraction, rhs: Float) { lhs = lhs + rhs } public static func -= (lhs: inout Fraction, rhs: Float) { lhs = lhs - rhs } public static func *= (lhs: inout Fraction, rhs: Float) { lhs = lhs * rhs } public static func /= (lhs: inout Fraction, rhs: Float) { lhs = lhs / rhs } public static func **= (lhs: inout Fraction, rhs: Float) { return lhs = lhs ** rhs } } // Extensions of numeric types to integrate Fraction public extension Int { public init (_ fraction: Fraction) { self = fraction.numerator / fraction.denominator } } public extension Double { public init (_ fraction: Fraction) { self = Double(fraction.numerator) / Double(fraction.denominator) } public static func += (lhs: inout Double, rhs: Fraction) { lhs = lhs + rhs.decimal } public static func -= (lhs: inout Double, rhs: Fraction) { lhs = lhs - rhs.decimal } public static func *= (lhs: inout Double, rhs: Fraction) { lhs = lhs * rhs.decimal } public static func /= (lhs: inout Double, rhs: Fraction) { lhs = lhs / rhs.decimal } } public extension Float { public init (_ fraction: Fraction) { self = Float(fraction.numerator) / Float(fraction.denominator) } }
29.509002
112
0.547421
8772ac44d260955bb81310b84128ff25d556bba9
15,294
import Foundation public struct TargetAction: Codable, Equatable { /// Order when the action gets executed. /// /// - pre: Before the sources and resources build phase. /// - post: After the sources and resources build phase. public enum Order: String, Codable, Equatable { case pre case post } /// Name of the build phase when the project gets generated. public let name: String /// Name of the tool to execute. Tuist will look up the tool on the environment's PATH. public let tool: String? /// Path to the script to execute. public let path: Path? /// Target action order. public let order: Order /// Arguments that to be passed. public let arguments: [String] /// List of input file paths public let inputPaths: [Path] /// List of input filelist paths public let inputFileListPaths: [Path] /// List of output file paths public let outputPaths: [Path] /// List of output filelist paths public let outputFileListPaths: [Path] public enum CodingKeys: String, CodingKey { case name case tool case path case order case arguments case inputPaths case inputFileListPaths case outputPaths case outputFileListPaths } /// Initializes the target action with its attributes. /// /// - Parameters: /// - name: Name of the build phase when the project gets generated. /// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH. /// - path: Path to the script to execute. /// - order: Target action order. /// - arguments: Arguments that to be passed. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. init(name: String, tool: String?, path: Path?, order: Order, arguments: [String], inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) { self.name = name self.path = path self.tool = tool self.order = order self.arguments = arguments self.inputPaths = inputPaths self.inputFileListPaths = inputFileListPaths self.outputPaths = outputPaths self.outputFileListPaths = outputFileListPaths } /// Returns a target action that gets executed before the sources and resources build phase. /// /// - Parameters: /// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH. /// - arguments: Arguments that to be passed. /// - name: Name of the build phase when the project gets generated. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. /// - Returns: Target action. public static func pre(tool: String, arguments: String..., name: String, inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) -> TargetAction { TargetAction(name: name, tool: tool, path: nil, order: .pre, arguments: arguments, inputPaths: inputPaths, inputFileListPaths: inputFileListPaths, outputPaths: outputPaths, outputFileListPaths: outputFileListPaths) } /// Returns a target action that gets executed before the sources and resources build phase. /// /// - Parameters: /// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH. /// - arguments: Arguments that to be passed. /// - name: Name of the build phase when the project gets generated. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. /// - Returns: Target action. public static func pre(tool: String, arguments: [String], name: String, inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) -> TargetAction { TargetAction(name: name, tool: tool, path: nil, order: .pre, arguments: arguments, inputPaths: inputPaths, inputFileListPaths: inputFileListPaths, outputPaths: outputPaths, outputFileListPaths: outputFileListPaths) } /// Returns a target action that gets executed before the sources and resources build phase. /// /// - Parameters: /// - path: Path to the script to execute. /// - arguments: Arguments that to be passed. /// - name: Name of the build phase when the project gets generated. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. /// - Returns: Target action. public static func pre(path: Path, arguments: String..., name: String, inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) -> TargetAction { TargetAction(name: name, tool: nil, path: path, order: .pre, arguments: arguments, inputPaths: inputPaths, inputFileListPaths: inputFileListPaths, outputPaths: outputPaths, outputFileListPaths: outputFileListPaths) } /// Returns a target action that gets executed before the sources and resources build phase. /// /// - Parameters: /// - path: Path to the script to execute. /// - arguments: Arguments that to be passed. /// - name: Name of the build phase when the project gets generated. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. /// - Returns: Target action. public static func pre(path: Path, arguments: [String], name: String, inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) -> TargetAction { TargetAction(name: name, tool: nil, path: path, order: .pre, arguments: arguments, inputPaths: inputPaths, inputFileListPaths: inputFileListPaths, outputPaths: outputPaths, outputFileListPaths: outputFileListPaths) } /// Returns a target action that gets executed after the sources and resources build phase. /// /// - Parameters: /// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH. /// - arguments: Arguments that to be passed. /// - name: Name of the build phase when the project gets generated. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. /// - Returns: Target action. public static func post(tool: String, arguments: String..., name: String, inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) -> TargetAction { TargetAction(name: name, tool: tool, path: nil, order: .post, arguments: arguments, inputPaths: inputPaths, inputFileListPaths: inputFileListPaths, outputPaths: outputPaths, outputFileListPaths: outputFileListPaths) } /// Returns a target action that gets executed after the sources and resources build phase. /// /// - Parameters: /// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH. /// - arguments: Arguments that to be passed. /// - name: Name of the build phase when the project gets generated. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. /// - Returns: Target action. public static func post(tool: String, arguments: [String], name: String, inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) -> TargetAction { TargetAction(name: name, tool: tool, path: nil, order: .post, arguments: arguments, inputPaths: inputPaths, inputFileListPaths: inputFileListPaths, outputPaths: outputPaths, outputFileListPaths: outputFileListPaths) } /// Returns a target action that gets executed after the sources and resources build phase. /// /// - Parameters: /// - path: Path to the script to execute. /// - arguments: Arguments that to be passed. /// - name: Name of the build phase when the project gets generated. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. /// - Returns: Target action. public static func post(path: Path, arguments: String..., name: String, inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) -> TargetAction { TargetAction(name: name, tool: nil, path: path, order: .post, arguments: arguments, inputPaths: inputPaths, inputFileListPaths: inputFileListPaths, outputPaths: outputPaths, outputFileListPaths: outputFileListPaths) } /// Returns a target action that gets executed after the sources and resources build phase. /// /// - Parameters: /// - path: Path to the script to execute. /// - arguments: Arguments that to be passed. /// - name: Name of the build phase when the project gets generated. /// - inputPaths: List of input file paths. /// - inputFileListPaths: List of input filelist paths. /// - outputPaths: List of output file paths. /// - outputFileListPaths: List of output filelist paths. /// - Returns: Target action. public static func post(path: Path, arguments: [String], name: String, inputPaths: [Path] = [], inputFileListPaths: [Path] = [], outputPaths: [Path] = [], outputFileListPaths: [Path] = []) -> TargetAction { TargetAction(name: name, tool: nil, path: path, order: .post, arguments: arguments, inputPaths: inputPaths, inputFileListPaths: inputFileListPaths, outputPaths: outputPaths, outputFileListPaths: outputFileListPaths) } // MARK: - Codable public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) order = try container.decode(Order.self, forKey: .order) arguments = try container.decode([String].self, forKey: .arguments) inputPaths = try container.decodeIfPresent([Path].self, forKey: .inputPaths) ?? [] inputFileListPaths = try container.decodeIfPresent([Path].self, forKey: .inputFileListPaths) ?? [] outputPaths = try container.decodeIfPresent([Path].self, forKey: .outputPaths) ?? [] outputFileListPaths = try container.decodeIfPresent([Path].self, forKey: .outputFileListPaths) ?? [] if let path = try container.decodeIfPresent(Path.self, forKey: .path) { self.path = path tool = nil } else { path = nil tool = try container.decode(String.self, forKey: .tool) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(order, forKey: .order) try container.encode(arguments, forKey: .arguments) try container.encode(inputPaths, forKey: .inputPaths) try container.encode(inputFileListPaths, forKey: .inputFileListPaths) try container.encode(outputPaths, forKey: .outputPaths) try container.encode(outputFileListPaths, forKey: .outputFileListPaths) if let tool = tool { try container.encode(tool, forKey: .tool) } if let path = path { try container.encode(path, forKey: .path) } } }
42.016484
108
0.543089
2f0d17e46601365b097edefac2d8e70da2e37b6b
7,774
// // IntroViewController.swift // iconex_ios // // Created by a1ahn on 29/07/2019. // Copyright © 2019 ICON Foundation. All rights reserved. // import UIKit import Alamofire class IntroViewController: BaseViewController { @IBOutlet weak var iconImage: UIImageView! @IBOutlet weak var satellite: UIImageView! @IBOutlet weak var logoLabel: UILabel! @IBOutlet weak var indicator: UIActivityIndicatorView! private var _animated: Bool = false private var _checked: Bool = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func initializeComponents() { super.initializeComponents() iconImage.alpha = 0.0 satellite.alpha = 0.0 logoLabel.alpha = 0.0 indicator.isHidden = true } override func refresh() { super.refresh() view.backgroundColor = .mint1 iconImage.image = #imageLiteral(resourceName: "imgLogoIcon0256W") satellite.image = #imageLiteral(resourceName: "imgLogoIcon0170W") logoLabel.size12(text: "@2019 ICON Foundation", color: UIColor(255, 255, 255, 0.5)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !UserDefaults.standard.bool(forKey: "permission") { let perm = UIStoryboard(name: "Intro", bundle: nil).instantiateViewController(withIdentifier: "PermissionView") as! PermissionViewController perm.action = { } perm.pop() } else { if !_animated { _animated = true startAlpha() } else { if !_checked { self.getVersion() } } } } func startAlpha() { UIView.animate(withDuration: 0.45, delay: 0.5, options: .curveLinear, animations: { self.iconImage.alpha = 1.0 self.satellite.alpha = 1.0 self.logoLabel.alpha = 1.0 }, completion: { _ in self.startRotate() }) } func startRotate() { UIView.animate(withDuration: 0.65, delay: 0.5, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: .curveEaseIn, animations: { self.iconImage.transform = CGAffineTransform(rotationAngle: .pi) self.satellite.transform = CGAffineTransform(rotationAngle: -3.14159256) }, completion : { _ in self.startHide() }) } func startHide() { UIView.animate(withDuration: 0.4, delay: 0.5, animations: { self.iconImage.alpha = 0.0 self.satellite.alpha = 0.0 self.logoLabel.alpha = 0.0 }, completion: { _ in self.iconImage.transform = .identity self.satellite.transform = .identity self.getVersion() }) } func getVersion() { indicator.isHidden = false _checked = true var tracker: Tracker { switch Config.host { case .main: return Tracker.main() case .euljiro: return Tracker.euljiro() case .yeouido: return Tracker.yeouido() default: return Tracker.euljiro() } } if(Config.host != .main){ //TODO Re-evaluate //Currently test net trackers do not supply this version information app.all = app.appVersion app.necessary = app.appVersion go() return } let versionURL = URL(string: tracker.provider)!.appendingPathComponent("app/ios.json") let request = URLRequest(url: versionURL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) Alamofire.request(request).responseJSON(queue: DispatchQueue.global(qos: .utility)) { (dataResponse) in DispatchQueue.main.async { self.indicator.isHidden = true switch dataResponse.result { case .success: guard case let json as [String: Any] = dataResponse.result.value, let result = json["result"] as? String else { self.lost() return } Log("Version: \(json)") if result == "OK" { let data = json["data"] as! [String: String] app.all = data["all"] app.necessary = data["necessary"] } self.checkVersion() case .failure(let error): Log("Error \(error)") self.lost() } } } } private func go() { Manager.balance.getAllBalances() let list = Manager.wallet.walletList if list.count == 0 { let start = UIStoryboard(name: "Intro", bundle: nil).instantiateViewController(withIdentifier: "StartView") app.change(root: start) } else { if Tool.isPasscode() { app.presentLock({ app.toMain() if !Manager.balance.isWorking { Manager.balance.getAllBalances() } }) } else if !Tool.isPasscode() && Conn.isConnect { app.toConnect() } else { app.toMain() } } } private func checkVersion() { if let version = app.necessary { let myVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String if version > myVersion { let message = "Version.Message".localized Alert.basic(title: message, subtitle: nil, hasHeaderTitle: false, isOnlyOneButton: false, leftButtonTitle: "Common.Cancel".localized, rightButtonTitle: "Version.Update".localized, cancelAction: { exit(0) }) { UIApplication.shared.open(URL(string: "itms-apps://itunes.apple.com/app/iconex-icon-wallet/id1368441529?mt=8")!, options: [:], completionHandler: { _ in exit(0) }) }.show() // Alert.Confirm(message: message, cancel: "Common.Cancel".localized, confirm: "Version.Update".localized, handler: { // UIApplication.shared.open(URL(string: "itms-apps://itunes.apple.com/app/iconex-icon-wallet/id1368441529?mt=8")!, options: [:], completionHandler: { _ in // exit(0) // }) // }, { // exit(0) // }).show(self.window!.rootViewController!) } else { if let presented = self.presentedViewController { presented.dismiss(animated: true) { self.go() } } else { go() } } } else { } } private func lost() { let lost = UIStoryboard(name: "Intro", bundle: nil).instantiateViewController(withIdentifier: "LostView") as! LostViewController lost.modalPresentationStyle = .fullScreen lost.retryHandler = { self._checked = false self.getVersion() } self.present(lost, animated: true, completion: nil) } }
35.497717
211
0.517366
f8e33f971558536c8dc15b4b9a7b5a933df62538
18,813
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 Flutter import UIKit import Amplify import AmplifyPlugins import AWSCore import Combine import amplify_core public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { private let bridge: DataStoreBridge private let flutterModelRegistration: FlutterModels private let dataStoreObserveEventStreamHandler: DataStoreObserveEventStreamHandler? private let dataStoreHubEventStreamHandler: DataStoreHubEventStreamHandler? private var channel: FlutterMethodChannel? var observeSubscription: AnyCancellable? init(bridge: DataStoreBridge = DataStoreBridge(), flutterModelRegistration: FlutterModels = FlutterModels(), dataStoreObserveEventStreamHandler: DataStoreObserveEventStreamHandler = DataStoreObserveEventStreamHandler(), dataStoreHubEventStreamHandler: DataStoreHubEventStreamHandler = DataStoreHubEventStreamHandler()) { self.bridge = bridge self.flutterModelRegistration = flutterModelRegistration self.dataStoreObserveEventStreamHandler = dataStoreObserveEventStreamHandler self.dataStoreHubEventStreamHandler = dataStoreHubEventStreamHandler } public static func register(with registrar: FlutterPluginRegistrar) { let instance = SwiftAmplifyDataStorePlugin() let observeChannel = FlutterEventChannel(name: "com.amazonaws.amplify/datastore_observe_events", binaryMessenger: registrar.messenger()) let hubChannel = FlutterEventChannel(name: "com.amazonaws.amplify/datastore_hub_events", binaryMessenger: registrar.messenger()) instance.channel = FlutterMethodChannel(name: "com.amazonaws.amplify/datastore", binaryMessenger: registrar.messenger()) observeChannel.setStreamHandler(instance.dataStoreObserveEventStreamHandler) hubChannel.setStreamHandler(instance.dataStoreHubEventStreamHandler) registrar.addMethodCallDelegate(instance, channel: instance.channel!) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { var arguments: [String: Any] = [:] do { if(call.arguments != nil) { try arguments = checkArguments(args: call.arguments as Any) } } catch { FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: result) return } switch call.method { case "configureDataStore": onConfigureDataStore(args: arguments, result: result) case "query": onQuery(args: arguments, flutterResult: result) case "save": onSave(args: arguments, flutterResult: result) case "delete": onDelete(args: arguments, flutterResult: result) case "setUpObserve": onSetUpObserve(flutterResult: result) case "clear": onClear(flutterResult: result) default: result(FlutterMethodNotImplemented) } } private func onConfigureDataStore(args: [String: Any], result: @escaping FlutterResult) { guard let modelSchemaList = args["modelSchemas"] as? [[String: Any]] else { result(false) return //TODO } guard channel != nil else { return } let syncExpressionList = args["syncExpressions"] as? [[String: Any]] ?? [] let syncInterval = args["syncInterval"] as? Double ?? DataStoreConfiguration.defaultSyncInterval let syncMaxRecords = args["syncMaxRecords"] as? UInt ?? DataStoreConfiguration.defaultSyncMaxRecords let syncPageSize = args["syncPageSize"] as? UInt ?? DataStoreConfiguration.defaultSyncPageSize do { let modelSchemas: [ModelSchema] = try modelSchemaList.map { try FlutterModelSchema.init(serializedData: $0).convertToNativeModelSchema() } modelSchemas.forEach { (modelSchema) in flutterModelRegistration.addModelSchema(modelName: modelSchema.name, modelSchema: modelSchema) } let syncExpressions: [DataStoreSyncExpression] = try createSyncExpressions(syncExpressionList: syncExpressionList) self.dataStoreHubEventStreamHandler?.registerModelsForHub(flutterModels: flutterModelRegistration) let dataStorePlugin = AWSDataStorePlugin(modelRegistration: flutterModelRegistration, configuration: .custom( syncInterval: syncInterval, syncMaxRecords: syncMaxRecords, syncPageSize: syncPageSize, syncExpressions: syncExpressions)) try Amplify.add(plugin: dataStorePlugin) Amplify.Logging.logLevel = .info print("Amplify configured with DataStore plugin") result(true) } catch ModelSchemaError.parse(let className, let fieldName, let desiredType){ FlutterDataStoreErrorHandler.handleDataStoreError( error: DataStoreError.decodingError( "Invalid modelSchema " + className + "-" + fieldName + " cannot be cast to " + desiredType, ErrorMessages.missingRecoverySuggestion), flutterResult: result) return } catch let error { if(error is DataStoreError){ FlutterDataStoreErrorHandler.handleDataStoreError( error: error as! DataStoreError, flutterResult: result) } else if(error is ConfigurationError) { let configError = error as! ConfigurationError var errorCode = "DataStoreException" if case .amplifyAlreadyConfigured = configError { errorCode = "AmplifyAlreadyConfiguredException" } ErrorUtil.postErrorToFlutterChannel( result: result, errorCode: errorCode, details: [ "message" : configError.errorDescription, "recoverySuggestion" : configError.recoverySuggestion, "underlyingError": configError.underlyingError != nil ? configError.underlyingError!.localizedDescription : "" ] ) } else{ print("Failed to initialize DataStore with \(error)") result(false) } return } } func onQuery(args: [String: Any], flutterResult: @escaping FlutterResult) { do { let modelName = try FlutterDataStoreRequestUtils.getModelName(methodChannelArguments: args) let modelSchema = try FlutterDataStoreRequestUtils.getModelSchema(modelSchemas: flutterModelRegistration.modelSchemas, modelName: modelName) let queryPredicates = try QueryPredicateBuilder.fromSerializedMap(args["queryPredicate"] as? [String : Any]) let querySortInput = try QuerySortBuilder.fromSerializedList(args["querySort"] as? [[String: Any]]) let queryPagination = QueryPaginationBuilder.fromSerializedMap(args["queryPagination"] as? [String: Any]) try bridge.onQuery(FlutterSerializedModel.self, modelSchema: modelSchema, where: queryPredicates, sort: querySortInput, paginate: queryPagination) { (result) in switch result { case .failure(let error): print("Query API failed. Error = \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: error, flutterResult: flutterResult) case .success(let res): let serializedResults = res.map { (queryResult) -> [String: Any] in return queryResult.toMap(modelSchema: modelSchema) } flutterResult(serializedResults) return } } } catch let error as DataStoreError { print("Failed to parse query arguments with \(error)") FlutterDataStoreErrorHandler.handleDataStoreError( error: error, flutterResult: flutterResult) } catch { print("An unexpected error occured when parsing query arguments: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) } } func onSave(args: [String: Any], flutterResult: @escaping FlutterResult) { do { let modelName = try FlutterDataStoreRequestUtils.getModelName(methodChannelArguments: args) let modelSchema = try FlutterDataStoreRequestUtils.getModelSchema(modelSchemas: flutterModelRegistration.modelSchemas, modelName: modelName) let serializedModelData = try FlutterDataStoreRequestUtils.getSerializedModelData(methodChannelArguments: args) let modelID = try FlutterDataStoreRequestUtils.getModelID(serializedModelData: serializedModelData) let serializedModel = FlutterSerializedModel(id: modelID, map: try FlutterDataStoreRequestUtils.getJSONValue(serializedModelData)) try bridge.onSave( serializedModel: serializedModel, modelSchema: modelSchema ) { (result) in switch result { case .failure(let error): print("Save API failed. Error: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError( error: error, flutterResult: flutterResult) case .success(let model): print("Successfully saved model: \(model)") flutterResult(nil) } } } catch let error as DataStoreError { print("Failed to parse save arguments with \(error)") FlutterDataStoreErrorHandler.handleDataStoreError( error: error, flutterResult: flutterResult) } catch { print("An unexpected error occured when parsing save arguments: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) } } func onDelete(args: [String: Any], flutterResult: @escaping FlutterResult) { do { let modelName = try FlutterDataStoreRequestUtils.getModelName(methodChannelArguments: args) let modelSchema = try FlutterDataStoreRequestUtils.getModelSchema(modelSchemas: flutterModelRegistration.modelSchemas, modelName: modelName) let serializedModelData = try FlutterDataStoreRequestUtils.getSerializedModelData(methodChannelArguments: args) let modelID = try FlutterDataStoreRequestUtils.getModelID(serializedModelData: serializedModelData) let serializedModel = FlutterSerializedModel(id: modelID, map: try FlutterDataStoreRequestUtils.getJSONValue(serializedModelData)) try bridge.onDelete( serializedModel: serializedModel, modelSchema: modelSchema) { (result) in switch result { case .failure(let error): print("Delete API failed. Error = \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: error, flutterResult: flutterResult) case .success(): flutterResult(nil) } } } catch let error as DataStoreError { print("Failed to parse delete arguments with \(error)") FlutterDataStoreErrorHandler.handleDataStoreError( error: error, flutterResult: flutterResult) } catch { print("An unexpected error occured when parsing delete arguments: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) return } } public func onSetUpObserve(flutterResult: @escaping FlutterResult) { do { observeSubscription = try observeSubscription ?? bridge.onObserve().sink { completion in switch completion { case .failure(let error): let flutterError = FlutterError(code: "DataStoreException", message: ErrorMessages.defaultFallbackErrorMessage, details: FlutterDataStoreErrorHandler.createSerializedError(error: error)) self.dataStoreObserveEventStreamHandler?.sendError(flutterError: flutterError) case .finished: print("finished") } } receiveValue: { (mutationEvent) in do { let serializedEvent = try mutationEvent.decodeModel(as: FlutterSerializedModel.self) guard let modelSchema = self.flutterModelRegistration.modelSchemas[mutationEvent.modelName] else { print("Received mutation event for a model \(mutationEvent.modelName) that is not registered.") return } guard let eventType = EventType(rawValue: mutationEvent.mutationType) else { print("Received mutation event for an unknown mutation type \(mutationEvent.mutationType).") return } let flutterSubscriptionEvent = FlutterSubscriptionEvent.init( item: serializedEvent, eventType: eventType) self.dataStoreObserveEventStreamHandler?.sendEvent(flutterEvent: flutterSubscriptionEvent.toJSON(modelSchema: modelSchema)) } catch { print("Failed to parse the event \(error)") // TODO communicate using datastore error handler? } } } catch { print("Failed to get the datastore plugin \(error)") flutterResult(false) } flutterResult(nil) } func onClear(flutterResult: @escaping FlutterResult) { do { try bridge.onClear() {(result) in switch result { case .failure(let error): print("Clear API failed. Error: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError( error: error, flutterResult: flutterResult) case .success(): print("Successfully cleared the store") // iOS tears down the publisher after clear. Let's setup again. // See https://github.com/aws-amplify/amplify-flutter/issues/395 self.observeSubscription = nil self.onSetUpObserve(flutterResult: flutterResult) flutterResult(nil) } } } catch { print("An unexpected error occured: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) } } private func checkArguments(args: Any) throws -> [String: Any] { guard let res = args as? [String: Any] else { throw DataStoreError.decodingError("Flutter method call arguments are not a map.", "Check the values that are being passed from Dart.") } return res; } private func createSyncExpressions(syncExpressionList: [[String: Any]]) throws -> [DataStoreSyncExpression] { return try syncExpressionList.map { syncExpression in let id = syncExpression["id"] as! String let modelName = syncExpression["modelName"] as! String let queryPredicate = try QueryPredicateBuilder.fromSerializedMap(syncExpression["queryPredicate"] as? [String: Any]) let modelSchema = flutterModelRegistration.modelSchemas[modelName] return DataStoreSyncExpression.syncExpression(modelSchema!) { var resolvedQueryPredicate = queryPredicate let semaphore = DispatchSemaphore(value: 0) self.channel!.invokeMethod("resolveQueryPredicate", arguments: id) { result in do { resolvedQueryPredicate = try QueryPredicateBuilder.fromSerializedMap(result as? [String: Any]) } catch { print("Failed to resolve query predicate. Reverting to original query predicate.") } semaphore.signal() } semaphore.wait() return resolvedQueryPredicate } } } // TODO: Remove once all configure is moved to the bridge func getPlugin() throws -> AWSDataStorePlugin { return try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin } }
49.769841
152
0.593207
bb14aa36d2528a9ca89ab4f88fbcb9b700d79fa1
1,061
// MenuTableViewCell.swift // MenuSlider // Created by vivek on 7/25/18. // import UIKit class MenuTableViewCell: UITableViewCell { //MARK:- Outlet @IBOutlet weak var cellTitleLabel: UILabel! //MARK:- Variables let cellArray = ["Row - 1", "Row - 2", "Row - 3", "Row - 4", "Row - 5"] //adjust according to your needs static var reuseIdentifier: String { get { return String(describing: self) } } static var nib:UINib { get { return UINib(nibName: String(describing: self), bundle: nil) } } //MARK:- Cell Methods override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configCell(indexNumber: NSInteger) { cellTitleLabel.text = cellArray[indexNumber] } }
22.104167
108
0.577757
385cdc314dd9c55f35858e5b359d3301310c65b2
1,472
// // Marmot // // Copyright (c) 2017 linhay - https://github.com/linhay // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE import UIKit public struct Marmot<Base> { public let base: Base public init(_ base: Base) { self.base = base } } public protocol MarmotCompatible { associatedtype CompatibleType var mt: CompatibleType { get } } public extension MarmotCompatible { public var mt: Marmot<Self> { return Marmot(self) } }
36.8
82
0.742527
790190b8f79fe3195fe577715e606bc3beb88062
1,021
import SQL struct User { let id: Int? let username: String let password: String let firstName: String? let lastName: String? init(username: String, password: String, firstName: String? = nil, lastName: String? = nil) { self.id = nil self.username = username self.password = password self.firstName = firstName self.lastName = lastName } } enum UserField: String, ModelFieldset { case Id = "id" case Username = "username" case Password = "password" case FirstName = "first_name" case LastName = "last_name" static var tableName: String { return "users" } } extension User: Entity { typealias Field = UserField var primaryKey: Int? { return id } static var fieldForPrimaryKey: Field { return .Id } init(row: Row) throws { id = try row.value(Field.Id) username = try row.value(Field.Username) password = try row.value(Field.Password) firstName = try row.value(Field.FirstName) lastName = try row.value(Field.LastName) } }
20.42
95
0.670911
8f7e51a7f03305cb9ef101cbd9cf05bc663f5716
533
// // UIColor+.swift // InteractiveClusteringMap // // Created by Oh Donggeon on 2020/12/13. // import UIKit extension UIColor { static let greenCyan = UIColor(named: "greenCyan") static let deepBlue = UIColor(named: "deepBlue") convenience init(hex: Int, alpha: Float = 1.0) { self.init(red: CGFloat((hex >> 16) & 0xFF) / 255.0, green: CGFloat((hex >> 8) & 0xFF) / 255.0, blue: CGFloat(hex & 0xFF) / 255.0, alpha: CGFloat(alpha)) } }
23.173913
60
0.553471
48854a2aeb842aff457d1fd729a9dc3ac242c8d3
3,817
// // FavoritesListViewController.swift // MyTunesMVVM // // Created by MacOS on 1.04.2022. // import Foundation import RxCocoa import RxSwift import RxGesture import XCoordinator import Kingfisher import Action import UIKit import RealmSwift class FavoriteListViewController : UIViewController, BindableType, UICollectionViewDelegate { private let cellIdentifier = String(describing: FavoritesListCell.self) let disposeBag = DisposeBag() var favoritesListView = FavoritesListView() var viewModel: FavoritesListViewModel! var gridFlowLayout = GridFlowLayout() var favoritesList = [Results]() override func loadView() { view = favoritesListView } override func viewDidLoad() { registerCollectionView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) favoritesListView.favoriteListCollectionView.reloadData() let image = UIImage(named: "delete") navigationItem.rightBarButtonItem = UIBarButtonItem(image: image , style: .plain, target: self, action: #selector(addTapped)) navigationController?.navigationBar.tintColor = .black navigationItem.rightBarButtonItem?.imageInsets = UIEdgeInsets(top: 3, left: 3, bottom: -4, right: -3) navigationController?.navigationBar.backgroundColor = UIColor(rgb: 0xF5F5F5) } @objc func addTapped(){ self.deleteButtonProcesses() } override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // navigationController?.setNavigationBarHidden(false, animated: animated) } func bindViewModel() { viewModel.output.favoriteList.bind(to: favoritesListView.favoriteListCollectionView.rx.items(cellIdentifier: cellIdentifier, cellType: FavoritesListCell.self)) { [self] _, model , cell in let urlString = model.artworkUrl100?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) cell.favoriteListCellImageView.kf.setImage(with: URL(string: urlString ?? "")) cell.favoriteListCellNameLabel.text = model.trackName cell.favoriteListCellTypeLabel.text = model.wrapperType cell.favoriteListCellKindLabel.text = model.kind cell.favoriteListCellDeleteButton.backgroundColor = .red cell.favoriteListCellDeleteButton.addTapGesture { RealmHelper.sharedInstance.deleteFromDb(tune: model) self.viewModel.fetchFavoriteList() } }.disposed(by: disposeBag) favoritesListView.favoriteListCollectionView.rx.modelSelected(Results.self).bind(to: viewModel.input.selectedTune).disposed(by: disposeBag) favoritesListView.favoritesListDeleteButton.rx.tapGesture().when(.recognized).subscribe(onNext : { gesture in self.deleteButtonProcesses() }).disposed(by: disposeBag) } func registerCollectionView() { favoritesListView.favoriteListCollectionView.delegate = self favoritesListView.favoriteListCollectionView.register(FavoritesListCell.self, forCellWithReuseIdentifier: "FavoritesListCell") favoritesListView.favoriteListCollectionView.collectionViewLayout = gridFlowLayout } func deleteButtonProcesses(){ RealmHelper.sharedInstance.deleteAllFromDatabase() self.viewModel.fetchFavoriteList() let alertAction = UIAlertAction(title: "OK", style: .default) { UIAlertAction in self.viewModel.dismiss() } self.alertAction(title: "Success", message: "Cleaned Favorite List", action: alertAction) } }
38.17
195
0.701598
381d46c087a58763508af6134a4ea987f97d7ee1
7,762
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-2020 Datadog, Inc. */ @testable import Datadog extension LoggingFeature { /// Mocks the feature instance which performs no writes and no uploads. static func mockNoOp() -> LoggingFeature { return LoggingFeature( storage: .init(writer: NoOpFileWriter(), reader: NoOpFileReader()), upload: .init(uploader: NoOpDataUploadWorker()), configuration: .mockAny(), commonDependencies: .mockAny() ) } /// Mocks the feature instance which performs uploads to `URLSession`. /// Use `ServerMock` to inspect and assert recorded `URLRequests`. static func mockWith( directories: FeatureDirectories, configuration: FeaturesConfiguration.Logging = .mockAny(), dependencies: FeaturesCommonDependencies = .mockAny() ) -> LoggingFeature { return LoggingFeature(directories: directories, configuration: configuration, commonDependencies: dependencies) } /// Mocks the feature instance which performs uploads to mocked `DataUploadWorker`. /// Use `LogFeature.waitAndReturnLogMatchers()` to inspect and assert recorded `Logs`. static func mockByRecordingLogMatchers( directories: FeatureDirectories, configuration: FeaturesConfiguration.Logging = .mockAny(), dependencies: FeaturesCommonDependencies = .mockAny() ) -> LoggingFeature { // Get the full feature mock: let fullFeature: LoggingFeature = .mockWith( directories: directories, dependencies: dependencies.replacing( dateProvider: SystemDateProvider() // replace date provider in mocked `Feature.Storage` ) ) let uploadWorker = DataUploadWorkerMock() let observedStorage = uploadWorker.observe(featureStorage: fullFeature.storage) // Replace by mocking the `FeatureUpload` and observing the `FatureStorage`: let mockedUpload = FeatureUpload(uploader: uploadWorker) return LoggingFeature( storage: observedStorage, upload: mockedUpload, configuration: configuration, commonDependencies: dependencies ) } // MARK: - Expecting Logs Data static func waitAndReturnLogMatchers(count: UInt, file: StaticString = #file, line: UInt = #line) throws -> [LogMatcher] { guard let uploadWorker = LoggingFeature.instance?.upload.uploader as? DataUploadWorkerMock else { preconditionFailure("Retrieving matchers requires that feature is mocked with `.mockByRecordingLogMatchers()`") } return try uploadWorker.waitAndReturnBatchedData(count: count, file: file, line: line) .flatMap { batchData in try LogMatcher.fromArrayOfJSONObjectsData(batchData, file: file, line: line) } } } // MARK: - Log Mocks extension Log { static func mockWith( date: Date = .mockAny(), status: Log.Status = .mockAny(), message: String = .mockAny(), serviceName: String = .mockAny(), environment: String = .mockAny(), loggerName: String = .mockAny(), loggerVersion: String = .mockAny(), threadName: String = .mockAny(), applicationVersion: String = .mockAny(), userInfo: UserInfo = .mockAny(), networkConnectionInfo: NetworkConnectionInfo = .mockAny(), mobileCarrierInfo: CarrierInfo? = .mockAny(), attributes: LogAttributes = .mockAny(), tags: [String]? = nil ) -> Log { return Log( date: date, status: status, message: message, serviceName: serviceName, environment: environment, loggerName: loggerName, loggerVersion: loggerVersion, threadName: threadName, applicationVersion: applicationVersion, userInfo: userInfo, networkConnectionInfo: networkConnectionInfo, mobileCarrierInfo: mobileCarrierInfo, attributes: attributes, tags: tags ) } } extension Log.Status { static func mockAny() -> Log.Status { return .info } } // MARK: - Component Mocks extension Logger { static func mockWith( logOutput: LogOutput = LogOutputMock(), dateProvider: DateProvider = SystemDateProvider(), identifier: String = .mockAny(), rumContextIntegration: LoggingWithRUMContextIntegration? = nil, activeSpanIntegration: LoggingWithActiveSpanIntegration? = nil ) -> Logger { return Logger( logOutput: logOutput, dateProvider: dateProvider, identifier: identifier, rumContextIntegration: rumContextIntegration, activeSpanIntegration: activeSpanIntegration ) } } extension LogBuilder { static func mockAny() -> LogBuilder { return mockWith() } static func mockWith( applicationVersion: String = .mockAny(), environment: String = .mockAny(), serviceName: String = .mockAny(), loggerName: String = .mockAny(), userInfoProvider: UserInfoProvider = .mockAny(), networkConnectionInfoProvider: NetworkConnectionInfoProviderType = NetworkConnectionInfoProviderMock.mockAny(), carrierInfoProvider: CarrierInfoProviderType = CarrierInfoProviderMock.mockAny(), dateCorrector: DateCorrectorType? = nil ) -> LogBuilder { return LogBuilder( applicationVersion: applicationVersion, environment: environment, serviceName: serviceName, loggerName: loggerName, userInfoProvider: userInfoProvider, networkConnectionInfoProvider: networkConnectionInfoProvider, carrierInfoProvider: carrierInfoProvider, dateCorrector: dateCorrector ) } } extension LogAttributes: Equatable { static func mockAny() -> LogAttributes { return mockWith() } static func mockWith( userAttributes: [String: Encodable] = [:], internalAttributes: [String: Encodable]? = [:] ) -> LogAttributes { return LogAttributes( userAttributes: userAttributes, internalAttributes: internalAttributes ) } public static func == (lhs: LogAttributes, rhs: LogAttributes) -> Bool { let lhsUserAttributesSorted = lhs.userAttributes.sorted { $0.key < $1.key } let rhsUserAttributesSorted = rhs.userAttributes.sorted { $0.key < $1.key } let lhsInternalAttributesSorted = lhs.internalAttributes?.sorted { $0.key < $1.key } let rhsInternalAttributesSorted = rhs.internalAttributes?.sorted { $0.key < $1.key } return String(describing: lhsUserAttributesSorted) == String(describing: rhsUserAttributesSorted) && String(describing: lhsInternalAttributesSorted) == String(describing: rhsInternalAttributesSorted) } } /// `LogOutput` recording received logs. class LogOutputMock: LogOutput { struct RecordedLog: Equatable { var level: LogLevel var message: String var date: Date var attributes = LogAttributes(userAttributes: [:], internalAttributes: [:]) var tags: Set<String> = [] } var recordedLog: RecordedLog? = nil func writeLogWith(level: LogLevel, message: String, date: Date, attributes: LogAttributes, tags: Set<String>) { recordedLog = RecordedLog(level: level, message: message, date: date, attributes: attributes, tags: tags) } }
38.425743
126
0.656661
e6a086132051d8c1e752100be003c67df9d42768
1,324
// // NavigationLinkView.swift // SwiftUI-d2-Buttons // // Created by pgq on 2020/3/18. // Copyright © 2020 pq. All rights reserved. // import SwiftUI struct NavigationLinkView: View { var nextView = NavigationLinkNextView() @State var isActive: Bool = false var body: some View { List { NavigationLink(destination: nextView, isActive: $isActive) { Text("NavigationLink(destination: nextView, isActive: $isActive)") } NavigationLink("NavigationLink(\"Title\", destination: nextView)", destination: nextView) NavigationLink(destination: nextView) { Text("NavigationLink(destination: nextView, isActive: $isActive)") }.isDetailLink(true) NavigationLink(destination: nextView) { Text("NavigationLink(destination: nextView, isActive: $isActive)") }.isDetailLink(false) } } } struct NavigationLinkView_Previews: PreviewProvider { static var previews: some View { NavigationLinkView() } } struct NavigationLinkNextView: View { var body: some View { NavigationView { Text("你好") .navigationBarTitle("Detail") } } }
24.981132
101
0.581571
621b055a0b928db3a7866ce33f96432d8ecb906c
1,406
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_NSArray // RUN: %target-codesign %t/reflect_NSArray // RUN: %target-run %target-swift-reflection-test %t/reflect_NSArray | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test import SwiftReflectionTest import Foundation class TestClass { var t: NSArray init(t: NSArray) { self.t = t } } var obj = TestClass(t: [1, 2, 3]) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_NSArray.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=24 alignment=8 stride=24 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (reference kind=strong refcounting=unknown))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_NSArray.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (reference kind=strong refcounting=unknown))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
28.693878
121
0.708393
6a44f2b8af5307be8d5df3b0b12b0ead3f96e4f8
322
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(TrieRouterTests.allTests), testCase(RouterParametersDecoderTests.allTests), testCase(EasyRouterHandlerTests.allTests), testCase(URLQueryItemsEncoderTests.allTests), ] } #endif
24.769231
56
0.717391
87a805efab8886699c823acac660bf262c158e73
502
// // MenuCell.swift // TwitteriOS // // Created by jiafang_jiang on 4/17/17. // Copyright © 2017 jiafang_jiang. All rights reserved. // import UIKit class MenuCell: UITableViewCell { @IBOutlet weak var menuItem: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
19.307692
63
0.689243
67e501481784479c3569873cdccec8c34cd87153
2,464
// // HWMultipartData.swift // LianDuoDuo // // Created by HouWan on 2020/8/15. // Copyright © 2020 CSData. All rights reserved. // import Foundation /// 常见数据类型的`MIME Type` public enum HWDataMimeType: String { case JPEG = "image/jpeg" case PNG = "image/png" case GIF = "image/gif" case HEIC = "image/heic" case HEIF = "image/heif" case WEBP = "image/webp" case TIF = "image/tif" case JSON = "application/json" } /// HWMultipartData for upload datas, eg: images/photos public class HWMultipartData { /// The data to be encoded and appended to the form data. let data: Data /// Name to associate with the `Data` in the `Content-Disposition` HTTP header. let name: String /// Filename to associate with the `Data` in the `Content-Disposition` HTTP header. let fileName: String /// The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types /// see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. let mimeType: String /// Create HWMultipartDataModel /// - Parameters: /// - data: The data to be encoded and appended to the form data. /// - name: The name to be associated with the specified data. /// - fileName: The filename to be associated with the specified data. /// - mimeType: The MIME type of the specified data. eg: image/jpeg init(data: Data, name: String, fileName: String, mimeType: String) { self.data = data self.name = name self.fileName = fileName self.mimeType = mimeType } /// Create HWMultipartDataModel /// - Parameters: /// - data: The data to be encoded and appended to the form data. /// - name: The name to be associated with the specified data. /// - fileName: The filename to be associated with the specified data. /// - type: The MIME type of the specified data. eg: image/jpeg convenience init(data: Data, name: String, fileName: String, type: HWDataMimeType) { self.init(data: data, name: name, fileName: fileName, mimeType: type.rawValue) } // mimeType --> image/jpeg, image/png, image/gif, // see: https://www.cnblogs.com/fuqiang88/p/4618652.html // 中文说明一下,增加理解: // 当提交一张图片或一个文件的时候 name 可以随便设置,服务端直接能拿到,如果服务端需要根据name去取不同文件的时候 // 则appendPartWithFileData 方法中的 name 需要根据form的中的name一一对应 // 所以name的值,是需要跟后台服务端商量好的. }
37.333333
136
0.66599
712c7de3e766067e02206adcf0f66b089cd7f516
392
//: Playground - noun: a place where people can play import Cocoa var str = "Hello;cat" var i:String.Index = str.startIndex var pin:String.Index = str.endIndex while i < str.endIndex { while i < str.endIndex { if str[i] == ";" { break } else { ++i } } let aa = str.substringWithRange(Range(start:pin, end:i)) pin = i }
17.818182
60
0.55102
648538cd5ec0ab92abe00d48a0ace56a9b39ea31
1,217
// Copyright (c) 2019 Spotify AB. // // 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 Contains { let str: String public init(_ str: String) { self.str = str.lowercased() } private func match(_ input: String) -> Bool { return input.lowercased().contains(str) } } extension Contains { static func ~= (contains: Contains, input: String) -> Bool { return contains.match(input) } }
30.425
64
0.709942
9cf059ada1c4e9f5cf2a3988c75a01b1c8951039
23,037
// // Utilities.swift // SpeakApp // // Created by Aviel Gross on 10/22/14. // Copyright (c) 2014 Aviel Gross. All rights reserved. // import UIKit // MARK: Operators/Typealiases /** * Set lhs to be rhs only if lhs is nil * Example: imageView.image ?= placeholderImage * Will set placeholderImage only if imageView.image is nil */ infix operator ?= func ?=<T>(lhs: inout T!, rhs: T) { if lhs == nil { lhs = rhs } } func ?=<T>(lhs: inout T?, rhs: T) { if lhs == nil { lhs = rhs } } func ?=<T>(lhs: inout T?, rhs: T?) { if lhs == nil { lhs = rhs } } typealias Seconds = TimeInterval //MARK: Tick/Tock private var tickD = Date() func TICK() { tickD = Date() } func TOCK(_ sender: Any = #function) { print("⏰ TICK/TOCK for: \(sender) :: \(-tickD.timeIntervalSinceNow) ⏰") } // MARK: Common/Generic func local(_ key: String, comment: String = "") -> String { return NSLocalizedString(key, comment: comment) } var brString: String { return "_________________________________________________________________" } func printbr() { print(brString) } func printFunc(_ val: Any = #function) { print("🚩 \(val)") } func prettyPrint<T>(_ val: T, filename: NSString = #file, line: Int = #line, funcname: String = #function) { print("\(Date()) [\(filename.lastPathComponent):\(line)] - \(funcname):\r\(val)\n") } public func resizeImage(_ image : UIImage, size : CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0); image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let out = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return out!; } func delay(_ delay:Double, closure:@escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } func async<T>(_ back:@escaping ()->(T), then main:@escaping (T)->()) { DispatchQueue.global(qos: .default).async { let some = back() DispatchQueue.main.async { main(some) } } } func async(_ back:@escaping ()->(), then main:@escaping ()->()) { DispatchQueue.global(qos: .default).async { back() DispatchQueue.main.async { main() } } } func sync(_ main:@escaping ()->()) { DispatchQueue.main.async { main() } } func async(_ back:@escaping ()->()) { DispatchQueue.global(qos: .default).async { back() } } extension Data { var unarchived: AnyObject? { return NSKeyedUnarchiver.unarchiveObject(with: self) as AnyObject? } } extension Array { func safeRetrieveElement(_ index: Int) -> Element? { if count > index { return self[index] } return nil } mutating func removeFirst(_ element: Element, equality: (Element, Element) -> Bool) -> Bool { for (index, item) in enumerated() { if equality(item, element) { self.remove(at: index) return true } } return false } mutating func removeFirst(_ compareTo: (Element) -> Bool) -> Bool { for (index, item) in enumerated() { if compareTo(item) { self.remove(at: index) return true } } return false } } extension UIStoryboardSegue { func destinationController<T>(_ type: T.Type) -> T? { if let destNav = destination as? UINavigationController, let dest = destNav.topViewController as? T { return dest } if let dest = destination as? T { return dest } return nil } } extension UIViewController { func parentViewController<T: UIViewController>(ofType type:T.Type) -> T? { if let parentVC = presentingViewController as? UINavigationController, let topParent = parentVC.topViewController as? T { return topParent } else if let parentVC = presentingViewController as? T { return parentVC } return nil } } extension UIAlertController { func show() { present(animated: true, completion: nil) } func present(animated: Bool, completion: (() -> Void)?) { if let rootVC = UIApplication.shared.keyWindow?.rootViewController { presentFromController(rootVC, animated: animated, completion: completion) } } fileprivate func presentFromController(_ controller: UIViewController, animated: Bool, completion: (() -> Void)?) { if let navVC = controller as? UINavigationController, let visibleVC = navVC.visibleViewController { presentFromController(visibleVC, animated: animated, completion: completion) } else if let tabVC = controller as? UITabBarController, let selectedVC = tabVC.selectedViewController { presentFromController(selectedVC, animated: animated, completion: completion) } else { controller.present(self, animated: animated, completion: completion) } } } extension UIAlertView { class func show(_ title: String?, message: String?, closeTitle: String?) { UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: closeTitle).show() } } extension UIImageView { func setImage(_ url: String, placeHolder: UIImage? = nil, animated: Bool = true) { if let placeHolderImage = placeHolder { self.image = placeHolderImage } UIImage.image(url, image: { (image) in if animated { UIView.transition(with: self, duration: 0.25, options: .transitionCrossDissolve, animations: { self.image = image }) { done in } } else { self.image = image } }) } } extension UIImage { func resizeToSquare() -> UIImage? { let originalWidth = self.size.width let originalHeight = self.size.height var edge: CGFloat if originalWidth > originalHeight { edge = originalHeight } else { edge = originalWidth } let posX = (originalWidth - edge) / 2.0 let posY = (originalHeight - edge) / 2.0 let cropSquare = CGRect(x: posX, y: posY, width: edge, height: edge) if let imageRef = self.cgImage?.cropping(to: cropSquare) { return UIImage(cgImage: imageRef, scale: UIScreen.main.scale, orientation: self.imageOrientation) } return nil } /// Returns an image in the given size (in pixels) func resized(_ size: CGSize) -> UIImage? { let image = self.cgImage let bitsPerComponent = image?.bitsPerComponent let bytesPerRow = image?.bytesPerRow let colorSpace = image?.colorSpace let bitmapInfo = image?.bitmapInfo let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: bitsPerComponent!, bytesPerRow: bytesPerRow!, space: colorSpace!, bitmapInfo: (bitmapInfo?.rawValue)!) context!.interpolationQuality = CGInterpolationQuality.medium context?.draw(image!, in: CGRect(origin: CGPoint.zero, size: size)) if let aCGImage = context?.makeImage() { return UIImage(cgImage: aCGImage) } return nil } func scaled(_ scale: CGFloat) -> UIImage? { return resized(CGSize(width: self.size.width * scale, height: self.size.height * scale)) } func resizedToFullHD() -> UIImage? { return resize(maxLongEdge: 1920) } func resizedToMediumHD() -> UIImage? { return resize(maxLongEdge: 1080) } func resizeToThumbnail() -> UIImage? { return resize(maxLongEdge: 50) } func resize(maxLongEdge: CGFloat) -> UIImage? { let longEdge = max(size.width, size.height) let shortEdge = min(size.width, size.height) if longEdge <= maxLongEdge { return self } let scale = maxLongEdge/longEdge if longEdge == size.width { return resized(CGSize(width: maxLongEdge, height: shortEdge * scale)) } else { return resized(CGSize(width: shortEdge * scale, height: maxLongEdge)) } } class func image(_ link: String, session: URLSession = URLSession.shared, image: @escaping (UIImage)->()) { let url = URL(string: link)! let downloadPhotoTask = session.downloadTask(with: url, completionHandler: { (location, response, err) in if let location = location, let data = try? Data(contentsOf: location), let img = UIImage(data: data) { DispatchQueue.main.async { image(img) } } }) downloadPhotoTask.resume() } class func imageWithInitials(_ initials: String, diameter: CGFloat, textColor: UIColor = UIColor.darkGray, backColor: UIColor = UIColor.lightGray, font: UIFont = UIFont.systemFont(ofSize: 14)) -> UIImage { let size = CGSize(width: diameter, height: diameter) let r = size.width / 2 UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext() context?.setStrokeColor(backColor.cgColor) context?.setFillColor(backColor.cgColor) let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: size.width, height: size.height)) path.addClip() path.lineWidth = 1.0 path.stroke() context?.setFillColor(backColor.cgColor) context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) let dict = [kCTFontAttributeName: font, kCTForegroundColorAttributeName: textColor] let nsInitials = initials as NSString let textSize = nsInitials.size(withAttributes: dict as [NSAttributedStringKey : Any]) nsInitials.draw(in: CGRect(x: r - textSize.width / 2, y: r - font.lineHeight / 2, width: size.width, height: size.height), withAttributes: dict as [NSAttributedStringKey : Any]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } extension UITextField { func passRegex(_ expression: Regex) -> Bool { if let text = self.text, text.empty { return false } return (self.text ?? "").passRegex(expression) } } extension UITableView { func reloadData(_ completion: @escaping ()->()) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } func calculateHeightForConfiguredSizingCell(_ cell: UITableViewCell) -> CGFloat { cell.bounds.size = CGSize(width: frame.width, height: cell.bounds.height) cell.setNeedsLayout() cell.layoutIfNeeded() let size = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize) return size.height + 1 } func deselectRowIfNeeded(animated animate: Bool = true) { if let selected = indexPathForSelectedRow { deselectRow(at: selected, animated: animate) } } /** !!WILL OVERRIDE ANY EXISTING TABLE FOOTER THAT MIGHT EXIST!! */ func hideEmptySeperators() { tableFooterView = UIView(frame: CGRect.zero) } } enum Regex: String { case FullName = ".*\\s.*." // two words with a space case Email = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$" case Password = "^[\\d\\w]{6,255}$" case LetterOrDigit = "[a-zA-Z0-9]" case Digit = "[0-9]" } extension String { func passRegex(_ expression: Regex) -> Bool { var error: NSError? let regex: NSRegularExpression? do { regex = try NSRegularExpression(pattern: expression.rawValue, options: NSRegularExpression.Options.caseInsensitive) } catch let error1 as NSError { error = error1 regex = nil } if let err = error { print(err) } if self.empty { return false } let str: NSString = self as NSString let options: NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions() let numOfMatches = regex!.numberOfMatches(in: str as String, options: options, range: str.range(of: str as String)) return numOfMatches > 0 } func stringByTrimmingHTMLTags() -> String { return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) } func firstWord() -> String? { return self.components(separatedBy: " ").first } func lastWord() -> String? { return self.components(separatedBy: " ").last } var firstChar: String? { return empty ? nil : String(self[0]) } var lastChar: String? { return String(self[characters.index(before: endIndex)]) } func firstCharAsLetterOrDigit() -> String? { if let f = firstChar, f.passRegex(.LetterOrDigit) { return f } return nil } var empty: Bool { return self.characters.count == 0 } /// Either empty or only whitespace and/or new lines var emptyDeduced: Bool { return empty || trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).empty } // discussion: http://stackoverflow.com/a/2933145/2242359 func stringByForcingWritingDirectionLTR() -> String { return "\u{200E}" + self } func stringByForcingWritingDirectionRTL() -> String { return "\u{200F}" + self } /** Returns the caller string with apostrophes. e.g., "Hello" will return "\"Hello\"" */ func forceApostrophes() -> String { return "\"\(self)\"" } func contains(_ substring: String, ignoreCase: Bool = false, ignoreDiacritic: Bool = false) -> Bool { var options = NSString.CompareOptions() if ignoreCase { options.insert(NSString.CompareOptions.caseInsensitive) } if ignoreDiacritic { options.insert(NSString.CompareOptions.diacriticInsensitive) } return range(of: substring, options: options) != nil } subscript (i: Int) -> Character { return self[self.characters.index(self.startIndex, offsetBy: i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { return substring(with: characters.index(startIndex, offsetBy: r.lowerBound)..<characters.index(startIndex, offsetBy: r.upperBound)) } } extension NSMutableAttributedString { public func addAttribute(_ name: String, value: AnyObject, ranges: [NSRange]) { for r in ranges { addAttribute(NSAttributedStringKey(rawValue: name), value: value, range: r) } } } extension Int { var ordinal: String { get { var suffix: String = "" let ones: Int = self % 10; let tens: Int = (self/10) % 10; if (tens == 1) { suffix = "th"; } else if (ones == 1){ suffix = "st"; } else if (ones == 2){ suffix = "nd"; } else if (ones == 3){ suffix = "rd"; } else { suffix = "th"; } return suffix } } var string: String { get{ return "\(self)" } } } extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } func shakeView() { let shake:CABasicAnimation = CABasicAnimation(keyPath: "position") shake.duration = 0.1 shake.repeatCount = 2 shake.autoreverses = true let from_point:CGPoint = CGPoint(x: self.center.x - 5, y: self.center.y) let from_value:NSValue = NSValue(cgPoint: from_point) let to_point:CGPoint = CGPoint(x: self.center.x + 5, y: self.center.y) let to_value:NSValue = NSValue(cgPoint: to_point) shake.fromValue = from_value shake.toValue = to_value self.layer.add(shake, forKey: "position") } func blowView() { UIView.animate(withDuration: 0.1, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1.06, y: 1.05) }) { _ in UIView.animate(withDuration: 0.06, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in self.transform = CGAffineTransform.identity }) { _ in } } } func snapShotImage(afterScreenUpdates after: Bool) -> UIImage? { UIGraphicsBeginImageContext(self.bounds.size) self.drawHierarchy(in: self.bounds, afterScreenUpdates: after) let snap = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return snap } } extension NotificationCenter { class func post(_ name: String) { `default`.post(name: Notification.Name(rawValue: name), object: nil) } class func observe(_ name: String, usingBlock block: @escaping (Notification!) -> Void) -> NSObjectProtocol { return `default`.addObserver(forName: NSNotification.Name(rawValue: name), object: nil, queue: nil, using:block) } class func observe<T: AnyObject>(_ target: T, name: String, usingBlock block: @escaping (_ note: Notification?, _ targetRef: T) -> Void) -> NSObjectProtocol { weak var weakTarget = target return `default`.addObserver(forName: NSNotification.Name(rawValue: name), object: nil, queue: nil) { if let strTarget = weakTarget { block($0, strTarget) } } } } extension Date { static func todayComponents() -> (day: Int, month: Int, year: Int) { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let units: NSCalendar.Unit = [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year] let comps = (calendar as NSCalendar).components(units, from: Date()) return (comps.day!, comps.month!, comps.year!) } var shortDescription: String { return self.customDescription(.short, date: .short) } var shortTime: String { return self.customDescription(.short) } var shortDate: String { return self.customDescription(date: .short) } var mediumDescription: String { return self.customDescription(.medium, date: .medium) } var mediumTime: String { return self.customDescription(.medium) } var mediumDate: String { return self.customDescription(date: .medium) } var longDescription: String { return self.customDescription(.long, date: .long) } var longTime: String { return self.customDescription(.long) } var longDate: String { return self.customDescription(date: .long) } func customDescription(_ time: DateFormatter.Style = .none, date: DateFormatter.Style = .none) -> String { let form = DateFormatter() form.timeStyle = time form.dateStyle = date return form.string(from: self) } func formattedFromCompenents(_ styleAttitude: DateFormatter.Style, year: Bool = true, month: Bool = true, day: Bool = true, hour: Bool = true, minute: Bool = true, second: Bool = true) -> String { let long = styleAttitude == .long || styleAttitude == .full ? true : false var comps = "" if year { comps += long ? "yyyy" : "yy" } if month { comps += long ? "MMMM" : "MMM" } if day { comps += long ? "dd" : "d" } if hour { comps += long ? "HH" : "H" } if minute { comps += long ? "mm" : "m" } if second { comps += long ? "ss" : "s" } let format = DateFormatter.dateFormat(fromTemplate: comps, options: 0, locale: Locale.current) let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: self) } func formatted(_ format: String) -> String { let form = DateFormatter() form.dateFormat = format return form.string(from: self) } /** Init an NSDate with string and format. eg. (W3C format: "YYYY-MM-DDThh:mm:ss") - parameter val: the value with the date info - parameter format: the format of the value string - parameter timeZone: optional, default is GMT time (not current locale!) - returns: returns the created date, if succeeded */ init?(val: String, format: String, timeZone: String = "") { let form = DateFormatter() form.dateFormat = format if timeZone.emptyDeduced { form.timeZone = TimeZone(secondsFromGMT: 0) } else { form.timeZone = TimeZone(identifier: timeZone) } if let date = form.date(from: val) { self.init(timeIntervalSince1970: date.timeIntervalSince1970) } else { self.init() return nil } } } extension UIApplication { static var isAppInForeground: Bool { return shared.applicationState == UIApplicationState.active } func registerForPushNotifications() { let types: UIUserNotificationType = ([.alert, .badge, .sound]) let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: types, categories: nil) registerUserNotificationSettings(settings) registerForRemoteNotifications() } } extension FileManager { class func documentsDir() -> String { var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) return paths[0] } class func cachesDir() -> String { var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) return paths[0] } class func tempBaseDir() -> String! { print("temp - \(NSTemporaryDirectory())") return NSTemporaryDirectory() } } func + <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) -> Dictionary<K,V> { var map = Dictionary<K,V>() for (k, v) in left { map[k] = v } for (k, v) in right { map[k] = v } return map }
32.446479
213
0.598559
e523c581b3077a8a1dab6212be119f04b113d00b
457
// // MockFavoriteView.swift // RealEstateTests // // Created by Isabela Karen on 25/12/18. // Copyright © 2018 Isabela Karen. All rights reserved. // import Foundation @testable import RealEstate class MockFavoriteView: IFavoritesView { var message = "" var title = "" func reloadList() { } func showAlert(message: String, title: String) { self.message = message self.title = title } }
17.576923
56
0.619256
036f181e501574725af25da59181d668e26636c4
813
// // NSBezierPath++.swift // OnlySwitch // // Created by Jacklandrin on 2021/12/9. // import AppKit extension NSBezierPath { var cgPath: CGPath { let path = CGMutablePath() var points = [CGPoint](repeating: .zero, count: 3) for i in 0 ..< self.elementCount { let type = self.element(at: i, associatedPoints: &points) switch type { case .moveTo: path.move(to: points[0]) case .lineTo: path.addLine(to: points[0]) case .curveTo: path.addCurve(to: points[2], control1: points[0], control2: points[1]) case .closePath: path.closeSubpath() @unknown default: continue } } return path } }
25.40625
86
0.510455
286449a3b4c9bbe8ebafb2f905c386fb4c0d7293
7,657
import UIKit import XCTest import Treasure fileprivate func == <K, V>(left: [K:V], right: [K:V]) -> Bool { return NSDictionary(dictionary: left).isEqual(to: right) } class Tests: XCTestCase { override func setUp() { Treasure.strictValidationOnInitialization = true super.setUp() } override func tearDown() { Treasure.clearChest() super.tearDown() } func testExample() { let testProject: Project? = Treasure(json: TestJson.projectJson)?.map() let testUser: User? = User.from(TestJson.userJson) if let manager = testProject?.manager, let user = testUser { XCTAssertTrue(manager == user) } else { XCTFail() } } func testTopLevelValidation() { let test = Treasure(json: TestJson.invalidTopLevelJson) let metaTest = Treasure(json: TestJson.metaJson) let includedTest = Treasure(json: TestJson.invalidTopLevelIncludedJson) let validTest = Treasure(json: TestJson.validTopLevelJson) let validDocumentWithRelationship = Treasure(json: TestJson.validDocumentWithRelationship) let validDocumentWithManyRelationships = Treasure(json: TestJson.validDocumentWithManyRelationships) XCTAssertTrue(test == nil) XCTAssertTrue(metaTest != nil) XCTAssertTrue(includedTest == nil) XCTAssertTrue(validTest != nil) XCTAssertTrue(validDocumentWithRelationship != nil) XCTAssertTrue(validDocumentWithManyRelationships != nil) } func testNoPool() { let testProjectNotRemoved: Project? = Treasure(json: TestJson.validTopLevelJson)?.map() let testProject: Project? = Treasure.map(json: TestJson.projectJson) let testUser: User? = User.from(TestJson.userJson) if let testNotRemoved = testProjectNotRemoved, let typeChest = Treasure.chest[testNotRemoved.type] as? [JSONObject] { XCTAssertTrue(typeChest.contains(where: {$0[Key.id] as! String == testNotRemoved.id})) } if let test = testProject, let typeChest = Treasure.chest[test.type] as? [JSONObject] { XCTAssertFalse(typeChest.contains(where: {$0[Key.id] as! String == test.id})) } if let manager = testProject?.manager, let user = testUser { XCTAssertTrue(manager == user) } else { XCTFail() } } func testCreateToOne() { let toOneRelationship = ToOneRelationship(data: RelationshipData(type: "users", id: "4")).jsonWith(key: "users")! let project = Treasure.jsonForResourceWith(type: "projects", attributes: ["title": "Test Project"], relationship: toOneRelationship) let testJson = [ "data": [ "type": "projects", "attributes": [ "title": "Test Project" ], "relationships": [ "users": [ "data": ["type": "users", "id": "4"] ] ] ] ] XCTAssertTrue(project as NSDictionary == testJson as NSDictionary) } func testCreateToMany() { let pointsData1 = RelationshipData(type: "points", id: "1") let pointsData2 = RelationshipData(type: "points", id: "2") let toManyRelationship = ToManyRelationship.jsonWith(key: "points", data: [pointsData1, pointsData2]) let uuid = UUID() let project = Treasure.jsonForResourceWith(type: "projects", id: uuid, attributes: ["title": "Test ToMany"], relationship: toManyRelationship) XCTAssertTrue(project as NSDictionary == TestJson.projectPointsJson(id: uuid) as NSDictionary) } func testCreateCombo() { let usersData = RelationshipData(type: "users", id: "4") let pointsData1 = RelationshipData(type: "points", id: "1") let pointsData2 = RelationshipData(type: "points", id: "2") let toOneRelationship = ToOneRelationship.jsonWith(key: "users", data: usersData) let toManyRelationship = ToManyRelationship(data: [pointsData1, pointsData2]).jsonWith(key: "points")! let project = Treasure.jsonForResourceWith(type: "projects", attributes: ["title": "Test ToMany"], relationships: [toOneRelationship, toManyRelationship]) XCTAssertTrue(project as NSDictionary == TestJson.projectJsonManyRelationships as NSDictionary) } func testUpdate() { let _: Project? = Treasure(json: TestJson.projectJson)?.map() let toOneRelationship = ToOneRelationship(data: RelationshipData(type: "users", id: "10")).jsonWith(key: "users")! let project = Treasure.jsonForResourceUpdateWith(type: "projects", id: "1", attributes: ["title": "The Best Project"], relationship: toOneRelationship) XCTAssertTrue(project as NSDictionary == TestJson.projectJsonUpdated as NSDictionary) } func testReplace() { let userJson: JSONObject = [ "id": "4", "type": "users", "attributes": [ "name": "New Name" ], "relationships": [ "projects": [ "data": ["type": "projects", "id": "1"] ] ] ] let testUserJson: JSONObject = [ "id": "4", "type": "users", "attributes": [ "name": "New Name", "description": "The best test user ever" ], "relationships": [ "projects": [ "data": ["type": "projects", "id": "1"] ] ] ] let json: JSONObject = [ "data": [ "id": "1", "type": "projects", "attributes": [ "title": "Test Project" ], "relationships": [ "users": [ "data": ["type": "users", "id": "4"] ] ] ], "included": [userJson] ] let _: Project? = Treasure(json: TestJson.projectJson)?.map() let _: Project? = Treasure(json: json)?.map() if let user = Treasure.chest["users"] as? [JSONObject] { XCTAssertTrue(user.first! == testUserJson) } else { XCTFail() } } func testStoreData() { let _: Project? = Treasure(json: TestJson.projectJson)?.map() let _: User? = Treasure(json: TestJson.userJson)?.map() let json = Treasure.chest if let data = Treasure.chestData() { Treasure.clearChest() Treasure.store(data) XCTAssertTrue(json == Treasure.chest) } else { XCTFail() } } func testResourceFromRelationship() { let project: Project? = Treasure(json: TestJson.projectJson)?.map() let relationship: ToOneRelationship = ToOneRelationship(data: RelationshipData(type: "users", id: "4")) let user: User? = try? Treasure.resourceFor(relationship: relationship) if let user = user, let manager = project?.manager { XCTAssert(manager == user) } else { XCTFail() } } }
34.031111
162
0.544208
2134dcf36494abdca1b88d2232d5869d1645f292
1,267
// // MyView.swift // iOS_Demo // // Created by Namazu on 2017/10/20. // Copyright © 2017年 namazu923. All rights reserved. // import UIKit @IBDesignable class MyView: UIView { var label: UILabel! @IBInspectable var showLabel: Bool = true { didSet { if showLabel == true { label.isHidden = false } else { label.isHidden = true } } } @IBInspectable var textColor: UIColor = UIColor.black { didSet { label.textColor = textColor } } override init(frame: CGRect) { super.init(frame: frame) label = UILabel.init(frame: CGRect(x: 10, y: 10, width: 150, height: 20)) label.text = "This is MyView" label.textColor = UIColor.black label.backgroundColor = UIColor.white self.addSubview(label) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) label = UILabel.init(frame: CGRect(x: 10, y: 10, width: 150, height: 20)) label.text = "This is MyView" label.textColor = UIColor.black label.backgroundColor = UIColor.white self.addSubview(label) } }
23.462963
81
0.54854
22e4225afa889f7a0f352e5ef8ceed0c86542771
1,890
// // GetLocationTool.swift // API Example // // Created by mac on 2018/10/31. // Copyright © 2018年 cho. All rights reserved. // 定位 import UIKit import CoreLocation class GetLocationTool: NSObject, CLLocationManagerDelegate { var locationManager: CLLocationManager! private var completionBlock: ((_ lat: String, _ longi: String)->())? /// 开启定位 func openLocation(completion:@escaping ((_ lat: String, _ longi: String)->())) { locationManager = CLLocationManager() locationManager.delegate = self // 定位方式 locationManager.desiredAccuracy = kCLLocationAccuracyBest // 更新距离 locationManager.distanceFilter = 150 // 使用应用程序期间允许访问位置数据 locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { // 开启定位 locationManager.startUpdatingLocation() } completionBlock = completion } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { // 判断是否为空 if location.horizontalAccuracy > 0 { let latitude = "\(location.coordinate.latitude)" let longtitude = "\(location.coordinate.longitude)" print("经度:\(latitude) 纬度:\(longtitude)") manager.stopUpdatingLocation() completionBlock?(latitude, longtitude) } } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("定位出现失败: \(error)") } // 出现错误 func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) { print("定位出现错误: \(error ?? "" as! Error)") } }
29.076923
105
0.601587
e43dd27f44cd7d3ec1a61b80e6917655902a8b97
533
class Solution { func calPoints(_ ops: [String]) -> Int { var history = [Int]() for op in ops { if op == "+" { history.append(history[history.count-1] + history[history.count-2]) } else if op == "D" { history.append(history[history.count-1] * 2) } else if op == "C" { history.removeLast() } else { history.append(Int(op)!) } } return history.reduce(0) { $0 + $1 } } }
28.052632
83
0.435272
5bbb43d2ea5aa9c3cd1d8f2f7554156cd0a18db5
3,825
// // MyComicsListView.swift // ComicsInfo // // Created by Aleksandar Dinic on 14/12/2021. // import SwiftUI struct MyComicsListView: View { private let character: Character private let seriesSummary: SeriesSummary @ObservedObject private var viewModel: MyComicsListViewModel @State private var showBanner = AppTrackingManager.authorization init( character: Character, seriesSummary: SeriesSummary, viewModel: MyComicsListViewModel = MyComicsListViewModel() ) { self.character = character self.seriesSummary = seriesSummary self.viewModel = viewModel } var body: some View { VStack(spacing: 4) { ScrollView { LazyVStack(spacing: 4) { if viewModel.status == .loading { Spacer() ProgressView("Loading...") Spacer() } else { comicsList if viewModel.canLoadMore { loadingIndicator } } } .padding() } if showBanner { BannerView(showBanner: $showBanner, adUnitID: Environment.comicsListADUnitID) } } .onAppear { viewModel.getComicSummaries(for: seriesSummary.identifier) } .alert(isPresented: $viewModel.showError) { Alert(title: Text(viewModel.errorMessage)) } .navigationBarTitle(seriesSummary.title, displayMode: .inline) } private var comicsList: some View { ForEach(viewModel.comics, id: \.identifier) { comic in NavigationLink( destination: ComicInfoView( viewModel: ComicInfoViewModel( character: character, seriesSummary: seriesSummary, comicSummary: comic, useCase: viewModel.useCase ) ) ) { ComicSummaryView( for: comic, seriesTitle: seriesSummary.title ) .onAppear { guard viewModel.lastIdentifier == comic.identifier else { return } viewModel.getComicSummaries( for: seriesSummary.identifier, lastID: viewModel.lastIdentifier ) } } .buttonStyle(PlainButtonStyle()) } } private var loadingIndicator: some View { HStack { Spacer() ProgressView() Spacer() } } } #if DEBUG struct MyComicsListView_Previews: PreviewProvider { private static let character = Character.make() static let seriesSummary = SeriesSummary.make( identifier: "1", popularity: 0, title: "Spider-Man", thumbnail: "", description: "", startYear: nil, endYear: nil ) static let viewModel = MyComicsListViewModel( comics: [ ComicSummary.make(), ComicSummary.make(), ComicSummary.make() ], status: .showComics ) static var previews: some View { NavigationView { ForEach(ColorScheme.allCases, id: \.self) { color in MyComicsListView( character: character, seriesSummary: seriesSummary, viewModel: viewModel ) .previewDisplayName("\(color)") .environment(\.colorScheme, color) } } } } #endif
28.333333
93
0.500654