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
fb99f5912ee7f97e9fb9d10a02dccc98a33c8b54
1,151
// https://github.com/Quick/Quick import Quick import Nimble import PopUpVC class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
22.568627
60
0.356212
79e873cea66e82c590ec94fdbd1c0f24f135a0aa
583
// // UISwitch+CustomPublisher.swift // STRV Project template // // Created by Jaroslav Janda on 10.03.2021. // Copyright © 2021 EndFA, LLC. All rights reserved. // import Combine import UIKit public extension UISwitch { var valueChangedPublisher: AnyPublisher<UISwitch, Never> { EventPublisher(control: self, event: .valueChanged) .share() .eraseToAnyPublisher() } var isOnPublisher: AnyPublisher<Bool, Never> { valueChangedPublisher .map(\.isOn) .share() .eraseToAnyPublisher() } }
22.423077
62
0.631218
ab5bd93cff286d1f35983277c76713538662c9c3
4,504
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import MaterialComponents.MaterialBottomNavigation_ColorThemer import MaterialComponents.MaterialColorScheme class BottomNavigationTitleVisibilityChangeExample: UIViewController, MDCBottomNavigationBarDelegate { @objc var colorScheme = MDCSemanticColorScheme() let instructionLabel = UILabel() // Create a bottom navigation bar to add to a view. let bottomNavBar = MDCBottomNavigationBar() init() { super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = colorScheme.backgroundColor view.addSubview(bottomNavBar) bottomNavBar.sizeThatFitsIncludesSafeArea = false // Always show bottom navigation bar item titles. bottomNavBar.titleVisibility = .always // Cluster and center the bottom navigation bar items. bottomNavBar.alignment = .centered // Add items to the bottom navigation bar. let tabBarItem1 = UITabBarItem(title: "Home", image: UIImage(named: "Home"), tag: 0) let tabBarItem2 = UITabBarItem(title: "Messages", image: UIImage(named: "Email"), tag: 1) let tabBarItem3 = UITabBarItem(title: "Favorites", image: UIImage(named: "Favorite"), tag: 2) bottomNavBar.items = [ tabBarItem1, tabBarItem2, tabBarItem3 ] // Select a bottom navigation bar item. bottomNavBar.selectedItem = tabBarItem2; bottomNavBar.delegate = self addInstructionLabel() } func layoutBottomNavBar() { let size = bottomNavBar.sizeThatFits(view.bounds.size) var bottomNavBarFrame = CGRect(x: 0, y: view.bounds.height - size.height, width: size.width, height: size.height) if #available(iOS 11.0, *) { bottomNavBarFrame.size.height += view.safeAreaInsets.bottom bottomNavBarFrame.origin.y -= view.safeAreaInsets.bottom } bottomNavBar.frame = bottomNavBarFrame } func addInstructionLabel() { instructionLabel.numberOfLines = 0 instructionLabel.textAlignment = .center instructionLabel.lineBreakMode = .byWordWrapping instructionLabel.text = "Choose the Home tab to make all titles disappear, and any other tab to make them reappear." view.addSubview(instructionLabel) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var viewBounds = view.bounds; if #available(iOS 11.0, *) { viewBounds = viewBounds.inset(by: view.safeAreaInsets) } let labelWidth = min(viewBounds.size.width - 32, 480); let labelSize = instructionLabel.sizeThatFits(CGSize(width: labelWidth, height: viewBounds.size.height)) instructionLabel.bounds = CGRect(x: 0, y: 0, width: labelSize.width, height: labelSize.height) instructionLabel.center = CGPoint(x: viewBounds.midX, y: viewBounds.midY); layoutBottomNavBar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } func bottomNavigationBar(_ bottomNavigationBar: MDCBottomNavigationBar, didSelect item: UITabBarItem) { if item == bottomNavigationBar.items[0] { bottomNavigationBar.titleVisibility = .never } else { bottomNavigationBar.titleVisibility = .always } } } // MARK: Catalog by convention extension BottomNavigationTitleVisibilityChangeExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Bottom Navigation", "Bottom Navigation Title Visibility (Swift)"], "primaryDemo": false, "presentable": false, ] } }
35.746032
120
0.701155
38f02f1525bc31a227f3ed6f54288c50dee7ae46
1,210
// // OctopusKitQuickStart.swift // OctopusUI // https://github.com/InvadingOctopus/octopusui // // Created by [email protected] on 2019/11/3. // Copyright © 2020 Invading Octopus. Licensed under Apache License v2.0 (see LICENSE.txt) // import SwiftUI struct FatButtonStyle: ButtonStyle { var color: Color = .accentColor func makeBody(configuration: Configuration) -> some View { configuration.label .foregroundColor(.white) .padding() .background(RoundedRectangle(cornerRadius: 10) .foregroundColor(color) .opacity(0.85) .brightness(configuration.isPressed ? 0.2 : 0) .shadow(color: .black, radius: configuration.isPressed ? 5 : 10)) .padding() } } /// Preview in live mode to test interactivity and animations. struct ButtonStyle_Previews: PreviewProvider { static var previews: some View { VStack(spacing: 20) { ForEach(0..<3) { _ in Button(action: {}) { Text("Fat Button Style") } .buttonStyle(FatButtonStyle(color: .randomExcludingBlackWhite)) } } .padding() .background(Color.random) .previewLayout(.sizeThatFits) } }
26.304348
91
0.65124
906ebb5027ec5f4ba8c902326c14fba9064e56a5
888
// // UserSettings.swift // AUSTTravels // // Created by Shahriar Nasim Nafi on 13/12/21. // Copyright © 2021 Shahriar Nasim Nafi. All rights reserved. // import Foundation import Defaults import FirebaseDatabase struct UserSettings: Codable, Defaults.Serializable { var isLocationNotification: Bool = false var isPingNotification: Bool = false var primaryBus: String = "None" init() { } init(snapshot: DataSnapshot) { guard let dict = snapshot.value as? NSDictionary else { return } isLocationNotification = dict["isLocationNotification"] as? Bool ?? false isPingNotification = dict["isPingNotification"] as? Bool ?? false primaryBus = dict["primaryBus"] as? String ?? "" } } extension Defaults.Keys { static let userSettings = Key<UserSettings>("userSettings", default: .init()) }
26.909091
81
0.666667
03b39f76c1ccc8bbccbcbf79ac044b45f4b11f5b
2,200
// // PlayerNameNode.swift // Smash Up Counter iOS // // Created by Cyril on 08/04/2018. // Copyright © 2018 Cyril GY. All rights reserved. // import SpriteKit // MARK: - Definition class PlayerNameNode: SKNode { // MARK: - Children nodes fileprivate lazy var nameLabel: SKLabelNode? = { self.childNode(withName: "name") as? SKLabelNode }() fileprivate lazy var removeNode: SKNode? = { self.childNode(withName: "remove") }() fileprivate lazy var disabledNode: SKSpriteNode? = { self.childNode(withName: "disabled") as? SKSpriteNode }() fileprivate lazy var disabledLabel: SKLabelNode? = { self.childNode(withName: ".//disabledLabel") as? SKLabelNode }() // MARK: - Properties private(set) var playerName: String? = nil private(set) var isDisabled = true var positionInScene: CGPoint? { return self.parent?.parent?.position } // MARK: - Life cycle func update(size: CGSize, andCenter center: CGRect) { self.disabledNode?.centerRect = center self.disabledNode?.size = size self.disabledLabel?.text = NSLocalizedString("playersScene.playerView.hint", value: "No One", comment: "Hint of the player's name.") self.disabledLabel?.applyTextStyle() } func setUp(withPlayer player: Player) { self.playerName = player.name self.isDisabled = false self.disabledNode?.isHidden = true self.nameLabel?.isHidden = false self.removeNode?.isHidden = false self.nameLabel?.text = self.playerName self.nameLabel?.applyTextStyle() if let nameLabel = self.nameLabel, let removeNode = self.removeNode { removeNode.position = CGPoint(x: (nameLabel.position.x + nameLabel.frame.size.width/2.0 + removeNode.frame.size.width/2.0 + 3), y: removeNode.position.y) } } func setDown() { self.playerName = nil self.isDisabled = true self.disabledNode?.isHidden = false self.nameLabel?.isHidden = true self.removeNode?.isHidden = true } }
27.848101
165
0.617273
e252e2d98c8a8da664819fef3010fd79cd280aae
1,477
// Generated from /Users/duda/Development/_scm/antlr/antlr4-4.7.2/runtime/Swift/Tests/Antlr4Tests/VisitorCalc.g4 by ANTLR 4.7.2 import Antlr4 /** * This class provides an empty implementation of {@link VisitorCalcVisitor}, * which can be extended to create a visitor which only needs to handle a subset * of the available methods. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ open class VisitorCalcBaseVisitor<T>: AbstractParseTreeVisitor<T> { /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ open func visitS(_ ctx: VisitorCalcParser.SContext) -> T? { return visitChildren(ctx) } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ open func visitAdd(_ ctx: VisitorCalcParser.AddContext) -> T? { return visitChildren(ctx) } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ open func visitNumber(_ ctx: VisitorCalcParser.NumberContext) -> T? { return visitChildren(ctx) } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ open func visitMultiply(_ ctx: VisitorCalcParser.MultiplyContext) -> T? { return visitChildren(ctx) } }
36.02439
127
0.700745
d552292dccebbf6e7ba1dd53c6ad428e163c19a4
1,976
// // Imversed+NFT+TransferRequest.swift // Imversed // // Created by Ilya S. on 15.12.2021. // import Foundation public extension NFT { class TransferRequest: TxMessage { private let doNotModifyValue = "[do-not-modify]" let token: Imversed.Token let recipient: Wallet.CosmAddress public init(token: Imversed.Token, recipient: Wallet.CosmAddress) { self.token = token self.recipient = recipient } override var content: Content? { return Imversed_Nft_MsgTransferNFT.with({ $0.id = self.token.id $0.denomID = self.token.denom $0.name = self.doNotModifyValue $0.uri = self.doNotModifyValue $0.data = self.doNotModifyValue $0.sender = self.token.owner $0.recipient = self.recipient }) } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.token.id, forKey: .id) try container.encode(self.token.denom, forKey: .denomId) try container.encode(self.doNotModifyValue, forKey: .name) try container.encode(self.doNotModifyValue, forKey: .uri) try container.encode(self.doNotModifyValue, forKey: .data) try container.encode(self.token.owner, forKey: .sender) try container.encode(self.recipient, forKey: .recipient) } } } extension NFT.TransferRequest { enum CodingKeys: String, CodingKey { case id = "id" case denomId = "denom_id" case name = "name" case uri = "uri" case data = "data" case sender = "sender" case recipient = "recipient" } }
30.4
75
0.560223
d90da331cf22db8707780b44b674ba42cecb1ef5
330
// // FeeTotalTableViewCell.swift // EliteSISSwift // // Created by Daffolap-51 on 22/04/18. // Copyright © 2018 Kunal Das. All rights reserved. // import UIKit class FeeTotalTableViewCell: UITableViewHeaderFooterView { override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
18.333333
58
0.687879
79f6e9cce1ea3259ade06ed945e94e74c6d9e572
850
// // MockLoader.swift // SwiftUICleanArchitectureTests // // Created by Quan on 10/6/21. // import Foundation struct MockLoader { static func load(_ file: String) -> String? { let bundle = Bundle.allBundles.first { $0.bundlePath.hasSuffix(".xctest") } guard let path = bundle?.path(forResource: file, ofType: "") else { return nil } let json = try? String(contentsOfFile: path) return json } static func load<T: Decodable>(_ file: String, ofType type: T.Type) -> T? { let bundle = Bundle.allBundles.first { $0.bundlePath.hasSuffix(".xctest") } guard let path = bundle?.url(forResource: file, withExtension: nil), let data = try? Data(contentsOf: path) else { return nil } let decoder = JSONDecoder() return try? decoder.decode(type, from: data) } }
32.692308
88
0.632941
d72b1c1fec7c48af8a5735d907559d76e82e870c
981
// // MapDataManager.swift // LetsEat // // Created by Craig Clayton on 11/15/16. // Copyright © 2016 Craig Clayton. All rights reserved. // import Foundation import MapKit class MapDataManager:DataManager { fileprivate var items:[RestaurantAnnotation] = [] var annotations:[RestaurantAnnotation] { return items } func fetch(completion: (_ annotations:[RestaurantAnnotation]) -> ()) { if items.count > 0 { items.removeAll() } for data in load(file: "MapLocations") { items.append(RestaurantAnnotation(dict: data)) } completion(items) } func currentRegion(latDelta:CLLocationDegrees, longDelta:CLLocationDegrees) -> MKCoordinateRegion { guard let item = items.first else { return MKCoordinateRegion() } let span = MKCoordinateSpanMake(latDelta, longDelta) return MKCoordinateRegion(center: item.coordinate, span: span) } }
19.235294
103
0.644241
487119ff285036be35f3bdf6207b056f73f4cb0d
2,764
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: proto.fbe // Version: 1.4.0.0 import ChronoxorFbe // Fast Binary Encoding Order final model public class OrderFinalModel: Model { private let _model: FinalModelOrder public override init(buffer: Buffer = Buffer()) { _model = FinalModelOrder(buffer: buffer, offset: 8) super.init(buffer: buffer) } // Model type public var fbeType: Int = fbeTypeConst static let fbeTypeConst: Int = FinalModelOrder.fbeTypeConst // Check if the struct value is valid public func verify() -> Bool { if (buffer.offset + _model.fbeOffset) > buffer.size { return false } let fbeStructSize = Int(readUInt32(offset: _model.fbeOffset - 8)) let fbeStructType = Int(readUInt32(offset: _model.fbeOffset - 4)) if (fbeStructSize <= 0) || (fbeStructType != fbeType) { return false } return ((8 + _model.verify()) == fbeStructSize) } // Serialize the struct value public func serialize(value: Order) throws -> Int { let fbeInitialSize = buffer.size let fbeStructType = fbeType var fbeStructSize = 8 + _model.fbeAllocationSize(value: value) let fbeStructOffset = try buffer.allocate(size: fbeStructSize) - buffer.offset if (buffer.offset + fbeStructOffset + fbeStructSize) > buffer.size { assertionFailure("Model is broken!") return 0 } fbeStructSize = try _model.set(value: value) + 8 try buffer.resize(size: fbeInitialSize + fbeStructSize) write(offset: _model.fbeOffset - 8, value: UInt32(fbeStructSize)) write(offset: _model.fbeOffset - 4, value: UInt32(fbeStructType)) return fbeStructSize } // Deserialize the struct value public func deserialize() -> Order { var value = Order(); _ = deserialize(value: &value); return value } public func deserialize(value: inout Order) -> Int { if (buffer.offset + _model.fbeOffset) > buffer.size { assertionFailure("Model is broken!") return 0 } let fbeStructSize = Int32(readUInt32(offset: _model.fbeOffset - 8)) let fbeStructType = Int32(readUInt32(offset: _model.fbeOffset - 4)) if (fbeStructSize <= 0) || (fbeStructType != fbeType) { assertionFailure("Model is broken!") return 8 } var fbeSize = Size() value = _model.get(size: &fbeSize, fbeValue: &value) return 8 + fbeSize.value } // Move to the next struct value public func next(prev: Int) { _model.fbeShift(size: prev) } }
32.517647
108
0.634226
b990b86668883c0d5a9a2357742bacf538f0d516
742
// // Created by Filipp Lebedev on 05/05/2019. // import RealmSwift class CitiesDataStore: AbstractDataStore { func setupCityObserving(completion: @escaping ([CityStorageModel]?, Error?) -> Void) { storageManager.setupObjectsObserver(type: CityStorageModel.self) { [weak self] (items, error) in if let items = items { completion(items, nil) } else if let error = error { completion(nil, error) } } } func deleteCity(id: UniqueIdentifier, completion: @escaping (_ success: Bool) -> Void) { storageManager.delete(type: CityStorageModel.self, id: id) { [weak self] (success) in completion(success) } } }
29.68
104
0.601078
c1e3e96ea568dafeeb17df0368866f0aa7c0691e
4,649
// RUN: %target-swift-frontend -enable-sil-ownership -sil-verify-all -primary-file %s -emit-sil -o - -verify | %FileCheck %s // These tests are deliberately shallow, because I do not want to depend on the // specifics of SIL generation, which might change for reasons unrelated to this // pass func foo(_ x: Float) -> Float { return bar(x); } // CHECK-LABEL: sil hidden @_T018mandatory_inlining3foo{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $Float): // CHECK-NEXT: debug_value %0 : $Float, let, name "x" // CHECK-NEXT: return %0 @_transparent func bar(_ x: Float) -> Float { return baz(x) } // CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3bar{{[_0-9a-zA-Z]*}}F // CHECK-NOT: function_ref // CHECK-NOT: apply // CHECK: return @_transparent func baz(_ x: Float) -> Float { return x } // CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3baz{{[_0-9a-zA-Z]*}}F // CHECK: return func spam(_ x: Int) -> Int { return x } // CHECK-LABEL: sil hidden @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F @_transparent func ham(_ x: Int) -> Int { return spam(x) } // CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3ham{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F // CHECK: apply // CHECK: return func eggs(_ x: Int) -> Int { return ham(x) } // CHECK-LABEL: sil hidden @_T018mandatory_inlining4eggs{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F // CHECK: apply // CHECK: return @_transparent func call_auto_closure(_ x: @autoclosure () -> Bool) -> Bool { return x() } func test_auto_closure_with_capture(_ x: Bool) -> Bool { return call_auto_closure(x) } // This should be fully inlined and simply return x; however, there's a lot of // non-SSA cruft that I don't want this test to depend on, so I'm just going // to verify that it doesn't have any function applications left // CHECK-LABEL: sil hidden @{{.*}}test_auto_closure_with_capture // CHECK-NOT: = apply // CHECK: return func test_auto_closure_without_capture() -> Bool { return call_auto_closure(false) } // This should be fully inlined and simply return false, which is easier to check for // CHECK-LABEL: sil hidden @_T018mandatory_inlining33test_auto_closure_without_captureSbyF // CHECK: [[FV:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK: [[FALSE:%.*]] = struct $Bool ([[FV:%.*]] : $Builtin.Int1) // CHECK: return [[FALSE]] infix operator &&& : LogicalConjunctionPrecedence infix operator ||| : LogicalDisjunctionPrecedence @_transparent func &&& (lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool { if lhs { return rhs() } return false } @_transparent func ||| (lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool { if lhs { return true } return rhs() } func test_chained_short_circuit(_ x: Bool, y: Bool, z: Bool) -> Bool { return x &&& (y ||| z) } // The test below just makes sure there are no uninlined [transparent] calls // left (i.e. the autoclosure and the short-circuiting boolean operators are // recursively inlined properly) // CHECK-LABEL: sil hidden @_T018mandatory_inlining26test_chained_short_circuit{{[_0-9a-zA-Z]*}}F // CHECK-NOT: = apply [transparent] // CHECK: return // Union element constructors should be inlined automatically. enum X { case onetransp case twotransp } func testInlineUnionElement() -> X { return X.onetransp // CHECK-LABEL: sil hidden @_T018mandatory_inlining22testInlineUnionElementAA1XOyF // CHECK: enum $X, #X.onetransp!enumelt // CHECK-NOT: = apply // CHECK: return } @_transparent func call_let_auto_closure(_ x: @autoclosure () -> Bool) -> Bool { return x() } // CHECK-LABEL: sil hidden @{{.*}}test_let_auto_closure_with_value_capture // CHECK: bb0(%0 : $Bool): // CHECK-NEXT: debug_value %0 : $Bool // CHECK-NEXT: return %0 : $Bool // CHECK-LABEL: // end sil function '{{.*}}test_let_auto_closure_with_value_capture func test_let_auto_closure_with_value_capture(_ x: Bool) -> Bool { return call_let_auto_closure(x) } class C {} // CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F @_transparent func class_constrained_generic<T : C>(_ o: T) -> AnyClass? { // CHECK: return return T.self } // CHECK-LABEL: sil hidden @_T018mandatory_inlining6invokeyyAA1CCF : $@convention(thin) (@owned C) -> () { func invoke(_ c: C) { // CHECK-NOT: function_ref @_T018mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F // CHECK-NOT: apply // CHECK: init_existential_metatype _ = class_constrained_generic(c) // CHECK: return }
28.521472
124
0.697569
de24d788a00027335ae959d29c8bedcb116597a6
2,128
/** * Question Link: https://leetcode.com/problems/minimum-window-substring/ * Primary idea: Use dictionary and int to verify if contain all characters, and update * startIndex and miniWindow as well * * Time Complexity: O(n^2), Space Complexity: O(n) * */ class MinimumWindowSubstring { func minWindow(_ s: String, _ t: String) -> String { let sChars = Array(s.characters) let sLen = sChars.count let tLen = t.characters.count guard sLen >= tLen else { return "" } var freqencyDict = calcCharFrec(t) var startIndex = 0 var minLen = Int.max var count = 0 var res = "" for (i, current) in sChars.enumerated() { guard freqencyDict[current] != nil else { continue } // update freqency dictionary freqencyDict[current]! -= 1 if freqencyDict[current]! >= 0 { count += 1 } // update startIndex while count == tLen { let startChar = sChars[startIndex] guard freqencyDict[startChar] != nil else { startIndex += 1 continue } freqencyDict[startChar]! += 1 if freqencyDict[startChar]! > 0 { // update res if i - startIndex + 1 < minLen { res = String(sChars[startIndex...i]) minLen = i - startIndex + 1 } count -= 1 } startIndex += 1 } } return res } private func calcCharFrec(_ t: String) -> [Character: Int] { var dict = [Character: Int]() for char in t.characters { if let freq = dict[char] { dict[char] = freq + 1 } else { dict[char] = 1 } } return dict } }
28.373333
88
0.443139
760fec2fbd372351d3b728750b728dc146ed02b1
1,209
// // UserMoyaNetwork.swift // ExampleApp // // Created by Artur Mkrtchyan on 3/1/18. // Copyright © 2018 Artur Mkrtchyan. All rights reserved. // import Foundation import Moya import ObjectMapper import RxSwift import RxCocoa struct UserMoyaNetwork: UserNetworking { private let reachability = try? DefaultReachabilityService() fileprivate let provider = MoyaProvider<UserMoyaApi>() func getPopularUsers() -> Observable<[User]> { return provider.rx.request(.getPopularUsers()) .asObservable() .map({ let json = (try? $0.mapJSON()) as? [String:Any] let users = Mapper<User>().mapArray(JSONObject: json?["items"]) ?? [] return users }) .share() } func getRepos(of username: String) -> Observable<[Repo]> { // guard let reachability = reachability else { return Observable.of([])} return provider.rx.request(.getRepos(username)) .asObservable() .map({ Mapper<Repo>().mapArray(JSONObject: try? $0.mapJSON()) ?? [] }) // .retryOnBecomesReachable([], reachabilityService: reachability) .share() } }
30.225
85
0.602151
56b1b396f0fceb798aa4dd437d1669c7f3743e8a
753
import Foundation public extension FileManager { var xcodeServerDirectory: URL { let folder = "XcodeServer" let root: URL do { #if os(tvOS) root = try url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) #else root = try url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) #endif let directory = root.appendingPathComponent(folder, isDirectory: true) try createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil) return directory } catch { fatalError(error.localizedDescription) } } }
34.227273
117
0.608234
e41dd4dc66b5474135c7f3d379c186ed326389b8
3,080
// // LoginViewReactor.swift // GitTime // // Created by Kanz on 16/05/2019. // Copyright © 2019 KanzDevelop. All rights reserved. // import FirebaseRemoteConfig import ReactorKit import RxCocoa import RxSwift final class LoginViewReactor: Reactor { enum Action { case login case trial } enum Mutation { case setLoading(Bool) case setLoggedIn(Bool) } struct State { var isLoading: Bool = false var isLoggedIn: Bool = false } let initialState = State() fileprivate let authService: AuthServiceType fileprivate let keychainService: KeychainServiceType fileprivate let userService: UserServiceType var remoteConfig: RemoteConfig! init(authService: AuthServiceType, keychainService: KeychainServiceType, userService: UserServiceType) { self.authService = authService self.keychainService = keychainService self.userService = userService } // MARK: Mutation func mutate(action: Action) -> Observable<Mutation> { switch action { case .login: GitTimeAnalytics.shared.logEvent(key: "login", parameters: nil) let startLoading: Observable<Mutation> = .just(Mutation.setLoading(true)) let endLoading: Observable<Mutation> = .just(Mutation.setLoading(false)) let setLoggedIn: Observable<Mutation> = self.getAccessToken() .do(onNext: { accessToken in log.debug(accessToken) let token = accessToken.accessToken try? self.keychainService.setAccessToken(token) }) .flatMap { _ in self.userService.fetchMe() } .map { _ in true } .catch({ error -> Observable<Bool> in log.error(error.localizedDescription) try? self.keychainService.removeAccessToken() return Observable.just(false) }) .map(Mutation.setLoggedIn) return .concat([startLoading, setLoggedIn, endLoading]) case .trial: GitTimeAnalytics.shared.logEvent(key: "trial", parameters: nil) // AppDependency.shared.isTrial = true GlobalStates.shared.isTrial.accept(true) return .just(.setLoggedIn(true)) } } // MARK: Reduce func reduce(state: State, mutation: Mutation) -> State { var state = state switch mutation { case .setLoading(let isLoading): state.isLoading = isLoading case .setLoggedIn(let isLoggedIn): state.isLoggedIn = isLoggedIn } return state } private func testLogin() -> Observable<GitHubAccessToken> { return Observable.just(GitHubAccessToken.devAccessToken()) } private func getAccessToken() -> Observable<GitHubAccessToken> { return self.authService.authorize() .flatMap { code in self.authService.requestAccessToken(code: code) } } }
31.111111
85
0.611688
ac757e715e4534c1f1bc33a00f9a348ce1b7a3ee
12,122
// // ViewController.swift // VideoFeed // // Created by Doyle Illusion on 9/5/19. // Copyright © 2019 Lixi Technologies. All rights reserved. // import UIKit import AsyncDisplayKit class VideoViewController: UIViewController { private var reviews : [Review] = [ Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ElephantsDream.jpg", title: "Big Buck Bunny", body: "By Blender Foundation", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ElephantsDream.jpg", title: "Elephant Dream", body: "By Blender Foundation", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ForBiggerBlazes.jpg", title: "For Bigger Blazes", body: "By Google", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ForBiggerBlazes.jpg", title: "For Bigger Blazes", body: "By Google", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ForBiggerBlazes.jpg", title: "For Bigger Blazes", body: "By Google", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ForBiggerBlazes.jpg", title: "For Bigger Blazes", body: "By Google", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ForBiggerBlazes.jpg", title: "For Bigger Blazes", body: "By Google", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ForBiggerBlazes.jpg", title: "For Bigger Blazes", body: "By Google", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ForBiggerBlazes.jpg", title: "For Bigger Blazes", body: "By Google", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123"), Review(videoUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", placeholderUrl: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ForBiggerBlazes.jpg", title: "For Bigger Blazes", body: "By Google", user: User(avatarUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1100&q=80", name: "Hieu Hiep Nguyen", level: "Lv5"), tags: [ Tag(name: "Hiepdeptrai"), Tag(name: "Hiepdethuong"), Tag(name: "Hieptaiba") ], likeCount: "123", commentCount: "123", starCount: "123") ] private let collectionNode : ASCollectionNode = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical let node = ASCollectionNode(collectionViewLayout: layout) node.backgroundColor = .black return node }() override func viewDidLoad() { super.viewDidLoad() configureCollectionNode() self.collectionNode.view.contentInsetAdjustmentBehavior = .never } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.collectionNode.frame = view.bounds } private func configureCollectionNode() { self.view.addSubnode(collectionNode) collectionNode.delegate = self collectionNode.dataSource = self self.collectionNode.view.isPagingEnabled = true (self.collectionNode.nodeForItem(at: IndexPath(item: 0, section: 0)) as? VideoCell)?.videoNode.videoNode.play() } private func checkVisibleNodes() { for node in collectionNode.visibleNodes { guard let videoCell = node as? VideoCell, let indexPath = collectionNode.indexPath(for: videoCell), let cellRect = collectionNode.view.layoutAttributesForItem(at: indexPath) else { (node as? VideoCell)?.videoNode.videoNode.pause() return } let superView = collectionNode.supernode let convertedRect = collectionNode.convert(cellRect.frame, to: superView) let intersect = collectionNode.frame.intersection(convertedRect) let visibleHeight = intersect.height if visibleHeight == UIScreen.main.bounds.size.height { videoCell.videoNode.videoNode.play() } else { videoCell.videoNode.videoNode.pause() } } } private func presentCommentsVC() { let controller = UINavigationController(rootViewController: CommentsViewController()) controller.setNavigationBarHidden(true, animated: true) let transitionDelegate = SPStorkTransitioningDelegate() transitionDelegate.showCloseButton = false transitionDelegate.translateForDismiss = 100 transitionDelegate.customHeight = UIScreen.main.bounds.size.height / 2 transitionDelegate.showIndicator = false transitionDelegate.hapticMoments = [.willPresent, .willDismiss] controller.transitioningDelegate = transitionDelegate controller.modalPresentationStyle = .custom controller.modalPresentationCapturesStatusBarAppearance = true self.present(controller, animated: true, completion: nil) } } extension VideoViewController : ASCollectionDataSource { func collectionNode(_ collectionNode: ASCollectionNode, numberOfItemsInSection section: Int) -> Int { return reviews.count } func collectionNode(_ collectionNode: ASCollectionNode, nodeBlockForItemAt indexPath: IndexPath) -> ASCellNodeBlock { guard reviews.count > indexPath.row else { return { ASCellNode() } } let review = reviews[indexPath.item] let cellNodeBlock = { () -> ASCellNode in let cellNode = VideoCell(review: review) cellNode.onTapTextField = { [weak self] in self?.presentCommentsVC() } cellNode.onTapCommentButton = { [weak self] in self?.presentCommentsVC() } return cellNode } return cellNodeBlock } } extension VideoViewController : ASCollectionDelegateFlowLayout, UICollectionViewDelegateFlowLayout { func collectionNode(_ collectionNode: ASCollectionNode, constrainedSizeForItemAt indexPath: IndexPath) -> ASSizeRange { let size = CGSize(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height) return ASSizeRange(min: size, max: size) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { checkVisibleNodes() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { checkVisibleNodes() } } }
59.131707
486
0.676951
1843cd0843992622c736c0388d10a9cf61cc4cbf
3,332
// // SearchCategoriesView.swift // Conventions // // Created by David Bahat on 9/24/16. // Copyright © 2016 Amai. All rights reserved. // import Foundation protocol SearchCategoriesProtocol : class { func filterSearchCategoriesChanged(_ enabledCategories: Array<AggregatedSearchCategory>) } class SearchCategoriesView : UIView { @IBOutlet private weak var lecturesSwitch: UISwitch! @IBOutlet private weak var workshopsSwitch: UISwitch! @IBOutlet private weak var showsSwitch: UISwitch! @IBOutlet private weak var othersSwitch: UISwitch! @IBOutlet private weak var lecturesLabel: UILabel! @IBOutlet private weak var workshopsLabel: UILabel! @IBOutlet private weak var showsLabel: UILabel! @IBOutlet private weak var othersLabel: UILabel! weak var delegate: SearchCategoriesProtocol? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); let view = Bundle.main.loadNibNamed(String(describing: SearchCategoriesView.self), owner: self, options: nil)![0] as! UIView; view.frame = self.bounds; addSubview(view); lecturesSwitch.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) workshopsSwitch.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) showsSwitch.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) othersSwitch.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) lecturesSwitch.onTintColor = Colors.switchButtonsColor workshopsSwitch.onTintColor = Colors.switchButtonsColor showsSwitch.onTintColor = Colors.switchButtonsColor othersSwitch.onTintColor = Colors.switchButtonsColor lecturesLabel.textColor = Colors.textColor workshopsLabel.textColor = Colors.textColor showsLabel.textColor = Colors.textColor othersLabel.textColor = Colors.textColor } @IBAction fileprivate func lecturesWasTapped(_ sender: UITapGestureRecognizer) { lecturesSwitch.setOn(!lecturesSwitch.isOn, animated: true) filterSearchCategoriesChanged() } @IBAction fileprivate func gamesWasTapped(_ sender: UITapGestureRecognizer) { workshopsSwitch.setOn(!workshopsSwitch.isOn, animated: true) filterSearchCategoriesChanged() } @IBAction fileprivate func showsWasTapped(_ sender: UITapGestureRecognizer) { showsSwitch.setOn(!showsSwitch.isOn, animated: true) filterSearchCategoriesChanged() } @IBAction fileprivate func othersWasTapped(_ sender: UITapGestureRecognizer) { othersSwitch.setOn(!othersSwitch.isOn, animated: true) filterSearchCategoriesChanged() } fileprivate func filterSearchCategoriesChanged() { var searchCategories = Array<AggregatedSearchCategory>() if lecturesSwitch.isOn { searchCategories.append(AggregatedSearchCategory.lectures) } if workshopsSwitch.isOn { searchCategories.append(AggregatedSearchCategory.workshops) } if showsSwitch.isOn { searchCategories.append(AggregatedSearchCategory.shows) } if othersSwitch.isOn { searchCategories.append(AggregatedSearchCategory.others) } delegate?.filterSearchCategoriesChanged(searchCategories) } }
39.2
133
0.708283
0ec5884950a3f8429d1150440fca5f48a6742726
3,254
/** * MVC iOS Design Pattern * */ import UIKit import PlaygroundSupport struct Person { // Model let firstName: String let lastName: String } class GreetingViewController : UIViewController { // View + Controller var person: Person! var showGreetingButton: UIButton! var greetingLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480) self.setupUIElements() self.layout() } func setupUIElements() { self.title = "Test" self._setupButton() self._setupLabel() } private func _setupButton() { self.showGreetingButton = UIButton() self.showGreetingButton.setTitle("Click me", for: .normal) self.showGreetingButton.setTitle("You badass", for: .highlighted) self.showGreetingButton.setTitleColor(UIColor.white, for: .normal) self.showGreetingButton.setTitleColor(UIColor.red, for: .highlighted) self.showGreetingButton.translatesAutoresizingMaskIntoConstraints = false self.showGreetingButton.addTarget(self, action: #selector(didTapButton(sender:)), for: .touchUpInside) self.view.addSubview(self.showGreetingButton) } private func _setupLabel() { self.greetingLabel = UILabel() self.greetingLabel.textColor = UIColor.white self.greetingLabel.textAlignment = .center self.greetingLabel.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.greetingLabel) } func layout() { self._layoutButton() self._layoutLabel() self.view.layoutIfNeeded() } private func _layoutButton() { // layout button at the center of the screen let cs1 = NSLayoutConstraint(item: self.showGreetingButton!, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 1.0) let cs2 = NSLayoutConstraint(item: self.showGreetingButton!, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 1.0) self.view.addConstraints([cs1, cs2]) } private func _layoutLabel() { // layout label at the center, bottom of the screen let cs1 = NSLayoutConstraint(item: self.greetingLabel!, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 1.0) let cs2 = NSLayoutConstraint(item: self.greetingLabel!, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: -10) let cs3 = NSLayoutConstraint(item: self.greetingLabel!, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0.70, constant: 0) self.view.addConstraints([cs1, cs2, cs3]) } @objc func didTapButton(sender: UIButton) { self.greetingLabel.text = "Hello " + self.person.firstName + " " + self.person.lastName } } let model = Person(firstName: "Tom", lastName: "Grant") let vc = GreetingViewController() vc.person = model PlaygroundPage.current.liveView = vc.view
36.977273
180
0.666872
0951593070718070bb3678347da2244397111e8d
1,819
// // PriceTransactionResponseTests.swift // DropBitTests // // Created by Ben Winters on 10/10/18. // Copyright © 2018 Coin Ninja, LLC. All rights reserved. // import XCTest @testable import DropBit class PriceTransactionResponseTests: XCTestCase, ResponseStringsTestable { typealias ResponseType = PriceTransactionResponse func testDecodingResponse() { let response = decodedSampleJSON() XCTAssertNotNil(response, decodingFailureMessage) } func testNegativePriceThrowsError() { let response = PriceTransactionResponse(average: -1) XCTAssertThrowsError(try PriceTransactionResponse.validateResponse(response), "Negative price should throw error", { error in if let networkError = error as? DBTError.Network, case let .invalidValue(keyPath, value, _) = networkError { XCTAssertEqual(keyPath, PriceTransactionResponseKey.average.path, "Incorrect key description") XCTAssertEqual(value, "-1.0", "Incorrect value description") } else { XCTFail("Negative price threw incorrect error type") } }) } func testZeroPriceThrowsError() { let response = PriceTransactionResponse(average: 0) XCTAssertThrowsError(try PriceTransactionResponse.validateResponse(response), "Zero price should throw error", { _ in }) } func testEmptyStringThrowsError() { guard let sample = decodedSampleJSON() else { XCTFail(decodingFailureMessage) return } // This response doesn't have any required strings XCTAssertNoThrow(try sample.copyWithEmptyRequiredStrings().validateStringValues(), emptyStringNoThrowMessage) } } extension PriceTransactionResponse: EmptyStringCopyable { func copyWithEmptyRequiredStrings() -> PriceTransactionResponse { return PriceTransactionResponse(average: self.average) } }
32.482143
129
0.748213
14d0e721d961c0e39956747161081422aa1e5860
2,183
// // AppCategory.swift // YouTube // // Created by MAC on 3/11/18. // Copyright © 2018 MAC. All rights reserved. // import Foundation class AppStore: Decodable { var categories: [AppCategory]? } class AppCategory: Decodable { var name: String? var type: String? var apps: [App]? static func fetchFeatureApps(completion: @escaping (AppStore) -> ()) { let urlString = "https://api.letsbuildthatapp.com/appstore/featured" guard let url = URL(string: urlString) else { return } URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { return } do { let appStore = try JSONDecoder().decode(AppStore.self, from: data) DispatchQueue.main.async { completion(appStore) } } catch let err { print("error serializing json, \(err.localizedDescription)") } }.resume() } static func sampleAppCategories() -> [AppCategory] { let bestNewAppsCategory = AppCategory() bestNewAppsCategory.name = "Best New Apps" var apps = [App]() let fronzenApp = App() fronzenApp.Name = "Disney Build It: Fronzen" fronzenApp.ImageName = "fronze" fronzenApp.Category = "Entertaiment" fronzenApp.Price = 3.99 apps.append(fronzenApp) bestNewAppsCategory.apps = apps let bestNewGamesCategory = AppCategory() bestNewGamesCategory.name = "Best New Games" var bestNewGameApps = [App]() let telepaintApp = App() telepaintApp.Name = "Telepaint" telepaintApp.Category = "Games" telepaintApp.ImageName = "kanye_profile" telepaintApp.Price = 2.99 bestNewGameApps.append(telepaintApp) bestNewGamesCategory.apps = bestNewGameApps return [bestNewAppsCategory, bestNewGamesCategory] } } class App: Decodable { var Id: Int? var Name: String? var Category: String? var ImageName: String? var Price: Double? }
28.350649
82
0.587265
1d08494f64c776737c5bcb5f401e8467f4bbcb67
624
// // CounterView.swift // iOSStateBindingExample // // Created by Wayne on 2020/6/22. // Copyright © 2020 WaynesTalk. All rights reserved. // import SwiftUI struct CounterView: View { @Binding var counter: Int var body: some View { HStack { Text(String(counter)) Button(action: { self.counter -= 1 }, label: { Text("-") }) Button(action: { self.counter += 1 }, label: { Text("+") }) } .padding() } } struct CounterView_Previews: PreviewProvider { static var previews: some View { CounterView(counter: .constant(0)) } }
21.517241
71
0.575321
23e454086f6e7e21b35a76fb0332008008690963
3,373
import XCTest public let TestVertexShader = "attribute vec4 position;\n attribute vec4 inputTextureCoordinate;\n \n varying vec2 textureCoordinate;\n \n void main()\n {\n gl_Position = position;\n textureCoordinate = inputTextureCoordinate.xy;\n }\n " public let TestFragmentShader = "varying vec2 textureCoordinate;\n \n uniform sampler2D inputImageTexture;\n \n void main()\n {\n gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n }\n " public let TestBrokenVertexShader = "attribute vec4 position;\n attribute vec4 inputTextureCoordinate;\n \n varing vec2 textureCoordinate;\n \n void main()\n {\n gl_Position = position;\n textureCoordinate = inputTextureCoordinate.xy;\n }\n " public let TestBrokenFragmentShader = "varying vec2 textureCoordinate;\n \n uniform sampler2D inputImageTexture;\n \n void ma)\n {\n gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n }\n " public let TestMismatchedFragmentShader = "varying vec2 textureCoordinateF;\n \n uniform sampler2D inputImageTexture;\n \n void main()\n {\n gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n }\n " class ShaderProgram_Tests: XCTestCase { func testExample() { sharedImageProcessingContext.makeCurrentContext() do { let shaderProgram = try ShaderProgram(vertexShader:TestVertexShader, fragmentShader:TestFragmentShader) let temporaryPosition = shaderProgram.attributeIndex("position") XCTAssert(temporaryPosition != nil, "Could not find position attribute") XCTAssert(temporaryPosition == shaderProgram.attributeIndex("position"), "Could not retrieve the same position attribute") let temporaryInputTextureCoordinate = shaderProgram.attributeIndex("inputTextureCoordinate") XCTAssert(temporaryInputTextureCoordinate != nil, "Could not find inputTextureCoordinate attribute") XCTAssert(temporaryInputTextureCoordinate == shaderProgram.attributeIndex("inputTextureCoordinate"), "Could not retrieve the same inputTextureCoordinate attribute") XCTAssert(shaderProgram.attributeIndex("garbage") == nil, "Should not have found the garbage attribute") let temporaryInputTexture = shaderProgram.uniformIndex("inputImageTexture") XCTAssert(temporaryInputTexture != nil, "Could not find inputImageTexture uniform") XCTAssert(temporaryInputTexture == shaderProgram.uniformIndex("inputImageTexture"), "Could not retrieve the same inputImageTexture uniform") XCTAssert(shaderProgram.uniformIndex("garbage") == nil, "Should not have found the garbage uniform") } catch { XCTFail("Should not have thrown error during shader compilation: \(error)") } if ((try? ShaderProgram(vertexShader:TestBrokenVertexShader, fragmentShader:TestFragmentShader)) != nil) { XCTFail("Program should not have compiled correctly") } if ((try? ShaderProgram(vertexShader:TestVertexShader, fragmentShader:TestBrokenFragmentShader)) != nil) { XCTFail("Program should not have compiled correctly") } if ((try? ShaderProgram(vertexShader:TestVertexShader, fragmentShader:TestMismatchedFragmentShader)) != nil) { XCTFail("Program should not have compiled correctly") } } }
71.765957
250
0.733768
21f6e9e176041a894f4aebe21fe0c8d2e4e3b023
13,706
// // ShareReplayScope.swift // RxSwift // // Created by Krunoslav Zaher on 5/28/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // /// Subject lifetime scope public enum SubjectLifetimeScope { /** **Each connection will have it's own subject instance to store replay events.** **Connections will be isolated from each another.** Configures the underlying implementation to behave equivalent to. ``` source.multicast(makeSubject: { MySubject() }).refCount() ``` **This is the recommended default.** This has the following consequences: * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. * Each connection to source observable sequence will use it's own subject. * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. ``` let xs = Observable.deferred { () -> Observable<TimeInterval> in print("Performing work ...") return Observable.just(Date().timeIntervalSince1970) } .share(replay: 1, scope: .whileConnected) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) ``` Notice how time interval is different and `Performing work ...` is printed each time) ``` Performing work ... next 1495998900.82141 completed Performing work ... next 1495998900.82359 completed Performing work ... next 1495998900.82444 completed ``` */ case whileConnected /** **One subject will store replay events for all connections to source.** **Connections won't be isolated from each another.** Configures the underlying implementation behave equivalent to. ``` source.multicast(MySubject()).refCount() ``` This has the following consequences: * Using `retry` or `concat` operators after this operator usually isn't advised. * Each connection to source observable sequence will share the same subject. * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will continue holding a reference to the same subject. If at some later moment a new observer initiates a new connection to source it can potentially receive some of the stale events received during previous connection. * After source sequence terminates any new observer will always immediately receive replayed elements and terminal event. No new subscriptions to source observable sequence will be attempted. ``` let xs = Observable.deferred { () -> Observable<TimeInterval> in print("Performing work ...") return Observable.just(Date().timeIntervalSince1970) } .share(replay: 1, scope: .forever) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) ``` Notice how time interval is the same, replayed, and `Performing work ...` is printed only once ``` Performing work ... next 1495999013.76356 completed next 1495999013.76356 completed next 1495999013.76356 completed ``` */ case forever } extension ObservableType { /** Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. This operator is equivalent to: * `.whileConnected` ``` // Each connection will have it's own subject instance to store replay events. // Connections will be isolated from each another. source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() ``` * `.forever` ``` // One subject will store replay events for all connections to source. // Connections won't be isolated from each another. source.multicast(Replay.create(bufferSize: replay)).refCount() ``` It uses optimized versions of the operators for most common operations. - parameter replay: Maximum element count of the replay buffer. - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) -> Observable<E> { switch scope { case .forever: switch replay { case 0: return multicast(PublishSubject()).refCount() default: return multicast(ReplaySubject.create(bufferSize: replay)).refCount() } case .whileConnected: switch replay { case 0: return ShareWhileConnected(source: asObservable()) case 1: return ShareReplay1WhileConnected(source: asObservable()) default: return multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() } } } } private final class ShareReplay1WhileConnectedConnection<Element>: ObserverType, SynchronizedUnsubscribeType { typealias E = Element typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType typealias Parent = ShareReplay1WhileConnected<Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private let _lock: RecursiveLock private var _disposed: Bool = false fileprivate var _observers = Observers() fileprivate var _element: Element? init(parent: Parent, lock: RecursiveLock) { _parent = parent _lock = lock #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } final func on(_ event: Event<E>) { _lock.lock() let observers = _synchronized_on(event) _lock.unlock() dispatch(observers, event) } private final func _synchronized_on(_ event: Event<E>) -> Observers { if _disposed { return Observers() } switch event { case let .next(element): _element = element return _observers case .error, .completed: let observers = _observers _synchronized_dispose() return observers } } final func connect() { _subscription.setDisposable(_parent._source.subscribe(self)) } final func _synchronized_subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock(); defer { self._lock.unlock() } if let element = self._element { observer.on(.next(element)) } let disposeKey = _observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: disposeKey) } private final func _synchronized_dispose() { _disposed = true if _parent._connection === self { _parent._connection = nil } _observers = Observers() } final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() let shouldDisconnect = _synchronized_unsubscribe(disposeKey) _lock.unlock() if shouldDisconnect { _subscription.dispose() } } @inline(__always) private final func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { // if already unsubscribed, just return if _observers.removeKey(disposeKey) == nil { return false } if _observers.count == 0 { _synchronized_dispose() return true } return false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // optimized version of share replay for most common case private final class ShareReplay1WhileConnected<Element>: Observable<Element> { fileprivate typealias Connection = ShareReplay1WhileConnectedConnection<Element> fileprivate let _source: Observable<Element> fileprivate let _lock = RecursiveLock() fileprivate var _connection: Connection? init(source: Observable<Element>) { _source = source } override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock() let connection = _synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) _lock.unlock() if count == 0 { connection.connect() } return disposable } @inline(__always) private func _synchronized_subscribe<O: ObserverType>(_: O) -> Connection where O.E == E { let connection: Connection if let existingConnection = self._connection { connection = existingConnection } else { connection = ShareReplay1WhileConnectedConnection<Element>( parent: self, lock: _lock ) _connection = connection } return connection } } private final class ShareWhileConnectedConnection<Element>: ObserverType, SynchronizedUnsubscribeType { typealias E = Element typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType typealias Parent = ShareWhileConnected<Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private let _lock: RecursiveLock private var _disposed: Bool = false fileprivate var _observers = Observers() init(parent: Parent, lock: RecursiveLock) { _parent = parent _lock = lock #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } final func on(_ event: Event<E>) { _lock.lock() let observers = _synchronized_on(event) _lock.unlock() dispatch(observers, event) } private final func _synchronized_on(_ event: Event<E>) -> Observers { if _disposed { return Observers() } switch event { case .next: return _observers case .error, .completed: let observers = _observers _synchronized_dispose() return observers } } final func connect() { _subscription.setDisposable(_parent._source.subscribe(self)) } final func _synchronized_subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock(); defer { self._lock.unlock() } let disposeKey = _observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: disposeKey) } private final func _synchronized_dispose() { _disposed = true if _parent._connection === self { _parent._connection = nil } _observers = Observers() } final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() let shouldDisconnect = _synchronized_unsubscribe(disposeKey) _lock.unlock() if shouldDisconnect { _subscription.dispose() } } @inline(__always) private final func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { // if already unsubscribed, just return if _observers.removeKey(disposeKey) == nil { return false } if _observers.count == 0 { _synchronized_dispose() return true } return false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // optimized version of share replay for most common case private final class ShareWhileConnected<Element>: Observable<Element> { fileprivate typealias Connection = ShareWhileConnectedConnection<Element> fileprivate let _source: Observable<Element> fileprivate let _lock = RecursiveLock() fileprivate var _connection: Connection? init(source: Observable<Element>) { _source = source } override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock() let connection = _synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) _lock.unlock() if count == 0 { connection.connect() } return disposable } @inline(__always) private func _synchronized_subscribe<O: ObserverType>(_: O) -> Connection where O.E == E { let connection: Connection if let existingConnection = self._connection { connection = existingConnection } else { connection = ShareWhileConnectedConnection<Element>( parent: self, lock: _lock ) _connection = connection } return connection } }
30.189427
164
0.63899
bb852531f1cff7fb6fa38b5fce1cf3c00f59abad
588
import BalancingBucketQueue import Extensions import Foundation import Models import RESTMethods import RESTServer public final class JobResultsEndpoint: RESTEndpoint { private let jobResultsProvider: JobResultsProvider public init(jobResultsProvider: JobResultsProvider) { self.jobResultsProvider = jobResultsProvider } public func handle(decodedRequest: JobResultsRequest) throws -> JobResultsResponse { let jobResults = try jobResultsProvider.results(jobId: decodedRequest.jobId) return JobResultsResponse(jobResults: jobResults) } }
29.4
88
0.784014
76ce9ad9b8b0d765a2d19a1ed595b5a41277c620
1,255
// // Circleview.swift // PlaygroundWWDC2020 // // Created by Gabriel Gazal on 23/02/20. // Copyright © 2020 com.gazodia. All rights reserved. // import UIKit @objc(BookCore_CircleView) public class Circleview: UIView { @IBInspectable public var cornerRadius: CGFloat = 0{ didSet{ // guard self.layer != nil else { return } self.layer.cornerRadius = self.frame.width / 2.0 } } @IBInspectable public var borderWidht: CGFloat = 0{ didSet{ // guard self.layer != nil else { return } layer.borderWidth = borderWidht } } @IBInspectable public var borderColor: UIColor = UIColor.clear { didSet{ // guard self.layer != nil else { return } layer.borderColor = borderColor.cgColor } } func updateLayerProperties() { self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor self.layer.shadowOffset = CGSize(width: 0, height: 3) self.layer.shadowOpacity = 3.0 self.layer.shadowRadius = 10.0 self.layer.masksToBounds = false } }
29.186047
97
0.551394
ccc50c3078870773658588d3f44f3fcf572991b6
141
// // PictureTool.swift // Example // // Created by 王立 on 2020/9/7. // Copyright © 2020 王立. All rights reserved. // import Foundation
11.75
45
0.638298
fcde0eaf8a33f7fa27eae68f3b74540518520efb
24,189
// // Yelp.swift // Yelp // // Created by Alex Kerendian on 6/27/19. // Copyright © 2019 Alexander Kerendian. All rights reserved. // import Foundation public class Yelp { private static let baseUrlString = "https://api.yelp.com/v3/" static var apiKey: String? private init() {} /// Sets the API key for the shared Yelp client. /// Should be called in AppDelegate didFinishLaunching... /// /// Sign up for Yelp as a developer and find your API key on /// the "Manage App" tab of the Yelp Fusion Documentation. /// (https://www.yelp.com/developers/v3/manage_app) /// /// Yelp API requests cannot be made without an API key. /// /// - Parameters: /// - apiKey: Personal key that identifies the caller. public static func set(apiKey: String) { self.apiKey = apiKey } // MARK: Business Endpoints /// Returns an array of bussinesses that meet the search criteria. /// /// See the business search endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/business_search) /// /// If the required parameter is not given the request cannot be made. /// /// - Parameters: /// - location: Required if either latitude or longitude is not provided. /// - latitude: Required if location is not provided. /// - longitude: Required if location is not provided. /// (remaining parameters are optional. See doc to for info on each one) /// /// - Returns: An optional BusinessSearch object and error public static func businessSearch(term: String? = nil, location: String? = nil, latitude: Double? = nil, longitude: Double? = nil, radius: Int? = nil, categories: String? = nil, locale: String? = nil, limit: Int? = nil, offset: Int? = nil, sortBy: String? = nil, price: String? = nil, openNow: Bool? = nil, openAt: Int? = nil, attributes: String? = nil, completion: @escaping (Result<BusinessesSearch, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } guard location != nil || (latitude != nil && longitude != nil) else { completion(.failure(YelpError.locationRequired)) return } var queryItems = [URLQueryItem]() if let term = term { queryItems.append(URLQueryItem(name: "term", value: term)) } if let location = location { queryItems.append(URLQueryItem(name: "location", value: location)) } if let latitude = latitude { queryItems.append(URLQueryItem(name: "latitude", value: "\(latitude)")) } if let longitude = longitude { queryItems.append(URLQueryItem(name: "longitude", value: "\(longitude)")) } if let radius = radius { queryItems.append(URLQueryItem(name: "radius", value: "\(radius)")) } if let categories = categories { queryItems.append(URLQueryItem(name: "categories", value: categories)) } if let locale = locale { queryItems.append(URLQueryItem(name: "locale", value: locale)) } if let limit = limit { queryItems.append(URLQueryItem(name: "limit", value: "\(limit)")) } if let offset = offset { queryItems.append(URLQueryItem(name: "offset", value: "\(offset)")) } if let sortBy = sortBy { queryItems.append(URLQueryItem(name: "sort_by", value: sortBy)) } if let price = price { queryItems.append(URLQueryItem(name: "price", value: price)) } if let openNow = openNow { queryItems.append(URLQueryItem(name: "open_now", value: "\(openNow)")) } if let openAt = openAt { queryItems.append(URLQueryItem(name: "open_at", value: "\(openAt)")) } if let attributes = attributes { queryItems.append(URLQueryItem(name: "attributes", value: attributes)) } if var urlComponents = URLComponents(string: baseUrlString + "businesses/search") { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: BusinessesSearch.self) { completion($0) } } } } /// Returns an array of businesses based on the provided phone number. /// It's possible for more than one business to have the same number /// (for example, chain stores with the same +1 800 phone number). /// /// See the phone search endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/business_search_phone) /// /// If the required parameter is not given the request cannot be made. /// /// - Parameters: /// - phone: Required. Phone number of the business you want to search for. /// It must start with + and include the country code, like +14159083801. /// /// - Returns: An optional PhoneSearch object and error public static func phoneSearch(phone: String, completion: @escaping (Result<PhoneSearch, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } guard phone.hasPrefix("+") else { print("error: phone number must start with '+'") completion(.failure(YelpError.phoneNumberInvalid)) return } let queryItems = [URLQueryItem(name: "phone", value: phone)] if var urlComponents = URLComponents(string: baseUrlString + "businesses/search/phone") { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: PhoneSearch.self) { completion($0) } } } } /// Returns an array of bussinesses which support the transaction type /// and are within the given location. /// /// See the transaction search endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/transaction_search) /// /// If the required parameter is not given the request cannot be made. /// /// - Parameters: /// - transactionType: Optional. Defaults to food delivery. /// - location: Required if either latitude or longitude is not provided. /// - latitude: Required if location is not provided. /// - longitude: Required if location is not provided. /// /// - Returns: An optional TransactionSearch object and error public static func transactionSearch(transactionType: String = "delivery", location: String? = nil, latitude: Double? = nil, longitude: Double? = nil, completion: @escaping (Result<TransactionSearch, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } guard location != nil || (latitude != nil && longitude != nil) else { print("error: the location or the latitude and longitude needs to be set") completion(.failure(YelpError.locationRequired)) return } var queryItems = [URLQueryItem]() if let location = location { queryItems.append(URLQueryItem(name: "location", value: location)) } if let latitude = latitude { queryItems.append(URLQueryItem(name: "latitude", value: "\(latitude)")) } if let longitude = longitude { queryItems.append(URLQueryItem(name: "longitude", value: "\(longitude)")) } if var urlComponents = URLComponents(string: baseUrlString + "transactions/" + transactionType + "/search") { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: TransactionSearch.self) { completion($0) } } } } /// Returns a bussiness with full details matching the given id. /// Ids can be obtained using another search method. /// /// See the business details endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/business) /// /// - Parameters: /// - id: Required. The yelp business id. /// - locale: Optional. How the business info is localized. Defaults to en_US. /// See the list of supported locales. /// (https://www.yelp.com/developers/documentation/v3/supported_locales) /// /// - Returns: An optional Business object and error public static func businessDetails(id: String, locale: String = "en_US", completion: @escaping (Result<Business, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } let queryItems = [URLQueryItem(name: locale, value: locale)] if var urlComponents = URLComponents(string: baseUrlString + "businesses/" + id) { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: Business.self) { completion($0) } } } } /// Returns an array of businesses based on the provided information. /// Use this endpoint when you have precise info like name & address. /// /// See the business match endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/business_match) /// /// - Parameters: /// - name: Required. The name of the business. /// - address1: Required. The first line of the business’s address. /// - city: Required. The city of the business. /// - state: Required. The ISO 3166-2 state code. /// - country: Required. The ISO 3166-1 alpha-2 country code. /// (remaining parameters are optional. See doc to for info on each one) /// /// - Returns: An optional BusinessMatch object and error public static func businessMatch(name: String, address1: String, address2: String? = nil, address3: String? = nil, city: String, state: String, country: String, latitude: Double? = nil, longitude: Double? = nil, phone: String? = nil, zipCode: String? = nil, id: String? = nil, limit: Int? = nil, matchThreshold: String? = nil, completion: @escaping (Result<BusinessMatch, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } guard state.count <= 3 else { completion(.failure(YelpError.stateCodeInvalid)) return } guard country.count <= 2 else { completion(.failure(YelpError.countryCodeInvalid)) return } // guard state.count <= 3, country.count <= 2 else { // print("error: use ISO 3166-2 code for state and ISO 3166-1 alpha-2 code for country") // completion(.failure(YelpError.stateOrCountryCode)) // return // } var queryItems = [URLQueryItem]() queryItems.append(URLQueryItem(name: "name", value: name)) queryItems.append(URLQueryItem(name: "address1", value: address1)) if let address2 = address2 { queryItems.append(URLQueryItem(name: "address2", value: address2)) } if let address3 = address3 { queryItems.append(URLQueryItem(name: "address3", value: address3)) } queryItems.append(URLQueryItem(name: "city", value: city)) queryItems.append(URLQueryItem(name: "state", value: state)) queryItems.append(URLQueryItem(name: "country", value: country)) if let latitude = latitude { queryItems.append(URLQueryItem(name: "latitude", value: "\(latitude)")) } if let longitude = longitude { queryItems.append(URLQueryItem(name: "longitude", value: "\(longitude)")) } if let phone = phone { queryItems.append(URLQueryItem(name: "phone", value: phone)) } if let zipCode = zipCode { queryItems.append(URLQueryItem(name: "zip_code", value: zipCode)) } if let id = id { queryItems.append(URLQueryItem(name: "yelp_business_id", value: id)) } if let limit = limit { queryItems.append(URLQueryItem(name: "limit", value: "\(limit)")) } if let matchThreshold = matchThreshold { queryItems.append(URLQueryItem(name: "match_threshold", value: matchThreshold)) } if var urlComponents = URLComponents(string: baseUrlString + "businesses/matches") { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: BusinessMatch.self) { completion($0) } } } } /// Returns reviews for the business matching the given id. /// Ids can be obtained using another search method. /// /// See the reviews endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/business_reviews) /// /// - Parameters: /// - id: Required. The yelp business id. /// - locale: Optional. How the business info is localized. Defaults to en_US. /// See the list of supported locales. /// (https://www.yelp.com/developers/documentation/v3/supported_locales) /// /// - Returns: An optional ReviewSearch object and error public static func reviews(id: String, locale: String = "en_US", completion: @escaping (Result<ReviewSearch, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } let queryItems = [URLQueryItem(name: "locale", value: locale)] if var urlComponents = URLComponents(string: baseUrlString + "businesses/" + id + "/reviews") { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: ReviewSearch.self) { completion($0) } } } } /// Returns autocomplete suggestions for the given text and coordinates. /// /// See the autocomplete endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/autocomplete) /// /// - Parameters: /// - text: Required. Text to return autocomplete suggestions for. /// - latitude: Required to get autocomplete suggestions for businesses. /// - longitude: Required to get autocomplete suggestions for businesses. /// - locale: Optional. How the business info is localized. Defaults to en_US. /// See the list of supported locales. /// (https://www.yelp.com/developers/documentation/v3/supported_locales) /// /// - Returns: An optional AutocompleteSearch object and error public static func autocomplete(text: String, latitude: Double? = nil, longitude: Double? = nil, locale: String = "en_US", completion: @escaping (Result<AutocompleteSearch, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } var queryItems: [URLQueryItem] = [URLQueryItem(name: "text", value: text)] if let latitude = latitude, let longitude = longitude { queryItems.append(URLQueryItem(name: "latitude", value: "\(latitude)")) queryItems.append(URLQueryItem(name: "longitude", value: "\(longitude)")) } queryItems.append(URLQueryItem(name: "locale", value: locale)) if var urlComponents = URLComponents(string: baseUrlString + "autocomplete") { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: AutocompleteSearch.self) { completion($0) } } } } // MARK: Event Endpoints (beta) /// Returns an event with full details based on the given id. /// /// See the event lookup endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/event) /// /// - Parameters: /// - id: Required. The yelp event id. /// - locale: Optional. How the business info is localized. Defaults to en_US. /// See the list of supported locales. /// (https://www.yelp.com/developers/documentation/v3/supported_locales) /// /// - Returns: An optional Event object and error public static func eventLookup(id: String, locale: String = "en_US", completion: @escaping (Result<Event, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } let queryItems = [URLQueryItem(name: "locale", value: locale)] if var urlComponents = URLComponents(string: baseUrlString + "events/" + id) { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: Event.self) { completion($0) } } } } /// Returns an array of events that meet the search criteria. /// /// See the event search endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/event_search) /// /// - Parameters: /// All parameters are optional. See doc to for info on each one /// /// - Returns: An optional EventSearch object and error public static func eventSearch(locale: String = "en_US", offset: Int? = nil, limit: Int = 3, sortBy: String = "desc", sortOn: String = "popularity", startDate: Int? = nil, endDate: Int? = nil, categories: String? = nil, isFree: Bool? = nil, location: String? = nil, latitude: Double? = nil, longitude: Double? = nil, radius: Int? = nil, excludedEvents: [String]? = nil, completion: @escaping (Result<EventSearch, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } var queryItems = [URLQueryItem]() queryItems.append(URLQueryItem(name: "locale", value: locale)) if let offset = offset { queryItems.append(URLQueryItem(name: "offset", value: "\(offset)")) } queryItems.append(URLQueryItem(name: "limit", value: "\(limit)")) queryItems.append(URLQueryItem(name: "sort_by", value: sortBy)) queryItems.append(URLQueryItem(name: "sort_on", value: sortOn)) if let startDate = startDate { queryItems.append(URLQueryItem(name: "start_date", value: "\(startDate)")) } if let endDate = endDate { queryItems.append(URLQueryItem(name: "end_date", value: "\(endDate)")) } if let categories = categories { queryItems.append(URLQueryItem(name: "categories", value: categories)) } if let isFree = isFree { queryItems.append(URLQueryItem(name: "is_free", value: "\(isFree)")) } if let location = location { queryItems.append(URLQueryItem(name: "location", value: location)) } if let latitude = latitude { queryItems.append(URLQueryItem(name: "latitude", value: "\(latitude)")) } if let longitude = longitude { queryItems.append(URLQueryItem(name: "longitude", value: "\(longitude)")) } if let radius = radius { queryItems.append(URLQueryItem(name: "radius", value: "\(radius)")) } if let excludedEvents = excludedEvents { let excludedEventsString = excludedEvents.reduce("") { $0 + $1 } queryItems.append(URLQueryItem(name: "excluded_events", value: excludedEventsString)) } if var urlComponents = URLComponents(string: baseUrlString + "events") { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: EventSearch.self) { completion($0) } } } } /// Returns a featured event based on location. /// /// See the featured event endpoint documentation for more information. /// (https://www.yelp.com/developers/documentation/v3/featured_event) /// /// - Parameters: /// - locale: Optional. How the business info is localized. Defaults to en_US. /// See the list of supported locales. /// (https://www.yelp.com/developers/documentation/v3/supported_locales) /// - location: Required if either latitude or longitude is not provided. /// - latitude: Required if location is not provided. /// - longitude: Required if location is not provided. /// /// - Returns: An optional Event object and error public static func featuredEvent(locale: String = "en_US", location: String? = nil, latitude: Double? = nil, longitude: Double? = nil, completion: @escaping (Result<Event, Error>) -> ()) { guard let apiKey = apiKey else { completion(.failure(YelpError.apiKeyNotSet)) return } guard location != nil || (latitude != nil && longitude != nil) else { print("error: the location or the latitude and longitude needs to be set") completion(.failure(YelpError.locationRequired)) return } var queryItems = [URLQueryItem]() queryItems.append(URLQueryItem(name: "locale", value: locale)) if let location = location { queryItems.append(URLQueryItem(name: "location", value: location)) } if let latitude = latitude { queryItems.append(URLQueryItem(name: "latitude", value: "\(latitude)")) } if let longitude = longitude { queryItems.append(URLQueryItem(name: "longitude", value: "\(longitude)")) } if var urlComponents = URLComponents(string: baseUrlString + "events/featured") { urlComponents.queryItems = queryItems if let url = urlComponents.url { NetworkService.makeRequest(with: url, and: apiKey, for: Event.self) { completion($0) } } } } // MARK: Category Endpoints (beta) public static func allCategories() {} public static func categoryDetails() {} }
48.089463
130
0.580636
f9f893df4c367fa7a5630fc2f50186376682265a
778
// // SegmentItemShadowStyle.swift // RESegmentedControl // // Created by Sherzod Khashimov on 11/21/19. // Copyright © 2019 Sherzod Khashimov. All rights reserved. // import Foundation import UIKit public struct SegmentItemShadowStyle: ShadowStylable { public var color: CGColor? = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.5).cgColor public var opacity: Float = 0.5 public var offset: CGSize = CGSize(width: 0, height: 2) public var radius: CGFloat = 2 public var path: CGPath? = nil public init() { } public init(color: CGColor, opacity: Float, offset: CGSize, radius: CGFloat, path: CGPath?) { self.color = color self.opacity = opacity self.offset = offset self.radius = radius } }
22.882353
99
0.663239
e987037d2366a4032dd398f8d536414317ddfdb3
317
// // NetworkConnectivity.swift // SnapShare // // Created by Oleg Abalonski on 6/10/18. // Copyright © 2018 Oleg Abalonski. All rights reserved. // import Foundation import Alamofire class NetworkConnectivity { class var isConnected: Bool { return NetworkReachabilityManager()!.isReachable } }
18.647059
57
0.712934
e60d3cdc6154c68401b9587f1ca83ecfe8dee195
959
// // StringExtensions.swift // erg // // Created by Christie on 22/03/18. // Copyright © 2018 star. All rights reserved. // import UIKit extension String { func apply(font: UIFont, color: UIColor) -> NSAttributedString { return NSAttributedString(string: self, attributes: [NSAttributedStringKey.font : font, NSAttributedStringKey.foregroundColor : color]) } func apply(font: UIFont) -> NSAttributedString { return NSAttributedString(string: self, attributes: [NSAttributedStringKey.font : font, NSAttributedStringKey.foregroundColor : UIColor.textNavy]) } func stringAtIndex(_ index: Int) -> String { let newIndex = self.index(startIndex, offsetBy: index) let stringToRetrun = String(self[newIndex]) return stringToRetrun } var localized: String { let localizedString = NSLocalizedString(self, comment: "") return localizedString } }
29.060606
154
0.675704
f572804f6abca9045e70c6317d5890bad2265099
103
import GameplayKit public protocol Targetable: GKEntity { static var identifier: String { get } }
17.166667
41
0.747573
abd340ba787307bbe614e731620e59c7c9655115
2,989
// // CardPartTableViewCardPartsCell.swift // Mint.com // // Created by Kier, Tom on 11/28/17. // Copyright © 2017 Mint.com. All rights reserved. // import Foundation open class CardPartTableViewCardPartsCell : UITableViewCell { private var rightTopConstraint: NSLayoutConstraint! private var leftTopConstraint: NSLayoutConstraint! private var constraintsAdded = false var stackView : UIStackView private var cardParts:[CardPartView] = [] override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.distribution = .equalSpacing stackView.alignment = .leading stackView.spacing = 0 super.init(style: style, reuseIdentifier: reuseIdentifier) separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) for subview in contentView.subviews { subview.removeFromSuperview() } contentView.addSubview(stackView) setNeedsUpdateConstraints() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func updateConstraints() { if !constraintsAdded { setupContraints() } super.updateConstraints() } func setupContraints() { constraintsAdded = true contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: [], metrics: nil, views: ["stackView" : stackView])) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: [], metrics: nil, views: ["stackView" : stackView])) } public func setupCardParts(_ cardParts:[CardPartView]) { self.cardParts = cardParts for cardPart in cardParts { if cardPart.margins.top > 0 { let spacer = CardPartSpacerView(height: cardPart.margins.top) stackView.addArrangedSubview(spacer) stackView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[spacer]|", options: [], metrics: nil, views: ["spacer" : spacer])) } if let _ = cardPart.viewController { // TODO add support for cardParts implemented as view controllers print("Viewcontroller card parts not supported in table view cells") } else { stackView.addArrangedSubview(cardPart.view) } let metrics = ["leftMargin" : cardPart.margins.left - 28, "rightMargin" : cardPart.margins.right - 28] stackView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-leftMargin-[cardPartView]-rightMargin-|", options: [], metrics: metrics, views: ["cardPartView" : cardPart.view])) if cardPart.margins.bottom > 0 { let spacer = CardPartSpacerView(height: cardPart.margins.bottom) stackView.addArrangedSubview(spacer) stackView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[spacer]|", options: [], metrics: nil, views: ["spacer" : spacer])) } } } }
31.797872
196
0.726999
6a654707b3e5f3a8a06b5d23706d2ee4de6160d7
5,707
// // Copyright 2018-2021 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation extension RealtimeConnectionProvider: AppSyncWebsocketDelegate { public func websocketDidConnect(provider: AppSyncWebsocketProvider) { // Call the ack to finish the connection handshake // Inform the callback when ack gives back a response. AppSyncLogger.debug("[RealtimeConnectionProvider] WebsocketDidConnect, sending init message") sendConnectionInitMessage() startStaleConnectionTimer() } public func websocketDidDisconnect(provider: AppSyncWebsocketProvider, error: Error?) { connectionQueue.async { [weak self] in guard let self = self else { return } self.status = .notConnected guard error != nil else { self.updateCallback(event: .connection(self.status)) return } self.updateCallback(event: .error(ConnectionProviderError.connection)) } } public func websocketDidReceiveData(provider: AppSyncWebsocketProvider, data: Data) { do { let response = try JSONDecoder().decode(RealtimeConnectionProviderResponse.self, from: data) handleResponse(response) } catch { AppSyncLogger.error(error) updateCallback(event: .error(ConnectionProviderError.jsonParse(nil, error))) } } // MARK: - Handle websocket response private func handleResponse(_ response: RealtimeConnectionProviderResponse) { resetStaleConnectionTimer() switch response.responseType { case .connectionAck: AppSyncLogger.debug("[RealtimeConnectionProvider] received connectionAck") connectionQueue.async { [weak self] in self?.handleConnectionAck(response: response) } case .error: AppSyncLogger.debug("[RealtimeConnectionProvider] received error") connectionQueue.async { [weak self] in self?.handleError(response: response) } case .subscriptionAck, .unsubscriptionAck, .data: if let appSyncResponse = response.toAppSyncResponse() { updateCallback(event: .data(appSyncResponse)) } case .keepAlive: AppSyncLogger.debug("[RealtimeConnectionProvider] received keepAlive") } } /// Updates connection status callbacks and sets stale connection timeout /// /// - Warning: This method must be invoked on the `connectionQueue` private func handleConnectionAck(response: RealtimeConnectionProviderResponse) { // Only from in progress state, the connection can transition to connected state. // The below guard statement make sure that. If we get connectionAck in other // state means that we have initiated a disconnect parallely. guard status == .inProgress else { return } status = .connected updateCallback(event: .connection(status)) // If the service returns a connection timeout, use that instead of the default guard case let .number(value) = response.payload?["connectionTimeoutMs"] else { return } let interval = value / 1_000 guard interval != staleConnectionTimer?.interval else { return } AppSyncLogger.debug( """ Resetting keep alive timer in response to service timeout \ instructions: \(interval)s """ ) staleConnectionTimeout.set(interval) startStaleConnectionTimer() } /// Resolves & dispatches errors from `response`. /// /// - Warning: This method must be invoked on the `connectionQueue` private func handleError(response: RealtimeConnectionProviderResponse) { // If we get an error in connection inprogress state, return back as connection error. guard status != .inProgress else { status = .notConnected updateCallback(event: .error(ConnectionProviderError.connection)) return } // Return back as generic error if there is no identifier. guard let identifier = response.id else { let genericError = ConnectionProviderError.other updateCallback(event: .error(genericError)) return } // Map to limit exceed error if we get MaxSubscriptionsReachedException if let errorType = response.payload?["errorType"], errorType == "MaxSubscriptionsReachedException" { let limitExceedError = ConnectionProviderError.limitExceeded(identifier) updateCallback(event: .error(limitExceedError)) return } let subscriptionError = ConnectionProviderError.subscription(identifier, response.payload) updateCallback(event: .error(subscriptionError)) } } extension RealtimeConnectionProviderResponse { func toAppSyncResponse() -> AppSyncResponse? { guard let appSyncType = responseType.toAppSyncResponseType() else { return nil } return AppSyncResponse(id: id, payload: payload, type: appSyncType) } } extension RealtimeConnectionProviderResponseType { func toAppSyncResponseType() -> AppSyncResponseType? { switch self { case .subscriptionAck: return .subscriptionAck case .unsubscriptionAck: return .unsubscriptionAck case .data: return .data default: return nil } } }
35.447205
104
0.642369
9ba569dd02c7e819eca42714ad7d8f79a8efa045
221
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func f<T{struct c{let:{{}func i(){for b{}}}func b}{c
44.2
87
0.733032
fff8c5eb8eaad879effba63f720def844b60c1d9
1,073
// // Promise+State.swift // EPPromiseM // // Created by Evgeniy on 24/11/2018. // Copyright © 2018 Evgeniy. All rights reserved. // import Foundation enum State<Value> { /// Will be either fulfilled or rejected case pending /// Successfully fulfilled case fulfilled(Value) /// Rejected with an Error case rejected(Error) } extension State { // MARK: - State var isPending: Bool { if case .pending = self { return true } return false } var isFulfilled: Bool { if case .fulfilled = self { return true } return false } var isRejected: Bool { if case .rejected = self { return true } return false } // MARK: - Members var value: Value? { guard case let .fulfilled(value) = self else { return nil } return value } var error: Error? { guard case let .rejected(error) = self else { return nil } return error } }
17.306452
54
0.533085
9bee34c965b478f8763d7fa24eba9fe6c2576ed9
1,931
import Library import Prelude import UIKit internal final class DiscoverySelectableRowCell: UITableViewCell, ValueCell { @IBOutlet private weak var filterTitleLabel: UILabel! private var rowIsSelected: Bool = false func configureWith(value: (row: SelectableRow, categoryId: Int?)) { if value.row.params.staffPicks == true { self.filterTitleLabel.text = Strings.Projects_We_Love() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_projects_we_love() } else if value.row.params.starred == true { self.filterTitleLabel.text = Strings.Saved() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_saved_projects() } else if value.row.params.social == true { self.filterTitleLabel.text = Strings.Backed_by_people_you_follow() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_projects_backed_by_friends() } else if let category = value.row.params.category { self.filterTitleLabel.text = category.name } else if value.row.params.recommended == true { self.filterTitleLabel.text = Strings.discovery_recommended_for_you() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_projects_recommended_for_you() } else { self.filterTitleLabel.text = Strings.All_Projects() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_all_projects() } _ = self.filterTitleLabel |> discoveryFilterLabelStyle(categoryId: value.categoryId, isSelected: value.row.isSelected) |> UILabel.lens.numberOfLines .~ 0 self.rowIsSelected = value.row.isSelected } override func bindStyles() { super.bindStyles() _ = self |> discoveryFilterRowMarginStyle |> UITableViewCell.lens.accessibilityTraits .~ UIAccessibilityTraitButton } internal func willDisplay() { _ = self.filterTitleLabel |> discoveryFilterLabelFontStyle(isSelected: self.rowIsSelected) } }
38.62
98
0.749353
6791b137cabb0c869303ada6bb9d0cc2bf68c8a7
505
// // ViewController.swift // ADKUtils // // Created by Radaev Mikhail on 31.03.2018. // Copyright © 2018 msfrms. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.423077
80
0.669307
281ff8d85484a59f1ecfeec5fbdbf2d19765b72f
275
// // LoginModel.swift // zScanner // // Created by Jakub Skořepa on 21/07/2019. // Copyright © 2019 Institut klinické a experimentální medicíny. All rights reserved. // import Foundation struct LoginDomainModel { var username: String var access_code: String }
18.333333
86
0.72
699b4ff41d484b56036e9f095fe31ab5dc67347e
825
// // DownloadCell.swift // FinalProject // // Created by PCI0007 on 9/21/20. // Copyright © 2020 MBA0176. All rights reserved. // import UIKit final class DownloadCell: UITableViewCell { var viewModel: DownloadCellViewModel? { didSet { updateUI() } } @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! override func awakeFromNib() { super.awakeFromNib() } private func updateUI() { titleLabel.text = viewModel?.title authorLabel.text = viewModel?.author guard let url = URL(string: viewModel?.imageUrl ?? "") else { return } thumbImageView.sd_setImage(with: url) } }
23.571429
78
0.638788
562146db5af36dc3c92a4b21e6a2989e8f746aec
2,558
// // RecordType.swift // Pods // // Created by zixun on 17/1/13. // // import Foundation private var unreadDic = [RecordType.log: 0,RecordType.crash: 0,RecordType.network: 0,RecordType.anr: 0,RecordType.leak: 0] enum RecordType { case log case crash case network case anr case leak case command } // MARK: Unred extension RecordType { func unread() -> Int { return unreadDic[self] ?? 0 } func addUnread() { unreadDic[self] = self.unread() + 1 } func cleanUnread() { unreadDic[self] = 0 } } // MARK: Title extension RecordType { func title() -> String { switch self { case .log: return "Log" case .crash: return "Crash" case .network: return "Network" case .anr: return "ANR" case .leak: return "Leak" case .command: return "Terminal" default: return "" } } func detail() -> String { switch self { case .log: return "asl and logger information" case .crash: return "crash call stack information" case .network: return "request and response information" case .anr: return "anr call stack information" case .leak: return "memory leak information" case .command: return "terminal with commands and results" default: return "" } } } // MARK: - ORM extension RecordType { func model() -> RecordORMProtocol.Type? { var clazz:AnyClass? switch self { case .log: clazz = LogRecordModel.classForCoder() case .crash: clazz = CrashRecordModel.classForCoder() case .network: clazz = NetworkRecordModel.classForCoder() case .anr: clazz = ANRRecordModel.classForCoder() case .command: clazz = CommandRecordModel.classForCoder() default: clazz = nil } return clazz as? RecordORMProtocol.Type } func tableName() -> String { switch self { case .log: return "t_log" case .crash: return "t_crash" case .network: return "t_natwork" case .anr: return "t_anr" case .leak: return "t_leak" case .command: return "t_command" } } }
21.316667
122
0.514073
e6e6e3654ebf9d43b0725ce25c91bd186bfb0c81
18,948
// // SearchReducerTests.swift // PlacesFinderTests // // Copyright (c) 2019 Justin Peckner // // 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 Nimble import Quick import Shared import SharedTestComponents import SwiftDuxTestComponents class SearchReducerTests: QuickSpec { // swiftlint:disable function_body_length // swiftlint:disable implicitly_unwrapped_optional override func spec() { describe("reduce") { let stubParams = PlaceLookupParams.stubValue() let stubSearchParams = SearchParams(keywords: stubParams.keywords) let stubSearchInputParams = SearchInputParams(params: stubSearchParams, isEditing: false) let stubDetailsViewModel = SearchEntityModel.stubValue() let stubEntities = NonEmptyArray(with: SearchEntityModel.stubValue()) let stubTokenContainer = PlaceLookupTokenAttemptsContainer.stubValue() var result: SearchState! context("when the action is not a SearchAction") { let currentState = SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) beforeEach { result = SearchReducer.reduce(action: StubAction.genericAction, currentState: currentState) } it("returns the current state") { expect(result) == currentState } } context("else when the action is SearchAction.locationRequested") { let currentState = SearchState(loadState: .idle, inputParams: SearchInputParams(params: stubSearchParams, isEditing: true), detailedEntity: stubDetailsViewModel) beforeEach { result = SearchReducer.reduce(action: SearchAction.locationRequested(stubSearchParams), currentState: currentState) } it("returns the expected state") { expect(result) == SearchState(loadState: .locationRequested(stubSearchParams), inputParams: stubSearchInputParams, detailedEntity: nil) } } context("else when the action is SearchAction.initialPageRequested") { let currentState = SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) beforeEach { result = SearchReducer.reduce(action: SearchAction.initialPageRequested(stubSearchParams), currentState: currentState) } it("returns the expected state") { expect(result) == SearchState(loadState: .initialPageRequested(stubSearchParams), inputParams: stubSearchInputParams, detailedEntity: nil) } } context("else when the action is SearchAction.noResultsFound") { let currentState = SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) beforeEach { result = SearchReducer.reduce(action: SearchAction.noResultsFound(stubSearchParams), currentState: currentState) } it("returns the expected state") { expect(result) == SearchState(loadState: .noResultsFound(stubSearchParams), inputParams: stubSearchInputParams, detailedEntity: nil) } } context("else when the action is SearchAction.subsequentRequest") { func verifyResult(expectedPageState: SearchPageState, expectedEntities: NonEmptyArray<SearchEntityModel>, expectedToken: PlaceLookupTokenAttemptsContainer) { guard case let .pagesReceived(submittedParams, pageState, entities, nextRequestToken) = result.loadState else { fail("Unexpected value: \(result.loadState)") return } expect(submittedParams) == stubSearchParams expect(pageState) == expectedPageState expect(entities) == expectedEntities expect(nextRequestToken) == expectedToken expect(result.detailedEntity) == stubDetailsViewModel } context("and the current loadState is not .pagesReceived") { let currentState = SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) beforeEach { let action = SearchAction.subsequentRequest( stubSearchParams, pageAction: .success, allEntities: stubEntities, nextRequestToken: stubTokenContainer ) result = SearchReducer.reduce(action: action, currentState: currentState) } it("returns the expected state") { verifyResult(expectedPageState: .inProgress, expectedEntities: stubEntities, expectedToken: stubTokenContainer) } } context("else and the pageAction is .inProgress") { let currentLoadState = SearchLoadState.pagesReceived( stubSearchParams, pageState: .success, allEntities: stubEntities, nextRequestToken: stubTokenContainer ) let currentState = SearchState(loadState: currentLoadState, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) beforeEach { let action = SearchAction.subsequentRequest( stubSearchParams, pageAction: .inProgress, allEntities: stubEntities, nextRequestToken: stubTokenContainer ) result = SearchReducer.reduce(action: action, currentState: currentState) } it("returns the expected state") { verifyResult(expectedPageState: .inProgress, expectedEntities: stubEntities, expectedToken: stubTokenContainer) } } context("and the pageAction is .success") { let currentLoadState = SearchLoadState.pagesReceived( stubSearchParams, pageState: .success, allEntities: stubEntities, nextRequestToken: stubTokenContainer ) let currentState = SearchState(loadState: currentLoadState, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) beforeEach { let action = SearchAction.subsequentRequest( stubSearchParams, pageAction: .success, allEntities: stubEntities, nextRequestToken: stubTokenContainer ) result = SearchReducer.reduce(action: action, currentState: currentState) } it("returns the expected state") { verifyResult(expectedPageState: .success, expectedEntities: stubEntities, expectedToken: stubTokenContainer) } } context("and the pageAction is .failure") { let currentLoadState = SearchLoadState.pagesReceived( stubSearchParams, pageState: .success, allEntities: stubEntities, nextRequestToken: stubTokenContainer ) let currentState = SearchState(loadState: currentLoadState, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) let underlyingError = IgnoredEquatable<Error>(SharedTestComponents.StubError.plainError) let pageError = SearchPageRequestError.cannotRetryRequest(underlyingError: underlyingError) beforeEach { let action = SearchAction.subsequentRequest( stubSearchParams, pageAction: .failure(pageError), allEntities: stubEntities, nextRequestToken: stubTokenContainer ) result = SearchReducer.reduce(action: action, currentState: currentState) } it("returns the expected state") { verifyResult(expectedPageState: .failure(pageError), expectedEntities: stubEntities, expectedToken: stubTokenContainer) } } } context("else when the action is SearchAction.failure") { let currentState = SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) beforeEach { let action = SearchAction.failure( stubSearchParams, underlyingError: IgnoredEquatable(SharedTestComponents .StubError.plainError) ) result = SearchReducer.reduce(action: action, currentState: currentState) } it("returns the expected state") { expect(result) == SearchState( loadState: .failure( stubSearchParams, underlyingError: IgnoredEquatable(SharedTestComponents.StubError.plainError) ), inputParams: stubSearchInputParams, detailedEntity: nil ) } } context("else when the action is SearchAction.updateInputEditing") { context("and the editEvent is .beganEditing") { let currentInputParams = SearchInputParams(params: stubSearchParams, isEditing: false) let currentState = SearchState(loadState: .idle, inputParams: currentInputParams, detailedEntity: nil) beforeEach { result = SearchReducer.reduce(action: SearchAction.updateInputEditing(.beganEditing), currentState: currentState) } it("returns the expected state") { expect(result) == SearchState(loadState: .idle, inputParams: SearchInputParams(params: stubSearchParams, isEditing: true), detailedEntity: nil) } } context("and the editEvent is .clearedInput") { let currentInputParams = SearchInputParams(params: stubSearchParams, isEditing: false) let currentState = SearchState(loadState: .idle, inputParams: currentInputParams, detailedEntity: nil) beforeEach { result = SearchReducer.reduce(action: SearchAction.updateInputEditing(.clearedInput), currentState: currentState) } it("returns the expected state") { expect(result) == SearchState(loadState: .idle, inputParams: SearchInputParams(params: nil, isEditing: true), detailedEntity: nil) } } context("and the editEvent is .endedEditing") { let currentParams = SearchParams.stubValue(keywords: NonEmptyString.stubValue()) let currentInputParams = SearchInputParams(params: currentParams, isEditing: true) let currentState = SearchState(loadState: .noResultsFound(stubSearchParams), inputParams: currentInputParams, detailedEntity: nil) beforeEach { result = SearchReducer.reduce(action: SearchAction.updateInputEditing(.endedEditing), currentState: currentState) } it("returns the expected state") { expect(result) == SearchState(loadState: .noResultsFound(stubSearchParams), inputParams: SearchInputParams(params: stubSearchParams, isEditing: false), detailedEntity: nil) } } } context("else when the action is SearchAction.detailedEntity") { let currentState = SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: nil) beforeEach { result = SearchReducer.reduce(action: SearchAction.detailedEntity(stubDetailsViewModel), currentState: currentState) } it("returns the expected state") { expect(result) == SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) } } context("else when the action is SearchAction.removeDetailedEntity") { let currentState = SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: stubDetailsViewModel) beforeEach { result = SearchReducer.reduce(action: SearchAction.removeDetailedEntity, currentState: currentState) } it("returns the expected state") { expect(result) == SearchState(loadState: .idle, inputParams: stubSearchInputParams, detailedEntity: nil) } } } } }
49.088083
111
0.463373
1ae0cda75ddfff87395382143336fdb8267c7800
285
@_implementationOnly import Invisible public func getObject() -> Any { return InvisibleStruct() } private class Conforming : InvisibleProtocol { let name = "conforming" } public func getConformingObject() -> Any { let proto : InvisibleProtocol = Conforming() return proto }
19
46
0.740351
385a25c2811becf05772a7dd176a93b7067dbde8
7,189
import SwiftUI extension View { public func popup<PopupContent: View>( isPresented: Binding<Bool>, type: Popup<PopupContent>.PopupType = .`default`, position: Popup<PopupContent>.Position = .bottom, animation: Animation = Animation.easeOut(duration: 0.3), autohideIn: Double? = nil, closeOnTap: Bool = true, closeOnTapOutside: Bool = false, view: @escaping () -> PopupContent) -> some View { self.modifier( Popup( isPresented: isPresented, type: type, position: position, animation: animation, autohideIn: autohideIn, closeOnTap: closeOnTap, closeOnTapOutside: closeOnTapOutside, view: view) ) } @ViewBuilder func applyIf<T: View>(_ condition: Bool, apply: (Self) -> T) -> some View { if condition { apply(self) } else { self } } @ViewBuilder func addTapIfNotTV(if condition: Bool, onTap: @escaping ()->()) -> some View { #if os(tvOS) self #else if condition { self.simultaneousGesture( TapGesture().onEnded { onTap() } ) } else { self } #endif } } public struct Popup<PopupContent>: ViewModifier where PopupContent: View { public enum PopupType { case `default` case toast case floater(verticalPadding: CGFloat = 50) func shouldBeCentered() -> Bool { switch self { case .`default`: return true default: return false } } } public enum Position { case top case bottom } // MARK: - Public Properties /// Tells if the sheet should be presented or not @Binding var isPresented: Bool var type: PopupType var position: Position var animation: Animation /// If nil - niver hides on its own var autohideIn: Double? /// Should close on tap - default is `true` var closeOnTap: Bool /// Should close on tap outside - default is `true` var closeOnTapOutside: Bool var view: () -> PopupContent /// holder for autohiding dispatch work (to be able to cancel it when needed) var dispatchWorkHolder = DispatchWorkHolder() // MARK: - Private Properties /// The rect of the hosting controller @State private var presenterContentRect: CGRect = .zero /// The rect of popup content @State private var sheetContentRect: CGRect = .zero /// The offset when the popup is displayed private var displayedOffset: CGFloat { switch type { case .`default`: return -presenterContentRect.midY + screenHeight/2 case .toast: if position == .bottom { return screenHeight - presenterContentRect.midY - sheetContentRect.height/2 } else { return -presenterContentRect.midY + sheetContentRect.height/2 } case .floater(let verticalPadding): if position == .bottom { return screenHeight - presenterContentRect.midY - sheetContentRect.height/2 - verticalPadding } else { return -presenterContentRect.midY + sheetContentRect.height/2 + verticalPadding } } } /// The offset when the popup is hidden private var hiddenOffset: CGFloat { if position == .top { if presenterContentRect.isEmpty { return -1000 } return -presenterContentRect.midY - sheetContentRect.height/2 - 5 } else { if presenterContentRect.isEmpty { return 1000 } return screenHeight - presenterContentRect.midY + sheetContentRect.height/2 + 5 } } /// The current offset, based on the **presented** property private var currentOffset: CGFloat { return isPresented ? displayedOffset : hiddenOffset } private var screenSize: CGSize { #if os(iOS) || os(tvOS) return UIScreen.main.bounds.size #elseif os(watchOS) return WKInterfaceDevice.current().screenBounds.size #else return NSScreen.main?.frame.size ?? .zero #endif } private var screenHeight: CGFloat { screenSize.height } // MARK: - Content Builders public func body(content: Content) -> some View { content .addTapIfNotTV(if: closeOnTapOutside) { self.dispatchWorkHolder.work?.cancel() self.isPresented = false } .background( GeometryReader { proxy -> AnyView in let rect = proxy.frame(in: .global) // This avoids an infinite layout loop if rect.integral != self.presenterContentRect.integral { DispatchQueue.main.async { self.presenterContentRect = rect } } return AnyView(EmptyView()) } ).overlay(sheet()) } /// This is the builder for the sheet content func sheet() -> some View { // if needed, dispatch autohide and cancel previous one if let autohideIn = autohideIn { dispatchWorkHolder.work?.cancel() dispatchWorkHolder.work = DispatchWorkItem(block: { self.isPresented = false }) if isPresented, let work = dispatchWorkHolder.work { DispatchQueue.main.asyncAfter(deadline: .now() + autohideIn, execute: work) } } return ZStack { Group { VStack { VStack { self.view() .addTapIfNotTV(if: closeOnTap) { self.dispatchWorkHolder.work?.cancel() self.isPresented = false } .background( GeometryReader { proxy -> AnyView in let rect = proxy.frame(in: .global) // This avoids an infinite layout loop if rect.integral != self.sheetContentRect.integral { DispatchQueue.main.async { self.sheetContentRect = rect } } return AnyView(EmptyView()) } ) } } .frame(width: screenSize.width) .offset(x: 0, y: currentOffset) .animation(animation) } } } } class DispatchWorkHolder { var work: DispatchWorkItem? }
30.722222
109
0.512032
fbec7ea2e602bcd45daf744976b373366545ce0e
761
// // CollectionLabelCell.swift // InterviewTest // // Created by Umair Aamir on 3/15/16. // Copyright © 2016 MyWorkout AS. All rights reserved. // import UIKit class CollectionLabelCell: UICollectionViewCell { @IBOutlet weak var lblTitle: UILabel! let kLabelHorizontalInsets: CGFloat = 8.0 // In layoutSubViews, need set preferredMaxLayoutWidth for multiple lines label override func layoutSubviews() { super.layoutSubviews() // Set what preferredMaxLayoutWidth you want lblTitle.preferredMaxLayoutWidth = self.bounds.width - 2 * kLabelHorizontalInsets } func configCell(title: String) { lblTitle.text = title self.setNeedsLayout() self.layoutIfNeeded() } }
25.366667
89
0.681997
fb303a288f260aaa87c6ad44445e32089da94581
11,043
// Copyright 2021-present Xsolla (USA), Inc. 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 q // // 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 and permissions and import UIKit protocol LoginVCProtocol: BaseViewController, LoadStatable { var loginRequestHandler: ((LoginVCProtocol, UIView, LoginFormData) -> Void)? { get set } var demoUserLoginRequestHandler: ((LoginVCProtocol, UIView) -> Void)? { get set } var socialNetworkLoginRequestHandler: ((LoginVCProtocol, SocialNetwork) -> Void)? { get set } var moreSocialNetworksRequestHandler: ((LoginVCProtocol) -> Void)? { get set } var privacyPolicyRequestHandler: (() -> Void)? { get set } var passwordRecoveryRequestHandler: (() -> Void)? { get set } } class LoginVC: BaseViewController, LoginVCProtocol { // LoginVCProtocol var loginRequestHandler: ((LoginVCProtocol, UIView, LoginFormData) -> Void)? var demoUserLoginRequestHandler: ((LoginVCProtocol, UIView) -> Void)? var socialNetworkLoginRequestHandler: ((LoginVCProtocol, SocialNetwork) -> Void)? var moreSocialNetworksRequestHandler: ((LoginVCProtocol) -> Void)? var privacyPolicyRequestHandler: (() -> Void)? var passwordRecoveryRequestHandler: (() -> Void)? /// Form validator, needs to be set before view load var formValidator: FormValidatorProtocol! // LoadStatable private var loadState: LoadState = .normal @IBOutlet private weak var usernameTextField: FloatingTitleTextField! @IBOutlet private weak var passwordTextField: FloatingTitleTextField! @IBOutlet private weak var passwordRecoverButton: UIButton! @IBOutlet private weak var loginButton: Button! @IBOutlet private weak var demoUserLoginButton: Button! @IBOutlet private weak var googleButton: Button! @IBOutlet private weak var facebookButton: Button! @IBOutlet private weak var baiduButton: Button! @IBOutlet private weak var moreButton: Button! @IBOutlet private weak var privacyPolicyLabel: UILabel! private let textColor = UIColor.xsolla_white private let activeColor = UIColor.xsolla_magenta private let normalColor = UIColor.xsolla_transparentSlateGrey private func performSocialNetworkLogin(_ network: SocialNetwork) { logger.event(.common, domain: .example) { "Login with \(network) pressed" } socialNetworkLoginRequestHandler?(self, network) } private func performPrivacyPolicyRequest() { logger.event(.common, domain: .example) { "Privacy policy pressed" } privacyPolicyRequestHandler?() } private func performLogin() { logger.event(.common, domain: .example) { "Login pressed" } let formData = LoginFormData(username: usernameTextField.text ?? "", password: passwordTextField.text ?? "") loginRequestHandler?(self, loginButton, formData) } private func performDemoUserLogin() { logger.event(.common, domain: .example) { "Login as demo pressed" } demoUserLoginRequestHandler?(self, demoUserLoginButton) } private func performPasswordRecovery() { logger.event(.common, domain: .example) { "Password recovery pressed" } passwordRecoveryRequestHandler?() } private func performShowMoreSocialNetworks() { logger.event(.common, domain: .example) { "Show more social networks pressed" } moreSocialNetworksRequestHandler?(self) } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() guard formValidator != nil else { fatalError("Form validator is not set") } setupInputFields() setupLoginButton() setupDemoUserLoginButton() setupPasswordRecoverButton() setupSocialButtons() setupPrivacyPolicyButton() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateLoginButton() updateLoginDemoUserButton() } // MARK: - Setup UI private func setupInputFields() { setupUsernameTextField() setupPasswordTextField() } private func setupUsernameTextField() { usernameTextField.placeholder = L10n.Form.Field.Username.placeholder usernameTextField.tag = 1 usernameTextField.delegate = self formValidator.addValidator(formValidator.factory.createDefaultValidator(for: usernameTextField), withKey: usernameTextField.tag) } private func setupPasswordTextField() { passwordTextField.placeholder = L10n.Form.Field.Password.placeholder passwordTextField.secure = true passwordTextField.tag = 2 passwordTextField.delegate = self formValidator.addValidator(formValidator.factory.createDefaultValidator(for: passwordTextField), withKey: passwordTextField.tag) } private func setupLoginButton() { loginButton.setupAppearance(config: Button.largeContained) loginButton.isEnabled = false } private func setupDemoUserLoginButton() { demoUserLoginButton.setupAppearance(config: Button.largeOutlined) } private func setupPasswordRecoverButton() { passwordRecoverButton.setTitleColor(.xsolla_transparentSlateGrey, for: .normal) passwordRecoverButton.titleLabel?.font = .xolla_link passwordRecoverButton.setTitle(L10n.Auth.Button.recoverPassword, for: .normal) } private func setupSocialButtons() { googleButton.setupAppearance(config: Button.largeOutlined) facebookButton.setupAppearance(config: Button.largeOutlined) baiduButton.setupAppearance(config: Button.largeOutlined) moreButton.setupAppearance(config: Button.largeOutlined) } private func setupPrivacyPolicyButton() { let text = L10n.Auth.Button.PrivacyPolicy.text(L10n.Auth.Button.PrivacyPolicy.linkTitle) let attrText = text.attributedMutable(.link, color: .xsolla_lightSlateGrey) let attrs: Attributes = [.underlineStyle: NSUnderlineStyle.single.rawValue] attrText.addAttributes(attrs, toSubstring: L10n.Auth.Button.PrivacyPolicy.linkTitle) privacyPolicyLabel.numberOfLines = 0 privacyPolicyLabel.attributedText = attrText privacyPolicyLabel.addTapHandler { [unowned self] in self.performPrivacyPolicyRequest() } privacyPolicyLabel.isUserInteractionEnabled = true } // MARK: - Updates private func updateLoginButton() { let enabled = formValidator.validate() if loginButton.isEnabled != enabled { loginButton.isEnabled = enabled } let color: UIColor = enabled ? .xsolla_white : .xsolla_inactiveWhite let attributedTitle = L10n.Auth.Button.login.attributed(.button, color: color) loginButton.setAttributedTitle(attributedTitle, for: .normal) } private func updateLoginDemoUserButton() { demoUserLoginButton.isEnabled = true let attributedTitle = L10n.Auth.Button.loginDemo.attributed(.button, color: .xsolla_lightSlateGrey) demoUserLoginButton.setAttributedTitle(attributedTitle, for: .normal) } // MARK: - Button Handlers @IBAction private func onPasswordRecoverButton(_ sender: UIButton) { performPasswordRecovery() } @IBAction private func onLoginButton(_ sender: UIButton) { performLogin() } @IBAction private func onDemoUserLoginButton(_ sender: UIButton) { performDemoUserLogin() } @IBAction private func onGoogleButton(_ sender: Button) { performSocialNetworkLogin(.google) } @IBAction private func onFacebookButton(_ sender: Button) { performSocialNetworkLogin(.facebook) } @IBAction private func onBaiduButton(_ sender: Button) { performSocialNetworkLogin(.baidu) } @IBAction private func onMoreButton(_ sender: Button) { performShowMoreSocialNetworks() } // MARK: - State func updateLoadState(_ animated: Bool = false) { switch loadState { case .normal, .error: do { hideActivityIndicator() updateLoginButton() updateLoginDemoUserButton() } case .loading(let view): do { loginButton.isEnabled = false demoUserLoginButton.isEnabled = false if view === loginButton { loginButton.setTitle(nil, for: .normal) showActivityIndicator(for: loginButton) } if view === demoUserLoginButton { demoUserLoginButton.setTitle(nil, for: .normal) showActivityIndicator(for: demoUserLoginButton) } } } } var activityIndicator: ActivityIndicator? private func showActivityIndicator(for view: UIView) { if activityIndicator == nil { if let superview = view.superview { activityIndicator = ActivityIndicator.add(to: superview, centeredBy: view) } } activityIndicator?.isHidden = false activityIndicator?.startAnimating() } private func hideActivityIndicator() { activityIndicator?.removeFromSuperview() activityIndicator = nil } } extension LoginVC: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { formValidator.enableValidator(withKey: textField.tag) formValidator.resetValidator(withKey: textField.tag) updateLoginButton() } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { formValidator.resetValidator(withKey: textField.tag) updateLoginButton() return true } } extension LoginVC: LoadStatable { func getState() -> LoadState { loadState } func setState(_ state: LoadState, animated: Bool) { loadState = state updateLoadState(animated) } }
32.479412
107
0.651182
214d0d6d08fdb9378905b684451816d2b4e46e41
1,030
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct FabricSpecificCreateNetworkMappingInputData : FabricSpecificCreateNetworkMappingInputProtocol { public init() { } public init(from decoder: Decoder) throws { if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { } } extension DataFactory { public static func createFabricSpecificCreateNetworkMappingInputProtocol() -> FabricSpecificCreateNetworkMappingInputProtocol { return FabricSpecificCreateNetworkMappingInputData() } }
33.225806
130
0.748544
5d271e7de83c007441b8ac131b59ccd7e5e3ad89
2,208
// // AppDelegate.swift // UsingCoreBluetoothClassic5_iOS // // Created by [email protected] on 11/01/2019. // Copyright (c) 2019 [email protected]. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.978723
285
0.756793
feda791f3fcbac310b519566fbfe8100fab7560e
2,958
// RUN: %target-swift-frontend -emit-ir %s -swift-version 5 -enable-experimental-concurrency | %IRGenFileCheck %s // REQUIRES: concurrency // CHECK: %T11actor_class7MyClassC = type <{ %swift.refcounted, %swift.defaultactor, %TSi }> // CHECK: %swift.defaultactor = type { [10 x i8*] } // CHECK-objc-LABEL: @"$s11actor_class7MyClassCMm" = global // CHECK-objc-SAME: %objc_class* @"OBJC_METACLASS_$__TtCs12_SwiftObject" // CHECK: @"$s11actor_class7MyClassCMf" = internal global // CHECK-SAME: @"$s11actor_class7MyClassCfD{{(.ptrauth)?}}" // CHECK-objc-SAME: %objc_class* @"OBJC_CLASS_$__TtCs12_SwiftObject" // CHECK-nonobjc-SAME: %swift.type* null, // Flags: uses Swift refcounting // CHECK-SAME: i32 2, // Instance size // CHECK-64-SAME: i32 104, // CHECK-32-SAME: i32 52, // Alignment mask // CHECK-64-SAME: i16 15, // CHECK-32-SAME: i16 7, // Field offset for 'x' // CHECK-objc-SAME: [[INT]] {{48|96}}, // Type descriptor. // CHECK-LABEL: @"$s11actor_class9ExchangerCMn" = {{.*}}constant // superclass ref, negative bounds, positive bounds, num immediate members, num fields, field offset vector offset // CHECK-SAME: i32 0, i32 2, i32 [[#CLASS_METADATA_HEADER+8]], i32 8, i32 2, i32 [[#CLASS_METADATA_HEADER+1]], // Reflection field records. // CHECK-LABEL: @"$s11actor_class9ExchangerCMF" = internal constant // Field descriptor kind, field size, num fields, // (artificial var, "BD", ...) // CHECK-SAME: i16 1, i16 12, i32 2, i32 6, // CHECK-SAME: @"symbolic BD" public actor MyClass { public var x: Int public init() { self.x = 0 } } // CHECK-LABEL: define {{.*}}@"$s11actor_class7MyClassC1xSivg" // CHECK: [[T0:%.*]] = getelementptr inbounds %T11actor_class7MyClassC, %T11actor_class7MyClassC* %0, i32 0, i32 2 // CHECK: [[T1:%.*]] = getelementptr inbounds %TSi, %TSi* [[T0]], i32 0, i32 0 // CHECK: load [[INT]], [[INT]]* [[T1]], align // CHECK-LABEL: define {{.*}}swiftcc %T11actor_class7MyClassC* @"$s11actor_class7MyClassCACycfc" // CHECK: swift_defaultActor_initialize // CHECK-LABEL: ret %T11actor_class7MyClassC* // CHECK-LABEL: define {{.*}}swiftcc %swift.refcounted* @"$s11actor_class7MyClassCfd" // CHECK: swift_defaultActor_destroy // CHECK-LABEL: ret public actor Exchanger<T> { public var value: T public init(value: T) { self.value = value } public func exchange(newValue: T) -> T { let oldValue = value value = newValue return oldValue } } // CHECK-LABEL: define{{.*}} void @"$s11actor_class9ExchangerC5valuexvg"( // Note that this is one more than the field offset vector offset from // the class descriptor, since this is the second field. // CHECK: [[T0:%.*]] = getelementptr inbounds [[INT]], [[INT]]* {{.*}}, [[INT]] [[#CLASS_METADATA_HEADER+2]] // CHECK-NEXT: [[OFFSET:%.*]] = load [[INT]], [[INT]]* [[T0]], align // CHECK-NEXT: [[T0:%.*]] = bitcast %T11actor_class9ExchangerC* %1 to i8* // CHECK-NEXT: getelementptr inbounds i8, i8* [[T0]], [[INT]] [[OFFSET]]
40.520548
116
0.676133
fe5bc2f18d43d16bf724e5db8d5321c7718bacf0
1,895
// // Solution.swift // Problem 77 // // Created by sebastien FOCK CHOW THO on 2019-08-10. // Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved. // import Foundation /** - First I would define a structure for my interval - Then I would right a function that check if an interval is overlapping another one - Finally I would build a custom function reducing my array based on the previous utility */ struct Interval { var start: Int var end: Int func isOverlapping(interval: Interval) -> Bool { return start >= interval.start && end <= interval.end } } extension Array where Element == Interval { mutating func reduceOverlapping() -> [Interval] { for i in 0..<count { // Loop through the elements let element = self[i] // Create a copy of the initial array without the current element var copy = self copy.remove(at: i) // If the element is overlapping any other interval, remove it and re-iterate for interval in copy { if element.isOverlapping(interval: interval) { remove(at: i) return reduceOverlapping() } } } return self } } /** Utility functions to switch from the tuple syntax to intervals */ func tuplesToIntervals(input: [(start: Int, end: Int)]) -> [Interval] { var result: [Interval] = [] for tuple in input { result.append(Interval(start: tuple.start, end: tuple.end)) } return result } func intervalsToTuples(input: [(Interval)]) -> [(start: Int, end: Int)] { var result: [(start: Int, end: Int)] = [] for interval in input { result.append((start: interval.start, end: interval.end)) } return result }
25.266667
93
0.584169
e85259d6be71a54256ce901c99a13dde1d3d6a29
507
// // ViewController.swift // TBOLog_iOS // // Created by TobyoTenma on 14/10/2017. // Copyright © 2017 TobyoTenma. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.5
80
0.672584
1edec629789afae8132c592ef5498fcf2a103cee
7,341
import UIKit import MultipeerConnectivity class ChatViewController: UIViewController { // This constraint will be used to adjust the UI in response to the keyboard being displayed/hidden. @IBOutlet private var bottomConstraint: NSLayoutConstraint! @IBOutlet private var textField: UITextField! @IBOutlet private var tableView: UITableView! private var appDelegate: AppDelegate! private var messages: [Dictionary<String, String>] = [] private let chatTableViewHandler = ChatTableViewHandler() // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() guard let appDelegate = Constants.appDelegate else { return } self.appDelegate = appDelegate configureTableView() configureTextField() configureEndChatButton() configureNavigationBar() registerKeyboardNotifications() registerDataReceivedNotification() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.hidesBackButton = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } // MARK: - Notifications private func registerKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(self.adjustForDisplayKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.adjustForHideKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } private func registerDataReceivedNotification() { NotificationCenter.default.addObserver(self, selector: #selector(self.handleDataReceived(notification:)), name: NSNotification.Name.oShareRecivedData, object: nil) } // MARK: - UI Configuration private func configureNavigationBar() { guard let peer = appDelegate.connectivityManager.session.connectedPeers.first else { return } navigationItem.title = "\(peer.displayName)" } private func configureTableView() { chatTableViewHandler.appDelegate = appDelegate chatTableViewHandler.tableView = tableView tableView.delegate = chatTableViewHandler tableView.dataSource = chatTableViewHandler } private func configureTextField() { textField.delegate = self textField.becomeFirstResponder() } private func configureEndChatButton() { let endChatButton = UIBarButtonItem(title: Constants.Strings.endButtonString, style: .done, target: self, action: #selector(self.endChat(sender:))) navigationItem.rightBarButtonItem = endChatButton } // MARK: - Data @objc private func handleDataReceived(notification: Notification) { guard let object = notification.object as? [String: Any], let data = object[DictionaryKeys.data.rawValue] as? Data, let peer = object[DictionaryKeys.peer.rawValue] as? MCPeerID, let messageData = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: String] else { return } if let message = messageData[DictionaryKeys.message.rawValue] { if message != Constants.Strings.endChatCodeString { let messageDictionary: [String: String] = [DictionaryKeys.sender.rawValue: peer.displayName, DictionaryKeys.message.rawValue: message] messages.append(messageDictionary) OperationQueue.main.addOperation { [weak self] () -> Void in guard let strongSelf = self else { return } strongSelf.chatTableViewHandler.reloadData(messages: strongSelf.messages) } } else { // If we receive the pre-set end chat code, we should be told that the peer ended the chat. // Randomly backing out of the chat screen could be quite confusing otherwise. handleChatEnded(peer) } } } private func handleChatEnded(_ peer: MCPeerID) { let alert = UIAlertController(title: "👋", message: "\(peer.displayName) ended the chat.", preferredStyle: .alert) let doneAction: UIAlertAction = UIAlertAction(title: Constants.Strings.closeButtonString, style: .default) { [weak self] (action) in self?.appDelegate.connectivityManager.session.disconnect() self?.navigationController?.popViewController(animated: true) } alert.addAction(doneAction) OperationQueue.main.addOperation { [weak self] () -> Void in self?.present(alert, animated: true, completion: nil) } } // MARK: - Keyboard Adjustments @objc private func adjustForDisplayKeyboard(_ notification: Notification) { if let keyboardSize = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect { bottomConstraint.constant = keyboardSize.size.height-(Constants.appDelegate?.window?.safeAreaInsets.bottom ?? 0) UIView.animate(withDuration: 0.5) { [weak self] in guard let strongSelf = self else { return } strongSelf.view.setNeedsLayout() strongSelf.view.layoutIfNeeded() } } } @objc private func adjustForHideKeyboard(_ notification: Notification) { bottomConstraint.constant = 0 UIView.animate(withDuration: 0.5) { [weak self] in guard let strongSelf = self else { return } strongSelf.view.setNeedsLayout() strongSelf.view.layoutIfNeeded() } } // MARK: - Call To Action (End Chat) @IBAction private func endChat(sender: UIBarButtonItem?) { // For the sake of simplicity, we are only going to support peer-to-peer chat, as opposed to multiple peers in a single chat. This is why I directly access [0] in the list of connected peers. let messageDictionary: [String: String] = [DictionaryKeys.sender.rawValue: Constants.Strings.selfSenderString, DictionaryKeys.message.rawValue: Constants.Strings.endChatCodeString] let waitTimeBeforeDisconnection: TimeInterval = 2 guard let connectedPeer = appDelegate.connectivityManager.session.connectedPeers.first else { return } if appDelegate.connectivityManager.send(dictionaryWithData: messageDictionary, toPeer: connectedPeer) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+waitTimeBeforeDisconnection, execute: { [weak self] in self?.appDelegate.connectivityManager.session.disconnect() self?.appDelegate.connectivityManager.startAdvertising() self?.appDelegate.connectivityManager.startBrowsingForDevices() self?.navigationController?.popViewController(animated: true) }) } } // MARK: - Call To Action (Send Message) @IBAction private func sendMessage(sender: UIButton?) { // Only proceed sending data if the text is not empty, and if there is still a connected peer. guard let text = textField.text, let peer = appDelegate.connectivityManager.session.connectedPeers.first, text.isEmpty == false else { return } let messageData: [String: String] = [DictionaryKeys.sender.rawValue: Constants.Strings.selfSenderString, DictionaryKeys.message.rawValue: text] if appDelegate.connectivityManager.send(dictionaryWithData: messageData, toPeer: peer) { messages.append(messageData) chatTableViewHandler.reloadData(messages: messages) } else { // TODO: - Handle Failure } textField.text = "" } } // MARK: - UITextFieldDelegate extension ChatViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() sendMessage(sender: nil) return true } } // MARK: - DictionaryKeys Enum private enum DictionaryKeys: String { case data case sender case message case peer }
35.809756
193
0.760114
ac13c41c11a395fb4781e0bfd00a7075b0f73cd2
4,047
import AdaptiveCardUI import XCTest final class TextRunTests: XCTestCase { func testStringDecodeReturnsTextRun() throws { struct Element: Codable, Equatable { var inline: TextRun } // given let json = """ { "inline": "Hello world!" } """.data(using: .utf8)! let expected = Element(inline: TextRun(text: "Hello world!")) // when let result = try JSONDecoder().decode(Element.self, from: json) // then XCTAssertEqual(expected, result) } func testMinimalTextRunDecodeReturnsTextRun() throws { // given let json = """ { "type": "TextRun", "text": "Hello world!" } """.data(using: .utf8)! let expected = TextRun(text: "Hello world!") // when let result = try JSONDecoder().decode(TextRun.self, from: json) // then XCTAssertEqual(expected, result) } func testTextRunDecodeReturnsTextRun() throws { // given let json = """ { "type": "TextRun", "text": "Hello world!", "color": "good", "fontType": "monospace", "highlight": true, "isSubtle": true, "italic": true, "selectAction": { "type": "Action.OpenUrl", "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ" }, "size": "small", "strikethrough": true, "weight": "bolder" } """.data(using: .utf8)! let expected = TextRun( text: "Hello world!", color: .good, fontType: .monospace, highlight: true, isSubtle: true, italic: true, selectAction: .openURL(OpenURLAction(url: URL(string: "https://www.youtube.com/watch?v=dQw4w9WgXcQ")!)), size: .small, strikethrough: true, weight: .bold ) // when let result = try JSONDecoder().decode(TextRun.self, from: json) // then XCTAssertEqual(expected, result) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) func testMinimalTextRunEncodeReturnsTextRunJSON() throws { // given let textRun = TextRun(text: "Hello world!") let expected = """ { "text" : "Hello world!", "type" : "TextRun" } """.data(using: .utf8)! let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] // when let result = try encoder.encode(textRun) // then XCTAssertEqual(expected, result) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) func testTextRunEncodeReturnsTextRunJSON() throws { // given let textRun = TextRun( text: "Hello world!", color: .good, fontType: .monospace, highlight: true, isSubtle: true, italic: true, selectAction: .openURL(OpenURLAction(url: URL(string: "https://www.youtube.com/watch?v=dQw4w9WgXcQ")!)), size: .small, strikethrough: true, weight: .bold ) let expected = #""" { "color" : "good", "fontType" : "monospace", "highlight" : true, "isSubtle" : true, "italic" : true, "selectAction" : { "type" : "Action.OpenUrl", "url" : "https:\/\/www.youtube.com\/watch?v=dQw4w9WgXcQ" }, "size" : "small", "strikethrough" : true, "text" : "Hello world!", "type" : "TextRun", "weight" : "bolder" } """#.data(using: .utf8)! let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] // when let result = try encoder.encode(textRun) // then XCTAssertEqual(expected, result) } }
27.910345
116
0.504324
4b158974bc0da0c7275ee8155cb324a641f82eef
69,086
/* * SwiftWebSocket (websocket.swift) * * Copyright (C) Josh Baker. All Rights Reserved. * Contact: @tidwall, [email protected] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * */ import Foundation private let windowBufferSize = 0x2000 private class Payload { var ptr : UnsafeMutableRawPointer var cap : Int var len : Int init(){ len = 0 cap = windowBufferSize ptr = malloc(cap) } deinit{ free(ptr) } var count : Int { get { return len } set { if newValue > cap { while cap < newValue { cap *= 2 } ptr = realloc(ptr, cap) } len = newValue } } func append(_ bytes: UnsafePointer<UInt8>, length: Int){ let prevLen = len count = len+length memcpy(ptr+prevLen, bytes, length) } var array : [UInt8] { get { var array = [UInt8](repeating: 0, count: count) memcpy(&array, ptr, count) return array } set { count = 0 append(newValue, length: newValue.count) } } var nsdata : Data { get { return Data(bytes: ptr.assumingMemoryBound(to: UInt8.self), count: count) } set { count = 0 append((newValue as NSData).bytes.bindMemory(to: UInt8.self, capacity: newValue.count), length: newValue.count) } } var buffer : UnsafeBufferPointer<UInt8> { get { return UnsafeBufferPointer<UInt8>(start: ptr.assumingMemoryBound(to: UInt8.self), count: count) } set { count = 0 append(newValue.baseAddress!, length: newValue.count) } } } private enum OpCode : UInt8, CustomStringConvertible { case `continue` = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xA var isControl : Bool { switch self { case .close, .ping, .pong: return true default: return false } } var description : String { switch self { case .`continue`: return "Continue" case .text: return "Text" case .binary: return "Binary" case .close: return "Close" case .ping: return "Ping" case .pong: return "Pong" } } } /// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection. public struct WebSocketEvents { /// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data. public var open : ()->() = {} /// An event to be called when the WebSocket connection's readyState changes to .Closed. public var close : (_ code : Int, _ reason : String, _ wasClean : Bool)->() = {(code, reason, wasClean) in} /// An event to be called when an error occurs. public var error : (_ error : Error)->() = {(error) in} /// An event to be called when a message is received from the server. public var message : (_ data : Any)->() = {(data) in} /// An event to be called when a pong is received from the server. public var pong : (_ data : Any)->() = {(data) in} /// An event to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events. public var end : (_ code : Int, _ reason : String, _ wasClean : Bool, _ error : Error?)->() = {(code, reason, wasClean, error) in} } /// The WebSocketBinaryType enum is used by the binaryType property and indicates the type of binary data being transmitted by the WebSocket connection. public enum WebSocketBinaryType : CustomStringConvertible { /// The WebSocket should transmit [UInt8] objects. case uInt8Array /// The WebSocket should transmit NSData objects. case nsData /// The WebSocket should transmit UnsafeBufferPointer<UInt8> objects. This buffer is only valid during the scope of the message event. Use at your own risk. case uInt8UnsafeBufferPointer public var description : String { switch self { case .uInt8Array: return "UInt8Array" case .nsData: return "NSData" case .uInt8UnsafeBufferPointer: return "UInt8UnsafeBufferPointer" } } } /// The WebSocketReadyState enum is used by the readyState property to describe the status of the WebSocket connection. @objc public enum WebSocketReadyState : Int, CustomStringConvertible { /// The connection is not yet open. case connecting = 0 /// The connection is open and ready to communicate. case open = 1 /// The connection is in the process of closing. case closing = 2 /// The connection is closed or couldn't be opened. case closed = 3 fileprivate var isClosed : Bool { switch self { case .closing, .closed: return true default: return false } } /// Returns a string that represents the ReadyState value. public var description : String { switch self { case .connecting: return "Connecting" case .open: return "Open" case .closing: return "Closing" case .closed: return "Closed" } } } private let defaultMaxWindowBits = 15 /// The WebSocketCompression struct is used by the compression property and manages the compression options for the WebSocket connection. public struct WebSocketCompression { /// Used to accept compressed messages from the server. Default is true. public var on = false /// request no context takeover. public var noContextTakeover = false /// request max window bits. public var maxWindowBits = defaultMaxWindowBits } /// The WebSocketService options are used by the services property and manages the underlying socket services. public struct WebSocketService : OptionSet { public typealias RawValue = UInt var value: UInt = 0 init(_ value: UInt) { self.value = value } public init(rawValue value: UInt) { self.value = value } public init(nilLiteral: ()) { self.value = 0 } public static var allZeros: WebSocketService { return self.init(0) } static func fromMask(_ raw: UInt) -> WebSocketService { return self.init(raw) } public var rawValue: UInt { return self.value } /// No services. public static var None: WebSocketService { return self.init(0) } /// Allow socket to handle VoIP. public static var VoIP: WebSocketService { return self.init(1 << 0) } /// Allow socket to handle video. public static var Video: WebSocketService { return self.init(1 << 1) } /// Allow socket to run in background. public static var Background: WebSocketService { return self.init(1 << 2) } /// Allow socket to handle voice. public static var Voice: WebSocketService { return self.init(1 << 3) } } private let atEndDetails = "streamStatus.atEnd" private let timeoutDetails = "The operation couldn’t be completed. Operation timed out" private let timeoutDuration : CFTimeInterval = 30 public enum WebSocketError : Error, CustomStringConvertible { case memory case needMoreInput case invalidHeader case invalidAddress case network(String) case libraryError(String) case payloadError(String) case protocolError(String) case invalidResponse(String) case invalidCompressionOptions(String) public var description : String { switch self { case .memory: return "Memory" case .needMoreInput: return "NeedMoreInput" case .invalidAddress: return "InvalidAddress" case .invalidHeader: return "InvalidHeader" case let .invalidResponse(details): return "InvalidResponse(\(details))" case let .invalidCompressionOptions(details): return "InvalidCompressionOptions(\(details))" case let .libraryError(details): return "LibraryError(\(details))" case let .protocolError(details): return "ProtocolError(\(details))" case let .payloadError(details): return "PayloadError(\(details))" case let .network(details): return "Network(\(details))" } } public var details : String { switch self { case .invalidResponse(let details): return details case .invalidCompressionOptions(let details): return details case .libraryError(let details): return details case .protocolError(let details): return details case .payloadError(let details): return details case .network(let details): return details default: return "" } } } private class UTF8 { var text : String = "" var count : UInt32 = 0 // number of bytes var procd : UInt32 = 0 // number of bytes processed var codepoint : UInt32 = 0 // the actual codepoint var bcount = 0 init() { text = "" } func append(_ byte : UInt8) throws { if count == 0 { if byte <= 0x7F { text.append(String(UnicodeScalar(byte))) return } if byte == 0xC0 || byte == 0xC1 { throw WebSocketError.payloadError("invalid codepoint: invalid byte") } if byte >> 5 & 0x7 == 0x6 { count = 2 } else if byte >> 4 & 0xF == 0xE { count = 3 } else if byte >> 3 & 0x1F == 0x1E { count = 4 } else { throw WebSocketError.payloadError("invalid codepoint: frames") } procd = 1 codepoint = (UInt32(byte) & (0xFF >> count)) << ((count-1) * 6) return } if byte >> 6 & 0x3 != 0x2 { throw WebSocketError.payloadError("invalid codepoint: signature") } codepoint += UInt32(byte & 0x3F) << ((count-procd-1) * 6) if codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) { throw WebSocketError.payloadError("invalid codepoint: out of bounds") } procd += 1 if procd == count { if codepoint <= 0x7FF && count > 2 { throw WebSocketError.payloadError("invalid codepoint: overlong") } if codepoint <= 0xFFFF && count > 3 { throw WebSocketError.payloadError("invalid codepoint: overlong") } procd = 0 count = 0 text.append(String.init(describing: UnicodeScalar(codepoint)!)) } return } func append(_ bytes : UnsafePointer<UInt8>, length : Int) throws { if length == 0 { return } if count == 0 { var ascii = true for i in 0 ..< length { if bytes[i] > 0x7F { ascii = false break } } if ascii { text += NSString(bytes: bytes, length: length, encoding: String.Encoding.ascii.rawValue)! as String bcount += length return } } for i in 0 ..< length { try append(bytes[i]) } bcount += length } var completed : Bool { return count == 0 } static func bytes(_ string : String) -> [UInt8]{ let data = string.data(using: String.Encoding.utf8)! return [UInt8](UnsafeBufferPointer<UInt8>(start: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), count: data.count)) } static func string(_ bytes : [UInt8]) -> String{ if let str = NSString(bytes: bytes, length: bytes.count, encoding: String.Encoding.utf8.rawValue) { return str as String } return "" } } private class Frame { var inflate = false var code = OpCode.continue var utf8 = UTF8() var payload = Payload() var statusCode = UInt16(0) var finished = true static func makeClose(_ statusCode: UInt16, reason: String) -> Frame { let f = Frame() f.code = .close f.statusCode = statusCode f.utf8.text = reason return f } func copy() -> Frame { let f = Frame() f.code = code f.utf8.text = utf8.text f.payload.buffer = payload.buffer f.statusCode = statusCode f.finished = finished f.inflate = inflate return f } } private class Delegate : NSObject, StreamDelegate { @objc func stream(_ aStream: Stream, handle eventCode: Stream.Event){ manager.signal() } } @_silgen_name("zlibVersion") private func zlibVersion() -> OpaquePointer @_silgen_name("deflateInit2_") private func deflateInit2(_ strm : UnsafeMutableRawPointer, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : OpaquePointer, stream_size : CInt) -> CInt @_silgen_name("deflateInit_") private func deflateInit(_ strm : UnsafeMutableRawPointer, level : CInt, version : OpaquePointer, stream_size : CInt) -> CInt @_silgen_name("deflateEnd") private func deflateEnd(_ strm : UnsafeMutableRawPointer) -> CInt @_silgen_name("deflate") private func deflate(_ strm : UnsafeMutableRawPointer, flush : CInt) -> CInt @_silgen_name("inflateInit2_") private func inflateInit2(_ strm : UnsafeMutableRawPointer, windowBits : CInt, version : OpaquePointer, stream_size : CInt) -> CInt @_silgen_name("inflateInit_") private func inflateInit(_ strm : UnsafeMutableRawPointer, version : OpaquePointer, stream_size : CInt) -> CInt @_silgen_name("inflate") private func inflateG(_ strm : UnsafeMutableRawPointer, flush : CInt) -> CInt @_silgen_name("inflateEnd") private func inflateEndG(_ strm : UnsafeMutableRawPointer) -> CInt private func zerror(_ res : CInt) -> Error? { var err = "" switch res { case 0: return nil case 1: err = "stream end" case 2: err = "need dict" case -1: err = "errno" case -2: err = "stream error" case -3: err = "data error" case -4: err = "mem error" case -5: err = "buf error" case -6: err = "version error" default: err = "undefined error" } return WebSocketError.payloadError("zlib: \(err): \(res)") } private struct z_stream { var next_in : UnsafePointer<UInt8>? = nil var avail_in : CUnsignedInt = 0 var total_in : CUnsignedLong = 0 var next_out : UnsafeMutablePointer<UInt8>? = nil var avail_out : CUnsignedInt = 0 var total_out : CUnsignedLong = 0 var msg : UnsafePointer<CChar>? = nil var state : OpaquePointer? = nil var zalloc : OpaquePointer? = nil var zfree : OpaquePointer? = nil var opaque : OpaquePointer? = nil var data_type : CInt = 0 var adler : CUnsignedLong = 0 var reserved : CUnsignedLong = 0 } private class Inflater { var windowBits = 0 var strm = z_stream() var tInput = [[UInt8]]() var inflateEnd : [UInt8] = [0x00, 0x00, 0xFF, 0xFF] var bufferSize = windowBufferSize var buffer = malloc(windowBufferSize) init?(windowBits : Int){ if buffer == nil { return nil } self.windowBits = windowBits let ret = inflateInit2(&strm, windowBits: -CInt(windowBits), version: zlibVersion(), stream_size: CInt(MemoryLayout<z_stream>.size)) if ret != 0 { return nil } } deinit{ _ = inflateEndG(&strm) free(buffer) } func inflate(_ bufin : UnsafePointer<UInt8>, length : Int, final : Bool) throws -> (p : UnsafeMutablePointer<UInt8>, n : Int){ var buf = buffer var bufsiz = bufferSize var buflen = 0 for i in 0 ..< 2{ if i == 0 { strm.avail_in = CUnsignedInt(length) strm.next_in = UnsafePointer<UInt8>(bufin) } else { if !final { break } strm.avail_in = CUnsignedInt(inflateEnd.count) strm.next_in = UnsafePointer<UInt8>(inflateEnd) } while true { strm.avail_out = CUnsignedInt(bufsiz) strm.next_out = buf?.assumingMemoryBound(to: UInt8.self) _ = inflateG(&strm, flush: 0) let have = bufsiz - Int(strm.avail_out) bufsiz -= have buflen += have if strm.avail_out != 0{ break } if bufsiz == 0 { bufferSize *= 2 let nbuf = realloc(buffer, bufferSize) if nbuf == nil { throw WebSocketError.payloadError("memory") } buffer = nbuf buf = buffer?.advanced(by: Int(buflen)) bufsiz = bufferSize - buflen } } } return (buffer!.assumingMemoryBound(to: UInt8.self), buflen) } } private class Deflater { var windowBits = 0 var memLevel = 0 var strm = z_stream() var bufferSize = windowBufferSize var buffer = malloc(windowBufferSize) init?(windowBits : Int, memLevel : Int){ if buffer == nil { return nil } self.windowBits = windowBits self.memLevel = memLevel let ret = deflateInit2(&strm, level: 6, method: 8, windowBits: -CInt(windowBits), memLevel: CInt(memLevel), strategy: 0, version: zlibVersion(), stream_size: CInt(MemoryLayout<z_stream>.size)) if ret != 0 { return nil } } deinit{ _ = deflateEnd(&strm) free(buffer) } /*func deflate(_ bufin : UnsafePointer<UInt8>, length : Int, final : Bool) -> (p : UnsafeMutablePointer<UInt8>, n : Int, err : NSError?){ return (nil, 0, nil) }*/ } /// WebSocketDelegate is an Objective-C alternative to WebSocketEvents and is used to delegate the events for the WebSocket connection. @objc public protocol WebSocketDelegate { /// A function to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data. func webSocketOpen() /// A function to be called when the WebSocket connection's readyState changes to .Closed. func webSocketClose(_ code: Int, reason: String, wasClean: Bool) /// A function to be called when an error occurs. func webSocketError(_ error: NSError) /// A function to be called when a message (string) is received from the server. @objc optional func webSocketMessageText(_ text: String) /// A function to be called when a message (binary) is received from the server. @objc optional func webSocketMessageData(_ data: Data) /// A function to be called when a pong is received from the server. @objc optional func webSocketPong() /// A function to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events. @objc optional func webSocketEnd(_ code: Int, reason: String, wasClean: Bool, error: NSError?) } /// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455. private class InnerWebSocket: Hashable { var id : Int var mutex = pthread_mutex_t() let request : URLRequest! let subProtocols : [String]! var frames : [Frame] = [] var delegate : Delegate var inflater : Inflater! var deflater : Deflater! var outputBytes : UnsafeMutablePointer<UInt8>? var outputBytesSize : Int = 0 var outputBytesStart : Int = 0 var outputBytesLength : Int = 0 var inputBytes : UnsafeMutablePointer<UInt8>? var inputBytesSize : Int = 0 var inputBytesStart : Int = 0 var inputBytesLength : Int = 0 var createdAt = CFAbsoluteTimeGetCurrent() var connectionTimeout = false var eclose : ()->() = {} var _eventQueue : DispatchQueue? = DispatchQueue.main var _subProtocol = "" var _compression = WebSocketCompression() var _allowSelfSignedSSL = false var _services = WebSocketService.None var _event = WebSocketEvents() var _eventDelegate: WebSocketDelegate? var _binaryType = WebSocketBinaryType.uInt8Array var _readyState = WebSocketReadyState.connecting var _networkTimeout = TimeInterval(-1) var url : String { return request.url!.description } var subProtocol : String { get { return privateSubProtocol } } var privateSubProtocol : String { get { lock(); defer { unlock() }; return _subProtocol } set { lock(); defer { unlock() }; _subProtocol = newValue } } var compression : WebSocketCompression { get { lock(); defer { unlock() }; return _compression } set { lock(); defer { unlock() }; _compression = newValue } } var allowSelfSignedSSL : Bool { get { lock(); defer { unlock() }; return _allowSelfSignedSSL } set { lock(); defer { unlock() }; _allowSelfSignedSSL = newValue } } var services : WebSocketService { get { lock(); defer { unlock() }; return _services } set { lock(); defer { unlock() }; _services = newValue } } var event : WebSocketEvents { get { lock(); defer { unlock() }; return _event } set { lock(); defer { unlock() }; _event = newValue } } var eventDelegate : WebSocketDelegate? { get { lock(); defer { unlock() }; return _eventDelegate } set { lock(); defer { unlock() }; _eventDelegate = newValue } } var eventQueue : DispatchQueue? { get { lock(); defer { unlock() }; return _eventQueue; } set { lock(); defer { unlock() }; _eventQueue = newValue } } var binaryType : WebSocketBinaryType { get { lock(); defer { unlock() }; return _binaryType } set { lock(); defer { unlock() }; _binaryType = newValue } } var readyState : WebSocketReadyState { get { return privateReadyState } } var privateReadyState : WebSocketReadyState { get { lock(); defer { unlock() }; return _readyState } set { lock(); defer { unlock() }; _readyState = newValue } } func copyOpen(_ request: URLRequest, subProtocols : [String] = []) -> InnerWebSocket{ let ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false) ws.eclose = eclose ws.compression = compression ws.allowSelfSignedSSL = allowSelfSignedSSL ws.services = services ws.event = event ws.eventQueue = eventQueue ws.binaryType = binaryType return ws } var hashValue: Int { return id } func hash(into hasher: inout Hasher) { hasher.combine(id) } init(request: URLRequest, subProtocols : [String] = [], stub : Bool = false){ pthread_mutex_init(&mutex, nil) self.id = manager.nextId() self.request = request self.subProtocols = subProtocols self.outputBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: windowBufferSize) self.outputBytesSize = windowBufferSize self.inputBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: windowBufferSize) self.inputBytesSize = windowBufferSize self.delegate = Delegate() if stub{ manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){ _ = self } } else { manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){ manager.add(self) } } } deinit{ if outputBytes != nil { free(outputBytes) } if inputBytes != nil { free(inputBytes) } pthread_mutex_init(&mutex, nil) } @inline(__always) fileprivate func lock(){ pthread_mutex_lock(&mutex) } @inline(__always) fileprivate func unlock(){ pthread_mutex_unlock(&mutex) } fileprivate var dirty : Bool { lock() defer { unlock() } if exit { return false } if connectionTimeout { return true } if stage != .readResponse && stage != .handleFrames { return true } if rd.streamStatus == .opening && wr.streamStatus == .opening { return false; } if rd.streamStatus != .open || wr.streamStatus != .open { return true } if rd.streamError != nil || wr.streamError != nil { return true } if rd.hasBytesAvailable || frames.count > 0 || inputBytesLength > 0 { return true } if outputBytesLength > 0 && wr.hasSpaceAvailable{ return true } return false } enum Stage : Int { case openConn case readResponse case handleFrames case closeConn case end } var stage = Stage.openConn var rd : InputStream! var wr : OutputStream! var atEnd = false var closeCode = UInt16(0) var closeReason = "" var closeClean = false var closeFinal = false var finalError : Error? var exit = false var more = true func step(){ if exit { return } do { try stepBuffers(more) try stepStreamErrors() more = false switch stage { case .openConn: try openConn() stage = .readResponse case .readResponse: try readResponse() privateReadyState = .open fire { self.event.open() self.eventDelegate?.webSocketOpen() } stage = .handleFrames case .handleFrames: try stepOutputFrames() if closeFinal { privateReadyState = .closing stage = .closeConn return } let frame = try readFrame() switch frame.code { case .text: fire { self.event.message(frame.utf8.text) self.eventDelegate?.webSocketMessageText?(frame.utf8.text) } case .binary: fire { switch self.binaryType { case .uInt8Array: self.event.message(frame.payload.array) case .nsData: self.event.message(frame.payload.nsdata) // The WebSocketDelegate is necessary to add Objective-C compability and it is only possible to send binary data with NSData. self.eventDelegate?.webSocketMessageData?(frame.payload.nsdata) case .uInt8UnsafeBufferPointer: self.event.message(frame.payload.buffer) } } case .ping: let nframe = frame.copy() nframe.code = .pong lock() frames += [nframe] unlock() case .pong: fire { switch self.binaryType { case .uInt8Array: self.event.pong(frame.payload.array) case .nsData: self.event.pong(frame.payload.nsdata) case .uInt8UnsafeBufferPointer: self.event.pong(frame.payload.buffer) } self.eventDelegate?.webSocketPong?() } case .close: lock() frames += [frame] unlock() default: break } case .closeConn: if let error = finalError { self.event.error(error) self.eventDelegate?.webSocketError(error as NSError) } privateReadyState = .closed if rd != nil { closeConn() fire { self.eclose() self.event.close(Int(self.closeCode), self.closeReason, self.closeFinal) self.eventDelegate?.webSocketClose(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal) } } stage = .end case .end: fire { self.event.end(Int(self.closeCode), self.closeReason, self.closeClean, self.finalError) self.eventDelegate?.webSocketEnd?(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError as NSError?) } exit = true manager.remove(self) } } catch WebSocketError.needMoreInput { more = true } catch { if finalError != nil { return } finalError = error if stage == .openConn || stage == .readResponse { stage = .closeConn } else { var frame : Frame? if let error = error as? WebSocketError{ switch error { case .network(let details): if details == atEndDetails{ stage = .closeConn frame = Frame.makeClose(1006, reason: "Abnormal Closure") atEnd = true finalError = nil } case .protocolError: frame = Frame.makeClose(1002, reason: "Protocol error") case .payloadError: frame = Frame.makeClose(1007, reason: "Payload error") default: break } } if frame == nil { frame = Frame.makeClose(1006, reason: "Abnormal Closure") } if let frame = frame { if frame.statusCode == 1007 { self.lock() self.frames = [frame] self.unlock() manager.signal() } else { manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){ self.lock() self.frames += [frame] self.unlock() manager.signal() } } } } } } func stepBuffers(_ more: Bool) throws { if rd != nil { if stage != .closeConn && rd.streamStatus == Stream.Status.atEnd { if atEnd { return; } throw WebSocketError.network(atEndDetails) } if more { while rd.hasBytesAvailable { var size = inputBytesSize while size-(inputBytesStart+inputBytesLength) < windowBufferSize { size *= 2 } if size > inputBytesSize { let ptr = realloc(inputBytes, size) if ptr == nil { throw WebSocketError.memory } inputBytes = ptr?.assumingMemoryBound(to: UInt8.self) inputBytesSize = size } let n = rd.read(inputBytes!+inputBytesStart+inputBytesLength, maxLength: inputBytesSize-inputBytesStart-inputBytesLength) if n > 0 { inputBytesLength += n } } } } if wr != nil && wr.hasSpaceAvailable && outputBytesLength > 0 { let n = wr.write(outputBytes!+outputBytesStart, maxLength: outputBytesLength) if n > 0 { outputBytesLength -= n if outputBytesLength == 0 { outputBytesStart = 0 } else { outputBytesStart += n } } } } func stepStreamErrors() throws { if finalError == nil { if connectionTimeout { throw WebSocketError.network(timeoutDetails) } if let error = rd?.streamError { throw WebSocketError.network(error.localizedDescription) } if let error = wr?.streamError { throw WebSocketError.network(error.localizedDescription) } } } func stepOutputFrames() throws { lock() defer { frames = [] unlock() } if !closeFinal { for frame in frames { try writeFrame(frame) if frame.code == .close { closeCode = frame.statusCode closeReason = frame.utf8.text closeFinal = true return } } } } @inline(__always) func fire(_ block: ()->()){ if let queue = eventQueue { queue.sync { block() } } else { block() } } var readStateSaved = false var readStateFrame : Frame? var readStateFinished = false var leaderFrame : Frame? func readFrame() throws -> Frame { var frame : Frame var finished : Bool if !readStateSaved { if leaderFrame != nil { frame = leaderFrame! finished = false leaderFrame = nil } else { frame = try readFrameFragment(nil) finished = frame.finished } if frame.code == .continue{ throw WebSocketError.protocolError("leader frame cannot be a continue frame") } if !finished { readStateSaved = true readStateFrame = frame readStateFinished = finished throw WebSocketError.needMoreInput } } else { frame = readStateFrame! finished = readStateFinished if !finished { let cf = try readFrameFragment(frame) finished = cf.finished if cf.code != .continue { if !cf.code.isControl { throw WebSocketError.protocolError("only ping frames can be interlaced with fragments") } leaderFrame = frame return cf } if !finished { readStateSaved = true readStateFrame = frame readStateFinished = finished throw WebSocketError.needMoreInput } } } if !frame.utf8.completed { throw WebSocketError.payloadError("incomplete utf8") } readStateSaved = false readStateFrame = nil readStateFinished = false return frame } func closeConn() { rd.remove(from: RunLoop.main, forMode: RunLoop.Mode.default) wr.remove(from: RunLoop.main, forMode: RunLoop.Mode.default) rd.delegate = nil wr.delegate = nil rd.close() wr.close() } func openConn() throws { var req = request! req.setValue("websocket", forHTTPHeaderField: "Upgrade") req.setValue("Upgrade", forHTTPHeaderField: "Connection") if req.value(forHTTPHeaderField: "User-Agent") == nil { req.setValue("SwiftWebSocket", forHTTPHeaderField: "User-Agent") } req.setValue("13", forHTTPHeaderField: "Sec-WebSocket-Version") if req.url == nil || req.url!.host == nil{ throw WebSocketError.invalidAddress } if req.url!.port == nil || req.url!.port! == 80 || req.url!.port! == 443 { req.setValue(req.url!.host!, forHTTPHeaderField: "Host") } else { req.setValue("\(req.url!.host!):\(req.url!.port!)", forHTTPHeaderField: "Host") } let origin = req.value(forHTTPHeaderField: "Origin") if origin == nil || origin! == ""{ req.setValue(req.url!.absoluteString, forHTTPHeaderField: "Origin") } if subProtocols.count > 0 { req.setValue(subProtocols.joined(separator: ","), forHTTPHeaderField: "Sec-WebSocket-Protocol") } if req.url!.scheme != "wss" && req.url!.scheme != "ws" { throw WebSocketError.invalidAddress } if compression.on { var val = "permessage-deflate" if compression.noContextTakeover { val += "; client_no_context_takeover; server_no_context_takeover" } val += "; client_max_window_bits" if compression.maxWindowBits != 0 { val += "; server_max_window_bits=\(compression.maxWindowBits)" } req.setValue(val, forHTTPHeaderField: "Sec-WebSocket-Extensions") } let security: TCPConnSecurity let port : Int if req.url!.scheme == "wss" { port = req.url!.port ?? 443 security = .negoticatedSSL } else { port = req.url!.port ?? 80 security = .none } var path = CFURLCopyPath(req.url! as CFURL) as String if path == "" { path = "/" } if let q = req.url!.query { if q != "" { path += "?" + q } } var reqs = "GET \(path) HTTP/1.1\r\n" for key in req.allHTTPHeaderFields!.keys { if let val = req.value(forHTTPHeaderField: key) { reqs += "\(key): \(val)\r\n" } } var keyb = [UInt32](repeating: 0, count: 4) for i in 0 ..< 4 { keyb[i] = arc4random() } let rkey = Data(bytes: &keyb, count: 16).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) reqs += "Sec-WebSocket-Key: \(rkey)\r\n" reqs += "\r\n" var header = [UInt8]() for b in reqs.utf8 { header += [b] } let addr = ["\(req.url!.host!)", "\(port)"] if addr.count != 2 || Int(addr[1]) == nil { throw WebSocketError.invalidAddress } var (rdo, wro) : (InputStream?, OutputStream?) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? CFStreamCreatePairWithSocketToHost(nil, addr[0] as CFString, UInt32(Int(addr[1])!), &readStream, &writeStream); rdo = readStream!.takeRetainedValue() wro = writeStream!.takeRetainedValue() (rd, wr) = (rdo!, wro!) rd.setProperty(security.level, forKey: Stream.PropertyKey.socketSecurityLevelKey) wr.setProperty(security.level, forKey: Stream.PropertyKey.socketSecurityLevelKey) if services.contains(.VoIP) { rd.setProperty(StreamNetworkServiceTypeValue.voIP.rawValue, forKey: Stream.PropertyKey.networkServiceType) wr.setProperty(StreamNetworkServiceTypeValue.voIP.rawValue, forKey: Stream.PropertyKey.networkServiceType) } if services.contains(.Video) { rd.setProperty(StreamNetworkServiceTypeValue.video.rawValue, forKey: Stream.PropertyKey.networkServiceType) wr.setProperty(StreamNetworkServiceTypeValue.video.rawValue, forKey: Stream.PropertyKey.networkServiceType) } if services.contains(.Background) { rd.setProperty(StreamNetworkServiceTypeValue.background.rawValue, forKey: Stream.PropertyKey.networkServiceType) wr.setProperty(StreamNetworkServiceTypeValue.background.rawValue, forKey: Stream.PropertyKey.networkServiceType) } if services.contains(.Voice) { rd.setProperty(StreamNetworkServiceTypeValue.voice.rawValue, forKey: Stream.PropertyKey.networkServiceType) wr.setProperty(StreamNetworkServiceTypeValue.voice.rawValue, forKey: Stream.PropertyKey.networkServiceType) } if allowSelfSignedSSL { let prop: Dictionary<NSObject,NSObject> = [kCFStreamSSLPeerName: kCFNull, kCFStreamSSLValidatesCertificateChain: NSNumber(value: false)] rd.setProperty(prop, forKey: Stream.PropertyKey(rawValue: kCFStreamPropertySSLSettings as String as String)) wr.setProperty(prop, forKey: Stream.PropertyKey(rawValue: kCFStreamPropertySSLSettings as String as String)) } rd.delegate = delegate wr.delegate = delegate rd.schedule(in: RunLoop.main, forMode: RunLoop.Mode.default) wr.schedule(in: RunLoop.main, forMode: RunLoop.Mode.default) rd.open() wr.open() try write(header, length: header.count) } func write(_ bytes: UnsafePointer<UInt8>, length: Int) throws { if outputBytesStart+outputBytesLength+length > outputBytesSize { var size = outputBytesSize while outputBytesStart+outputBytesLength+length > size { size *= 2 } let ptr = realloc(outputBytes, size) if ptr == nil { throw WebSocketError.memory } outputBytes = ptr?.assumingMemoryBound(to: UInt8.self) outputBytesSize = size } memcpy(outputBytes!+outputBytesStart+outputBytesLength, bytes, length) outputBytesLength += length } func readResponse() throws { let end : [UInt8] = [ 0x0D, 0x0A, 0x0D, 0x0A ] let ptr = memmem(inputBytes!+inputBytesStart, inputBytesLength, end, 4) if ptr == nil { throw WebSocketError.needMoreInput } let buffer = inputBytes!+inputBytesStart let bufferCount = ptr!.assumingMemoryBound(to: UInt8.self)-(inputBytes!+inputBytesStart) let string = NSString(bytesNoCopy: buffer, length: bufferCount, encoding: String.Encoding.utf8.rawValue, freeWhenDone: false) as String? if string == nil { throw WebSocketError.invalidHeader } let header = string! var needsCompression = false var serverMaxWindowBits = 15 let clientMaxWindowBits = 15 var key = "" let trim : (String)->(String) = { (text) in return text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)} let eqval : (String,String)->(String) = { (line, del) in return trim(line.components(separatedBy: del)[1]) } let lines = header.components(separatedBy: "\r\n") for i in 0 ..< lines.count { let line = trim(lines[i]) if i == 0 { if !line.hasPrefix("HTTP/1.1 101"){ throw WebSocketError.invalidResponse(line) } } else if line != "" { var value = "" if line.hasPrefix("\t") || line.hasPrefix(" ") { value = trim(line) } else { key = "" if let r = line.range(of: ":") { key = trim(String(line[..<r.lowerBound])) value = trim(String(line[r.upperBound...])) } } switch key.lowercased() { case "sec-websocket-subprotocol": privateSubProtocol = value case "sec-websocket-extensions": let parts = value.components(separatedBy: ";") for p in parts { let part = trim(p) if part == "permessage-deflate" { needsCompression = true } else if part.hasPrefix("server_max_window_bits="){ if let i = Int(eqval(line, "=")) { serverMaxWindowBits = i } } } default: break } } } if needsCompression { if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 { throw WebSocketError.invalidCompressionOptions("server_max_window_bits") } if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 { throw WebSocketError.invalidCompressionOptions("client_max_window_bits") } inflater = Inflater(windowBits: serverMaxWindowBits) if inflater == nil { throw WebSocketError.invalidCompressionOptions("inflater init") } deflater = Deflater(windowBits: clientMaxWindowBits, memLevel: 8) if deflater == nil { throw WebSocketError.invalidCompressionOptions("deflater init") } } inputBytesLength -= bufferCount+4 if inputBytesLength == 0 { inputBytesStart = 0 } else { inputBytesStart += bufferCount+4 } } class ByteReader { var start : UnsafePointer<UInt8> var end : UnsafePointer<UInt8> var bytes : UnsafePointer<UInt8> init(bytes: UnsafePointer<UInt8>, length: Int){ self.bytes = bytes start = bytes end = bytes+length } func readByte() throws -> UInt8 { if bytes >= end { throw WebSocketError.needMoreInput } let b = bytes.pointee bytes += 1 return b } var length : Int { return end - bytes } var position : Int { get { return bytes - start } set { bytes = start + newValue } } } var fragStateSaved = false var fragStatePosition = 0 var fragStateInflate = false var fragStateLen = 0 var fragStateFin = false var fragStateCode = OpCode.continue var fragStateLeaderCode = OpCode.continue var fragStateUTF8 = UTF8() var fragStatePayload = Payload() var fragStateStatusCode = UInt16(0) var fragStateHeaderLen = 0 var buffer = [UInt8](repeating: 0, count: windowBufferSize) var reusedPayload = Payload() func readFrameFragment(_ leader : Frame?) throws -> Frame { var inflate : Bool var len : Int var fin = false var code : OpCode var leaderCode : OpCode var utf8 : UTF8 var payload : Payload var statusCode : UInt16 var headerLen : Int var leader = leader let reader = ByteReader(bytes: inputBytes!+inputBytesStart, length: inputBytesLength) if fragStateSaved { // load state reader.position += fragStatePosition inflate = fragStateInflate len = fragStateLen fin = fragStateFin code = fragStateCode leaderCode = fragStateLeaderCode utf8 = fragStateUTF8 payload = fragStatePayload statusCode = fragStateStatusCode headerLen = fragStateHeaderLen fragStateSaved = false } else { var b = try reader.readByte() fin = b >> 7 & 0x1 == 0x1 let rsv1 = b >> 6 & 0x1 == 0x1 let rsv2 = b >> 5 & 0x1 == 0x1 let rsv3 = b >> 4 & 0x1 == 0x1 if inflater != nil && (rsv1 || (leader != nil && leader!.inflate)) { inflate = true } else if rsv1 || rsv2 || rsv3 { throw WebSocketError.protocolError("invalid extension") } else { inflate = false } code = OpCode.binary if let c = OpCode(rawValue: (b & 0xF)){ code = c } else { throw WebSocketError.protocolError("invalid opcode") } if !fin && code.isControl { throw WebSocketError.protocolError("unfinished control frame") } b = try reader.readByte() if b >> 7 & 0x1 == 0x1 { throw WebSocketError.protocolError("server sent masked frame") } var len64 = Int64(b & 0x7F) var bcount = 0 if b & 0x7F == 126 { bcount = 2 } else if len64 == 127 { bcount = 8 } if bcount != 0 { if code.isControl { throw WebSocketError.protocolError("invalid payload size for control frame") } len64 = 0 var i = bcount-1 while i >= 0 { b = try reader.readByte() len64 += Int64(b) << Int64(i*8) i -= 1 } } len = Int(len64) if code == .continue { if code.isControl { throw WebSocketError.protocolError("control frame cannot have the 'continue' opcode") } if leader == nil { throw WebSocketError.protocolError("continue frame is missing it's leader") } } if code.isControl { if leader != nil { leader = nil } if inflate { throw WebSocketError.protocolError("control frame cannot be compressed") } } statusCode = 0 if leader != nil { leaderCode = leader!.code utf8 = leader!.utf8 payload = leader!.payload } else { leaderCode = code utf8 = UTF8() payload = reusedPayload payload.count = 0 } if leaderCode == .close { if len == 1 { throw WebSocketError.protocolError("invalid payload size for close frame") } if len >= 2 { let b1 = try reader.readByte() let b2 = try reader.readByte() statusCode = (UInt16(b1) << 8) + UInt16(b2) len -= 2 if statusCode < 1000 || statusCode > 4999 || (statusCode >= 1004 && statusCode <= 1006) || (statusCode >= 1012 && statusCode <= 2999) { throw WebSocketError.protocolError("invalid status code for close frame") } } } headerLen = reader.position } let rlen : Int let rfin : Bool let chopped : Bool if reader.length+reader.position-headerLen < len { rlen = reader.length rfin = false chopped = true } else { rlen = len-reader.position+headerLen rfin = fin chopped = false } let bytes : UnsafeMutablePointer<UInt8> let bytesLen : Int if inflate { (bytes, bytesLen) = try inflater!.inflate(reader.bytes, length: rlen, final: rfin) } else { (bytes, bytesLen) = (UnsafeMutablePointer<UInt8>.init(mutating: reader.bytes), rlen) } reader.bytes += rlen if leaderCode == .text || leaderCode == .close { try utf8.append(bytes, length: bytesLen) } else { payload.append(bytes, length: bytesLen) } if chopped { // save state fragStateHeaderLen = headerLen fragStateStatusCode = statusCode fragStatePayload = payload fragStateUTF8 = utf8 fragStateLeaderCode = leaderCode fragStateCode = code fragStateFin = fin fragStateLen = len fragStateInflate = inflate fragStatePosition = reader.position fragStateSaved = true throw WebSocketError.needMoreInput } inputBytesLength -= reader.position if inputBytesLength == 0 { inputBytesStart = 0 } else { inputBytesStart += reader.position } let f = Frame() (f.code, f.payload, f.utf8, f.statusCode, f.inflate, f.finished) = (code, payload, utf8, statusCode, inflate, fin) return f } var head = [UInt8](repeating: 0, count: 0xFF) func writeFrame(_ f : Frame) throws { if !f.finished{ throw WebSocketError.libraryError("cannot send unfinished frames") } var hlen = 0 let b : UInt8 = 0x80 var deflate = false if deflater != nil { if f.code == .binary || f.code == .text { deflate = true // b |= 0x40 } } head[hlen] = b | f.code.rawValue hlen += 1 var payloadBytes : [UInt8] var payloadLen = 0 if f.utf8.text != "" { payloadBytes = UTF8.bytes(f.utf8.text) } else { payloadBytes = f.payload.array } payloadLen += payloadBytes.count if deflate { } var usingStatusCode = false if f.statusCode != 0 && payloadLen != 0 { payloadLen += 2 usingStatusCode = true } if payloadLen < 126 { head[hlen] = 0x80 | UInt8(payloadLen) hlen += 1 } else if payloadLen <= 0xFFFF { head[hlen] = 0x80 | 126 hlen += 1 var i = 1 while i >= 0 { head[hlen] = UInt8((UInt16(payloadLen) >> UInt16(i*8)) & 0xFF) hlen += 1 i -= 1 } } else { head[hlen] = UInt8((0x1 << 7) + 127) hlen += 1 var i = 7 while i >= 0 { head[hlen] = UInt8((UInt64(payloadLen) >> UInt64(i*8)) & 0xFF) hlen += 1 i -= 1 } } let r = arc4random() var maskBytes : [UInt8] = [UInt8(r >> 0 & 0xFF), UInt8(r >> 8 & 0xFF), UInt8(r >> 16 & 0xFF), UInt8(r >> 24 & 0xFF)] for i in 0 ..< 4 { head[hlen] = maskBytes[i] hlen += 1 } if payloadLen > 0 { if usingStatusCode { var sc = [UInt8(f.statusCode >> 8 & 0xFF), UInt8(f.statusCode >> 0 & 0xFF)] for i in 0 ..< 2 { sc[i] ^= maskBytes[i % 4] } head[hlen] = sc[0] hlen += 1 head[hlen] = sc[1] hlen += 1 for i in 2 ..< payloadLen { payloadBytes[i-2] ^= maskBytes[i % 4] } } else { for i in 0 ..< payloadLen { payloadBytes[i] ^= maskBytes[i % 4] } } } try write(head, length: hlen) try write(payloadBytes, length: payloadBytes.count) } func close(_ code : Int = 1000, reason : String = "Normal Closure") { let f = Frame() f.code = .close f.statusCode = UInt16(truncatingIfNeeded: code) f.utf8.text = reason sendFrame(f) } func sendFrame(_ f : Frame) { lock() frames += [f] unlock() manager.signal() } func send(_ message : Any) { let f = Frame() if let message = message as? String { f.code = .text f.utf8.text = message } else if let message = message as? [UInt8] { f.code = .binary f.payload.array = message } else if let message = message as? UnsafeBufferPointer<UInt8> { f.code = .binary f.payload.append(message.baseAddress!, length: message.count) } else if let message = message as? Data { f.code = .binary f.payload.nsdata = message } else { f.code = .text f.utf8.text = "\(message)" } sendFrame(f) } func ping() { let f = Frame() f.code = .ping sendFrame(f) } func ping(_ message : Any){ let f = Frame() f.code = .ping if let message = message as? String { f.payload.array = UTF8.bytes(message) } else if let message = message as? [UInt8] { f.payload.array = message } else if let message = message as? UnsafeBufferPointer<UInt8> { f.payload.append(message.baseAddress!, length: message.count) } else if let message = message as? Data { f.payload.nsdata = message } else { f.utf8.text = "\(message)" } sendFrame(f) } } private func ==(lhs: InnerWebSocket, rhs: InnerWebSocket) -> Bool { return lhs.id == rhs.id } private enum TCPConnSecurity { case none case negoticatedSSL var level: String { switch self { case .none: return StreamSocketSecurityLevel.none.rawValue case .negoticatedSSL: return StreamSocketSecurityLevel.negotiatedSSL.rawValue } } } // Manager class is used to minimize the number of dispatches and cycle through network events // using fewers threads. Helps tremendously with lowing system resources when many conncurrent // sockets are opened. private class Manager { var queue = DispatchQueue(label: "SwiftWebSocketInstance", attributes: []) var once = Int() var mutex = pthread_mutex_t() var cond = pthread_cond_t() var websockets = Set<InnerWebSocket>() var _nextId = 0 init(){ pthread_mutex_init(&mutex, nil) pthread_cond_init(&cond, nil) DispatchQueue(label: "SwiftWebSocket", attributes: []).async { var wss : [InnerWebSocket] = [] while true { var wait = true wss.removeAll() pthread_mutex_lock(&self.mutex) for ws in self.websockets { wss.append(ws) } for ws in wss { self.checkForConnectionTimeout(ws) if ws.dirty { pthread_mutex_unlock(&self.mutex) ws.step() pthread_mutex_lock(&self.mutex) wait = false } } if wait { _ = self.wait(250) } pthread_mutex_unlock(&self.mutex) } } } func checkForConnectionTimeout(_ ws : InnerWebSocket) { if ws.rd != nil && ws.wr != nil && (ws.rd.streamStatus == .opening || ws.wr.streamStatus == .opening) { let age = CFAbsoluteTimeGetCurrent() - ws.createdAt if age >= timeoutDuration { ws.connectionTimeout = true } } } func wait(_ timeInMs : Int) -> Int32 { var ts = timespec() var tv = timeval() gettimeofday(&tv, nil) ts.tv_sec = time(nil) + timeInMs / 1000; let v1 = Int(tv.tv_usec * 1000) let v2 = Int(1000 * 1000 * Int(timeInMs % 1000)) ts.tv_nsec = v1 + v2; ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000); ts.tv_nsec %= (1000 * 1000 * 1000); return pthread_cond_timedwait(&self.cond, &self.mutex, &ts) } func signal(){ pthread_mutex_lock(&mutex) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func add(_ websocket: InnerWebSocket) { pthread_mutex_lock(&mutex) websockets.insert(websocket) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func remove(_ websocket: InnerWebSocket) { pthread_mutex_lock(&mutex) websockets.remove(websocket) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func nextId() -> Int { pthread_mutex_lock(&mutex) defer { pthread_mutex_unlock(&mutex) } _nextId += 1 return _nextId } } private let manager = Manager() /// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455. @objcMembers open class WebSocket: NSObject { fileprivate var ws: InnerWebSocket fileprivate var id = manager.nextId() fileprivate var opened: Bool open override var hash: Int { return id } open override func isEqual(_ other: Any?) -> Bool { guard let other = other as? WebSocket else { return false } return self.id == other.id } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public convenience init(_ url: String){ self.init(request: URLRequest(url: URL(string: url)!), subProtocols: []) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public convenience init(url: URL){ self.init(request: URLRequest(url: url), subProtocols: []) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols. public convenience init(_ url: String, subProtocols : [String]){ self.init(request: URLRequest(url: URL(string: url)!), subProtocols: subProtocols) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol. public convenience init(_ url: String, subProtocol : String){ self.init(request: URLRequest(url: URL(string: url)!), subProtocols: [subProtocol]) } /// Create a WebSocket connection from an NSURLRequest; Also include a list of protocols. public init(request: URLRequest, subProtocols : [String] = []){ let hasURL = request.url != nil opened = hasURL ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: !hasURL) super.init() // weak/strong pattern from: // http://stackoverflow.com/a/17105368/424124 // https://dhoerl.wordpress.com/2013/04/23/i-finally-figured-out-weakself-and-strongself/ ws.eclose = { [weak self] in if let strongSelf = self { strongSelf.opened = false } } } /// Create a WebSocket object with a deferred connection; the connection is not opened until the .open() method is called. public convenience override init(){ var request = URLRequest(url: URL(string: "http://apple.com")!) request.url = nil self.init(request: request, subProtocols: []) } /// The URL as resolved by the constructor. This is always an absolute URL. Read only. open var url : String{ return ws.url } /// A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object. open var subProtocol : String{ return ws.subProtocol } /// The compression options of the WebSocket. open var compression : WebSocketCompression{ get { return ws.compression } set { ws.compression = newValue } } /// Allow for Self-Signed SSL Certificates. Default is false. open var allowSelfSignedSSL : Bool{ get { return ws.allowSelfSignedSSL } set { ws.allowSelfSignedSSL = newValue } } /// The services of the WebSocket. open var services : WebSocketService{ get { return ws.services } set { ws.services = newValue } } /// The events of the WebSocket. open var event : WebSocketEvents{ get { return ws.event } set { ws.event = newValue } } /// The queue for firing off events. default is main_queue open var eventQueue : DispatchQueue?{ get { return ws.eventQueue } set { ws.eventQueue = newValue } } /// A WebSocketBinaryType value indicating the type of binary data being transmitted by the connection. Default is .UInt8Array. open var binaryType : WebSocketBinaryType{ get { return ws.binaryType } set { ws.binaryType = newValue } } /// The current state of the connection; this is one of the WebSocketReadyState constants. Read only. open var readyState : WebSocketReadyState{ return ws.readyState } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. open func open(_ url: String){ open(request: URLRequest(url: URL(string: url)!), subProtocols: []) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. open func open(nsurl url: URL){ open(request: URLRequest(url: url), subProtocols: []) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols. open func open(_ url: String, subProtocols : [String]){ open(request: URLRequest(url: URL(string: url)!), subProtocols: subProtocols) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol. open func open(_ url: String, subProtocol : String){ open(request: URLRequest(url: URL(string: url)!), subProtocols: [subProtocol]) } /// Opens a deferred or closed WebSocket connection from an NSURLRequest; Also include a list of protocols. open func open(request: URLRequest, subProtocols : [String] = []){ if opened{ return } opened = true ws = ws.copyOpen(request, subProtocols: subProtocols) } /// Opens a closed WebSocket connection from an NSURLRequest; Uses the same request and protocols as previously closed WebSocket open func open(){ open(request: ws.request, subProtocols: ws.subProtocols) } /** Closes the WebSocket connection or connection attempt, if any. If the connection is already closed or in the state of closing, this method does nothing. :param: code An integer indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal closure) is assumed. :param: reason A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters). */ open func close(_ code : Int = 1000, reason : String = "Normal Closure"){ if !opened{ return } opened = false ws.close(code, reason: reason) } /** Transmits message to the server over the WebSocket connection. :param: message The message to be sent to the server. */ open func send(_ message : Any){ if !opened{ return } ws.send(message) } /** Transmits a ping to the server over the WebSocket connection. :param: optional message The data to be sent to the server. */ open func ping(_ message : Any){ if !opened{ return } ws.ping(message) } /** Transmits a ping to the server over the WebSocket connection. */ open func ping(){ if !opened{ return } ws.ping() } } public func ==(lhs: WebSocket, rhs: WebSocket) -> Bool { return lhs.id == rhs.id } extension WebSocket { /// The events of the WebSocket using a delegate. @objc public var delegate : WebSocketDelegate? { get { return ws.eventDelegate } set { ws.eventDelegate = newValue } } /** Transmits message to the server over the WebSocket connection. :param: text The message (string) to be sent to the server. */ @objc public func send(text: String){ send(text) } /** Transmits message to the server over the WebSocket connection. :param: data The message (binary) to be sent to the server. */ @objc public func send(data: Data){ send(data) } }
37.465293
225
0.556176
72a2b79f20f57b480dcf648d28656ab01f7ef9d4
3,466
import RxSwift import RxRelay import MarketKit import CurrencyKit class MarketGlobalDefiMetricService: IMarketSingleSortHeaderService { typealias Item = DefiItem private let marketKit: MarketKit.Kit private let currencyKit: CurrencyKit.Kit private let disposeBag = DisposeBag() private var syncDisposeBag = DisposeBag() private let stateRelay = PublishRelay<MarketListServiceState<DefiItem>>() private(set) var state: MarketListServiceState<DefiItem> = .loading { didSet { stateRelay.accept(state) } } var sortDirectionAscending: Bool = false { didSet { syncIfPossible() } } let initialMarketField: MarketModule.MarketField = .marketCap init(marketKit: MarketKit.Kit, currencyKit: CurrencyKit.Kit) { self.marketKit = marketKit self.currencyKit = currencyKit syncMarketInfos() } private func syncMarketInfos() { syncDisposeBag = DisposeBag() if case .failed = state { state = .loading } marketKit.marketInfosSingle(top: MarketModule.MarketTop.top250.rawValue, currencyCode: currency.code, defi: true) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated)) .subscribe(onSuccess: { [weak self] marketInfos in let rankedItems = marketInfos.enumerated().map { index, info in Item(marketInfo: info, tvlRank: index + 1) } self?.sync(items: rankedItems) }, onError: { [weak self] error in self?.state = .failed(error: error) }) .disposed(by: syncDisposeBag) } private func sync(items: [Item], reorder: Bool = false) { state = .loaded(items: sorted(items: items), softUpdate: false, reorder: reorder) } private func syncIfPossible() { guard case .loaded(let items, _, _) = state else { return } sync(items: items, reorder: true) } func sorted(items: [Item]) -> [Item] { items.sorted { lhsItem, rhsItem in if sortDirectionAscending { return lhsItem.tvlRank > rhsItem.tvlRank } else { return lhsItem.tvlRank < rhsItem.tvlRank } } } } extension MarketGlobalDefiMetricService: IMarketListService { var stateObservable: Observable<MarketListServiceState<DefiItem>> { stateRelay.asObservable() } func refresh() { syncMarketInfos() } } extension MarketGlobalDefiMetricService: IMarketListCoinUidService { func coinUid(index: Int) -> String? { guard case .loaded(let items, _, _) = state, index < items.count else { return nil } return items[index].marketInfo.fullCoin.coin.uid } } extension MarketGlobalDefiMetricService: IMarketListDecoratorService { var currency: Currency { currencyKit.baseCurrency } var priceChangeType: MarketModule.PriceChangeType { .day } func onUpdate(marketField: MarketModule.MarketField) { if case .loaded(let items, _, _) = state { stateRelay.accept(.loaded(items: items, softUpdate: false, reorder: false)) } } } extension MarketGlobalDefiMetricService { struct DefiItem { let marketInfo: MarketInfo let tvlRank: Int } }
26.868217
121
0.619158
e62cedc697a9f84fc4a90ee570c42ecb4127ab67
3,875
//// //// TopicViewController.swift //// task //// //// Created by 柏超曾 on 2017/9/15. //// Copyright © 2017年 柏超曾. All rights reserved. //// // // //// 记录点击的顶部标题 ////var topicTitle: TopicTitle? // //import UIKit //import Foundation //class TopicViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{ // // private lazy var viewModels : [Tasks] = [Tasks]() // var topicTitle: TopicTitle? // var tableView : UITableView? // // fileprivate var arrayy = [TopicTitle]() // // // override func viewWillAppear(_ animated: Bool) { // super.viewWillAppear(animated) // // 设置导航栏颜色 //// navigationController?.navigationBar.theme_barTintColor = "colors.homeNavBarTintColor" // } // // override func viewDidLoad() { // super.viewDidLoad() // // print("123") // // let first = UserDefaults.standard.object(forKey: "firstOpen") // // if (first != nil) { // tableView = UITableView(frame: CGRect(x: 0 , y: 64, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height ), style: UITableViewStyle.plain) // tableView?.dataSource = self // tableView?.delegate = self // self.view.addSubview(tableView!) // self.tableView?.register(UITableViewCell().classForCoder, forCellReuseIdentifier: "cell") // /// 设置上拉和下拉刷新 // setRefreshh() // view.backgroundColor = UIColor.globalBackgroundColor() // automaticallyAdjustsScrollViewInsets = false // }else{ // // UserDefaults.standard.set("first", forKey: "firstOpen") // // } // // //// tableView = UITableView(frame: CGRect(x: 0 , y: 64, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height ), style: UITableViewStyle.plain) //// tableView?.dataSource = self //// tableView?.delegate = self //// self.view.addSubview(tableView!) //// self.tableView?.register(UITableViewCell().classForCoder, forCellReuseIdentifier: "cell") //// /// 设置上拉和下拉刷新 //// setRefreshh() //// view.backgroundColor = UIColor.globalBackgroundColor() //// automaticallyAdjustsScrollViewInsets = false // // } // // // func numberOfSectionsInTableView(tableView: UITableView) -> Int { // return 1 // } // //每一块有多少行 // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return arrayy.count // } // // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // cell.textLabel!.text = arrayy[indexPath.row].name // return cell // } // // func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // return 200; // } // // // //} // // //extension TopicViewController { // // /// 设置上拉和下拉刷新 // @objc fileprivate func setRefreshh() { // // // let header = RefreshHeder(refreshingBlock: { [weak self] in // // 获取标题数据 // NetworkTool.loadHomeTitlesData(fromViewController: String(describing: TasksViewController.self)) { (topTitles, homeTopicVCs) in // // // self!.tableView?.mj_header.endRefreshing() // self!.arrayy = topTitles // self!.tableView?.reloadData() // } // }) // // header?.isAutomaticallyChangeAlpha = true // header?.lastUpdatedTimeLabel.isHidden = true // tableView?.mj_header = header // tableView?.mj_header.beginRefreshing() // tableView?.mj_header = header // // } //} //
33.405172
171
0.585806
dd806b959c89a6f2a0f3778f91f5d2a60021d63f
262
// // Constants.swift // NestedCloudKitCodable // // Created by Guilherme Girotto on 22/11/18. // Copyright © 2018 Guilherme Girotto. All rights reserved. // import Foundation internal struct Constants { static let locationSeparator: Character = ";" }
18.714286
60
0.717557
3a4184c819030500cc65ce7b909d0f3202918bd8
197
// // MessageBird.swift // stts // import Foundation class MessageBird: StatusPageService { let url = URL(string: "https://status.messagebird.com")! let statusPageID = "xf8120tyqx8n" }
16.416667
60
0.690355
750e8b0d1f6e492b6a78237fe16f8729fde08f91
8,171
// // AbundanceTester.swift // Numbers // // Created by Stephan Jancar on 11.12.17. // Copyright © 2017 Stephan Jancar. All rights reserved. // import Foundation import BigInt import PrimeFactors public class TaxiCabTester : SumOfTwoCubesTester { override public func property() -> String { return "Taxicab" } override public func isSpecial(n: BigUInt,cancel : CalcCancelProt?) -> Bool? { guard let iscube = CubeTester().isSpecial(n: n, cancel: cancel) else { return nil } if iscube { return false } guard let issum = SumOfTwoCubesTester().isSpecial(n: n,cancel: cancel) else { return nil } if !issum { return false } return OEIS.shared.ContainsNumber(key: self.property(), n: n) } override public func getLatex(n: BigUInt) -> String? { guard let special = isSpecial(n: n,cancel: nil) else { return nil } if !special { return nil } if let (a,b,c,d) = Express2(n: n) { let (stra,strb,strc,strd) = (String(a),String(b),String(c),String(d)) let latex = String(n) + "=" + stra + "^3 + " + strb + "^3" + " = " + strc + "^3 + " + strd return latex } return nil } public func Express2(n: BigUInt) -> (BigUInt,BigUInt,BigUInt,BigUInt)? { var (n0,cube) = (n,BigUInt(1)) if n > 1000000000 { (n0,cube) = RemoveCubes(n: n) } guard let (c,d) = super.Express(n: n0) else { return nil } var a = d - 1 while a > c { let a3 = a * a * a let b3 = n0 - a3 let r3 = b3.iroot3() if r3 * r3 * r3 == b3 { return (a:a*cube, b: r3*cube,c:c*cube,d:d*cube) } a = a - 1 } return nil } } public class SumOfTwoCubesTester : NumTester { public init() {} public func getLatex(n: BigUInt) -> String? { guard let special = isSpecial(n: n,cancel: TimeOut()) else { return nil } if !special { return nil } if let (a,b) = Express(n: n) { let stra = String(a) let strb = String(b) let latex = String(n) + "=" + stra + "^3 + " + strb + "^3" return latex } return nil } public func property() -> String { return "sum of two cubes" } private let r63 = [3,4,5,6,10,11,12,13,14,15,17,18,21, 22, 23, 24, 25, 30, 31, 32, 33, 38, 39, 40, 41, 42, 45, 46, 48, 49, 50, 51, 52, 53, 57, 58, 59, 60] public func isSpecial(n: BigUInt,cancel : CalcCancelProt?) -> Bool? { if n <= 1 { return false } if n == 2 { return true } do { let n7 = Int(n % 7) if n7 == 3 || n7 == 4 { return false } } do { let n9 = Int(n % 9) if n9 >= 3 && n9<=6 { return false } } do { let n63 = Int(n%63) if r63.contains(n63) { return false } } var (n0,_) = (n,BigUInt(1)) if n > 1000000000 { (n0,_) = RemoveCubes(n: n) } let r3 = n0.iroot3() let r4 = (n0*4).iroot3() let divisors = FactorCache.shared.Divisors(p: n0,cancel: cancel) if cancel?.IsCancelled() ?? false { return nil } for m in divisors.sorted() { if m < r3 { continue } if m > r4 { return false } if m*m < n0/m { continue } let temp = (m*m-n0/m) * 4 if temp % 3 != 0 { continue } if m*m < temp / 3 { return false } let temp2 = m*m - temp / 3 let rtemp2 = temp2.squareRoot() if rtemp2 * rtemp2 == temp2 { return true } } return false } internal func RemoveCubes(n:BigUInt) -> (n:BigUInt,cube: BigUInt) { if n.isPrime() { return (n:n,cube:1) } var cube : BigUInt = 1 let factors = FactorsWithPot(n: n, cancel: TimeOut()) for f in factors.factors { if f.e >= 3 { cube = cube * f.f.power(f.e - f.e % 3) } } return (n: n/cube, cube:cube.iroot3()) } public func Express(n: BigUInt) -> (a: BigUInt, b:BigUInt)? { guard let special = isSpecial(n: n, cancel: nil) else { return nil } if !special { return nil } //let (n0,cube) = RemoveCubes(n: n) var (n0,cube) = (n,BigUInt(1)) if n > 1000000000 { (n0,cube) = RemoveCubes(n: n) } var a : BigUInt = 0 while true { let a3 = a * a * a if a3 > n0 { return nil } if a3 == n0 { return (a: a*cube, b: 0) } let b3 = n0 - a3 let r3 = b3.iroot3() if r3 * r3 * r3 == b3 { return (a:a*cube, b: r3*cube) } a = a + 1 } } } public class EulerCounterexampleTester : NumTester { let counterex = 144 public init() {} public func isSpecial(n: BigUInt, cancel : CalcCancelProt?) -> Bool? { if n < BigUInt(counterex) { return false } if n % BigUInt(counterex) == 0 { return true } return false } public func property() -> String { return "Sum of 4 fifth power" } //Name of tested property public func invers() -> NumTester? { return nil } public func subtester() -> [NumTester]? { return nil } public func issubTester() -> Bool { return false } public func getLatex(n: BigUInt) -> String? { let special = isSpecial(n: n, cancel: TimeOut()) ?? false if !special { return nil } let faktor = n / BigUInt(counterex) let a = 27 * faktor let b = 84 * faktor let c = 110 * faktor let d = 133 * faktor let sum = (a^5)+(b^5)+(c^5)+(d^5) let n5 = n^5 let latex = "\(String(n))^5 = \(a)^5 + \(b)^5 +\(c)^5 +\(d)^5 = \(sum)" return latex } } public class FermatNearMissTester : NumTester { let x = [9, 64, 73, 135, 334, 244, 368, 1033, 1010, 577, 3097, 3753, 1126, 4083, 5856, 3987, 1945, 11161, 13294, 3088, 10876, 16617, 4609, 27238, 5700, 27784, 11767, 26914, 38305, 6562, 49193, 27835, 35131, 7364, 65601, 50313, 9001, 11980, 39892, 20848] //A050792 let z = [ 12, 103, 150, 249, 495, 738, 1544, 1852, 1988, 2316, 4184, 5262, 5640, 8657, 9791, 9953, 11682, 14258, 21279, 21630, 31615, 36620, 36888, 38599, 38823, 40362, 41485, 47584, 57978, 59076, 63086, 73967, 79273, 83711, 83802, 86166, 90030] //A050791 public init() {} public func isSpecial(n: BigUInt, cancel : CalcCancelProt?) -> Bool? { if !n.isInt64() { return nil } if Int(n)>z.max()! { return nil } if z.contains(Int(n)) { return true } return false } public func property() -> String { return "Fermat near miss" } //Name of tested property public func invers() -> NumTester? { return nil } public func subtester() -> [NumTester]? { return nil } public func issubTester() -> Bool { return false } public func Miss(n: BigUInt) -> (a: BigUInt,b: BigUInt)? { for (j,zval) in z.enumerated() { if zval == Int(n) { let xval = BigUInt(x[j]) let x3 = xval*xval*xval let n3 = n*n*n let y3 = n3 - x3 + 1 let yval = y3.iroot3() return (xval,yval) } } return nil } public func getLatex(n: BigUInt) -> String? { let special = isSpecial(n: n, cancel: TimeOut()) ?? false if !special { return nil } guard let (xval,yval) = Miss(n: n) else { return nil } // let x3 = xval*xval*xval // let y3 = yval*yval*yval let latex = "\(String(n))^3+1 = \(String(xval))^3 + \(String(yval))^3" return latex } }
31.793774
267
0.491005
f4aecb2b265132646099911c4e6e74aed74f8d60
2,166
// // CharacterViewModel.swift // MarvelApp // // Created by Homero Oliveira on 06/12/18. // Copyright © 2018 Homero Oliveira. All rights reserved. // import Foundation final class CharacterDetailViewModel { private let character: Character private let paginator: Paginator<Comic> var count: Int { return paginator.results.count } var offset: Int { return paginator.offset } var hasMore: Bool { return paginator.hasMore } var isLoading: Bool { return paginator.isLoading } var name: String { return character.name } var description: String { if character.description.isEmpty { return "Description not available." } else { return character.description } } var thumbnail: Image { return character.thumbnail } let marvelApiProvider: MarvelApiProviderType subscript(_ index: Int) -> ComicViewModel { return ComicViewModel(comic: paginator.results[index]) } init(character: Character, marvelApiProvider: MarvelApiProviderType, paginator: Paginator<Comic> = Paginator()) { self.character = character self.marvelApiProvider = marvelApiProvider self.paginator = paginator } func fetchComics(completion: @escaping (ChangeState) -> Void) { guard !isLoading && hasMore else { completion(.inserted([])) return } self.paginator.isLoading = true let endpoint = MarvelApi.comics(characterId: character.id, offset: offset) marvelApiProvider.request(for: endpoint) { [weak self] (result: Result<DataWrapper<Comic>>) in guard let self = self else { return } switch result { case .success(let dataWrapper): let changeState = self.paginator.paginate(dataWrapper: dataWrapper) completion(changeState) case .failure(let error): completion(.error(LoadingError(message: error.localizedDescription))) } } } }
27.417722
102
0.606648
fe4f450440db523384273bd0332e44735e565e44
1,337
// // PopoverPresentationController.swift // ljwb // // Created by comma on 16/6/1. // Copyright © 2016年 lj. All rights reserved. // import UIKit class PopoverPresentationController: UIPresentationController { // 负责转场动画的对象 override init(presentedViewController: UIViewController, presentingViewController: UIViewController) { super.init(presentedViewController: presentedViewController, presentingViewController: presentedViewController) print(presentedViewController) } // 即将布局转场子视图的调用 override func containerViewWillLayoutSubviews() { // presentedView()被展现的视图 containerView 容器视图 presentedView()?.frame = CGRectMake(100, 59, 200, 200) containerView?.insertSubview(coverView, atIndex: 0) } private lazy var coverView: UIView = { let view = UIView() view.backgroundColor = UIColor(white: 0.0, alpha: 0.2) view.frame = UIScreen.mainScreen().bounds let tap = UITapGestureRecognizer(target: self, action: "close") view.addGestureRecognizer(tap) return view }() func close(){ presentedViewController.dismissViewControllerAnimated(true, completion: nil) } }
24.309091
119
0.629768
fed6b14ada555c1b62594c8085d11662b1981254
869
// // TBGradientButton.swift // ToolBox // // Created by Berthelot Nicolas on 13/10/2017. // import Foundation final class TBGradientButton: UIButton { @IBInspectable public var startColor: UIColor = UIColor.clear { didSet { updateColor() } } @IBInspectable public var endColor: UIColor = UIColor.clear { didSet { updateColor() } } var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } @IBInspectable public var isVertical: Bool = true public override class var layerClass : AnyClass { return CAGradientLayer.self } fileprivate func updateColor() { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] if isVertical == false { gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) } } }
20.209302
65
0.66168
2669751c50dc1f8513640df5341c60578c1be83b
392
// // CKRequest.swift // OpenCloudKit // // Created by Benjamin Johnson on 19/1/17. // // import Foundation struct CKRequestOptions { var serverType: String? init(serverType: String) { self.serverType = serverType } init() {} } class CKRequest { static func options() -> CKRequestOptions { return CKRequestOptions() } }
13.066667
47
0.589286
2ff21460f7873873afb412177d800a0d260b9307
575
// // PhotoCollectionViewCell.swift // PhotoLibrary // // Created by Németh Bendegúz on 2017. 10. 23.. // Copyright © 2017. Németh Bendegúz. All rights reserved. // import UIKit class PhotoCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! var representedAssetIdentifier: String! var thumbnailImage: UIImage! { didSet { imageView.image = thumbnailImage } } override func prepareForReuse() { super.prepareForReuse() thumbnailImage = nil } }
19.166667
59
0.64
bb053d42ef6f613e19bf50c5be6049e71304f930
1,045
// // GhostTests.swift // GhostTests // // Created by Ray Bradley on 4/24/18. // Copyright © 2018 Analemma Heavy Industries. All rights reserved. // import XCTest @testable import Ghost class GhostRESTClientTests: 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 testFullURL() { let client = GhostRESTClient() client.baseURL = "https://foo" let path = "/a/b/c" let fullPath = client.fullURL(path: path) XCTAssertEqual(fullPath, "https://foo/ghost/api/v0.1/a/b/c") } func testFullURLWithoutLeadingSlash() { let client = GhostRESTClient() client.baseURL = "https://foo" let path = "a/b/c" let fullPath = client.fullURL(path: path) XCTAssertEqual(fullPath, "https://foo/ghost/api/v0.1/a/b/c") } }
26.125
107
0.670813
bb3ae717825412b9adeed7bb5ddda32ea74185ec
1,761
// // AnotherFakeAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation open class AnotherFakeAPI { /** To test special tags - parameter body: (body) client model - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** To test special tags - PATCH /another-fake/dummy - To test special tags and operation ID starting with number - parameter body: (body) client model - returns: RequestBuilder<Client> */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder<Client> { let path = "/another-fake/dummy" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<Client>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } }
34.529412
195
0.677456
fb745fd93150a20cb70541761443514c2d6d80aa
145
protocol EpisodeModelDelegate { var name: String { get set } var episodeNumber: String { get set } var airDate: String { get set } }
24.166667
41
0.668966
ed9644d4d3586c7540f8bef40da22887061298ac
1,193
import Foundation // MARK: - FeedbackLoopSystem public class FeedbackLoopSystem<TState: Equatable, TEvent> { public typealias Feedback = (_ newState: TState, _ oldState: TState, _ action: @escaping (TEvent) -> Void) -> Void private var queue = DispatchQueue(label: "FeedbackLoopSystem_queue") private var state: TState private let reducer: (TState, TEvent) -> TState private let feedbacks: [Feedback] init(initialState: TState, reducer: @escaping (TState, TEvent) -> TState, feedbacks: [Feedback]) { self.state = initialState self.reducer = reducer self.feedbacks = feedbacks } public func acceptEvent(_ event: TEvent) { queue.async { [weak self] in guard let __self = self else { return } let oldState = __self.state let newState = __self.reducer(oldState, event) guard newState != oldState else { return } __self.state = newState __self.feedbacks.forEach { $0(newState, oldState, { [weak self] (event) in self?.acceptEvent(event) }) } } } }
32.243243
118
0.592624
d9e7ba91fb9acbc53bbc6d09ba75a6de2582acda
2,101
// // AccountCredentialsTest.swift // AccountTests // // Created by Maurice Parker on 5/4/19. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import XCTest import RSWeb @testable import Account class AccountCredentialsTest: XCTestCase { private var account: Account! override func setUp() { account = TestAccountManager.shared.createAccount(type: .feedbin, transport: TestTransport()) } override func tearDown() { TestAccountManager.shared.deleteAccount(account) } func testCreateRetrieveDelete() { // Make sure any left over from failed tests are gone do { try account.removeBasicCredentials() } catch { XCTFail(error.localizedDescription) } var credentials: Credentials? = Credentials.basic(username: "maurice", password: "hardpasswd") // Store the credentials do { try account.storeCredentials(credentials!) } catch { XCTFail(error.localizedDescription) } // Retrieve them credentials = nil do { credentials = try account.retrieveBasicCredentials() } catch { XCTFail(error.localizedDescription) } switch credentials! { case .basic(let username, let password): XCTAssertEqual("maurice", username) XCTAssertEqual("hardpasswd", password) } // Update them credentials = Credentials.basic(username: "maurice", password: "easypasswd") do { try account.storeCredentials(credentials!) } catch { XCTFail(error.localizedDescription) } // Retrieve them again credentials = nil do { credentials = try account.retrieveBasicCredentials() } catch { XCTFail(error.localizedDescription) } switch credentials! { case .basic(let username, let password): XCTAssertEqual("maurice", username) XCTAssertEqual("easypasswd", password) } // Delete them do { try account.removeBasicCredentials() } catch { XCTFail(error.localizedDescription) } // Make sure they are gone do { try credentials = account.retrieveBasicCredentials() } catch { XCTFail(error.localizedDescription) } XCTAssertNil(credentials) } }
21.659794
96
0.70633
0ab6189b360bce3fbc198308012815445b3b8284
590
// Created by Juan David Cruz Serrano on 6/27/19. Copyright © Juan David Cruz Serrano & Vhista Inc. All rights reserved. import Foundation struct FeatureNames { static let contextual = NSLocalizedString("Image_Recognition", comment: "") static let text = NSLocalizedString("Text_Recognition", comment: "") } struct Feature { var featureName: String var imageName: String } extension Feature: Equatable { static func == (lhs: Feature, rhs: Feature) -> Bool { return lhs.featureName == rhs.featureName && lhs.imageName == rhs.imageName } }
28.095238
121
0.688136
edb5659592ea0b97f4a01af4c09e91568c978051
710
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import RealmSwift // ======================================================= public class GithubNotification: Object { public dynamic var notificationID = "" public dynamic var unread = false public dynamic var reason = "" public dynamic var title = "" public dynamic var subjectURL = "" public dynamic var latestCommentURL = "" public dynamic var type = "" public dynamic var repository: GithubRepo? public override class func primaryKey() -> String { return "notificationID" } }
26.296296
58
0.509859
08fb6ef7be7c56a562a5602b508d51411bdb6bc3
1,127
/** * Copyright 2019, Momentum Ideas, Co. All rights reserved. * Source and object computer code contained herein is the private intellectual * property of Momentum Ideas Co., a Delaware Corporation. Use of this * code in source form requires permission in writing before use or the * assembly, distribution, or publishing of derivative works, for commercial * purposes or any other purpose, from a duly authorized officer of Momentum * Ideas Co. * * 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 /// Describes an object that can be used as a `MenuSection` or a `ProductKind` interchangeably. public protocol SectionConvertible { /// Supply a `ProductKind` for this section-convertible object. var type: ProductKind? { get } /// Supply a `MenuSection` for this section-convertible object. var section: MenuSection? { get } }
40.25
95
0.770186
11b0ab236cb9bfdbab726ffe069790da57a67200
2,830
// // AppCoordinator+Analytics.swift // DropBit // // Created by Ben Winters on 5/15/19. // Copyright © 2019 Coin Ninja, LLC. All rights reserved. // import Foundation extension AppCoordinator { func trackAnalytics() { trackGenericPlatform() trackEventForFirstTimeOpeningAppIfApplicable() trackIfUserHasWallet() trackIfUserHasWordsBackedUp() trackIfDropBitMeIsEnabled() } func trackGenericPlatform() { analyticsManager.track(property: MixpanelProperty(key: .platform, value: "iOS")) } func trackEventForFirstTimeOpeningAppIfApplicable() { if persistenceManager.brokers.activity.isFirstTimeOpeningApp { analyticsManager.track(event: .firstOpen, with: nil) persistenceManager.brokers.activity.isFirstTimeOpeningApp = false } } func trackIfUserHasWallet() { if walletManager == nil { analyticsManager.track(property: MixpanelProperty(key: .hasWallet, value: false)) } else { analyticsManager.track(property: MixpanelProperty(key: .hasWallet, value: true)) } } func trackIfUserHasWordsBackedUp() { if walletManager == nil || !wordsBackedUp { analyticsManager.track(property: MixpanelProperty(key: .wordsBackedUp, value: false)) } else { analyticsManager.track(property: MixpanelProperty(key: .wordsBackedUp, value: true)) } } func trackIfDropBitMeIsEnabled() { let bgContext = self.persistenceManager.createBackgroundContext() bgContext.perform { let isEnabled = self.persistenceManager.brokers.user.getUserPublicURLInfo(in: bgContext)?.isEnabled ?? false self.analyticsManager.track(property: MixpanelProperty(key: .isDropBitMeEnabled, value: isEnabled)) } } func trackIfUserHasABalance() { let bgContext = persistenceManager.createBackgroundContext() guard let wmgr = walletManager else { self.analyticsManager.track(property: MixpanelProperty(key: .hasBTCBalance, value: false)) return } bgContext.perform { let bal = wmgr.spendableBalance(in: bgContext) let balance = bal.onChain let lightningBalance = bal.lightning let balanceIsPositive = balance > 0 let lightningBalanceIsPositive = lightningBalance > 0 DispatchQueue.main.async { let btcBalanceProperty = MixpanelProperty(key: .hasBTCBalance, value: balanceIsPositive) self.analyticsManager.track(property: btcBalanceProperty) let lightningBalanceProperty = MixpanelProperty(key: .hasLightningBalance, value: lightningBalanceIsPositive) self.analyticsManager.track(property: lightningBalanceProperty) let rangeProperty = MixpanelProperty(key: .relativeWalletRange, value: AnalyticsRelativeWalletRange(satoshis: balance).rawValue) self.analyticsManager.track(property: rangeProperty) } } } }
33.294118
136
0.733216
64e2acc8a7a0d14772dae66d4456fa4095239255
233
import RxSwift import RxCocoa class WalletConnectScanQrViewModel { private let openErrorRelay = PublishRelay<Error>() init() { } } extension WalletConnectScanQrViewModel { func didScan(string: String) { } }
12.944444
54
0.703863
28a97abf5059f92e36f94ba44bfcaf52b6b54fb3
32,963
// Copyright 2021-present Xsolla (USA), Inc. 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 q // // 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 and permissions and // swiftlint:disable opening_braces // swiftlint:disable function_parameter_count import Foundation import XsollaSDKLoginKit protocol XsollaSDKAuthorizationErrorDelegate: AnyObject { func xsollaSDK(_ xsollaSDK: XsollaSDK, didFailAuthorizationWithError error: Error) } final class XsollaSDK { let accessTokenProvider: AccessTokenProvider weak var authorizationErrorDelegate: XsollaSDKAuthorizationErrorDelegate? private var login: LoginKit { .shared } @Atomic private var isTokenDependedTasksInProcess = false private var tokenDependentTasksQueue = ThreadSafeArray<TokenDependentTask>() init(accessTokenProvider: AccessTokenProvider) { self.accessTokenProvider = accessTokenProvider } private func startTokenDependentTask(_ completion: @escaping (String?) -> Void) { let task = TokenDependentTask(completion: completion) startTokenDependentTask(task) } private func startTokenDependentTask(_ task: TokenDependentTask) { tokenDependentTasksQueue.append(task) guard !isTokenDependedTasksInProcess else { return } isTokenDependedTasksInProcess = true accessTokenProvider.getAccessToken { [weak self] result in switch result { case .success(let token): self?.processTokenDependedTasksQueue(withToken: token) case .failure: self?.invalidateQueue() } self?.isTokenDependedTasksInProcess = false } } private func processTokenDependedTasksQueue(withToken token: String) { while tokenDependentTasksQueue.count > 0 { tokenDependentTasksQueue.first?.completion(token) tokenDependentTasksQueue.dropFirst() } } private func invalidateQueue() { while tokenDependentTasksQueue.count > 0 { tokenDependentTasksQueue.first?.completion(nil) tokenDependentTasksQueue.dropFirst() } } } // MARK: - Login API extension XsollaSDK: XsollaSDKProtocol { func authByUsernameAndPassword(username: String, password: String, oAuth2Params: OAuth2Params, completion: @escaping LoginKitCompletion<String>) { login.authByUsernameAndPassword(username: username, password: password, oAuth2Params: oAuth2Params, completion: completion) } func authByUsernameAndPasswordJWT(username: String, password: String, clientId: Int, scope: String?, completion: ((Result<AccessTokenInfo, Error>) -> Void)?) { login.authByUsernameAndPasswordJWT(username: username, password: password, clientId: clientId, scope: scope) { [weak self] result in switch result { case .success(let tokenInfo): do { completion?(.success(tokenInfo)) } case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func getLinkForSocialAuth(providerName: String, oauth2params: OAuth2Params, completion: @escaping LoginKitCompletion<URL>) { login.getLinkForSocialAuth(providerName: providerName, oauth2params: oauth2params, completion: completion) } func authBySocialNetwork(oAuth2Params: OAuth2Params, providerName: String, socialNetworkAccessToken: String, socialNetworkAccessTokenSecret: String?, socialNetworkOpenId: String?, completion: @escaping LoginKitCompletion<String>) { login.authBySocialNetwork(oAuth2Params: oAuth2Params, providerName: providerName, socialNetworkAccessToken: socialNetworkAccessToken, socialNetworkAccessTokenSecret: socialNetworkAccessTokenSecret, socialNetworkOpenId: socialNetworkOpenId, completion: completion) } func generateJWT(grantType: TokenGrantType, clientId: Int, refreshToken: RefreshToken?, clientSecret: String?, redirectUri: String?, authCode: String?, completion: ((Result<AccessTokenInfo, Error>) -> Void)?) { login.generateJWT(grantType: grantType, clientId: clientId, refreshToken: refreshToken, clientSecret: clientSecret, redirectUri: redirectUri, authCode: authCode) { [weak self] result in switch result { case .success(let tokenInfo): do { completion?(.success(tokenInfo)) } case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func registerNewUser(oAuth2Params: OAuth2Params, username: String, password: String, email: String, acceptConsent: Bool?, fields: [String: String]?, promoEmailAgreement: Int?, completion: ((Result<URL?, Error>) -> Void)?) { login.registerNewUser(oAuth2Params: oAuth2Params, username: username, password: password, email: email, acceptConsent: acceptConsent, fields: fields, promoEmailAgreement: promoEmailAgreement) { [weak self] result in switch result { case .success(let url): completion?(.success(url)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func resetPassword(loginProjectId: String, username: String, loginUrl: String?, completion: ((Result<Void, Error>) -> Void)?) { login.resetPassword(loginProjectId: loginProjectId, username: username, loginUrl: loginUrl) { [weak self] result in switch result { case .success: completion?(.success(())) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func startAuthByEmail(oAuth2Params: OAuth2Params, email: String, linkUrl: String?, sendLink: Bool, completion: ((Result<String, Error>) -> Void)?) { login.startAuthByEmail(oAuth2Params: oAuth2Params, email: email, linkUrl: linkUrl, sendLink: sendLink) { [weak self] result in switch result { case .success(let operationId): completion?(.success(operationId)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func completeAuthByEmail(clientId: Int, code: String, email: String, operationId: String, completion: ((Result<String, Error>) -> Void)?) { login.completeAuthByEmail(clientId: clientId, code: code, email: email, operationId: operationId) { [weak self] result in switch result { case .success(let loginUrl): completion?(.success(loginUrl)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func startAuthByPhone(oAuth2Params: OAuth2Params, phoneNumber: String, linkUrl: String?, sendLink: Bool, completion: ((Result<String, Error>) -> Void)?) { login.startAuthByPhone(oAuth2Params: oAuth2Params, phoneNumber: phoneNumber, linkUrl: linkUrl, sendLink: sendLink) { [weak self] result in switch result { case .success(let operationId): completion?(.success(operationId)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func completeAuthByPhone(clientId: Int, code: String, phoneNumber: String, operationId: String, completion: ((Result<String, Error>) -> Void)?) { login.completeAuthByPhone(clientId: clientId, code: code, phoneNumber: phoneNumber, operationId: operationId) { [weak self] result in switch result { case .success(let loginUrl): completion?(.success(loginUrl)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func getConfirmationCode(projectId: String, login: String, operationId: String, completion: ((Result<String, Error>) -> Void)?) { self.login.getConfirmationCode(projectId: projectId, login: login, operationId: operationId) { [weak self] result in switch result { case .success(let code): completion?(.success(code)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func resendConfirmationLink(clientId: Int, redirectUri: String, state: String, username: String, completion: ((Result<Void, Error>) -> Void)?) { self.login.resendConfirmationLink(clientId: clientId, redirectUri: redirectUri, state: state, username: username) { [weak self] result in switch result { case .success: completion?(.success(())) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func authWithDeviceId(oAuth2Params: OAuth2Params, device: String, deviceId: String, completion: ((Result<String, Error>) -> Void)?) { login.authWithDeviceId(oAuth2Params: oAuth2Params, device: device, deviceId: deviceId) { [weak self] result in switch result { case .success(let loginUrl): completion?(.success(loginUrl)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } func getUserConnectedDevices(completion: ((Result<[DeviceInfo], Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getUserDevices(accessToken: token) { [weak self] result in switch result { case .success(let devicesInfo): do { completion?(.success(devicesInfo)) } case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func linkDeviceToAccount(device: String, deviceId: String, completion: ((Result<Void, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.linkDeviceToAccount(device: device, deviceId: deviceId, accessToken: token) { [weak self] result in switch result { case .success: do { completion?(.success(())) } case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func unlinkDeviceFromAccount(deviceId: String, completion: ((Result<Void, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.unlinkDeviceFromAccount(deviceId: deviceId, accessToken: token) { [weak self] result in switch result { case .success: do { completion?(.success(())) } case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func addUsernameAndPassword(username: String, password: String, email: String, promoEmailAgreement: Bool, redirectUri: String?, completion: ((Result<Bool, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.addUsernameAndPassword(username: username, password: password, email: email, promoEmailAgreement: promoEmailAgreement, accessToken: token, redirectUri: redirectUri) { [weak self] result in switch result { case .success(let emailConfirmationRequired): completion?(.success(emailConfirmationRequired)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func getCurrentUserDetails(completion: ((Result<UserProfileDetails, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getCurrentUserDetails(accessToken: token) { result in switch result { case .success(let userDetails): do { completion?(.success(userDetails)) } case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func updateCurrentUserDetails(birthday: Date?, firstName: String?, lastName: String?, nickname: String?, gender: UserProfileDetails.Gender?, completion: ((Result<UserProfileDetails, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.updateCurrentUserDetails(accessToken: token, birthday: birthday, firstName: firstName, lastName: lastName, nickname: nickname, gender: gender) { result in switch result { case .success(let userDetails): do { completion?(.success(userDetails)) } case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func getUserEmail(completion: ((Result<String?, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getUserEmail(accessToken: token) { result in switch result { case .success(let email): completion?(.success(email)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func deleteUserPicture(completion: ((Result<Void, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.deleteUserPicture(accessToken: token) { result in switch result { case .success: completion?(.success(())) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func uploadUserPicture(imageURL: URL, completion: ((Result<String, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.uploadUserPicture(accessToken: token, imageURL: imageURL) { result in switch result { case .success(let urlString): completion?(.success(urlString)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func getCurrentUserPhone(completion: ((Result<String?, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getCurrentUserPhone(accessToken: token) { result in switch result { case .success(let phone): completion?(.success(phone)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func updateCurrentUserPhone(phoneNumber: String, completion: ((Result<Void, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.updateCurrentUserPhone(accessToken: token, phoneNumber: phoneNumber) { result in switch result { case .success: completion?(.success(())) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func deleteCurrentUserPhone(phoneNumber: String, completion: ((Result<Void, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.deleteCurrentUserPhone(accessToken: token, phoneNumber: phoneNumber) { result in switch result { case .success: completion?(.success(())) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func getCurrentUserFriends(listType: FriendsListType, sortType: FriendsListSortType, sortOrderType: FriendsListOrderType, after: String?, limit: Int?, completion: ((Result<FriendsList, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getCurrentUserFriends(accessToken: token, listType: listType, sortType: sortType, sortOrderType: sortOrderType, after: after, limit: limit) { result in switch result { case .success(let friendsList): completion?(.success(friendsList)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func updateCurrentUserFriends(actionType: FriendsListUpdateAction, userID: String, completion: ((Result<Void, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.updateCurrentUserFriends(accessToken: token, actionType: actionType, userID: userID) { result in switch result { case .success: completion?(.success(())) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func getLinkedSocialNetworks(completion: ((Result<[UserSocialNetworkInfo], Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getLinkedNetworks(accessToken: token) { result in switch result { case .success(let userSocialNetworks): completion?(.success(userSocialNetworks)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func getSocialNetworkLinkingURL(for socialNetwork: SocialNetwork, callbackURL: String, completion: ((Result<URL, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getURLToLinkSocialNetworkToAccount(accessToken: token, providerName: socialNetwork.rawValue, loginURL: callbackURL) { result in switch result { case .success(let string): do { guard let url = URL(string: string) else { completion?(.failure(LoginKitError.failedURLExtraction)) return } completion?(.success(url)) } case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func getClientUserAttributes(keys: [String]?, publisherProjectId: Int?, userId: String?, completion: ((Result<[UserAttribute], Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getClientUserAttributes(accessToken: token, keys: keys, publisherProjectId: publisherProjectId, userId: userId) { result in switch result { case .success(let userAttributes): completion?(.success(userAttributes)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func getClientUserReadOnlyAttributes(keys: [String]?, publisherProjectId: Int?, userId: String?, completion: ((Result<[UserAttribute], Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.getClientUserReadOnlyAttributes(accessToken: token, keys: keys, publisherProjectId: publisherProjectId, userId: userId) { result in switch result { case .success(let userAttributes): completion?(.success(userAttributes)) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } func updateClientUserAttributes(attributes: [UserAttribute]?, publisherProjectId: Int?, removingKeys: [String]?, completion: ((Result<Void, Error>) -> Void)?) { startTokenDependentTask { [weak self] token in guard let token = token else { completion?(.failure(LoginKitError.invalidToken)); return } self?.login.updateClientUserAttributes(accessToken: token, attributes: attributes, publisherProjectId: publisherProjectId, removingKeys: removingKeys) { result in switch result { case .success: completion?(.success(())) case .failure(let error): do { self?.processError(error) completion?(.failure(error)) } } } } } } // MARK: - Helpers extension XsollaSDK { private func processError(_ error: Error) { switch error { case LoginKitError.invalidToken: authorizationErrorDelegate?.xsollaSDK(self, didFailAuthorizationWithError: error) default: break } } } extension XsollaSDK { struct TokenDependentTask { let completion: (String?) -> Void } }
36.503876
117
0.446288
ac9697d67d75447e18e686df4d39d24fec10abd8
1,415
// // PickerTextField.swift // DCKit // // Created by Denis Nascimento on 10/24/16. // Copyright © 2016 Denis Nascimento. All rights reserved. // import UIKit /// This text field can be used for UIDatePicker and UIPickerView. /// It has Select/Paste menu disabled, as well as zoom functionality and blinking cursor @IBDesignable open class FDNPickerTextField: FDNBorderedTextField { // MARK: - Initializers override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Building control override open func customInit() { super.customInit() tintColor = UIColor.clear } override open func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { if gestureRecognizer is UILongPressGestureRecognizer { gestureRecognizer.isEnabled = false } super.addGestureRecognizer(gestureRecognizer) } /** Disables copy/cut/paste/select all menu. - note: http://stackoverflow.com/questions/1426731/how-disable-copy-cut-select-select-all-in-uitextview - parameter action: A selector. - parameter sender: A sender. - returns: canPerformAction. */ override open func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return false } }
24.396552
108
0.679152
dd4a7e2be1403b92b939148ba885a119c248aa7d
3,912
import Foundation public extension String { public func decodeJsonString<T>() -> T? where T: Decodable { guard let data = self.data(using: .utf8), let object = try? JSONDecoder().decode(T.self, from: data) else { return nil } return object } public var decimalSpanishValue: Decimal? { return Decimal(string: self, locale: Locale.spanish) } public var base64Encoded: String { let base64String = dataUTF8.base64EncodedString(options: Data.Base64EncodingOptions.endLineWithCarriageReturn) return base64String } public var base64Decoded: String? { guard let decodedData = Data(base64Encoded: self) else { return nil } let decodedString = NSString(data: decodedData as Data, encoding: String.Encoding.utf8.rawValue) return decodedString as String? } public var dataUTF8: Data { guard let utf8 = data(using: String.Encoding.utf8) else { fatalError("A convertion from String to UTF8 never fails") } return utf8 } public var isNotEmpty: Bool { return !self.isEmpty } public var trimed: String { return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } public func isValidUrl() -> Bool { let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+" let predicate = NSPredicate(format: "SELF MATCHES %@", argumentArray: [regEx]) return predicate.evaluate(with: self) } public func isValidEmail() -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } public func suffix(from start: String) -> String? { if let foundRange = range(of: start) { return String(suffix(from: foundRange.upperBound)) } return nil } public func prefix(upTo string: String) -> String { if let foundRange = range(of: string) { return String(prefix(upTo: foundRange.lowerBound)) } return self } public var replacedPercentEncodingFromLatinToUTF8: String { let table = ["%E1": "%C3%A1", "%E9": "%C3%A9", "%ED": "%C3%AD", "%F3": "%C3%B3", "%FA": "%C3%BA", "%FC": "%C3%BC", "%C1": "%C3%81", "%C9": "%C3%89", "%CD": "%C3%8D", "%D3": "%C3%93", "%DA": "%C3%9A", "%DC": "%C3%9C"] var newValue = self for pair in table { newValue = newValue.replacingOccurrences(of: pair.key, with: pair.value) } return newValue } public subscript (bounds: CountableClosedRange<Int>) -> String { if bounds.lowerBound > count - 1 { return "" } let start = index(startIndex, offsetBy: bounds.lowerBound) let end = bounds.upperBound < count ? index(startIndex, offsetBy: bounds.upperBound) : index(startIndex, offsetBy: count - 1) return String(self[start...end]) } public subscript (bounds: CountableRange<Int>) -> String { if bounds.lowerBound > count { return "" } let start = index(startIndex, offsetBy: bounds.lowerBound) let end = bounds.upperBound < count ? index(startIndex, offsetBy: bounds.upperBound) : index(startIndex, offsetBy: count) return String(self[start..<end]) } public var withoutSpaces: String { return replacingOccurrences(of: " ", with: "") } }
32.6
118
0.539877
2626e167ce2b909856ed48279488b35095604e7f
409
// RUN: %target-typecheck-verify-swift protocol Empty {} protocol P { associatedtype Element init() } struct A<T> : P { typealias Element = T } struct A1<T> : P { typealias Element = T } struct A2<T> : P { typealias Element = T } func toA<S: Empty, AT:P>(_ s: S) -> AT where AT.Element == S.Generator.Element { // expected-error{{'Generator' is not a member type of type 'S'}} return AT() }
16.36
146
0.638142
f807a53f971715df69eaa3a0720f498da0617a0f
126
import XCTest import DSFSparklineTests var tests = [XCTestCaseEntry]() tests += DSFSparklineTests.allTests() XCTMain(tests)
15.75
37
0.793651
bff7f10fd2b95dd8b1843e336a1d1515eaf4a2fa
1,029
// // RectangleChartView.swift // CAShapeLayerTutorial // // Created by shenjie on 2021/9/24. // import SwiftUI struct RectangleChartView: View { var body: some View { ZStack(alignment: .center) { // RoundedRectangle(cornerRadius: 4) // .fill(LinearGradient(gradient: Gradient(colors: [Color.red, Color.purple]), startPoint: .bottom, endPoint: .top)) // .frame(width: CGFloat(20), height: 100) // .scaleEffect(CGSize(width: 1, height: 100), anchor: .bottom) // } Capsule() .fill(Color.green) .frame(width: 100, height: 50) Ellipse() .fill(Color.blue) .frame(width: 100, height: 50) Circle() .fill(Color.white) .frame(width: 100, height: 50) } } } struct RectangleChartView_Previews: PreviewProvider { static var previews: some View { RectangleChartView() } }
25.097561
131
0.531584
8ae6c8103f93495d4bf1131dc15fcf35af879225
352
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "CAPSPageMenu", products: [ .library(name: "CAPSPageMenu", targets: ["CAPSPageMenu"]), ], targets: [ .target(name: "CAPSPageMenu") ] )
23.466667
96
0.661932
c17e98e4d945ce9253e4ea1f5813b1b5a2f49a55
3,616
import Foundation import azureSwiftRuntime public protocol WorkspaceCollectionsRegenerateKey { var headerParameters: [String: String] { get set } var subscriptionId : String { get set } var resourceGroupName : String { get set } var workspaceCollectionName : String { get set } var apiVersion : String { get set } var _body : WorkspaceCollectionAccessKeyProtocol? { get set } func execute(client: RuntimeClient, completionHandler: @escaping (WorkspaceCollectionAccessKeysProtocol?, Error?) -> Void) -> Void ; } extension Commands.WorkspaceCollections { // RegenerateKey regenerates the primary or secondary access key for the specified Power BI Workspace Collection. internal class RegenerateKeyCommand : BaseCommand, WorkspaceCollectionsRegenerateKey { public var subscriptionId : String public var resourceGroupName : String public var workspaceCollectionName : String public var apiVersion = "2016-01-29" public var _body : WorkspaceCollectionAccessKeyProtocol? public init(subscriptionId: String, resourceGroupName: String, workspaceCollectionName: String, _body: WorkspaceCollectionAccessKeyProtocol) { self.subscriptionId = subscriptionId self.resourceGroupName = resourceGroupName self.workspaceCollectionName = workspaceCollectionName self._body = _body super.init() self.method = "Post" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBI/workspaceCollections/{workspaceCollectionName}/regenerateKey" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{workspaceCollectionName}"] = String(describing: self.workspaceCollectionName) self.queryParameters["api-version"] = String(describing: self.apiVersion) self.body = _body } public override func encodeBody() throws -> Data? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let encoder = try CoderFactory.encoder(for: mimeType) let encodedValue = try encoder.encode(_body as? WorkspaceCollectionAccessKeyData) return encodedValue } throw DecodeError.unknownMimeType } 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(WorkspaceCollectionAccessKeysData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (WorkspaceCollectionAccessKeysProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: WorkspaceCollectionAccessKeysData?, error: Error?) in completionHandler(result, error) } } } }
50.929577
182
0.662334
acd49d057f8d487c167100397b514830472621cb
6,657
// 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 MobiusCore import MobiusTest import Nimble import Quick class FirstMatchersTests: QuickSpec { // swiftlint:disable function_body_length override func spec() { describe("assertThatFirst") { var failureMessages: [String] = [] let model = "3" func testInitiator(model: String) -> First<String, String> { return First<String, String>(model: model, effects: Set(["2", "4"])) } func failureDetector(message: String, file: StaticString, line: UInt) { failureMessages.append(message) } beforeEach { failureMessages = [] } // Testing through proxy: InitSpec context("when asserting through predicates that fail") { beforeEach { InitSpec<AllStrings>(testInitiator) .when("a model") .then(assertThatFirst( hasModel(model + "1"), hasNoEffects(), failFunction: failureDetector )) } it("should have registered all failures") { expect(failureMessages.count).to(equal(2)) } } } describe("FirstMatchers") { let expectedModel = 1 var result: MobiusTest.PredicateResult? beforeEach { result = nil } context("when creating a matcher to check a First for a specific model") { context("when the model is the expected") { beforeEach { let first = First<Int, Int>(model: expectedModel) let sut: FirstPredicate<Int, Int> = hasModel(expectedModel) result = sut(first) } it("should match") { expect(result?.wasSuccessful).to(beTrue()) } } context("when the model isn't the expected") { let actualModel = 2 beforeEach { let first = First<Int, Int>(model: actualModel) let sut: FirstPredicate<Int, Int> = hasModel(expectedModel) result = sut(first) } it("should fail with an appropriate error message") { expect(result?.failureMessage).to(equal("Expected model to be <\(expectedModel)>, got <\(actualModel)>")) } } } context("when creating a matcher to check that a First has no effects") { context("when the First has no effects") { beforeEach { let first = First<Int, Int>(model: 3) let sut: FirstPredicate<Int, Int> = hasNoEffects() result = sut(first) } it("should match") { expect(result?.wasSuccessful).to(beTrue()) } } context("when the First has effects") { let effects = [4] beforeEach { let first = First<Int, Int>(model: 3, effects: Set(effects)) let sut: FirstPredicate<Int, Int> = hasNoEffects() result = sut(first) } it("should fail with an appropriate error message") { expect(result?.failureMessage).to(equal("Expected no effects, got <\(effects)>")) } } } context("when creating a matcher to check that a First has specific effects") { context("when the First has those effects") { let expectedEffects = [4, 7, 0] beforeEach { let first = First<Int, Int>(model: 3, effects: Set(expectedEffects)) let sut: FirstPredicate<Int, Int> = hasEffects(expectedEffects) result = sut(first) } it("should match") { expect(result?.wasSuccessful).to(beTrue()) } } context("when the First contains the expected effects and a few more") { let expectedEffects = [4, 7, 0] let actualEffects = [1, 4, 7, 0] beforeEach { let first = First<Int, Int>(model: 3, effects: Set(actualEffects)) let sut: FirstPredicate<Int, Int> = hasEffects(expectedEffects) result = sut(first) } it("should match") { expect(result?.wasSuccessful).to(beTrue()) } } context("when the First does not contain all the expected effects") { let expectedEffects = [10] let actualEffects = [4] beforeEach { let first = First<Int, Int>(model: 3, effects: Set(actualEffects)) let sut: FirstPredicate<Int, Int> = hasEffects(expectedEffects) result = sut(first) } it("should fail with an appropriate error message") { expect(result?.failureMessage).to(equal("Expected effects <\(actualEffects)> to contain <\(expectedEffects)>")) } } } } } }
39.390533
135
0.488508
bffb44a9f87a7297825d0c20ff349fd0bde520af
2,167
// // AppDelegate.swift // TicTacToeSecondTry // // Created by Cris on 9/30/16. // Copyright © 2016 Cris. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.106383
285
0.755422
627eecef6e6375a007ec44ae8e5f0c490650469c
2,845
// // RSTBTextFieldStepGenerator.swift // Pods // // Created by James Kizer on 1/9/17. // // import ResearchKit import Gloss open class RSTBTextFieldStepGenerator: RSTBQuestionStepGenerator { override open var supportedTypes: [String]! { return ["textfield"] } public override init(){} override open func generateAnswerFormat(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKAnswerFormat? { guard let textFieldDescriptor = RSTBTextFieldStepDescriptor(json: jsonObject) else { return nil } let answerFormat: ORKTextAnswerFormat = { if let validationRegex = textFieldDescriptor.validationRegex { return ORKTextAnswerFormat(validationRegex: validationRegex, invalidMessage: textFieldDescriptor.invalidMessage ?? "Entry invalid") } else { return ORKTextAnswerFormat(maximumLength: textFieldDescriptor.maximumLength ?? 0) } } () answerFormat.multipleLines = textFieldDescriptor.multipleLines switch textFieldDescriptor.textType { case .normal: break case .email: answerFormat.autocapitalizationType = .none answerFormat.autocorrectionType = .default answerFormat.spellCheckingType = .no answerFormat.keyboardType = .emailAddress answerFormat.isSecureTextEntry = false case .name: answerFormat.autocapitalizationType = .words answerFormat.autocorrectionType = .default answerFormat.spellCheckingType = .default answerFormat.keyboardType = .default answerFormat.isSecureTextEntry = false case .password: answerFormat.autocapitalizationType = .none answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no answerFormat.keyboardType = .default answerFormat.isSecureTextEntry = true case .number: answerFormat.autocapitalizationType = .none answerFormat.autocorrectionType = .default answerFormat.spellCheckingType = .no answerFormat.keyboardType = .numberPad answerFormat.isSecureTextEntry = false } return answerFormat } override open func processQuestionResult(type: String, result: ORKQuestionResult, helper: RSTBTaskBuilderHelper) -> JSON? { if let result = result as? ORKTextQuestionResult, let answer = result.textAnswer { return [ "identifier": result.identifier, "type": type, "answer": answer ] } return nil } }
33.470588
147
0.617223
08060f64900045387aab11809cb55d0946cec491
5,271
// // BBSInspectorDataSource.swift // BBSInspector // // Created by Cyril Chandelier on 06/03/15. // Copyright (c) 2015 Big Boss Studio. All rights reserved. // import Foundation import UIKit @objc public class BBSInspectorDataSource: NSObject { /** Served data array */ private var informationItems: [BBSInspectorInformation] /** Entry point to register more information items in list */ public var customInspectorInformationItems: (() -> [BBSInspectorInformation])? /** Convenient accessor for the count of information items */ public var count: Int { return informationItems.count } /** Read only access to information items through subscript syntax */ public subscript(index: Int) -> BBSInspectorInformation { get { return informationItems[index] } } /** Text displayed in bottom view, default is: ```Bundle name (Bundle version)``` */ public var excerptContent: String? /** Device push notifications token */ public var deviceToken: NSData? // MARK: - Initializers public override init() { informationItems = [BBSInspectorInformation]() } // MARK: - Data management /** Recompute all information items and execute custom information items closure to fill an array of InspectorInformation */ internal func reloadData() { informationItems.removeAll(keepCapacity: false) // App information name let infoDictionary = NSBundle.mainBundle().infoDictionary! informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Bundle name", comment: ""), caption: infoDictionary[kCFBundleNameKey as String] as! String)) informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Bundle identifier", comment: ""), caption: infoDictionary[kCFBundleIdentifierKey as String] as! String)) informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Version", comment: ""), caption: infoDictionary["CFBundleShortVersionString"] as! String)) informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Build", comment: ""), caption: infoDictionary[kCFBundleVersionKey as String] as! String)) // Device information let device = UIDevice.currentDevice() informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Device model", comment: ""), caption: device.model)) informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Device name", comment: ""), caption: device.name)) informationItems.append(BBSInspectorInformation(title: NSLocalizedString("System name", comment: ""), caption: device.systemName)) informationItems.append(BBSInspectorInformation(title: NSLocalizedString("System version", comment: ""), caption: device.systemVersion)) informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Identifier for vendor", comment: ""), caption: device.identifierForVendor!.UUIDString)) // Locale let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String let language = NSLocale.preferredLanguages().first as String! informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Locale", comment: ""), caption: "\(language)_\(countryCode)")) // Push notifications var pushNotificationsEnabled = false if #available(iOS 8.0, *) { let currentUserNotificationSettings = UIApplication.sharedApplication().currentUserNotificationSettings() pushNotificationsEnabled = (currentUserNotificationSettings!.types != UIUserNotificationType.None) } else { let enabledRemoteNotificationTypes = UIApplication.sharedApplication().enabledRemoteNotificationTypes() pushNotificationsEnabled = (enabledRemoteNotificationTypes != UIRemoteNotificationType.None) } informationItems.append(BBSInspectorInformation(title: NSLocalizedString("Push notifications", comment: ""), caption: (pushNotificationsEnabled ? NSLocalizedString("Enabled", comment: "") : NSLocalizedString("Disabled", comment: "")), captionColor: (pushNotificationsEnabled ? UIColor.greenColor() : UIColor.redColor()), action: nil)) // Device token if (pushNotificationsEnabled) { var deviceTokenString: String = NSLocalizedString("Undefined", comment: "") if deviceToken != nil { deviceTokenString = deviceToken!.description.stringByReplacingOccurrencesOfString("<", withString: "").stringByReplacingOccurrencesOfString(">", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "") } informationItems.append(BBSInspectorInformation(title: "Push token", caption: deviceTokenString)) } // Custom items if let customInspectorInformationItems = self.customInspectorInformationItems { for information in customInspectorInformationItems() { informationItems.append(information) } } } }
45.834783
342
0.695504
289592e26b883ddb4a07c0a89c8c4e68861ab16f
149
import Foundation import UIKit public class TableExampleHeaderView: UITableViewHeaderFooterView { @IBOutlet public var titleLabel: UILabel? }
14.9
66
0.812081
f4e5bdb46077cd7acda5f6b7b1408265389fb185
888
// // SKTableViewController.swift // SKUIKit // // Created by Britton Katnich on 2018-02-05. // Copyright © 2018 SandKatt Solutions Inc. All rights reserved. // import UIKit import SandKattFoundation /** * The SandKatt base version of a custom ViewController with a table view. * It is specifically concerned with ContentHolders available within the * application to show it's menu items. */ open class SKTableViewController: UIViewController { // MARK: -- Properties -- open var dataSource: SKTableViewDataSource? // MARK: -- IBOutlets -- @IBOutlet open weak var tableView: UITableView? // MARK: -- Lifecycle -- open override func viewDidLoad() { super.viewDidLoad() } open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() log.warning("called") } }
19.733333
74
0.663288
3a6967530700101c1c09999325f9b02b95d4997a
2,548
// // DispatchQueue+Ext.swift // BartAPI // // Created by Adrian Duran on 12/27/19. // Copyright © 2019 Adrian Duran. All rights reserved. // import Foundation import UIKit extension DispatchQueue { /* Simpler way to initate background code https://stackoverflow.com/questions/24056205/how-to-use-background-thread-in-swift example: DispatchQueue.backgroundThread(delay: 2.0, background: { // background work }, completion: { // update main }) */ static func backgroundThread(delay: Double = 0.0, background:(() -> Void)? = nil, completion: (() -> Void)? = nil) { DispatchQueue.global(qos: .background).async { background?() if let completion = completion { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { completion() }) } } } static func utilityThread(delay: Double = 0.0, background:(() -> Void)? = nil, completion: (() -> Void)? = nil) { DispatchQueue.global(qos: .utility).async { background?() if let completion = completion { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { completion() }) } } } static func userInitiatedThread(delay: Double = 0.0, background:(() -> Void)? = nil, completion: (() -> Void)? = nil) { DispatchQueue.global(qos: .userInitiated).async { background?() if let completion = completion { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { completion() }) } } } static func userInteractiveThread(delay: Double = 0.0, background:(() -> Void)? = nil, completion: (() -> Void)? = nil) { DispatchQueue.global(qos: .userInteractive).async { background?() if let completion = completion { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { completion() }) } } } static func mainThread(delay: Double = 0.0, firstBlock:(() -> Void)? = nil, secondBlock: (() -> Void)? = nil) { DispatchQueue.main.async { firstBlock?() if let secondBlock = secondBlock { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {secondBlock()}) } } } }
31.45679
125
0.531005
7aa0b72dc29cbba1abd2862e6bbf6b4fa9008211
749
import XCTest import NSFWDetector class Tests: 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. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.827586
111
0.602136
d607c21234a95c8047819470a65490eebef8bdc2
3,151
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation import UIKit public extension UIAlertAction { /// Action types most commonly used enum ActionType { ///Ok Option case ok /// Default Cancel Option case cancel /// Destructive action with custom title case destructive(String) /// Custom action with title and style case custom(String, UIAlertAction.Style) /** Creates the action instance for UIAlertController - parameter handler: Call Back function - returns UIAlertAction Instance */ public func action(handler: ((String) -> Void)? = nil) -> UIAlertAction { //Default value var actionStyle: UIAlertAction.Style = .default var title = "" // Action configuration based on the action type switch self { case .cancel: actionStyle = .cancel title = "Cancel" case .destructive(let optionTitle): title = optionTitle actionStyle = .destructive case let .custom(optionTitle, style): title = optionTitle actionStyle = style default: title = "OK" } //Creating UIAlertAction instance return UIAlertAction(title: title, style: actionStyle) { _ in if let handler = handler { handler(title) } } } } } extension UIAlertController { /** Creates the alert view controller using the actions specified, including an "OK" Action - parameter title: Title of the alert. - parameter message: Alert message body. - parameter style: UIAlertControllerStyle enum value - parameter handler: Handler block/closure for the clicked option. */ convenience init(title: String, message: String, style: UIAlertController.Style = .alert, handler: ((String) -> Swift.Void)? = nil) { //initialize the contoller (self) instance self.init(title: title, message: message, preferredStyle: style) if actions.isEmpty { addAction(UIAlertAction.ActionType.ok.action(handler: handler)) } } }
33.521277
90
0.68391
28488a5471dbaa08f26814be40f5a295d8c650c4
2,201
// // 🦠 Corona-Warn-App // import XCTest @testable import ENA class Tracelocation_GenerateQRCodeTests: XCTestCase { func testQRCodeGeneration() throws { let stringToEncode = "HTTPS://CORONAWARN.APP/E1/BIPEY33SMVWSA2LQON2W2IDEN5WG64RAONUXIIDBNVSXILBAMNXRBCM4UQARRKM6UQASAHRKCC7CTDWGQ4JCO7RVZSWVIMQK4UPA.GBCAEIA7TEORBTUA25QHBOCWT26BCA5PORBS2E4FFWMJ3UU3P6SXOL7SHUBCA7UEZBDDQ2R6VRJH7WBJKVF7GZYJA6YMRN27IPEP7NKGGJSWX3XQ" let qrCodeImage = try XCTUnwrap(QRCodePlayground.generateQRCode(with: stringToEncode)) let decodedString = extractFirstMessageFrom(qrCode: qrCodeImage) XCTAssertEqual(qrCodeImage.size.height, qrCodeImage.size.width) XCTAssertEqual(qrCodeImage.size.height, 400) XCTAssertEqual(stringToEncode, decodedString) } func testQRCodeGenerationWithCustomSize() throws { let stringToEncode = "HTTPS://CORONAWARN.APP/E1/BIPEY33SMVWSA2LQON2W2IDEN5WG64RAONUXIIDBNVSXILBAMNXRBCM4UQARRKM6UQASAHRKCC7CTDWGQ4JCO7RVZSWVIMQK4UPA.GBCAEIA7TEORBTUA25QHBOCWT26BCA5PORBS2E4FFWMJ3UU3P6SXOL7SHUBCA7UEZBDDQ2R6VRJH7WBJKVF7GZYJA6YMRN27IPEP7NKGGJSWX3XQ" let qrCodeImage = try XCTUnwrap(QRCodePlayground.generateQRCode(with: stringToEncode, size: CGSize(width: 1000, height: 1000))) let decodedString = extractFirstMessageFrom(qrCode: qrCodeImage) XCTAssertEqual(qrCodeImage.size.height, qrCodeImage.size.width) XCTAssertEqual(qrCodeImage.size.height, 1000) XCTAssertEqual(stringToEncode, decodedString) } func extractFirstMessageFrom(qrCode: UIImage) -> String? { if let ciImage = qrCode.ciImage { var options: [String: Any] let context = CIContext() options = [CIDetectorAccuracy: CIDetectorAccuracyHigh] let qrDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: options) if ciImage.properties.keys.contains((kCGImagePropertyOrientation as String)) { options = [CIDetectorImageOrientation: ciImage.properties[(kCGImagePropertyOrientation as String)] ?? 1] } else { options = [CIDetectorImageOrientation: 1] } let features = qrDetector?.features(in: ciImage, options: options) let firstFeature = features?.first as? CIQRCodeFeature return firstFeature?.messageString } return nil } }
39.303571
264
0.808723
ef88c28deb261edd7099d38aba73ef7837863b3e
8,930
// // NFSpotifyOAuth.swift // NFSpotifyAuth // // Created by Neil Francis Hipona on 4/9/20. // import Foundation import Alamofire public class NFSpotifyOAuth: NSObject { public static let shared = NFSpotifyOAuth() public var clientID: String! public var clientSecret: String! public var redirectURI: String! public var userDefaultKey: String! private override init() { super.init() } /* FLOW ACCESS USER RESOURCES REQUIRES SECRET KEY (SERVER-SIDE) ACCESS TOKEN REFRESH Authorization Code Yes Yes Yes Client Credentials No Yes No Implicit Grant Yes No No */ public func set(clientId id: String, clientSecret secret: String, redirectURI uri: String, userDefaultKey key: String! = nil) { clientID = id clientSecret = secret redirectURI = uri userDefaultKey = key } } // MARK: - Requests extension NFSpotifyOAuth { /* Client Credentials Flow The Client Credentials flow is used in server-to-server authentication. Only endpoints that do not access user information can be accessed. The advantage here in comparison with requests to the Web API made without an access token, is that a higher rate limit is applied. */ // 1a. authorizes access returns access code public func getClientCredentialToken(completion: CompletionHandler = nil) { guard let clientID = clientID, let clientSecret = clientSecret else { return } let parameters: [String: AnyObject] = [ "client_id": clientID as AnyObject, "client_secret": clientSecret as AnyObject, "grant_type": "client_credentials" as AnyObject ] AF .request(NFSpotifyAutorizationTokenExchangeURL, method: .post, parameters: parameters) .responseJSON { (response) in switch response.result { case .success(let value): let tokenInfo = value as! [String: AnyObject] if tokenInfo["error"] == nil { let tokenObject = NFSpotifyToken(tokenInfo: tokenInfo) let _ = archive(object: tokenObject, secure: true, key: NFSpotifyClientCredentialKey) completion?(tokenObject, nil) }else{ completion?(nil, processError(responseData: tokenInfo)) } case .failure(let error): completion?(nil, processError(error: error)) } } } /* Implicit Grant Flow Implicit grant flow is for clients that are implemented entirely using JavaScript and running in the resource owner’s browser. You do not need any server-side code to use it. Rate limits for requests are improved but there is no refresh token provided. This flow is described in RFC-6749. */ // 1b. request application authorization public func authorizeApplication(state: String = "", show_dialog: Bool = false, completion: CompletionHandler = nil) { guard let clientID = clientID, let redirectURI = redirectURI else { return } let parameters: [String: AnyObject] = [ "client_id": clientID as AnyObject, "response_type": "code" as AnyObject, "redirect_uri": redirectURI as AnyObject, "grant_type": "client_credentials" as AnyObject, "state": state as AnyObject, "scope": NFSpotifyAvailableScopes.joined(separator: " ") as AnyObject, "show_dialog": show_dialog as AnyObject ] AF .request(NFSpotifyAutorizationCodeURL, method: .post, parameters: parameters) .responseJSON { (response) in switch response.result { case .success(let value): let tokenInfo = value as! [String: AnyObject] if tokenInfo["error"] == nil { let tokenObject = NFSpotifyToken(tokenInfo: tokenInfo) let _ = archive(object: tokenObject, secure: true, key: NFSpotifyClientCredentialKey) completion?(tokenObject, nil) }else{ completion?(nil, processError(responseData: tokenInfo)) } case .failure(let error): completion?(nil, processError(error: error)) } } } /* Authorization Code Flow This flow is suitable for long-running applications in which the user grants permission only once. It provides an access token that can be refreshed. Since the token exchange involves sending your secret key, perform this on a secure location, like a backend service, and not from a client such as a browser or from a mobile app. */ // 2. access and refresh tokens from access code public func accessTokenFromAccessCode(_ code: String, completion: CompletionHandler = nil) { guard let clientID = clientID, let clientSecret = clientSecret, let redirectURI = redirectURI else { return } let parameters: [String: AnyObject] = [ "client_id": clientID as AnyObject, "client_secret": clientSecret as AnyObject, "grant_type": "authorization_code" as AnyObject, "redirect_uri": redirectURI as AnyObject, "code": code as AnyObject ] AF .request(NFSpotifyAutorizationTokenExchangeURL, method: .post, parameters: parameters) .responseJSON { (response) in switch response.result { case .success(let value): let tokenInfo = value as! [String: AnyObject] if tokenInfo["error"] == nil { let tokenObject = NFSpotifyToken(tokenInfo: tokenInfo) let _ = archive(object: tokenObject, secure: true, key: NFSpotifyClientCredentialKey) completion?(tokenObject, nil) }else{ completion?(nil, processError(responseData: tokenInfo)) } case .failure(let error): completion?(nil, processError(error: error)) } } } // 3. access token from refresh access token public func renewAccessToken(refreshToken token: String, completion: CompletionHandler = nil) { guard let clientID = clientID, let clientSecret = clientSecret else { return } let parameters: [String: AnyObject] = [ "client_id": clientID as AnyObject, "client_secret": clientSecret as AnyObject, "grant_type": "refresh_token" as AnyObject, "refresh_token": token as AnyObject ] AF .request(NFSpotifyAutorizationTokenExchangeURL, method: .post, parameters: parameters) .responseJSON { (response) in switch response.result { case .success(let value): let tokenInfo = value as! [String: AnyObject] if tokenInfo["error"] == nil { let tokenObject = NFSpotifyToken(tokenInfo: tokenInfo) let _ = archive(object: tokenObject, secure: true, key: NFSpotifyClientCredentialKey) completion?(tokenObject, nil) }else{ completion?(nil, processError(responseData: tokenInfo)) } case .failure(let error): completion?(nil, processError(error: error)) } } } } // MARK: - Error extension NFSpotifyOAuth { public class func createCustomError(withDomain domain: String = "com.NFSpotifyAuth.error", code: Int = 4776, userInfo: [String: Any]?) -> Error { return NSError(domain: domain, code: code, userInfo: userInfo) } public class func createCustomError(withDomain domain: String = "com.NFSpotifyAuth.error", code: Int = 4776, errorMessage msg: String) -> Error { return NSError(domain: domain, code: code, userInfo: ["message": msg]) } }
39.513274
334
0.552632
91abe0bc4848a69a77e6844b467738d2198e513f
16,915
//****************************************************************************** // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import SwiftRT import XCTest #if swift(>=5.3) && canImport(_Differentiation) import _Differentiation #endif class test_Pool: XCTestCase { //========================================================================== // support terminal test run static var allTests = [ // scalar tests ("test_poolAverage1D", test_poolAverage1D), ("test_poolBatchAverage1D", test_poolBatchAverage1D), ("test_poolAverage2D", test_poolAverage2D), ("test_poolBatchAverage2D", test_poolBatchAverage2D), ("test_poolAverage3D", test_poolAverage3D), ("test_poolBatchAverage3D", test_poolBatchAverage3D), ("test_poolAveragePadding", test_poolAveragePadding), ("test_poolMax", test_poolMax), // vector tests // ("test_pool1DPixelAverage", test_pool1DPixelAverage), // ("test_poolBatch1DPixelAverage", test_poolBatch1DPixelAverage), // ("test_pool2DPixelAverage", test_pool2DPixelAverage), // ("test_poolBatch2DPixelAverage", test_poolBatch2DPixelAverage), // ("test_pool3DPixelAverage", test_pool3DPixelAverage), // ("test_poolBatch3DPixelAverage", test_poolBatch3DPixelAverage), ] //-------------------------------------------------------------------------- func test_pool1DPixelAverage() { #if canImport(SwiftRTCuda) typealias Pixel = RGBA<UInt8> let pixels = array([Pixel(0), Pixel(1), Pixel(2), Pixel(3), Pixel(4), Pixel(5)]) let avg = pool(x: pixels, windowSize: 3, padding: 1, op: .average) print(avg) XCTAssert(avg.shape == pixels.shape) // XCTAssert( // same == [ // [2.0, 2.5, 3.0], // [3.5, 4.0, 4.5], // [5.0, 5.5, 6.0], // ]) #endif } //-------------------------------------------------------------------------- func test_poolBatch1DPixelAverage() { #if canImport(SwiftRTCuda) typealias Pixel = RGBA<UInt8> let image = array([ [Pixel(0), Pixel(1), Pixel(2)], [Pixel(3), Pixel(4), Pixel(5)], [Pixel(6), Pixel(7), Pixel(8)], ]) let avg = pool(x: image, windowSize: 3, padding: 1, op: .average) print(avg) XCTAssert(avg.shape == image.shape) // XCTAssert( // same == [ // [2.0, 2.5, 3.0], // [3.5, 4.0, 4.5], // [5.0, 5.5, 6.0], // ]) #endif } //-------------------------------------------------------------------------- func test_pool2DPixelAverage() { #if canImport(SwiftRTCuda) typealias Pixel = RGBA<UInt8> let image = array([ [Pixel(0), Pixel(1), Pixel(2)], [Pixel(3), Pixel(4), Pixel(5)], [Pixel(6), Pixel(7), Pixel(8)], ]) let avg = pool(x: image, windowSize: 3, padding: 1, op: .average) print(avg) XCTAssert(avg.shape == image.shape) // XCTAssert( // same == [ // [2.0, 2.5, 3.0], // [3.5, 4.0, 4.5], // [5.0, 5.5, 6.0], // ]) #endif } //-------------------------------------------------------------------------- func test_pool3DPixelAverage() { #if canImport(SwiftRTCuda) typealias Pixel = RGBA<UInt8> let volume = array([ [ [Pixel(0), Pixel(1), Pixel(2)], [Pixel(3), Pixel(4), Pixel(5)], [Pixel(6), Pixel(7), Pixel(8)], ], [ [Pixel(9), Pixel(10), Pixel(11)], [Pixel(12), Pixel(13), Pixel(14)], [Pixel(15), Pixel(16), Pixel(17)], ], ]) let avg = pool(x: volume, windowSize: 3, padding: 1, op: .average) print(avg) XCTAssert(avg.shape == volume.shape) // XCTAssert( // same == [ // [2.0, 2.5, 3.0], // [3.5, 4.0, 4.5], // [5.0, 5.5, 6.0], // ]) #endif } //-------------------------------------------------------------------------- func test_poolBatch2DPixelAverage() { #if canImport(SwiftRTCuda) typealias Pixel = RGBA<UInt8> let images = array([ [ [Pixel(0), Pixel(1), Pixel(2)], [Pixel(3), Pixel(4), Pixel(5)], [Pixel(6), Pixel(7), Pixel(8)], ], [ [Pixel(9), Pixel(10), Pixel(11)], [Pixel(12), Pixel(13), Pixel(14)], [Pixel(15), Pixel(16), Pixel(17)], ], ]) let avg = pool(batch: images, windowSize: 3, padding: 1, op: .average) print(avg) XCTAssert(avg.shape == images.shape) // XCTAssert( // same == [ // [2.0, 2.5, 3.0], // [3.5, 4.0, 4.5], // [5.0, 5.5, 6.0], // ]) #endif } //-------------------------------------------------------------------------- func test_poolBatch3DPixelAverage() { #if canImport(SwiftRTCuda) typealias Pixel = RGBA<UInt8> let volumes = array([ // volume 0 [ [ [Pixel(0), Pixel(1), Pixel(2)], [Pixel(3), Pixel(4), Pixel(5)], [Pixel(6), Pixel(7), Pixel(8)], ], [ [Pixel(9), Pixel(10), Pixel(11)], [Pixel(12), Pixel(13), Pixel(14)], [Pixel(15), Pixel(16), Pixel(17)], ], ], // volume 1 [ [ [Pixel(18), Pixel(19), Pixel(20)], [Pixel(21), Pixel(22), Pixel(23)], [Pixel(24), Pixel(25), Pixel(26)], ], [ [Pixel(27), Pixel(28), Pixel(29)], [Pixel(30), Pixel(31), Pixel(32)], [Pixel(33), Pixel(34), Pixel(35)], ], ], ]) let avg = pool(batch: volumes, windowSize: 3, padding: 1, op: .average) print(avg) XCTAssert(avg.shape == volumes.shape) // XCTAssert( // same == [ // [2.0, 2.5, 3.0], // [3.5, 4.0, 4.5], // [5.0, 5.5, 6.0], // ]) #endif } //-------------------------------------------------------------------------- func test_poolBatchAverage2D() { #if canImport(SwiftRTCuda) let a = array(0..<18, shape: (2, 3, 3)) let avg = pool(batch: a, windowSize: 3, padding: 1, op: .average) XCTAssert(avg.shape == a.shape) XCTAssert( avg == [ [ [2.0, 2.5, 3.0], [3.5, 4.0, 4.5], [5.0, 5.5, 6.0], ], [ [11.0, 11.5, 12.0], [12.5, 13.0, 13.5], [14.0, 14.5, 15.0], ], ] ) #endif } //-------------------------------------------------------------------------- func test_poolAverage1D() { #if canImport(SwiftRTCuda) let a = array(0..<6) let avg = pool(x: a, windowSize: 3, padding: 1, op: .average) XCTAssert(avg == [0.5, 1.0, 2.0, 3.0, 4.0, 4.5]) #endif } //-------------------------------------------------------------------------- func test_poolBatchAverage1D() { #if canImport(SwiftRTCuda) let a = array(0..<12, shape: (2, 6)) let avg = pool(batch: a, windowSize: 3, padding: 1, op: .average) XCTAssert( avg == [ [0.5, 1.0, 2.0, 3.0, 4.0, 4.5], [6.5, 7.0, 8.0, 9.0, 10.0, 10.5], ]) #endif } //-------------------------------------------------------------------------- func test_poolAverage3D() { #if canImport(SwiftRTCuda) let a = array(0..<27, shape: (3, 3, 3)) let avgrow = pool(x: a, windowSize: (1, 1, 3), padding: (0, 0, 1), op: .average) XCTAssert( avgrow == [ [ [0.5, 1.0, 1.5], [3.5, 4.0, 4.5], [6.5, 7.0, 7.5], ], [ [9.5, 10.0, 10.5], [12.5, 13.0, 13.5], [15.5, 16.0, 16.5], ], [ [18.5, 19.0, 19.5], [21.5, 22.0, 22.5], [24.5, 25.0, 25.5], ], ]) let avgcol = pool(x: a, windowSize: (1, 3, 1), padding: (0, 1, 0), op: .average) XCTAssert( avgcol == [ [ [1.5, 2.5, 3.5], [3.0, 4.0, 5.0], [4.5, 5.5, 6.5], ], [ [10.5, 11.5, 12.5], [12.0, 13.0, 14.0], [13.5, 14.5, 15.5], ], [ [19.5, 20.5, 21.5], [21.0, 22.0, 23.0], [22.5, 23.5, 24.5], ], ]) let avgdepth = pool(x: a, windowSize: (1, 3, 3), padding: (0, 1, 1), op: .average) XCTAssert( avgdepth == [ [ [2.0, 2.5, 3.0], [3.5, 4.0, 4.5], [5.0, 5.5, 6.0], ], [ [11.0, 11.5, 12.0], [12.5, 13.0, 13.5], [14.0, 14.5, 15.0], ], [ [20.0, 20.5, 21.0], [21.5, 22.0, 22.5], [23.0, 23.5, 24.0], ], ]) let avgvolume = pool(x: a, windowSize: 3, padding: 1, op: .average) XCTAssert( avgvolume == [ [ [6.5, 7.0, 7.5], [8.0, 8.5, 9.0], [9.5, 10.0, 10.5], ], [ [11.0, 11.5, 12.0], [12.5, 13.0, 13.5], [14.0, 14.5, 15.0], ], [ [15.5, 16.0, 16.5], [17.0, 17.5, 18.0], [18.5, 19.0, 19.5], ], ]) #endif } //-------------------------------------------------------------------------- func test_poolBatchAverage3D() { #if canImport(SwiftRTCuda) let a = array(0..<54, shape: (2, 3, 3, 3)) let avg = pool(batch: a, windowSize: 3, padding: 1, op: .average) XCTAssert( avg == [ [ [ [6.5, 7.0, 7.5], [8.0, 8.5, 9.0], [9.5, 10.0, 10.5], ], [ [11.0, 11.5, 12.0], [12.5, 13.0, 13.5], [14.0, 14.5, 15.0], ], [ [15.5, 16.0, 16.5], [17.0, 17.5, 18.0], [18.5, 19.0, 19.5], ], ], [ [ [33.5, 34.0, 34.5], [35.0, 35.5, 36.0], [36.5, 37.0, 37.5], ], [ [38.0, 38.5, 39.0], [39.5, 40.0, 40.5], [41.0, 41.5, 42.0], ], [ [42.5, 43.0, 43.5], [44.0, 44.5, 45.0], [45.5, 46.0, 46.5], ], ], ]) #endif } //-------------------------------------------------------------------------- func test_poolAverage2D() { #if canImport(SwiftRTCuda) // average rows do { let a = array(0..<9, shape: (3, 3)) let avg = pool(x: a, windowSize: (1, 3), padding: (0, 1), op: .average) XCTAssert(avg.shape == a.shape) XCTAssert( avg == [ [0.5, 1.0, 1.5], [3.5, 4.0, 4.5], [6.5, 7.0, 7.5], ]) } // average cols do { let a = array(0..<9, shape: (3, 3)) let avg = pool(x: a, windowSize: (3, 1), padding: (1, 0), op: .average) XCTAssert(avg.shape == a.shape) XCTAssert( avg == [ [1.5, 2.5, 3.5], [3.0, 4.0, 5.0], [4.5, 5.5, 6.5], ]) } do { let a = array([ [0, 1, 2], [3, 4, 5], [6, 7, 8], ]) // same let same = pool(x: a, windowSize: 3, padding: 1, op: .average) XCTAssert(a.shape == same.shape) XCTAssert( same == [ [2.0, 2.5, 3.0], [3.5, 4.0, 4.5], [5.0, 5.5, 6.0], ]) // default is strides 1 padding 0 let valid = pool(x: a, windowSize: 3, op: .average) XCTAssert(valid == [[4.0]]) // using a configuration let config = PoolingConfig(x: a, windowSize: Shape2(3, 3), op: .average) var out = Tensor2(shape: config.shape, order: a.order) currentQueue.pool(config, a, &out) XCTAssert(out == [[4.0]]) } do { let a = array(0..<25, shape: (5, 5)) // same let same = pool(x: a, windowSize: 5, padding: 2, op: .average) XCTAssert(a.shape == same.shape) let expsame = array([ [6.0, 6.5, 7.0, 7.5, 8.0], [8.5, 9.0, 9.5, 10.0, 10.5], [11.0, 11.5, 12.0, 12.5, 13.0], [13.5, 14.0, 14.5, 15.0, 15.5], [16.0, 16.5, 17.0, 17.5, 18.0], ]) XCTAssert(almostEqual(same, expsame, tolerance: 0.001)) // valid let valid = pool(x: a, windowSize: 5, op: .average) XCTAssert(valid == [[12.0]]) // using a configuration let config = PoolingConfig(x: a, windowSize: 5, op: .average) var out = Tensor2(shape: config.shape, order: a.order) currentQueue.pool(config, a, &out) XCTAssert(out == [[12.0]]) } #endif } //-------------------------------------------------------------------------- func test_poolAveragePadding() { #if canImport(SwiftRTCuda) // 3D do { let a = ones(shape: (3, 3, 3)) let avg = pool(x: a, windowSize: 3, padding: 1, op: .averagePadding) let expavg = array( [ [ [0.2962963, 0.44444445, 0.2962963], [0.44444445, 0.6666667, 0.44444445], [0.2962963, 0.44444445, 0.2962963], ], [ [0.44444445, 0.6666667, 0.44444445], [0.6666667, 1.0, 0.6666667], [0.44444445, 0.6666667, 0.44444445], ], [ [0.2962963, 0.44444445, 0.2962963], [0.44444445, 0.6666667, 0.44444445], [0.2962963, 0.44444445, 0.2962963], ], ]) XCTAssert(almostEqual(avg, expavg, tolerance: 0.001)) } // 2D do { let a = array([ [0, 1, 2], [3, 4, 5], [6, 7, 8], ]) // same let same = pool(x: a, windowSize: 3, padding: 1, op: .averagePadding) XCTAssert(a.shape == same.shape) XCTAssert( almostEqual( same, array([ [0.8888889, 1.6666666, 1.3333334], [2.3333333, 4.0, 3.0], [2.2222223, 3.6666667, 2.6666667], ]), tolerance: 0.001)) // valid let valid = pool(x: a, windowSize: 3, op: .averagePadding) XCTAssert(valid == [[4.0]]) // using a configuration let config = PoolingConfig(x: a, windowSize: 3, op: .averagePadding) var out = Tensor2(shape: config.shape, order: a.order) currentQueue.pool(config, a, &out) XCTAssert(out == [[4.0]]) } do { let a = array(0..<25, shape: (5, 5)) // same let same = pool(x: a, windowSize: 5, padding: 2, op: .averagePadding) let expsame = array([ [2.1599998, 3.12, 4.2, 3.6, 2.8799999], [4.08, 5.7599998, 7.6, 6.3999996, 5.04], [6.6, 9.2, 12.0, 10.0, 7.7999997], [6.48, 8.96, 11.599999, 9.599999, 7.44], [5.7599998, 7.9199996, 10.2, 8.4, 6.48], ]) XCTAssert(almostEqual(same, expsame, tolerance: 0.001)) // valid let valid = pool(x: a, windowSize: 5, op: .averagePadding) XCTAssert(valid == [[12.0]]) // using a configuration let config = PoolingConfig(x: a, windowSize: 5, op: .averagePadding) var out = Tensor2(shape: config.shape, order: a.order) currentQueue.pool(config, a, &out) XCTAssert(out == [[12.0]]) } #endif } //-------------------------------------------------------------------------- func test_poolMax() { #if canImport(SwiftRTCuda) let a = array([ [0, 1, 2], [3, 4, 5], [6, 7, 8], ]) // same let same = pool(x: a, windowSize: 3, padding: 1, op: .max) XCTAssert(a.shape == same.shape) XCTAssert( same == [ [4.0, 5.0, 5.0], [7.0, 8.0, 8.0], [7.0, 8.0, 8.0], ]) // valid let valid = pool(x: a, windowSize: 3, op: .max) XCTAssert(valid == [[8.0]]) #endif } }
28.865188
88
0.415785
16b34590be899bd51a28739ec0ed7a726a7d3381
2,550
// // ScrollingTabBarUtils.swift // ScrollingTabBarUtils // // Created by Franklin Schrans on 24/12/2015. // Copyright © 2015 Franklin Schrans. All rights reserved. // import UIKit class ScrollingTabBarControllerDelegate: NSObject, UITabBarControllerDelegate { func tabBarController(tabBarController: UITabBarController, animationControllerForTransitionFromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ScrollingTransitionAnimator(tabBarController: tabBarController, lastIndex: tabBarController.selectedIndex) } } class ScrollingTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning { weak var transitionContext: UIViewControllerContextTransitioning? var tabBarController: UITabBarController! var lastIndex = 0 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.4 } init(tabBarController: UITabBarController, lastIndex: Int) { self.tabBarController = tabBarController self.lastIndex = lastIndex } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext let containerView = transitionContext.containerView() let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) containerView?.addSubview(toViewController!.view) var viewWidth = CGRectGetWidth(toViewController!.view.bounds) if tabBarController.selectedIndex < lastIndex { viewWidth = -viewWidth } toViewController!.view.transform = CGAffineTransformMakeTranslation(viewWidth, 0) UIView.animateWithDuration(self.transitionDuration((self.transitionContext)), delay: 0.0, usingSpringWithDamping: 1.2, initialSpringVelocity: 2.5, options: .TransitionNone, animations: { toViewController!.view.transform = CGAffineTransformIdentity fromViewController!.view.transform = CGAffineTransformMakeTranslation(-viewWidth, 0) }, completion: { _ in self.transitionContext?.completeTransition(!self.transitionContext!.transitionWasCancelled()) fromViewController!.view.transform = CGAffineTransformIdentity }) } }
45.535714
225
0.747451
4aa44d9b66a0ce631bbef534bd075de6e9ea58ea
1,250
// // ViewController.swift // Develop // // Created by Artem Shimanski on 27.11.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI import Alamofire class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } var session: URLSession? @IBAction func onButton(_ sender: Any) { let configuration = URLSessionConfiguration.default configuration.requestCachePolicy = .reloadIgnoringLocalCacheData /*session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) let task = session!.dataTask(with: URL(string: "http://refreshyourcache.com/cache-test/test.php")!) task.resume()*/ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: URLSessionDataDelegate { func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { let image = UIImage(data: data) print("\(image)") } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { print("\(error)") } }
25
101
0.74
1e071b4519735e632f3aa7728c6b5a9d44ba79a1
326
struct ReceivedCenReport: Codable, CustomStringConvertible { let report: CenReport var description: String { "ReceivedCenReport: \(report)" } } extension ReceivedCenReport: Equatable { static func == (lhs: ReceivedCenReport, rhs: ReceivedCenReport) -> Bool { lhs.report == rhs.report } }
23.285714
77
0.677914
22c3a79de7369395e8517b7996aa462e00c8da6f
124
import XCTest @testable import JsonObjectConvertibleTests XCTMain([ testCase(JsonObjectConvertibleTests.allTests), ])
17.714286
51
0.814516