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
acdc9c00e3b81de7b091a58c64a48f43245501f3
1,120
// ___FILEHEADER___ // This file was generated by I-VIPER Xcode Templates // so you can design a more scalable and maintainable // design to your iOS projects, see https://github.com/fdorado985/I-VIPER // import UIKit private let cellIdentifier = "___VARIABLE_productName:identifier___Cell" class ___VARIABLE_productName:identifier___ViewController: UITableViewController { // MARK: - Properties var presenter: ___VARIABLE_productName:identifier___PresenterInterface? } // MARK: - UITableView extension ___VARIABLE_productName:identifier___ViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) // TODO: Configure cell return cell } } // MARK: - ___VARIABLE_productName:identifier___ViewInterface extension ___VARIABLE_productName:identifier___ViewController: ___VARIABLE_productName:identifier___ViewInterface {}
31.111111
116
0.798214
08fc07907b8a52e0aabac075ecd37b21ddb5c621
1,430
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation private let scale = UIScreen.main.scale infix operator >=~ func >=~ (lhs: CGFloat, rhs: CGFloat) -> Bool { return round(lhs * scale) >= round(rhs * scale) } @inline(__always) public func bma_combine(hashes: [Int]) -> Int { return hashes.reduce(0, { 31 &* $0 &+ $1.hashValue }) }
37.631579
78
0.756643
39e9ef7cd437656af5e200d6c34636434ffc107c
569
// Created by Eric Marchand on 07/06/2017. // Copyright © 2017 phimage. All rights reserved. // import Foundation extension MomXML: XMLObject { public init?(xml: XML) { var hasModel = false for child in xml.children { if let model = MomModel(xml: child) { self.model = model hasModel = true } } if !hasModel { return nil } // TODO parse root attributes } } extension MomXML { public static var orphanCallback: ((XML, Any) -> Void)? }
20.321429
59
0.543058
3a841150da8097983b48a9e748c01c0a1247b6ff
492
// // ViewController.swift // Demo // // Created by Pushy on 7/2/17. // Copyright © 2017 Pushy. 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. } }
21.391304
80
0.652439
5b75e18c1bab2bad280ce05715ced72836914a9d
884
// // ResponseHandler.swift // Flat // // Created by xuyunshi on 2021/10/22. // Copyright © 2021 agora.io. All rights reserved. // import Foundation import RxSwift protocol ResponseDataHandler { func processResponseData<T: Decodable>(_ data: Data, decoder: JSONDecoder, forResponseType: T.Type) throws -> T } extension ResponseDataHandler { func processObservableResponseData<T>(_ data: Data, decoder: JSONDecoder, forResponseType: T.Type) -> Observable<T> where T : Decodable { return .create { observer in do { let result: T = try self.processResponseData(data, decoder: decoder, forResponseType: T.self) observer.onNext(result) observer.onCompleted() } catch { observer.onError(error) } return Disposables.create() } } }
27.625
141
0.623303
e8b45f68ec5b6b635541c6a8523e5145bfddd5a9
2,115
// // Created by Yaroslav Zhurakovskiy // Copyright © 2019-2020 Yaroslav Zhurakovskiy. All rights reserved. // import Foundation import XCTest class HTTPCookieStorageStub: HTTPCookieStorage { fileprivate var cookiesStub: [HTTPCookie]? func stubCookies(with stub: [HTTPCookie]?) { cookiesStub = stub } } class HTTPCookieStorageSpy: HTTPCookieStorageStub { fileprivate var setCookies: [HTTPCookie] = [] fileprivate var deletedCookies: [HTTPCookie] = [] override func setCookie(_ cookie: HTTPCookie) { setCookies.append(cookie) } override func deleteCookie(_ cookie: HTTPCookie) { deletedCookies.append(cookie) } override var cookies: [HTTPCookie]? { return cookiesStub } } class HTTPCookieStorageMock: HTTPCookieStorageSpy { func assertSetCookieOnce(_ cookie: HTTPCookie, file: StaticString = #file, line: UInt = #line) { assertNumberOfSetCookies(1, file: file, line: line) XCTAssertEqual(setCookies[0], cookie, "Set cookie", file: file, line: line) } func assertNoSetCookies(file: StaticString = #file, line: UInt = #line) { assertNumberOfSetCookies(0, file: file, line: line) } func assertNumberOfSetCookies(_ number: Int, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(setCookies.count, number, "Number of set cookies", file: file, line: line) } } extension HTTPCookieStorageMock { func assertDeleteCookieOnce(_ cookie: HTTPCookie, file: StaticString = #file, line: UInt = #line) { assertNumberOfDeletedCookies(1, file: file, line: line) XCTAssertEqual(deletedCookies[0], cookie, "Deleted cookie", file: file, line: line) } func assertNoDeletedCookies(file: StaticString = #file, line: UInt = #line) { assertNumberOfDeletedCookies(0, file: file, line: line) } func assertNumberOfDeletedCookies(_ number: Int, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(deletedCookies.count, number, "Number of deleted cookies", file: file, line: line) } }
33.571429
105
0.682742
39e28d83c9d0d71e476327e54346c3fd9731cd24
5,410
/* See LICENSE folder for this sample’s licensing information. Abstract: Main view controller for the AR experience. */ import ARKit import SceneKit import UIKit class ViewController: UIViewController, ARSessionDelegate { // MARK: Outlets @IBOutlet var sceneView: ARSCNView! @IBOutlet weak var tabBar: UITabBar! // MARK: Properties var contentControllers: [VirtualContentType: VirtualContentController] = [:] var selectedVirtualContent: VirtualContentType! { didSet { guard oldValue != nil, oldValue != selectedVirtualContent else { return } // Remove existing content when switching types. contentControllers[oldValue]?.contentNode?.removeFromParentNode() // If there's an anchor already (switching content), get the content controller to place initial content. // Otherwise, the content controller will place it in `renderer(_:didAdd:for:)`. if let anchor = currentFaceAnchor, let node = sceneView.node(for: anchor), let newContent = selectedContentController.renderer(sceneView, nodeFor: anchor) { node.addChildNode(newContent) } } } var selectedContentController: VirtualContentController { if let controller = contentControllers[selectedVirtualContent] { return controller } else { let controller = selectedVirtualContent.makeController() contentControllers[selectedVirtualContent] = controller return controller } } var currentFaceAnchor: ARFaceAnchor? // MARK: - View Controller Life Cycle override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self sceneView.session.delegate = self sceneView.automaticallyUpdatesLighting = true // Set the initial face content. tabBar.selectedItem = tabBar.items!.first! selectedVirtualContent = VirtualContentType(rawValue: tabBar.selectedItem!.tag) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // AR experiences typically involve moving the device without // touch input for some time, so prevent auto screen dimming. UIApplication.shared.isIdleTimerDisabled = true // "Reset" to run the AR session for the first time. resetTracking() } // MARK: - ARSessionDelegate func session(_ session: ARSession, didFailWithError error: Error) { guard error is ARError else { return } let errorWithInfo = error as NSError let messages = [ errorWithInfo.localizedDescription, errorWithInfo.localizedFailureReason, errorWithInfo.localizedRecoverySuggestion ] let errorMessage = messages.compactMap({ $0 }).joined(separator: "\n") DispatchQueue.main.async { self.displayErrorMessage(title: "The AR session failed.", message: errorMessage) } } /// - Tag: ARFaceTrackingSetup func resetTracking() { guard ARFaceTrackingConfiguration.isSupported else { return } let configuration = ARFaceTrackingConfiguration() sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors]) } // MARK: - Error handling func displayErrorMessage(title: String, message: String) { // Present an alert informing about the error that has occurred. let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let restartAction = UIAlertAction(title: "Restart Session", style: .default) { _ in alertController.dismiss(animated: true, completion: nil) self.resetTracking() } alertController.addAction(restartAction) present(alertController, animated: true, completion: nil) } } extension ViewController: UITabBarDelegate { func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { guard let contentType = VirtualContentType(rawValue: item.tag) else { fatalError("unexpected virtual content tag") } selectedVirtualContent = contentType } } extension ViewController: ARSCNViewDelegate { func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { guard let faceAnchor = anchor as? ARFaceAnchor else { return } currentFaceAnchor = faceAnchor // If this is the first time with this anchor, get the controller to create content. // Otherwise (switching content), will change content when setting `selectedVirtualContent`. if node.childNodes.isEmpty, let contentNode = selectedContentController.renderer(renderer, nodeFor: faceAnchor) { node.addChildNode(contentNode) } } /// - Tag: ARFaceGeometryUpdate func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { guard anchor == currentFaceAnchor, let contentNode = selectedContentController.contentNode, contentNode.parent == node else { return } selectedContentController.renderer(renderer, didUpdate: contentNode, for: anchor) } }
36.802721
121
0.660813
463ff65e64c99781d668d8ae04dc26079786f676
267
// // UITableView+Extensions.swift // LegoKit // // Created by forkon on 2019/7/17. // import UIKit extension UITableView { func removeSeparatorOnLastCell() { tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.001)) } }
15.705882
84
0.632959
9190363378a7fd6e823e9bf9f6ae54cf530b3add
2,898
import UIKit open class AdapterSection<ItemType: DeepHashable & UniqIdentifier>: BatchUpdateSection, Hashable, SectionUniqIdentifier { // MARK: - Properties /// Идентификатор public let id: String public private(set) var rows: [ItemType] = [] // MARK: - Init public required init(with id: String) { self.id = id } // MARK: - Count /// Пустая ли секция public var isEmpty: Bool { return rows.isEmpty } /// Количество элементов в секции public var numberOfRows: Int { return rows.count } // MARK: - Update list rows /// Добавить строку в секцию /// /// - Parameter row: Добавляемая строка public func append(row: ItemType) { rows.append(row) } /// Добавить строки в секцию /// /// - Parameter rows: Добавляемые строки public func append(rows: [ItemType]) { self.rows.append(contentsOf: rows) } /// Вставка строки в секцию /// /// - Parameters: /// - row: Вставляемая строка /// - index: Индекс вставки public func insert(row: ItemType, at index: Int) { rows.insert(row, at: index) } /// Вставка строк в секцию /// /// - Parameters: /// - rows: Вставляемые строки /// - index: Начиная с какого индекса вставлять public func insert(rows: [ItemType], at index: Int) { self.rows.insert(contentsOf: rows, at: index) } /// Удалить строку по индексу /// /// - Parameter index: Индекс удаляемой строки /// - Returns: Удаленная строка @discardableResult public func remove(rowAt index: Int) -> ItemType { return rows.remove(at: index) } /// Очистить список строк public func clear() { rows = [] } // MARK: - Subscript /// Найдет и вернет строку с переданным id или nil иначе /// /// - Parameter id: Идентификатор строки public subscript(id: Int) -> ItemType? { get { return self["\(id)"] } } /// Найдет и вернет строку с переданным id или nil иначе /// /// - Parameter id: Идентификатор строки public subscript(id: String) -> ItemType? { get { for row in rows where row.id == id { return row } return nil } } // MARK: - Hashable public var hashValue: Int { return id.hashValue } public static func == (lhs: AdapterSection, rhs: AdapterSection) -> Bool { guard lhs.id == rhs.id else { return false } return true } public func equal(object: Any?) -> Bool { guard let object = object as? AdapterSection else { return false } return self == object } // MARK: - BatchUpdateSection func getRows() -> [DeepHashable] { return rows } }
24.352941
78
0.560732
645f1b4ea2f4351e4e83005156c1a96335f0d21d
4,071
// // APViewController.swift // FinalProjectFa16 // // Created by Jake Mullins on 11/23/16. // Copyright © 2016 Jake Mullins. All rights reserved. // import UIKit var up_speed_ret = Double(0.0) var down_speed_ret = Double(0.0) var start = Date() var end = Date() class APViewController: UIViewController { // MARK: Fields // url - http://138.197.30.160/outbound/TPMidna.jpg @IBOutlet weak var DownloadInfo: UILabel! @IBOutlet weak var imagedl: UIImageView! let Space_picSize = Int(763251) let BotW_picSize = Int(2891975) let TPMidna_picSize = Int(284720) //size of img being uploaded/downloaded (in BYTES) //divide by 8 when calc mbps/kbps //have a way to test final value and change unit/decimal //location for easy reading override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func runTest(_ sender: AnyObject) { //this is what will be activated by "Run Test" button DownloadInfo.text = "Loading..." //comment lines separate the core functionality from the timer stuff. //use the timer stuff when doing a syncronized download to get //the time it takes to complete func test_download() { //---------------- Double(downTest()) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: test_download) } //--------------------------------------------------------------------------------------------- /* * The only part of the code that needs to change from here on out is the below functions. * There may need to be some more functions/nested functions added to make it work properly, * but the above is already coded to handle the speed value (as a double) and put it on screen. */ func getImg() { /* let url = URL(string: "http://138.197.30.160/outbound/TPMidna.jpg") let request = URLRequest(url: url!) let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in if error != nil { print("some error!") } else { if let midna = UIImage(data: data!) { self.imagedl.image = midna } } }) task.resume() */ let url = URL(string: "http://138.197.30.160/outbound/TPMidna.jpg") let request = URLRequest(url: url!) let startTime = Date() let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in if error != nil { print("connection error or data is nill") return } else { let pic_size_mb = Double((response?.expectedContentLength)!) / 1000000.0 print(pic_size_mb) let end = Date() let runtime = Double(end.timeIntervalSince(startTime)) var u_speed = Double(pic_size_mb/runtime) u_speed = round(1000 * u_speed) / 1000 self.DownloadInfo.text = String(u_speed) + " Mbps" } } task.resume() } func downTest() -> Double { getImg() return down_speed_ret } func upTest() -> Double { return up_speed_ret } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
29.078571
115
0.562515
26bd4618f5c681d84c6a74af9381037c335405b8
2,066
// // NSToolbar.swift // WaveLabs // // Created by Vlad Gorlov on 06.06.2020. // Copyright © 2020 Vlad Gorlov. All rights reserved. // #if canImport(AppKit) import Cocoa extension NSToolbar { public class GenericDelegate: NSObject, NSToolbarDelegate { public var selectableItemIdentifiers: [NSToolbarItem.Identifier] = [] public var defaultItemIdentifiers: [NSToolbarItem.Identifier] = [] public var allowedItemIdentifiers: [NSToolbarItem.Identifier] = [] var eventHandler: ((Event) -> Void)? public var makeItemCallback: ((_ itemIdentifier: NSToolbarItem.Identifier, _ willBeInserted: Bool) -> NSToolbarItem?)? } } extension NSToolbar.GenericDelegate { enum Event { case willAddItem(item: NSToolbarItem, index: Int) case didRemoveItem(item: NSToolbarItem) } } extension NSToolbar.GenericDelegate { public func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { return makeItemCallback?(itemIdentifier, flag) } public func toolbarDefaultItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] { return defaultItemIdentifiers } public func toolbarAllowedItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] { return allowedItemIdentifiers } public func toolbarSelectableItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] { return selectableItemIdentifiers } // MARK: Notifications public func toolbarWillAddItem(_ notification: Notification) { if let toolbarItem = notification.userInfo?["item"] as? NSToolbarItem, let index = notification.userInfo?["newIndex"] as? Int { eventHandler?(.willAddItem(item: toolbarItem, index: index)) } } public func toolbarDidRemoveItem(_ notification: Notification) { if let toolbarItem = notification.userInfo?["item"] as? NSToolbarItem { eventHandler?(.didRemoveItem(item: toolbarItem)) } } } #endif
30.382353
124
0.713456
f4c40d1e471eed0b069ab043ebe9301f6b8056e5
1,213
// // LogBuilderTests.swift // LinnaTests // // Created by Suita Fujino on 2018/11/14. // Copyright © 2018 Suita Fujino. All rights reserved. // @testable import Linna import XCTest class LogBuilderTests: XCTestCase { private let testObjects = ["HogeMessage"] private let testTags: Set<String> = ["HOGE"] private let testFileName = "HogeFile" private let testFunction = "HogeFunction" private let testLine: Int = 1_212 private let logBuilder = LogBuilder( logFormatter: DefaultLogFormatter(pattern: .detailed), dateFormatter: DefaultDateFormatter().formatter ) // MARK: - Test cases func testBuild() { guard let actual = logBuilder.build( objects: testObjects, level: .info, tags: testTags, caller: Caller( filePath: testFileName, functionName: testFunction, lineNumber: testLine) ) else { XCTFail("Unexpected nil.") return } let expected = "[INFO] [\(testFileName)::\(testFunction):\(testLine)] \(testObjects[0])" XCTAssert(actual.contains(expected)) } }
25.808511
96
0.594394
f81ea9eee1343c17011dcc23137d7ecb1d64700f
117
import XCTest import SwiftVLCTests var tests = [XCTestCaseEntry]() tests += SwiftVLCTests.allTests() XCTMain(tests)
16.714286
33
0.786325
9bc572b1e55d7cc89c2e21cfdf9a493759d73e17
1,152
// https://github.com/Quick/Quick import Quick import Nimble import Empyr class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { xit("can do maths") { expect(1) == 2 } xit("can read") { expect("number") == "string" } xit("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.588235
60
0.356771
0eb5d6e6c4a38a608c5c68510069d3f7787e625d
2,303
// // SceneDelegate.swift // MyProject19 // // Created by Viktor Khotimchenko on 2021-02-08. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.45283
147
0.714286
9050c8e323d3ac6e46f66179697f2324fe0f7738
529
// // RestApiRequest.swift // RestApiClient // // Created by Daniel Illescas Romero on 16/01/2019. // Copyright © 2019 Daniel Illescas Romero. All rights reserved. // import Foundation protocol RestApiClientQueryRequest { associatedtype Response: Decodable var resourceName: String { get } var extraResourcesPath: String { get } var queryDictionary: [String: Encodable] { get } } extension RestApiClientQueryRequest { var extraResourcesPath: String { return "" } } protocol RestApiClientBodyRequest: Encodable {}
21.16
65
0.754253
01535502349b1445157f6b82a8f178f339dc3129
511
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "libextobjc", platforms: [ .iOS(.v9), .tvOS(.v9), .watchOS(.v3) ], products: [ .library( name: "libextobjc", targets: ["libextobjc"] ), ], targets: [ .target( name: "libextobjc" ), .testTarget( name: "libextobjc-tests", dependencies: ["libextobjc"] ) ] )
18.25
40
0.444227
2253379c1487237e201d4fd25a4be1caff6aa1d4
1,796
import Foundation public typealias Byte = UInt8 public protocol PackProtocol { func pack() throws -> [Byte] static func unpack(_ bytes: ArraySlice<Byte>) throws -> Self } public enum PackError: Error { case notPackable } public enum UnpackError: Error { case incorrectNumberOfBytes case incorrectValue case unexpectedByteMarker case notImplementedYet } public enum PackProtocolError: Error { case notPossible } public extension PackProtocol { static func unpack(_ bytes: [Byte]) throws -> Self { return try unpack(bytes[0..<bytes.count]) } func asUInt64() -> UInt64? { if let i = self as? UInt64 { return i } if let i = self as? UInt32 { return UInt64(i) } if let i = self as? UInt16 { return UInt64(i) } if let i = self as? UInt8 { return UInt64(i) } if let i = self as? Int64 { if i < 0 { return nil } else { return UInt64(i) } } if let i = self as? Int32 { if i < 0 { return nil } else { return UInt64(i) } } if let i = self as? Int16 { if i < 0 { return nil } else { return UInt64(i) } } if let i = self as? Int8 { if i < 0 { return nil } else { return UInt64(i) } } return nil } } public extension Int { init?(_ value: PackProtocol) { if let n = value.asUInt64() { self.init(n) } else { return nil } } }
18.905263
64
0.466036
6476032ac4f966669e667ca1d009f5fc32b17f77
2,383
// // MovieTest.swift // Upcoming MoviesTests // // Created by Leonardo Baptista on 9/3/18. // import XCTest import OHHTTPStubs import Nimble import ObjectMapper @testable import Upcoming_Movies class MovieTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func mappedMovie() -> Movie { let json: [String: Any] = [ "vote_count": 96, "id": 399360, "video": false, "vote_average": 5.7, "title": "Mocked Movie Title", "popularity": 74.429, "poster_path": "/afdZAIcAQscziqVtsEoh2PwsYTW.jpg", "original_language": "en", "original_title": "Alpha", "backdrop_path": "/nKMeTdm72LQ756Eq20uTjF1zDXu.jpg", "adult": false, "overview": "After a hunting expedition goes awry, a young caveman struggles against the elements to find his way home.", "release_date": "2018-08-17", "genre_ids": [12, 18, 12376278] ] let mapper = Map(mappingType: .fromJSON, JSON: json) return Movie(map: mapper)! } func testName() { let movie = mappedMovie() expect(movie.name).to(equal("Mocked Movie Title")) } func testImageURLPath() { let movie = mappedMovie() expect(movie.imageURLPath).to(equal("https://image.tmdb.org/t/p/w500/afdZAIcAQscziqVtsEoh2PwsYTW.jpg")) } func testThumbURLPath() { let movie = mappedMovie() expect(movie.thumbURLPath).to(equal("https://image.tmdb.org/t/p/w92/afdZAIcAQscziqVtsEoh2PwsYTW.jpg")) } func testReleaseDate() { let movie = mappedMovie() let formatter = DateFormatter(withFormat: "yyyy-MM-dd", locale: "en") let textDate = formatter.string(from: movie.releaseDate) expect(textDate).to(equal("2018-08-17")) } func testOverview() { let movie = mappedMovie() expect(movie.overview).to(contain("a young caveman struggles")) } func testGenres() { let movie = mappedMovie() expect(movie.genres).to(equal("Adventure, Drama")) } func testReleaseDateAsText() { let movie = mappedMovie() expect(movie.releaseDateAsText()).to(contain("Aug 17, 2018")) } }
28.710843
133
0.588334
014eb4f1dc2cc5b5e46f31bd2cae61454b716cce
8,535
// // ViewController.swift // MASegmentControl-Example // // Created by Alok Choudhary on 12/30/19. // Copyright © 2019 Alok Choudhary. All rights reserved. // import UIKit import MASegmentedControl class ViewController: UIViewController { private var colorsViewModel: GenericViewModel<UIColor>? /** Circular design */ @IBOutlet weak var imagesSegmentedControl: MASegmentedControl! { didSet { //Set this booleans to adapt control imagesSegmentedControl.fillEqually = false imagesSegmentedControl.buttonsWithDynamicImages = true imagesSegmentedControl.roundedControl = true let images = ContentDataSource.imageItems() imagesSegmentedControl.setSegmentedWith(items: images) imagesSegmentedControl.padding = 2 imagesSegmentedControl.thumbViewColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1) } } /** When control is having text */ @IBOutlet weak var textSegmentedControl: MASegmentedControl! { didSet { //Set this booleans to adapt control textSegmentedControl.itemsWithText = true textSegmentedControl.fillEqually = true textSegmentedControl.roundedControl = true let strings = ContentDataSource.textItems() textSegmentedControl.setSegmentedWith(items: strings) textSegmentedControl.padding = 2 textSegmentedControl.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) textSegmentedControl.selectedTextColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) textSegmentedControl.thumbViewColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1) textSegmentedControl.titlesFont = UIFont(name: "OpenSans-Semibold", size: 14) } } /** Another example with icons square */ @IBOutlet weak var iconsSegmentedControl: MASegmentedControl! { didSet { //Set this booleans to adapt control iconsSegmentedControl.itemsWithText = false iconsSegmentedControl.fillEqually = false iconsSegmentedControl.roundedControl = false let icons = ContentDataSource.iconItems() iconsSegmentedControl.setSegmentedWith(items: icons) iconsSegmentedControl.padding = 2 iconsSegmentedControl.thumbViewColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1) iconsSegmentedControl.buttonColorForNormal = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1) iconsSegmentedControl.buttonColorForSelected = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) } } /** Another example with text square */ @IBOutlet weak var textSquareSegmentedControl: MASegmentedControl! { didSet { //Set this booleans to adapt control textSquareSegmentedControl.itemsWithText = true textSquareSegmentedControl.fillEqually = true let strings = ContentDataSource.textItems() textSquareSegmentedControl.setSegmentedWith(items: strings) textSquareSegmentedControl.padding = 2 textSquareSegmentedControl.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) textSquareSegmentedControl.selectedTextColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) textSquareSegmentedControl.thumbViewColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1) } } /** Segmented control customized as youtue segment control */ @IBOutlet weak var youtubeLikeSegmentedControl: MASegmentedControl! { didSet { //Set this booleans to adapt control youtubeLikeSegmentedControl.itemsWithText = false youtubeLikeSegmentedControl.bottomLineThumbView = true youtubeLikeSegmentedControl.fillEqually = true let icons = ContentDataSource.iconItems() youtubeLikeSegmentedControl.setSegmentedWith(items: icons) youtubeLikeSegmentedControl.padding = 2 youtubeLikeSegmentedControl.thumbViewColor = #colorLiteral(red: 0.9411764706, green: 0.2549019608, blue: 0.2020437331, alpha: 1) youtubeLikeSegmentedControl.buttonColorForNormal = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1) youtubeLikeSegmentedControl.buttonColorForSelected = #colorLiteral(red: 0.9411764706, green: 0.2549019608, blue: 0.2020437331, alpha: 1) } } /** Segmented control customized with Text highlight and no thumb view */ @IBOutlet weak var hiddenThumbViewSegmentedControl: MASegmentedControl! { didSet { //Set this booleans to adapt control hiddenThumbViewSegmentedControl.itemsWithText = true hiddenThumbViewSegmentedControl.fillEqually = true hiddenThumbViewSegmentedControl.thumbViewHidden = true let strings = ContentDataSource.textItems() hiddenThumbViewSegmentedControl.setSegmentedWith(items: strings) hiddenThumbViewSegmentedControl.padding = 2 hiddenThumbViewSegmentedControl.textColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1) hiddenThumbViewSegmentedControl.selectedTextColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) } } /** Segmented control customized with Text highlight and thumb view */ @IBOutlet weak var linearThumbViewSegmentedControl: MASegmentedControl! { didSet { //Set this booleans to adapt control linearThumbViewSegmentedControl.itemsWithText = true linearThumbViewSegmentedControl.fillEqually = true linearThumbViewSegmentedControl.bottomLineThumbView = true let strings = ContentDataSource.options() linearThumbViewSegmentedControl.setSegmentedWith(items: strings) linearThumbViewSegmentedControl.padding = 2 linearThumbViewSegmentedControl.textColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1) linearThumbViewSegmentedControl.selectedTextColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) linearThumbViewSegmentedControl.thumbViewColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1) } } // MARK: Type 8 @IBOutlet weak var colorsSegmentedControl: MASegmentedControl! { didSet { //Set this booleans to adapt control colorsSegmentedControl.itemsWithDynamicColor = true colorsSegmentedControl.fillEqually = false colorsSegmentedControl.roundedControl = true let colors = ContentDataSource.colorItems() colorsSegmentedControl.setSegmentedWith(items: colors) colorsSegmentedControl.imageForItemWithDynamicColors = UIImage(named: "circle") colorsSegmentedControl.padding = 2 colorsSegmentedControl.thumbViewColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) colorsSegmentedControl.animationDuration = 0.2 colorsViewModel = GenericViewModel<UIColor>(items: colors) } } @IBAction func changrBackgroundColor(_ sender: MASegmentedControl) { let backGroundColor = colorsViewModel?.getItem(at: sender.selectedSegmentIndex) UIView.animate(withDuration: 0.3) { self.view.backgroundColor = backGroundColor } } override func viewDidLoad() { super.viewDidLoad() let backGroundColor = colorsViewModel?.getItem(at: 0) UIView.animate(withDuration: 0.3) { self.view.backgroundColor = backGroundColor } // Do any additional setup after loading the view. } }
44.222798
148
0.661746
e658da71f4044991d24659066ddd00e5fa1aa088
964
/* * Confess It * * This app is provided as-is with no warranty or guarantee * See the license file under "Confess It" -> "License" -> * "License.txt" * * Copyright © 2019 Brick Water Studios * */ import UIKit public extension UIColor { var stringValue: String? { if let comp = self.cgColor.components { return "[\(comp[0]), \(comp[1]), \(comp[2]), \(comp[3])]" } else { return nil } } convenience init(from string: String) { let filteredString = string.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "") let comp = filteredString.components(separatedBy: ", ") self.init(red: CGFloat((comp[0] as NSString).floatValue), green: CGFloat((comp[1] as NSString).floatValue), blue: CGFloat((comp[2] as NSString).floatValue), alpha: CGFloat((comp[3] as NSString).floatValue)) } }
30.125
115
0.576763
5b9300cacdaea697d23a123e1b3b3bb370fd3313
1,408
// // AppDelegate.swift // TCRDemo // // Created by Jakub Turek on 12/11/2019. // Copyright © 2019 ELP. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.052632
179
0.746449
1a8bac6ecf6b6ecd23b9d7c125f6c56ce59adf20
703
// // main.swift // SHListGen // // Created by Yusuke Hosonuma on 2020/03/27. // import Foundation import SHListGenLib let generateCount = 20 let output = """ // // This source is automatically generated. // \(generateFunction(count: generateCount)) \(generateStruct(count: generateCount)) """ let outputPath = "Sources/SHList/SHList.swift" let currentPath = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) let flattenSwiftPath = currentPath.appendingPathComponent(outputPath) do { try output.write(to: flattenSwiftPath, atomically: true, encoding: String.Encoding.utf8) print("Finished, source file written at \(outputPath) 🎉") } catch { print("Error: \(error)") }
21.30303
92
0.73542
5bf87799e4aae56bad4ed8bb162dc8e52f8bfabe
1,196
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "ThinPlateSplineTransform", platforms: [.macOS(.v10_13), .iOS(.v10), .watchOS(.v5), .tvOS(.v10)], products: [ .library( name: "ThinPlateSplineTransform", targets: ["ThinPlateSplineTransform"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "ThinPlateSplineTransform", dependencies: ["ThinPlateSplineTransformCore"]), .target( name: "ThinPlateSplineTransformCore", dependencies: []), .testTarget( name: "ThinPlateSplineTransformTests", dependencies: ["ThinPlateSplineTransform"]), ] )
37.375
122
0.631271
1d5987925270fcd11ba394cc963401f288324ab3
1,767
// // BackButton.swift // ios-doctor // // Created by Jun Ho Hong on 1/27/20. // Copyright © 2020 Jun Ho Hong. All rights reserved. // import Foundation class BackButton: TouchableOpacityView { lazy var arrowView: UIImageView = self.createBackArrow() lazy var titleLabel: UILabel = self.createTitleLabel() let title: String init(title: String) { self.title = title super.init(frame: CGRect.zero) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { self.isUserInteractionEnabled = true titleLabel.text = title self.backgroundColor = Colors.clear layout() } } extension BackButton { func layout() { layoutArrow() layoutTitleLabel() } func layoutArrow() { self.addSubview(arrowView) arrowView.snp.makeConstraints { (make) in make.top.left.bottom.equalToSuperview() make.width.equalTo(10) make.height.equalTo(15) } } func layoutTitleLabel() { self.addSubview(titleLabel) titleLabel.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.left.equalTo(arrowView.snp.right).offset(20) make.right.equalToSuperview() } } } extension BackButton { func createBackArrow() -> UIImageView { let view = UIImageView(image: UIImage(named: "backArrow")) view.contentMode = .scaleAspectFill return view } func createTitleLabel() -> UILabel { let label = UILabel() label.textColor = Colors.white label.font = Fonts.semiBold(14) return label } }
25.242857
66
0.606112
081f4ba2b4c611f9c66f91a67fd33a21172fbce6
1,456
// // QSCatalogPresenter.swift // zhuishushenqi // // Created yung on 2017/4/21. // Copyright © 2017年 QS. All rights reserved. // // Template generated by Juanpe Catalán @JuanpeCMiOS // class ZSVoiceCategoryHeaderView: UITableViewHeaderFooterView { override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupSubviews() { imageView = UIImageView(frame: CGRect.zero) contentView.addSubview(imageView) titleLabel = UILabel(frame: CGRect.zero) titleLabel.textColor = UIColor.black titleLabel.textAlignment = .left titleLabel.font = UIFont.systemFont(ofSize: 17) contentView.addSubview(titleLabel) } override func layoutSubviews() { super.layoutSubviews() guard let image = imageView.image else { titleLabel.frame = CGRect(x: 20, y: 0, width: bounds.width, height: bounds.height) return } imageView.frame = CGRect(x: 20, y: bounds.height/2 - image.size.height/2, width: image.size.width, height: image.size.height) titleLabel.frame = CGRect(x: imageView.frame.maxX + 10, y: 0, width: bounds.width, height: bounds.height) } var imageView:UIImageView! var titleLabel:UILabel! }
30.978723
133
0.652473
acb46c85bb41b0bec46da5fca96c7cc1fdc4be68
1,544
// // QuickReplyViewSizeCalculator.swift // RichMessageKit // // Created by Shivam Pokhriyal on 21/01/19. // import Foundation class SuggestedReplyViewSizeCalculator { func rowHeight(model: SuggestedReplyMessage, maxWidth: CGFloat, font _: UIFont) -> CGFloat { var width: CGFloat = 0 var totalHeight: CGFloat = 0 var size = CGSize(width: 0, height: 0) var prevHeight: CGFloat = 0 for suggestion in model.suggestion { let title = suggestion.title if suggestion.type == .link { let image = UIImage(named: "link", in: Bundle.richMessageKit, compatibleWith: nil) size = CurvedImageButton.buttonSize(text: title, image: image, maxWidth: maxWidth) } else { size = CurvedImageButton.buttonSize(text: title, maxWidth: maxWidth) } let currWidth = size.width + 10 // Button Padding if currWidth > maxWidth { totalHeight += size.height + prevHeight + 10 // 10 padding between buttons width = 0 prevHeight = 0 continue } if width + currWidth > maxWidth { totalHeight += prevHeight + 10 // 10 padding between buttons width = currWidth prevHeight = size.height } else { width += currWidth prevHeight = size.height } } totalHeight += prevHeight return totalHeight } }
33.565217
98
0.561528
72e84f894ece3b79cbc839e61c7fd6f6897b333f
462
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck var b{struct B:A protocol A{ typealias e:Collection typealias e
35.538462
79
0.761905
1e7d1bd6d9e385c69133d4a0af167b73ca41c883
1,715
/**************************************************************************** * Copyright 2019, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ import Foundation /// Simple DataStore using key value. This abstracts away the datastore layer. The datastore should take into account synchronization. public protocol OPTDataStore { /// getItem - get an item by key. /// - Parameter forKey: key to lookup datastore value. /// - Returns: the value saved or nil func getItem(forKey: String) -> Any? /// saveItem - save the item to the datastore. /// - Parameter forKey: key to save value /// - Parameter value: value to save. func saveItem(forKey: String, value: Any) }
55.322581
135
0.489796
de1d991f1963e2d0ca595fbfdfccfebfd22bb4dc
4,379
// // MainSearchView.swift // LoveQiYi // // Created by mac on 2019/7/17. // Copyright © 2019 bingdaohuoshan. All rights reserved. // import UIKit class MainSearchView: UIView { private lazy var searchBar: UISearchBar = { let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: screenWidth - 30, height: 34)) searchBar.placeholder = "老湿,请多多 “指” 教" searchBar.changeFont(UIFont.systemFont(ofSize: 13)) searchBar.searchBarStyle = .default searchBar.backgroundColor = UIColor.clear searchBar.backgroundImage = UIImage() searchBar.changeTextFieldBackgroundColor(UIColor(r: 56, g: 56, b: 59, a: 0.99)) return searchBar }() private lazy var searchFakeBtn: UIButton = { let button = UIButton(type: .custom) button.addTarget(self, action: #selector(searchViewBtnClick), for: .touchUpInside) return button }() private lazy var histroyBtn: UIButton = { let button = UIButton(type: .custom) button.setImage(UIImage(named: "mainHisIcon"), for: .normal) button.addTarget(self, action: #selector(searchViewBtnClick), for: .touchUpInside) return button }() private lazy var typeBtn: UIButton = { let button = UIButton(type: .custom) button.setImage(UIImage(named: "doubleArrow"), for: .normal) button.setTitle("最新", for: .normal) button.setTitle("最热", for: .selected) button.titleLabel?.font = UIFont.systemFont(ofSize: 12) button.addTarget(self, action: #selector(searchViewBtnClick), for: .touchUpInside) button.backgroundColor = UIColor(r: 56, g: 56, b: 59, a: 0.99) button.layer.cornerRadius = 17 button.layer.masksToBounds = true button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0) button.isHidden = true return button }() /// 是否是推荐 var isModuleVc: Bool = true { didSet { typeBtn.isHidden = isModuleVc histroyBtn.isHidden = !isModuleVc searchBar.snp.updateConstraints { (make) in make.trailing.equalTo(isModuleVc ? -47 : -72) } } } var actionHandler:((_ actionId: Int) -> Void)? var sort: String = HotListApi.kSort_new override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = kBarColor addSubview(searchBar) addSubview(searchFakeBtn) addSubview(histroyBtn) addSubview(typeBtn) layoutPageSubviews() if let searchField: UITextField = searchBar.value(forKey: "searchField") as? UITextField { searchField.layer.cornerRadius = 17.0 searchField.layer.masksToBounds = true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func searchViewBtnClick(_ sender: UIButton) { if sender == searchFakeBtn { actionHandler?(1) } if sender == histroyBtn { actionHandler?(2) } if sender == typeBtn { typeBtn.isSelected = !typeBtn.isSelected sort = typeBtn.isSelected ? HotListApi.kSort_hot : HotListApi.kSort_new actionHandler?(3) } } } private extension MainSearchView { func layoutPageSubviews() { layoutHistroyBtn() layoutTypeBtn() layoutSearchBar() layoutSearchBtn() } func layoutSearchBar() { searchBar.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.trailing.equalTo(-47) make.leading.equalTo(5) make.height.equalTo(34) } } func layoutSearchBtn() { searchFakeBtn.snp.makeConstraints { (make) in make.edges.equalTo(searchBar) } } func layoutHistroyBtn() { histroyBtn.snp.makeConstraints { (make) in make.trailing.equalTo(-8) make.centerY.equalToSuperview() make.height.width.equalTo(34) } } func layoutTypeBtn() { typeBtn.snp.makeConstraints { (make) in make.trailing.equalTo(-8) make.centerY.equalToSuperview() make.height.equalTo(34) make.width.equalTo(62) } } }
32.437037
99
0.603791
fc9c7e55d35bffd9cf33eaa287c91b17baba89f6
1,753
// // UtilityUnitTests.swift // InfiniteScrollTests // // Created by Anirudh Das on 7/8/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import XCTest import SwiftyJSON @testable import InfiniteScroll class UtilityUnitTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } func testGenerateQueryString() { let paramDict: [String: String] = [ "key": ServerConfiguration.apiKey, "image_type": ServerConfiguration.imageType, "page": "1", "per_page": "\(ServerConfiguration.imagesPerPage)" ] let queryString = ServerConfiguration.apiBaseUrl + Utility.generateQueryString(paramDict) XCTAssertEqual(queryString, "https://pixabay.com/api?page=1&per_page=20&key=9484956-87df9bae333acc29060cb2e77&image_type=photo") } func testURLEncodingString() { let queryString = "https://pixabay.com/api?page=1&per_page=20&key=9484956-87df9bae333acc29060cb2e77& image_type=photo" let urlEncodedString = Utility.addURLEncoding(queryString) XCTAssertEqual(urlEncodedString, "https://pixabay.com/api?page=1&per_page=20&key=9484956-87df9bae333acc29060cb2e77&%20image_type=photo") } func testDictionarytoJSONString() { let dict: [String: Any] = ["key1": 1234, "key2": "Hello"] let jsonString = dict.toJSONString() XCTAssertNotEqual(jsonString, "Not a valid JSON") let json = JSON(parseJSON: jsonString) XCTAssertEqual(json["key1"].int, dict["key1"] as? Int) XCTAssertEqual(json["key2"].string, dict["key2"] as? String) } }
37.297872
144
0.673132
6750c1fa4556dcaacac4db3689fcc6c59644999f
964
// // IOS8SwiftCocoapodsTutorialTests.swift // IOS8SwiftCocoapodsTutorialTests // // Created by Arthur Knopper on 23/06/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit import XCTest class IOS8SwiftCocoapodsTutorialTests: 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.measureBlock() { // Put the code you want to measure the time of here. } } }
26.054054
111
0.639004
18ff1546bd2a9223e9c390636404c04a7a179c32
3,916
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import NIO import NIOExtras class FixedLengthFrameDecoderTest: XCTestCase { public func testDecodeIfFewerBytesAreSent() throws { let channel = EmbeddedChannel() let frameLength = 8 try channel.pipeline.add(handler: FixedLengthFrameDecoder(frameLength: frameLength)).wait() var buffer = channel.allocator.buffer(capacity: frameLength) buffer.write(string: "xxxx") XCTAssertFalse(try channel.writeInbound(buffer)) XCTAssertTrue(try channel.writeInbound(buffer)) var outputBuffer: ByteBuffer? = channel.readInbound() XCTAssertEqual("xxxxxxxx", outputBuffer?.readString(length: frameLength)) XCTAssertFalse(try channel.finish()) } public func testDecodeIfMoreBytesAreSent() throws { let channel = EmbeddedChannel() let frameLength = 8 try channel.pipeline.add(handler: FixedLengthFrameDecoder(frameLength: frameLength)).wait() var buffer = channel.allocator.buffer(capacity: 19) buffer.write(string: "xxxxxxxxaaaaaaaabbb") XCTAssertTrue(try channel.writeInbound(buffer)) var outputBuffer: ByteBuffer? = channel.readInbound() XCTAssertEqual("xxxxxxxx", outputBuffer?.readString(length: frameLength)) outputBuffer = channel.readInbound() XCTAssertEqual("aaaaaaaa", outputBuffer?.readString(length: frameLength)) outputBuffer = channel.readInbound() XCTAssertNil(outputBuffer?.readString(length: frameLength)) XCTAssertFalse(try channel.finish()) } public func testRemoveHandlerWhenBufferIsNotEmpty() throws { let channel = EmbeddedChannel() let frameLength = 8 let handler = FixedLengthFrameDecoder(frameLength: frameLength) try channel.pipeline.add(handler: handler).wait() var buffer = channel.allocator.buffer(capacity: 15) buffer.write(string: "xxxxxxxxxxxxxxx") XCTAssertTrue(try channel.writeInbound(buffer)) var outputBuffer: ByteBuffer? = channel.readInbound() XCTAssertEqual("xxxxxxxx", outputBuffer?.readString(length: frameLength)) _ = try channel.pipeline.remove(handler: handler).wait() XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in guard let error = error as? NIOExtrasErrors.LeftOverBytesError else { XCTFail() return } var expectedBuffer = channel.allocator.buffer(capacity: 7) expectedBuffer.write(string: "xxxxxxx") XCTAssertEqual(error.leftOverBytes, expectedBuffer) } XCTAssertFalse(try channel.finish()) } public func testRemoveHandlerWhenBufferIsEmpty() throws { let channel = EmbeddedChannel() let frameLength = 8 let handler = FixedLengthFrameDecoder(frameLength: frameLength) try channel.pipeline.add(handler: handler).wait() var buffer = channel.allocator.buffer(capacity: 6) buffer.write(string: "xxxxxxxx") XCTAssertTrue(try channel.writeInbound(buffer)) var outputBuffer: ByteBuffer? = channel.readInbound() XCTAssertEqual("xxxxxxxx", outputBuffer?.readString(length: frameLength)) _ = try channel.pipeline.remove(handler: handler).wait() XCTAssertNoThrow(try channel.throwIfErrorCaught()) XCTAssertFalse(try channel.finish()) } }
37.295238
99
0.664198
1c093718e6bb1939957f2ec4545cfbc80744f363
661
// swift-tools-version:4.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Gherkin", products: [ .library(name: "Gherkin", targets: ["Gherkin"]), ], dependencies: [ .package(url: "https://github.com/nicklockwood/Consumer.git", .upToNextMinor(from: "0.3.4")), ], targets: [ .target( name: "Gherkin", dependencies: ["Consumer"]), .testTarget( name: "GherkinTests", dependencies: ["Gherkin"]), ], swiftLanguageVersions: [.v4_2, .version("5")] )
27.541667
101
0.590015
1d0c41af1e183fbe2dc026a7d6af0e29b52403d8
2,728
/* The MIT License * * Copyright © 2020 NBCO YooMoney LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit // MARK: - Styles extension ActivityIndicatorView { enum Styles { /// Light style /// /// transparent background color, default activity indicator static let light = InternalStyle(name: "ActivityIndicatorView.Styles.light") { (view: ActivityIndicatorView) in view.setStyles(UIView.Styles.transparent) view.activity.setStyles(ActivityIndicator.Styles.default) } /// Dark style /// /// semiTransparent background color, default activity indicator static let dark = InternalStyle(name: "ActivityIndicatorView.Styles.dark") { (view: ActivityIndicatorView) in view.setStyles(UIView.Styles.semiTransparent) view.activity.setStyles(ActivityIndicator.Styles.default) } /// Heavy light style /// /// gray background color, default activity indicator static let heavyLight = InternalStyle( name: "ActivityIndicatorView.Styles.heavyLight") { (view: ActivityIndicatorView) in view.setStyles(UIView.Styles.grayBackground) view.activity.setStyles(ActivityIndicator.Styles.default) } /// Cloudy style /// /// cararra 50% alpha background color, default activity indicator static let cloudy = InternalStyle(name: "ActivityIndicatorView.cloudy") { (view: ActivityIndicatorView) in view.backgroundColor = UIColor.cararra.withAlphaComponent(0.5) view.activity.setStyles(ActivityIndicator.Styles.default) } } }
40.716418
119
0.69978
090cf014a33464a43212775db933c44998a76d2a
3,751
// // TSTransationDetailVC.swift // ThinkSNS + // // Created by GorCat on 2017/6/1. // Copyright © 2017年 ZhiYiCX. All rights reserved. // // 交易详情信息 视图控制器 import UIKit import Kingfisher class TSWalletTransationDetailVC: UITableViewController { /// 交易结果 @IBOutlet weak var labelForResult: TSLabel! /// 交易金额 @IBOutlet weak var labelForMoney: TSLabel! /// 交易人类型(付款人 or 收款人) @IBOutlet weak var labelForUserType: TSLabel! /// 头像 @IBOutlet weak var buttonForAvatar: AvatarView! /// 用户名 @IBOutlet weak var labelForUsername: TSLabel! /// 交易说明 @IBOutlet weak var labelForDescription: TSLabel! /// 交易账户 @IBOutlet weak var labelForAccount: TSLabel! /// 交易时间 @IBOutlet weak var labelForTime: TSLabel! /// 视图数据模型 var viewModel: TSWalletTransationDetailModel? // MARK: - Lifecycle class func vc() -> TSWalletTransationDetailVC { let sb = UIStoryboard(name: "TSWalletTransationDetailVC", bundle: nil) let vc = sb.instantiateInitialViewController() as! TSWalletTransationDetailVC return vc } override func viewDidLoad() { super.viewDidLoad() setUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let model = viewModel else { return } setInfo(model: model) } // MARK: - Custom user interface func setUI() { title = "显示_账单详情".localized tableView.estimatedRowHeight = 50 tableView.allowsSelection = false } // MARK: - Public func setInfo(model: TSWalletTransationDetailModel) { /// 交易结果 labelForResult.text = model.resultString /// 交易金额 labelForMoney.text = model.moneyString /// 付款人 if let userIdentity = model.userIdentity { /// 交易人类型(付款人 or 收款人) labelForUserType.text = model.userType /// 交易人信息 TSDataQueueManager.share.userInfoQueue.getData(userIds: [userIdentity], isQueryDB: false, isMust: false, complete: { [weak self] (datas: Array<TSUserInfoObject>?, _) in guard let weakSelf = self, let data = datas?.first else { return } // TODO: UserInfoModelUpdate - 用户数据模型更改,这里需同步更改 /// 头像 weakSelf.buttonForAvatar.avatarPlaceholderType = AvatarView.PlaceholderType(sexNumber: data.sex) let avatarInfo = AvatarInfo() avatarInfo.avatarURL = TSUtil.praseTSNetFileUrl(netFile: data.avatar) avatarInfo.verifiedIcon = data.verified?.icon ?? "" avatarInfo.verifiedType = data.verified?.type ?? "" weakSelf.buttonForAvatar.avatarInfo = avatarInfo /// 用户名 weakSelf.labelForUsername.text = data.name }) } /// 交易说明 labelForDescription.text = model.descriptionString /// 交易账户 labelForAccount.text = model.accountString /// 交易时间 labelForTime.text = model.dateString } // MARK: - Delegate // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let model = viewModel else { return UITableViewAutomaticDimension } // 1.如果是用户交易和系统交易,显示收付款人栏,隐藏交易账号栏 if model.accountString.isEmpty { if indexPath.row == 2 { return 0 } } // 2.如果是支付宝交易,显示交易账号栏,隐藏收付款人栏 if model.userIdentity == nil { if indexPath.row == 0 { return 0 } } return UITableViewAutomaticDimension } }
30.745902
180
0.603039
ff4c376abd6521473badb2e0e877df0a8616d5b3
1,245
import Foundation import HTTP import libc /// Servers files from the supplied public directory /// on not found errors. public final class FileMiddleware: Middleware { private var publicDir: String private let loader = DataFile() private let chunkSize: Int public init(publicDir: String, chunkSize: Int? = nil) { // Remove last "/" from the publicDir if present, so we can directly append uri path from the request. self.publicDir = publicDir.finished(with: "/") self.chunkSize = chunkSize ?? 32_768 // 2^15 } public func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { return try next.respond(to: request) } catch RouterError.missingRoute { // Check in file system var path = request.uri.path guard !path.contains("../") else { throw HTTP.Status.forbidden } if path.hasPrefix("/") { path = String(path.characters.dropFirst()) } let filePath = publicDir + path let ifNoneMatch = request.headers["If-None-Match"] return try Response(filePath: filePath, ifNoneMatch: ifNoneMatch, chunkSize: chunkSize) } } }
35.571429
110
0.628916
4b24b32ac64413497bf7452a6b04a610ac9c8901
12,407
// // Unsplash.swift // Papr // // Created by Joan Disho on 31.10.17. // Copyright © 2017 Joan Disho. All rights reserved. // import Foundation import TinyNetworking enum Unsplash { /// Get the user's profile case getMe /// Update the current user’s profile case updateMe( username: String?, firstName: String?, lastName: String?, email: String?, url: String?, location: String?, bio: String?, instagramUsername: String?) /// Get a user’s public profile case userProfile( username: String, width: Int?, height: Int?) /// Get a user’s portfolio link case userPortfolio(username: String) /// List a user’s photos case userPhotos( username: String, page: Int?, perPage: Int?, orderBy: OrderBy?, showStats: Bool?, resolution: Resolution?, quantity: Int?) /// List a user’s liked photos case userLikedPhotos( username: String, page: Int?, perPage: Int?, orderBy: OrderBy?) /// List a user’s collections case userCollections( username:String, page: Int?, perPage: Int?) /// Get a user’s statistics case userStatistics( username: String, resolution: Resolution?, quantity: Int?) /// Get the list of all photos case photos( page: Int?, perPage: Int?, orderBy: OrderBy?) /// Retrieve a single photo. case photo( id: String, width: Int?, height: Int?, rect: [Int]?) /// Get a random photo case randomPhoto( collections: [String]?, isFeatured: Bool?, username: String?, query: String?, width: Int?, height: Int?, orientation: Orientation?, count: Int?) /// Get a photo’s statistics case photoStatistics( id: String, resolution: Resolution?, quantity: Int?) /// Retrieve a single photo’s download link case photoDownloadLink(id: String) /// Like a photo on behalf of the logged-in user case likePhoto(id: String) /// Remove a user’s like of a photo. case unlikePhoto(id: String) /// Get photo results for a query case searchPhotos( query: String, page: Int?, perPage: Int?, collections: [String]?, orientation: Orientation?) /// Get collection results for a query case searchCollections( query: String, page: Int?, perPage: Int?) /// Get user results for a query case searchUsers( query: String, page: Int?, perPage: Int?) /// Get a list of all collections case collections( page: Int?, perPage: Int?) /// Get a list of featured collections case featuredCollections( page: Int?, perPage: Int?) /// Retrieve a collection case collection(id: Int) /// Retrieve a related collection case relatedCollections(id: Int) /// Retrieve a collection’s photos case collectionPhotos( id: Int, page: Int?, perPage: Int?) /// Create a new collection case createCollection( title: String, description: String?, isPrivate: Bool?) /// Update an existing collection case updateCollection( id: Int, title: String?, description: String?, isPrivate: Bool?) /// Delete an existing collection case deleteCollection(id: Int) /// Add a photo to a collection case addPhotoToCollection( collectionID: Int, photoID: String) /// Remove a photo from a collection case removePhotoFromCollection( collectionID: Int, photoID: String) // MARK: - TODO: Support these cases // id(required) // case updatePhoto(String) } extension Unsplash: Resource { var baseURL: URL { guard let url = URL(string: "https://api.unsplash.com") else { fatalError("FAILED: https://api.unsplash.com") } return url } var endpoint: Endpoint { switch self { case .getMe: return .get(path: "/me") case .updateMe: return .put(path: "/me") case let .userProfile(param): return .get(path: "/users/\(param.username)") case let .userPortfolio(username): return .get(path: "/users/\(username)/portfolio") case let .userPhotos(param): return .get(path: "/users/\(param.username)/photos") case let .userLikedPhotos(param): return .get(path: "/users/\(param.username)/likes") case let .userCollections(param): return .get(path: "/users/\(param.username)/collections") case let .userStatistics(param): return .get(path: "/users/\(param.username)/statistics") case .photos: return .get(path: "/photos") case let .photo(param): return .get(path: "/photos/\(param.id)") case .randomPhoto: return .get(path: "/photos/random") case let .photoStatistics(param): return .get(path: "/photos/\(param.id)/statistics") case let .photoDownloadLink(id): return .get(path: "/photos/\(id)/download") case let .likePhoto(id): return .post(path: "/photos/\(id)/like") case let .unlikePhoto(id): return .delete(path: "/photos/\(id)/like") case .searchPhotos: return .get(path: "/search/photos") case .searchCollections: return .get(path: "/search/collections") case .searchUsers: return .get(path: "/search/users") case .collections: return .get(path: "/collections") case .createCollection: return .post(path: "/collections") case .featuredCollections: return .get(path: "/collections/featured") case let .collection(id): return .get(path: "/collections/\(id)") case let .collectionPhotos(params): return .get(path: "/collections/\(params.id)/photos") case let .relatedCollections(id): return .get(path: "/collections/\(id)/related") case let .updateCollection(params): return .put(path: "/collections\(params.id)") case let .deleteCollection(id): return .delete(path: "/collections/\(id)") case let .addPhotoToCollection(params): return .post(path: "/collections/\(params.collectionID)/add") case let .removePhotoFromCollection(params): return .delete(path: "/collections/\(params.collectionID)/remove") } } var task: Task { let noBracketsAndLiteralBoolEncoding = URLEncoding( arrayEncoding: .noBrackets, boolEncoding: .literal ) switch self { case let .updateMe(value): var params: [String: Any] = [:] params["username"] = value.username params["first_name"] = value.firstName params["last_name"] = value.lastName params["email"] = value.email params["url"] = value.url params["location"] = value.location params["bio"] = value.bio params["instagram_username"] = value.instagramUsername return .requestWithParameters(params, encoding: URLEncoding()) case let .userProfile(value): var params: [String: Any] = [:] params["w"] = value.width params["h"] = value.height return .requestWithParameters(params, encoding: URLEncoding()) case let .userPhotos(value): var params: [String: Any] = [:] params["page"] = value.page params["per_page"] = value.perPage params["order_by"] = value.orderBy params["stats"] = value.showStats params["resolution"] = value.resolution?.rawValue params["quantity"] = value.quantity return .requestWithParameters(params, encoding: URLEncoding()) case let .userLikedPhotos(_, pageNumber, photosPerPage, orderBy), let .photos(pageNumber, photosPerPage, orderBy): var params: [String: Any] = [:] params["page"] = pageNumber params["per_page"] = photosPerPage params["order_by"] = orderBy return .requestWithParameters(params, encoding: URLEncoding()) case let .photo(value): var params: [String: Any] = [:] params["w"] = value.width params["h"] = value.height params["rect"] = value.rect return .requestWithParameters(params, encoding: noBracketsAndLiteralBoolEncoding) case let .userStatistics(_, resolution, quantity), let .photoStatistics(_, resolution, quantity): var params: [String: Any] = [:] params["resolution"] = resolution?.rawValue params["quantity"] = quantity return .requestWithParameters(params, encoding: URLEncoding()) case let .randomPhoto(value): var params: [String: Any] = [:] params["collections"] = value.collections params["featured"] = value.isFeatured params["username"] = value.username params["query"] = value.query params["w"] = value.width params["h"] = value.height params["orientation"] = value.orientation?.rawValue params["count"] = value.count return .requestWithParameters(params, encoding: noBracketsAndLiteralBoolEncoding) case let .userCollections(_, pageNumber, photosPerPage), let .collections(pageNumber, photosPerPage), let .featuredCollections(pageNumber, photosPerPage), let .collectionPhotos(_, pageNumber, photosPerPage): var params: [String: Any] = [:] params["page"] = pageNumber params["per_page"] = photosPerPage return .requestWithParameters(params, encoding: URLEncoding()) case let .searchCollections(value), let .searchUsers(value): var params: [String: Any] = [:] params["query"] = value.query params["page"] = value.page params["per_page"] = value.perPage return .requestWithParameters(params, encoding: URLEncoding()) case let .searchPhotos(value): var params: [String: Any] = [:] params["query"] = value.query params["page"] = value.page params["per_page"] = value.perPage params["collections"] = value.collections params["orientation"] = value.orientation?.rawValue return .requestWithParameters(params,encoding: noBracketsAndLiteralBoolEncoding) case let .createCollection(value): var params: [String: Any] = [:] params["title"] = value.title params["description"] = value.description params["private"] = value.isPrivate return .requestWithParameters(params, encoding: URLEncoding()) case let .updateCollection(value): var params: [String: Any] = [:] params["title"] = value.title params["description"] = value.description params["private"] = value.isPrivate return .requestWithParameters(params, encoding: URLEncoding()) case let .addPhotoToCollection(value), let .removePhotoFromCollection(value): var params: [String: Any] = [:] params["photo_id"] = value.photoID return .requestWithParameters(params, encoding: URLEncoding()) default: return .requestWithParameters([:], encoding: URLEncoding()) } } var headers: [String : String] { let clientID = Papr.Unsplash.clientID guard let token = UserDefaults.standard.string(forKey: clientID) else { return ["Authorization": "Client-ID \(clientID)"] } return ["Authorization": "Bearer \(token)"] } var cachePolicy: URLRequest.CachePolicy { return .useProtocolCachePolicy } }
30.634568
93
0.574676
f870074d4026c0c6832ad546f0844b7ec24edb42
360
// // TOTP.swift // Cidaas // // Created by ganesh on 30/07/18. // Copyright © 2018 Cidaas. All rights reserved. // import Foundation public class TOTP : Codable { public var name: String = "" public var issuer: String = "" public var timer_count: String = "" public var totp_string: String = "" public init() { } }
17.142857
49
0.594444
d660dec70cb31e34eba7f1c41c5290c8d7f485c7
60
// // File.swift // CarouselExample // import Foundation
8.571429
19
0.666667
efd4f8a18d8877c47fdfdefc5b498f0e9c1d667a
1,404
// // douyuUITests.swift // douyuUITests // // Created by Sober Man on 2020/12/8. // import XCTest class douyuUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
32.651163
182
0.653134
1a95a4584c9d9a6fd1de49fd8141c1a65becc78e
929
// // Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. // // // 1 2 3 // 4 5 6 // 7 8 9 //BigO: time: O(MN + Z(M+N)) space: O(Z) Z - Number of zeros public func zeroMatrix(matrix: [[Int]]) -> [[Int]] { var zeroMatrix = matrix var rows = [Int]() var columns = [Int]() //find the zeros in the matix for i in 0..<matrix.count { //rows for j in 0..<matrix[0].count { //columns if matrix[i][j] == 0 { rows.append(i) columns.append(j) } } } //nullify the rows for i in rows { for j in 0..<matrix[0].count { zeroMatrix[i][j] = 0 } } //nullify the columns for i in columns { for j in 0..<matrix.count { zeroMatrix[j][i] = 0 } } return zeroMatrix }
22.658537
122
0.482239
bb4a2a369b5a1488c665351965eb691c68c437b9
256
// // APITemplate.swift // ModelSynchroLibrary // // Created by Jonathan Samudio on 2/1/19. // import Foundation struct APITemplate: Codable { // MARK: - Public Properties let name: String let apiRequests: [APIRequestTemplate] }
15.058824
42
0.664063
ddef80386b343e1deedebeb5dd92fc4c2e6f9f15
5,688
// // DashboardController.swift // Chromatic // // Created by Lakr Aream on 2021/8/10. // Copyright © 2021 Lakr Aream. All rights reserved. // import AptRepository import UIKit class DashboardController: UICollectionViewController, UICollectionViewDelegateFlowLayout { var dataSource = [InterfaceBridge.DashboardDataSection]() let refreshControl = UIRefreshControl() let packageCellID = UUID().uuidString let moreCellID = UUID().uuidString let generalHeaderID = UUID().uuidString var collectionViewFrameCache: CGSize? var collectionViewCellSizeCache = CGSize() var cellLimit = 16 let searchBar: UIView = SearchBarButton() init() { let flowLayout = UICollectionViewFlowLayout() flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) flowLayout.scrollDirection = UICollectionView.ScrollDirection.vertical flowLayout.minimumInteritemSpacing = 0.0 super.init(collectionViewLayout: flowLayout) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError() } override func viewDidLoad() { super.viewDidLoad() collectionView.clipsToBounds = false collectionView.contentInset = UIEdgeInsets(top: 50, left: 20, bottom: 50, right: 20) collectionView.dataSource = self collectionView.delegate = self collectionView.alwaysBounceVertical = true collectionView.backgroundColor = .clear collectionView.register(LXDashboardSupplementHeaderCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: generalHeaderID) collectionView.register(PackageCollectionCell.self, forCellWithReuseIdentifier: packageCellID) collectionView.register(LXDashboardMoreCell.self, forCellWithReuseIdentifier: moreCellID) (searchBar as? SearchBarButton)?.onTouch = { [weak self] in self?.searchButton() } collectionView.addSubview(searchBar) searchBar.snp.makeConstraints { x in x.left.equalTo(view).offset(20) x.right.equalTo(view).offset(-20) x.bottom.equalTo(collectionView.snp.top) x.height.equalTo(40) } refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged) collectionView.addSubview(refreshControl) reloadDataSource(wait: true) NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: RepositoryCenter.metadataUpdate, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: RepositoryCenter.registrationUpdate, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: PackageCenter.packageRecordChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: .PackageCollectionChanged, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc func searchButton() { let target = SearchController() present(next: target) DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { target.searchController.searchBar.becomeFirstResponder() } } } private class SearchBarButton: UIView { var iconView: UIImageView = { let view = UIImageView() view.image = .fluent(.search24Filled) view.tintColor = .gray return view }() var placeholder = UILabel() var coverButton = UIButton() var onTouch: (() -> Void)? @available(*, unavailable) required init?(coder _: NSCoder) { fatalError() } required init() { super.init(frame: CGRect()) backgroundColor = .gray.withAlphaComponent(0.1) layer.cornerRadius = 8 let gap = 12 iconView.contentMode = .scaleAspectFit addSubview(iconView) iconView.snp.makeConstraints { x in x.centerY.equalTo(self.snp.centerY) x.left.equalTo(self.snp.left).offset(gap) x.height.equalTo(25) x.width.equalTo(30) } placeholder.text = NSLocalizedString("SEARCH", comment: "Search") placeholder.textColor = .gray placeholder.font = .roundedFont(ofSize: 18, weight: .semibold) addSubview(placeholder) placeholder.snp.makeConstraints { x in x.centerY.equalTo(self.snp.centerY) x.left.equalTo(iconView.snp.right).offset(gap) x.top.equalTo(self.snp.top).offset(gap / 2) x.width.equalTo(233) } addSubview(coverButton) coverButton.snp.makeConstraints { x in x.edges.equalToSuperview() } coverButton.addTarget(self, action: #selector(touched), for: .touchUpInside) } @objc private func touched() { puddingAnimate() onTouch?() } }
34.682927
102
0.591245
76a629597c75f124e610f8878ce68ea5da7f9c43
2,868
// // PersonPayloadTests.swift // ApptentiveUnitTests // // Created by Frank Schmitt on 2/4/21. // Copyright © 2021 Apptentive, Inc. All rights reserved. // import XCTest @testable import ApptentiveKit class PersonPayloadTests: XCTestCase { var testPayload: Payload! let propertyListEncoder = PropertyListEncoder() let propertyListDecoder = PropertyListDecoder() let jsonEncoder = JSONEncoder() let jsonDecoder = JSONDecoder() override func setUp() { self.jsonEncoder.dateEncodingStrategy = .secondsSince1970 self.jsonDecoder.dateDecodingStrategy = .secondsSince1970 var person = Person() person.name = "Testy McTestface" person.emailAddress = "[email protected]" person.mParticleID = "abc123" person.customData["string"] = "foo" person.customData["number"] = 42 person.customData["bool"] = true self.testPayload = Payload(wrapping: person) super.setUp() } func testSerialization() throws { let encodedPayloadData = try self.propertyListEncoder.encode(self.testPayload) let decodedPayload = try self.propertyListDecoder.decode(Payload.self, from: encodedPayloadData) XCTAssertEqual(self.testPayload, decodedPayload) } func testEncoding() throws { let actualEncodedContent = try jsonEncoder.encode(self.testPayload.jsonObject) let actualDecodedContent = try jsonDecoder.decode(Payload.JSONObject.self, from: actualEncodedContent) let expectedEncodedContent = """ { "person": { "name": "Testy McTestface", "email": "[email protected]", "mparticle_id": "abc123", "custom_data": { "string": "foo", "number": 42, "bool": true }, "nonce": "abc123", "client_created_at": 1600904569, "client_created_at_utc_offset": 0, "label": "local#app#Foo bar" } } """.data(using: .utf8)! let expectedDecodedContent = try jsonDecoder.decode(Payload.JSONObject.self, from: expectedEncodedContent) XCTAssertNotNil(actualDecodedContent.nonce) XCTAssertNotNil(expectedDecodedContent.nonce) XCTAssertGreaterThan(actualDecodedContent.creationDate, Date(timeIntervalSince1970: 1_600_904_569)) XCTAssertEqual(expectedDecodedContent.creationDate, Date(timeIntervalSince1970: 1_600_904_569)) XCTAssertNotNil(actualDecodedContent.creationUTCOffset) XCTAssertNotNil(expectedDecodedContent.creationUTCOffset) XCTAssertEqual(expectedDecodedContent.specializedJSONObject, actualDecodedContent.specializedJSONObject) } }
34.554217
114
0.642957
396e6ebb05f7a481068c596d81ee185fe053f2d3
342
// // PrimaryKeyColumnProtocol.swift // RepoDB // // Created by Groot on 11.09.2020. // Copyright © 2020 K. All rights reserved. // import GRDB public protocol PrimaryKeyColumnProtocol: TableColumnProtocol { var autoincremented: Bool { get set } func save(to container: inout PersistenceContainer, wiht key: String) }
20.117647
73
0.707602
c17d883c94554e2260b9fccbb6e3224a6e5fb464
5,076
// // TCCProfileImporterTests.swift // PPPC UtilityTests // // MIT License // // Copyright (c) 2019 Jamf Software // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import XCTest @testable import PPPC_Utility class TCCProfileImporterTests: XCTestCase { func testBrokenSignedTCCProfile() { let tccProfileImporter = TCCProfileImporter() let resourceURL = getResourceProfile(fileName: "TestTCCProfileSigned-Broken") tccProfileImporter.decodeTCCProfile(fileUrl: resourceURL) { tccProfileResult in switch tccProfileResult { case .success: XCTFail("Broken Signed Profile, it shouldn't be success") case .failure(let tccProfileError): XCTAssertTrue(tccProfileError.localizedDescription.contains("The given data was not a valid property list.")) } } } func testEmptyContentTCCProfile() { let tccProfileImporter = TCCProfileImporter() let resourceURL = getResourceProfile(fileName: "TestTCCUnsignedProfile-Empty") let expectedTCCProfileError = TCCProfileImportError.invalidProfileFile(description: "PayloadContent") tccProfileImporter.decodeTCCProfile(fileUrl: resourceURL) { tccProfileResult in switch tccProfileResult { case .success: XCTFail("Empty Content, it shouldn't be success") case .failure(let tccProfileError): XCTAssertEqual(tccProfileError.localizedDescription, expectedTCCProfileError.localizedDescription) } } } func testCorrectUnsignedProfileContentData() { let tccProfileImporter = TCCProfileImporter() let resourceURL = getResourceProfile(fileName: "TestTCCUnsignedProfile") tccProfileImporter.decodeTCCProfile(fileUrl: resourceURL) { tccProfileResult in switch tccProfileResult { case .success(let tccProfile): XCTAssertNotNil(tccProfile.content) XCTAssertNotNil(tccProfile.content[0].services) case .failure(let tccProfileError): XCTFail("Unable to read tccProfile \(tccProfileError.localizedDescription)") } } } func testCorrectUnsignedProfileContentDataAllLowercase() { let tccProfileImporter = TCCProfileImporter() let resourceURL = getResourceProfile(fileName: "TestTCCUnsignedProfile-allLower") tccProfileImporter.decodeTCCProfile(fileUrl: resourceURL) { tccProfileResult in switch tccProfileResult { case .success(let tccProfile): XCTAssertNotNil(tccProfile.content) XCTAssertNotNil(tccProfile.content[0].services) case .failure(let tccProfileError): XCTFail("Unable to read tccProfile \(tccProfileError.localizedDescription)") } } } func testBrokenUnsignedProfile() { let tccProfileImporter = TCCProfileImporter() let resourceURL = getResourceProfile(fileName: "TestTCCUnsignedProfile-Broken") let expectedTCCProfileError = TCCProfileImportError.invalidProfileFile(description: "The given data was not a valid property list.") tccProfileImporter.decodeTCCProfile(fileUrl: resourceURL) { tccProfileResult in switch tccProfileResult { case .success: XCTFail("Broken Unsigned Profile, it shouldn't be success") case .failure(let tccProfileError): XCTAssertEqual(tccProfileError.localizedDescription, expectedTCCProfileError.localizedDescription) } } } private func getResourceProfile(fileName: String) -> URL { let testBundle = Bundle(for: type(of: self)) guard let resourceURL = testBundle.url(forResource: fileName, withExtension: "mobileconfig") else { XCTFail("Resource file should exists") return URL(fileURLWithPath: "invalidPath") } return resourceURL } }
40.608
140
0.693065
76313a23015d6ab8cfdeac179bf6bd7b22dd3a84
8,102
// // Copyright (c) 2019 Adyen B.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// A component that provides a form for card payments. public final class CardComponent: PaymentComponent, PresentableComponent { /// The card payment method. public let paymentMethod: PaymentMethod /// The delegate of the component. public weak var delegate: PaymentComponentDelegate? /// The supported card types. public var supportedCardTypes: [CardType] /// Indicates if the holder name should be collected in the card form. public var showsHolderName = false /// Initializes the card component. /// /// - Parameters: /// - paymentMethod: The card payment method. /// - publicKey: The key used for encrypting card data. public init(paymentMethod: CardPaymentMethod, publicKey: String) { self.paymentMethod = paymentMethod self.publicKey = publicKey self.supportedCardTypes = paymentMethod.brands.compactMap(CardType.init) } /// Initializes the card component for stored cards. /// /// - Parameters: /// - paymentMethod: The stored card payment method. /// - publicKey: The key used for encrypting card data. public init(paymentMethod: StoredCardPaymentMethod, publicKey: String) { self.paymentMethod = paymentMethod self.publicKey = publicKey self.supportedCardTypes = [] } // MARK: - Presentable Component Protocol /// :nodoc: public lazy var viewController: UIViewController = { Analytics.sendEvent(component: paymentMethod.type, flavor: _isDropIn ? .dropin : .components, environment: environment) if let storedCardAlertManager = storedCardAlertManager { return storedCardAlertManager.alertController } else { return ComponentViewController(rootViewController: formViewController, cancelButtonHandler: didSelectCancelButton) } }() /// :nodoc: public var preferredPresentationMode: PresentableComponentPresentationMode { if storedCardAlertManager != nil { return .present } else { return .push } } /// :nodoc: public func stopLoading(withSuccess success: Bool, completion: (() -> Void)?) { footerItem.showsActivityIndicator.value = false completion?() } // MARK: - Private private let publicKey: String private var encryptedCard: CardEncryptor.EncryptedCard { let card = CardEncryptor.Card(number: numberItem.value, securityCode: securityCodeItem.value, expiryMonth: expiryDateItem.value[0...1], expiryYear: "20" + expiryDateItem.value[2...3]) return CardEncryptor.encryptedCard(for: card, publicKey: publicKey) } private func didSelectSubmitButton() { guard formViewController.validate() else { return } footerItem.showsActivityIndicator.value = true let details = CardDetails(paymentMethod: paymentMethod as! CardPaymentMethod, // swiftlint:disable:this force_cast encryptedCard: encryptedCard, holderName: holderNameItem?.value) let data = PaymentComponentData(paymentMethodDetails: details, storePaymentMethod: storeDetailsItem.value) delegate?.didSubmit(data, from: self) } private lazy var didSelectCancelButton: (() -> Void) = { [weak self] in guard let self = self else { return } self.delegate?.didFail(with: ComponentError.cancelled, from: self) } // MARK: - Stored Card private lazy var storedCardAlertManager: StoredCardAlertManager? = { guard let paymentMethod = paymentMethod as? StoredCardPaymentMethod else { return nil } let manager = StoredCardAlertManager(paymentMethod: paymentMethod, publicKey: publicKey, amount: payment?.amount) manager.completionHandler = { [weak self] result in guard let self = self else { return } switch result { case let .success(details): self.delegate?.didSubmit(PaymentComponentData(paymentMethodDetails: details), from: self) case let .failure(error): self.delegate?.didFail(with: error, from: self) } } return manager }() // MARK: - Form Items private lazy var formViewController: FormViewController = { let formViewController = FormViewController() let headerItem = FormHeaderItem() headerItem.title = paymentMethod.name formViewController.append(headerItem) formViewController.append(numberItem, using: FormCardNumberItemView.self) let splitTextItem = FormSplitTextItem(items: [expiryDateItem, securityCodeItem]) formViewController.append(splitTextItem) if let holderNameItem = holderNameItem { formViewController.append(holderNameItem) } formViewController.append(storeDetailsItem) formViewController.append(footerItem) return formViewController }() private lazy var numberItem: FormCardNumberItem = { FormCardNumberItem(supportedCardTypes: supportedCardTypes, environment: environment) }() private lazy var expiryDateItem: FormTextItem = { let expiryDateItem = FormTextItem() expiryDateItem.title = ADYLocalizedString("adyen.card.expiryItem.title") expiryDateItem.placeholder = ADYLocalizedString("adyen.card.expiryItem.placeholder") expiryDateItem.formatter = CardExpiryDateFormatter() expiryDateItem.validator = CardExpiryDateValidator() expiryDateItem.validationFailureMessage = ADYLocalizedString("adyen.card.expiryItem.invalid") expiryDateItem.keyboardType = .numberPad return expiryDateItem }() private lazy var securityCodeItem: FormTextItem = { let securityCodeItem = FormTextItem() securityCodeItem.title = ADYLocalizedString("adyen.card.cvcItem.title") securityCodeItem.placeholder = ADYLocalizedString("adyen.card.cvcItem.placeholder") securityCodeItem.formatter = CardSecurityCodeFormatter() securityCodeItem.validator = CardSecurityCodeValidator() securityCodeItem.validationFailureMessage = ADYLocalizedString("adyen.card.cvcItem.invalid") securityCodeItem.keyboardType = .numberPad return securityCodeItem }() private lazy var holderNameItem: FormTextItem? = { guard showsHolderName else { return nil } let holderNameItem = FormTextItem() holderNameItem.title = ADYLocalizedString("adyen.card.nameItem.title") holderNameItem.placeholder = ADYLocalizedString("adyen.card.nameItem.placeholder") holderNameItem.validator = LengthValidator(minimumLength: 2) holderNameItem.validationFailureMessage = ADYLocalizedString("adyen.card.nameItem.invalid") holderNameItem.autocapitalizationType = .words return holderNameItem }() private lazy var storeDetailsItem: FormSwitchItem = { let storeDetailsItem = FormSwitchItem() storeDetailsItem.title = ADYLocalizedString("adyen.card.storeDetailsButton") return storeDetailsItem }() private lazy var footerItem: FormFooterItem = { let footerItem = FormFooterItem() footerItem.submitButtonTitle = ADYLocalizedSubmitButtonTitle(with: payment?.amount) footerItem.submitButtonSelectionHandler = { [weak self] in self?.didSelectSubmitButton() } return footerItem }() }
38.216981
127
0.651814
e58c70ccc0151eaa3453eab323ffff9433113bc5
306
// // ApplicationTheme.swift // StyleGuide // // Created by Shubham Agrawal on 28/10/17. // import Foundation import SwiftyJSON extension StyleGuide { public class ApplicationTheme: ViewTheme { override init(fromJSON json: JSON) { super.init(fromJSON: json) } } }
16.105263
46
0.647059
761f7d44a50e38c5aa179749e93dfef512753ed4
2,558
/* Copyright 2019 APPNEXUS INC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest class ANInterstitialAdViewTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. continueAfterFailure = false } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testRTBInterstitial() { let adObject = AdObject(adType: "Interstitial", accessibilityIdentifier: PlacementTestConstants.InterstitialAd.testRTBInterstitial, placement: "19065996") let interstitialAdObject = InterstitialAdObject(closeDelay: 5, adObject: adObject) let interstitialAdObjectString = AdObjectModel.encodeInterstitialObject(adObject: interstitialAdObject) let app = XCUIApplication() app.launchArguments.append(PlacementTestConstants.InterstitialAd.testRTBInterstitial) app.launchArguments.append(interstitialAdObjectString) app.launch() // Asserts Ad Elemnts once ad Did Receive let interstitialAd = app.children(matching: .window).element(boundBy: 0).children(matching: .other).element.children(matching: .other).element wait(for: interstitialAd, timeout: 10) XCGlobal.screenshotWithTitle(title: PlacementTestConstants.InterstitialAd.testRTBInterstitial) XCTAssertEqual(interstitialAd.exists, true) wait(10) let closeButton = app.buttons["interstitial flat closebox"] XCTAssertEqual(closeButton.exists, true) closeButton.tap() wait(1) let element = app.otherElements.containing(.navigationBar, identifier:"Interstitial Ad").children(matching: .other).element.children(matching: .other).element.children(matching: .other).element // No Ad on Screen XCTAssertEqual(element.exists, true) wait(2) } }
33.657895
201
0.705629
b931a79c4b59d2319de8d0c0f506c9504aaaca1c
997
// // Transform3DDragTests.swift // Transform3DDragTests // // Created by Xue Yang on 2017/6/26. // Copyright © 2017年 Xue Yang. All rights reserved. // import XCTest @testable import Transform3DDrag class Transform3DDragTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.945946
111
0.641926
9c2fa5e4b0a01043d50515a375adc64f73543bed
637
// // URLRequest+Extensions.swift // GoodNews // // Created by Kas Song on 1/10/21. // import Foundation import RxSwift import RxCocoa struct Resource<T: Decodable> { let url: URL } extension URLRequest { static func load<T>(resource: Resource<T>) -> Observable<T?> { return Observable.from([resource.url]) .flatMap { url -> Observable<Data> in let request = URLRequest(url: url) return URLSession.shared.rx.data(request: request) }.map { data -> T? in return try? JSONDecoder().decode(T.self, from: data) }.asObservable() } }
23.592593
68
0.594976
717c571e6a738ae484b3a1c00e9b10c2821b2e90
3,970
// // NavigationActions.swift // // Copyright © 2022 ALTEN. All rights reserved. // import Foundation import SwiftUI @MainActor protocol NavigationActionsInjectable: AnyObject { func createViewController<Destination: NavigableView>(_ view: Destination) -> UIHostingController<AnyNavigableView> func createPresentViewController<Destination: NavigableView>(_ view: Destination) -> UIHostingController<AnyNavigableView> func injectNavigationAction(_ hostingController: UIHostingController<AnyNavigableView>) -> UIHostingController<AnyNavigableView> func injectPresentAction(_ hostingController: UIHostingController<AnyNavigableView>) -> UIHostingController<AnyNavigableView> } /** Contiene las funcionalidades de navegación que se pueden realizar. Al usar `ALTENNavigationView` se inyecta como `Environment` una instancia de esta clase que se usará para realizar las acciones de navegación modales o de tipo push */ public final class NavigationActions { /// Acciones de navegación de tipo push. Existe si se navega a una vista embebida en `ALTENNavigationView` public private(set) var pushActions: NavigationPushActions? /// Acciones de navegación de tipo modal public var modalActions: NavigationModalActions { let modalAction: NavigationModalActionsImpl if let viewController = viewController { modalAction = NavigationModalActionsImpl(viewController: viewController) } else if let viewController = pushActions?.navigationController?.topViewController { modalAction = NavigationModalActionsImpl(viewController: viewController) } else { modalAction = NavigationModalActionsImpl(viewController: UIApplication.topViewController) } modalAction.navigationInjectable = self return modalAction } private weak var viewController: UIViewController? = nil init(pushActions: NavigationPushActionsImpl?) { pushActions?.navigationInjectable = self self.pushActions = pushActions } init(viewController: UIViewController?) { self.viewController = viewController self.pushActions = nil } } extension NavigationActions: NavigationActionsInjectable { func createViewController<Destination: NavigableView>(_ view: Destination) -> UIHostingController<AnyNavigableView> { let navigationViewController = UIHostingController(rootView: view.navigationActions(self)) return navigationViewController } func createPresentViewController<Destination: NavigableView>(_ view: Destination) -> UIHostingController<AnyNavigableView> { let viewController = UIHostingController(rootView: view.eraseToAnyNavigableView()) viewController.rootView = viewController.rootView.navigationActions(NavigationActions(viewController: viewController)) return viewController } func injectNavigationAction(_ hostingController: UIHostingController<AnyNavigableView>) -> UIHostingController<AnyNavigableView> { hostingController.rootView = hostingController.rootView.navigationActions(self) return hostingController } func injectPresentAction(_ hostingController: UIHostingController<AnyNavigableView>) -> UIHostingController<AnyNavigableView> { hostingController.rootView = hostingController.rootView.navigationActions(NavigationActions(viewController: hostingController)) return hostingController } } fileprivate extension UIApplication { static var topViewController: UIViewController { let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first if var topController = keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } return topController } return UIViewController() } }
44.606742
232
0.753652
3843da96114ebd361d785fae55f3cd751314e3c0
19,510
// // LICustomActionSheetVC.swift // LICustomActionSheet // // Created by Vishal on 04/04/19. // Copyright © 2019 Logistic Infotech Pvt Ltd. All rights reserved. // import UIKit public enum ActionSheetType: Int { case regular, sectionWise public func description() -> String { switch self { case .regular: return "regular" case .sectionWise: return "sectionWise" } } } @objc public protocol ConfigureActionSheet { @objc optional func didSelectedActionView(_ objCustomAction : LICustomActionSheetVC, isEmojiSelected:Bool ,index:IndexPath, selectedActionIndex:Int) } public class LICustomActionSheetVC: UIViewController,UIGestureRecognizerDelegate { //MARK: - Class Variables //MARK: - var arrProfilePicture:NSMutableArray! var arrEmoji:NSMutableArray? = NSMutableArray() var arrOtherAction:NSMutableArray! public var actionSheetType:ActionSheetType! var delegate:ConfigureActionSheet! public var selected_indexPath:IndexPath? public var cancelButtonTextColor:UIColor? public var actionButtonTextColor:UIColor? @IBOutlet weak var tblActionSheet: UITableView! @IBOutlet weak var consTblActionSheetHeight: NSLayoutConstraint! var isForProfile:Bool = false var selected_indexPath2:IndexPath? var containerView:UIView? var containerViewYPos:Int = 0 //MARK: - IBOutlets //MARK: - @IBOutlet weak var viewBackground: UIView! @IBOutlet weak var constTblActionSheetBottomSpace: NSLayoutConstraint! public static func create() -> LICustomActionSheetVC { let podBundle = Bundle(for: LICustomActionSheetVC.self) return UIStoryboard(name: "LICustomActionSheetSB", bundle: podBundle).instantiateViewController(withIdentifier: "LICustomActionSheetVC") as! LICustomActionSheetVC // return UIStoryboard(name: "LICustomActionSheetSB", bundle: nil).instantiateViewController(withIdentifier: "LICustomActionSheetVC") as! LICustomActionSheetVC } //MARK: - ViewController Life Cycle //MARK: - public func loadActionSheet(fromView:UIViewController!, arrEmoji:NSMutableArray?, arrActionData:NSMutableArray?,type:ActionSheetType){ self.actionSheetType = type self.arrOtherAction = arrActionData self.arrEmoji = arrEmoji self.delegate = (fromView as! ConfigureActionSheet) self.modalPresentationStyle = .overCurrentContext fromView.present(self, animated: false, completion: nil) } override public func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self, action: #selector(self.tappedOutside)) self.viewBackground.addGestureRecognizer(tap) if(cancelButtonTextColor == nil){ cancelButtonTextColor = UIColor.gray } if(actionButtonTextColor == nil) { actionButtonTextColor = UIColor.init(red: 234/255, green: 38/255, blue: 132/255, alpha: 1) } } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.settingAppearance() viewBackground.isHidden = false Timer.scheduledTimer(timeInterval: 0, target: self, selector: #selector(showMenu), userInfo: nil, repeats: false) } public override func viewWillDisappear(_ animated: Bool) { } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override public func viewDidAppear(_ animated: Bool) { } func animateBackgroundView(isVisible:Bool){ if isVisible{ viewBackground.alpha = 0.0 UIView.animate(withDuration: 0.0, delay: 0.0, options: .curveEaseInOut, animations: { self.viewBackground.alpha = 1.0 }, completion: nil) }else{ viewBackground.alpha = 1.0 UIView.animate(withDuration: 0.0, delay: 0.0, options: .curveEaseInOut, animations: { self.viewBackground.alpha = 0.0 }, completion: nil) } } /// Setting appearance func settingAppearance() { self.tblActionSheet.separatorStyle = .none tblActionSheet.estimatedRowHeight = 60 tblActionSheet.rowHeight = UITableView.automaticDimension } /// Show menu with animation @objc func showMenu() { UIView.animate(withDuration: 0.0, delay: 0, options: .transitionCurlUp, animations: { self.constTblActionSheetBottomSpace.constant = 0 self.view.layoutIfNeeded() }) { (success) in self.view.bringSubviewToFront(self.tblActionSheet) } } @objc func tappedOutside() { self.animateBackgroundView(isVisible: false) UIView.animate(withDuration: 0.3, animations: { self.tblActionSheet.frame = CGRect(x: self.tblActionSheet.frame.origin.x, y: UIScreen.main.bounds.height , width: self.tblActionSheet.frame.width, height: self.tblActionSheet.frame.height) self.constTblActionSheetBottomSpace.constant = -self.consTblActionSheetHeight.constant }) { (success) in self.dismiss(animated: false, completion: nil) } } // Gesture Delegate private func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if (touch.view?.isDescendant(of: tblActionSheet))! { return false } return true } // Action Method } extension LICustomActionSheetVC:DismissViewDelegate{ func onClickDismiss() { self.animateBackgroundView(isVisible: false) UIView.animate(withDuration: 0.3, animations: { self.tblActionSheet.frame = CGRect(x: self.tblActionSheet.frame.origin.x, y: UIScreen.main.bounds.height , width: self.tblActionSheet.frame.width, height: self.tblActionSheet.frame.height) self.constTblActionSheetBottomSpace.constant = -self.consTblActionSheetHeight.constant }) { (success) in self.dismiss(animated: false, completion: nil) } } } extension LICustomActionSheetVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let profilePicCell = collectionView.dequeueReusableCell(withReuseIdentifier: "LIProfilePicCell", for: indexPath) as! LIProfilePicCell profilePicCell.imgViewProfilePic.image = UIImage.init(named: "\(arrEmoji?.object(at: indexPath.row) as! String)") if DeviceType.IS_IPHONE_6P{ profilePicCell.viewSelectedProfile.layer.cornerRadius = (profilePicCell.imgViewProfilePic.image?.size.width)!/1.8 } if selected_indexPath != nil { if selected_indexPath == indexPath { profilePicCell.imgViewSelectedProfile.isHidden = false profilePicCell.viewSelectedProfile.isHidden = false } else { profilePicCell.imgViewSelectedProfile.isHidden = true profilePicCell.viewSelectedProfile.isHidden = true } } else { profilePicCell.imgViewSelectedProfile.isHidden = true profilePicCell.viewSelectedProfile.isHidden = true } // configureCell(cell: profilePicCell, forItemAt: indexPath) return profilePicCell } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (arrEmoji?.count)! } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: CGFloat((collectionView.frame.size.width / 3) - 16), height: CGFloat((collectionView.frame.size.width / 3) - 16)) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0.0; } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 13.0; } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 13.0, left: 13.0, bottom: 13.0, right: 13.0) } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.animateBackgroundView(isVisible: false) UIView.animate(withDuration: 0.3, animations: { self.tblActionSheet.frame = CGRect(x: self.tblActionSheet.frame.origin.x, y: UIScreen.main.bounds.height , width: self.tblActionSheet.frame.width, height: self.tblActionSheet.frame.height) self.constTblActionSheetBottomSpace.constant = -self.consTblActionSheetHeight.constant }) { (success) in self.dismiss(animated: false, completion: { self.selected_indexPath = indexPath self.tblActionSheet.reloadData() if (self.delegate != nil) { self.delegate.didSelectedActionView?(self, isEmojiSelected: true, index: indexPath, selectedActionIndex: indexPath.row) } }) } } } extension LICustomActionSheetVC:UITableViewDelegate,UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if arrEmoji != nil { if arrOtherAction != nil { return arrOtherAction.count + 2 } else { return 2 } } else { if arrOtherAction != nil { return arrOtherAction.count + 1 } else { return 1 } } } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if tableView.contentSize.height > self.view.frame.height { tblActionSheet.isScrollEnabled = true } else { tblActionSheet.isScrollEnabled = false } let maxHeight = tableView.contentSize.height > viewBackground.frame.height ? viewBackground.frame.height : tableView.contentSize.height consTblActionSheetHeight.constant = maxHeight self.view.layoutIfNeeded() } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if arrEmoji != nil { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "LIEmojiTableViewCell", for: indexPath) as! LIEmojiTableViewCell cell.actionSheetType = self.actionSheetType cell.selectionStyle = .none return cell } else { if arrOtherAction != nil { if indexPath.row == arrOtherAction.count + 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "LICancelButtonCell", for: indexPath) as! LICancelButtonCell cell.actionSheetType = self.actionSheetType cell.btnCancel.setTitleColor(cancelButtonTextColor, for: .normal) cell.delegate = self cell.selectionStyle = .none return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "LICustomActionSheetTableViewCell", for: indexPath) as! LICustomActionSheetTableViewCell cell.actionSheetType = self.actionSheetType cell.lblActionName.textColor = actionButtonTextColor cell.selectionStyle = .none if indexPath.row == 1 { cell.isRoundCell = "1" } else if indexPath.row == arrOtherAction.count { cell.isRoundCell = "2" } else{ cell.isRoundCell = "3" } if(((((self.arrOtherAction[indexPath.row - 1] as! NSDictionary).value(forKey: "icon"))) != nil) && (((self.arrOtherAction[indexPath.row - 1] as! NSDictionary).value(forKey: "icon")) as? String) != nil ){ cell.imgLogo.isHidden = false cell.imgLogo.image = UIImage(named: (((self.arrOtherAction[indexPath.row - 1] as! NSDictionary).value(forKey: "icon")) as! String)) }else{ cell.imgLogo.isHidden = true } cell.lblActionName.text = (((self.arrOtherAction[indexPath.row - 1] as! NSDictionary).value(forKey: "title")) as! String) return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "LICancelButtonCell", for: indexPath) as! LICancelButtonCell cell.actionSheetType = self.actionSheetType cell.btnCancel.setTitleColor(cancelButtonTextColor, for: .normal) cell.selectionStyle = .none cell.delegate = self return cell } } } else { if arrOtherAction != nil { if indexPath.row == arrOtherAction.count { let cell = tableView.dequeueReusableCell(withIdentifier: "LICancelButtonCell", for: indexPath) as! LICancelButtonCell cell.actionSheetType = self.actionSheetType cell.btnCancel.setTitleColor(cancelButtonTextColor, for: .normal) cell.selectionStyle = .none cell.delegate = self return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "LICustomActionSheetTableViewCell", for: indexPath) as! LICustomActionSheetTableViewCell cell.actionSheetType = self.actionSheetType cell.selectionStyle = .none cell.lblActionName.textColor = actionButtonTextColor if indexPath.row == 0 && arrOtherAction.count == 1{ cell.isRoundCell = "4" }else if indexPath.row == 0 { cell.isRoundCell = "1" } else if indexPath.row == arrOtherAction.count-1 { cell.isRoundCell = "2" } else { cell.isRoundCell = "3" } if(((((self.arrOtherAction[indexPath.row ] as! NSDictionary).value(forKey: "icon"))) != nil) && (((self.arrOtherAction[indexPath.row ] as! NSDictionary).value(forKey: "icon")) as? String) != nil ){ cell.imgLogo.isHidden = false cell.imgLogo.image = UIImage(named: (((self.arrOtherAction[indexPath.row] as! NSDictionary).value(forKey: "icon")) as! String)) }else{ cell.imgLogo.isHidden = true } cell.lblActionName.text = (((self.arrOtherAction[indexPath.row ] as! NSDictionary).value(forKey: "title")) as! String) return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "LICancelButtonCell", for: indexPath) as! LICancelButtonCell cell.actionSheetType = self.actionSheetType cell.btnCancel.setTitleColor(cancelButtonTextColor, for: .normal) cell.selectionStyle = .none cell.delegate = self return cell } } } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if arrEmoji != nil { if indexPath.row == 0 { return view.frame.size.width } else { if arrOtherAction != nil { if indexPath.row == arrOtherAction.count + 1 { return 76 } else { return 60 } } else { return 76 } } } else { if arrOtherAction != nil { if indexPath.row == arrOtherAction.count { return 76 } else { return 60 } } else { return 76 } } } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ let totalRow = tableView.numberOfRows(inSection: indexPath.section) if indexPath.row != totalRow - 1{ self.animateBackgroundView(isVisible: false) UIView.animate(withDuration: 0.3, animations: { self.tblActionSheet.frame = CGRect(x: self.tblActionSheet.frame.origin.x, y: UIScreen.main.bounds.height , width: self.tblActionSheet.frame.width, height: self.tblActionSheet.frame.height) self.constTblActionSheetBottomSpace.constant = -self.consTblActionSheetHeight.constant }) { (success) in self.dismiss(animated: false, completion: { if (self.delegate != nil) { self.delegate.didSelectedActionView?(self, isEmojiSelected: false, index: indexPath, selectedActionIndex: indexPath.row ) } }) } } } }
39.334677
227
0.570989
011e47ba605ad918468df9a2f6e6882120d791e7
1,297
// // CollectionViewSampleAppUITests.swift // CollectionViewSampleAppUITests // // Created by Teruki Nakano on 2018/09/21. // Copyright © 2018年 Teruki Nakano. All rights reserved. // import XCTest class CollectionViewSampleAppUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
35.054054
182
0.676176
75bf3192519198786ad7aec695767f90f24cf209
3,789
// // LoginVC.swift // Gourmet // // Created by David Martinez on 08/12/2016. // Copyright © 2016 Atenea. All rights reserved. // import UIKit import GourmetModel class MainVC : UIViewController, MainView { private var signUpVC : SignUpVC? private var loginVC : LoginVC? private var currentVC : UIViewController? private var presenter : MainPresenter! override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) presenter = MainFactory.default.getMainPresenter() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) presenter = MainFactory.default.getMainPresenter() } override func viewDidLoad() { super.viewDidLoad() localize() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) presenter.updateView(view: self) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) currentVC?.resignFirstResponder() } private func localize () { self.title = Localizable.getString(key: "login_window_title") } func showAccountInfo(account: AccountVM) { if (isMountedViewController(vc: loginVC)) { return } if (currentVC != nil) { remove(viewController: currentVC!) } if (loginVC == nil) { loginVC = MainFactory.default.getLoginVC() } currentVC = loginVC add(viewController: loginVC!) animateAppear(childVC: loginVC!) } func showNoAccount() { if (isMountedViewController(vc: signUpVC)) { return } if (currentVC != nil) { remove(viewController: currentVC!) } if (signUpVC == nil) { signUpVC = MainFactory.default.getSignUpView() } currentVC = signUpVC add(viewController: signUpVC!) animateAppear(childVC: signUpVC!) } private func animateAppear (childVC : UIViewController) { childVC.view.alpha = 0.0 childVC.view.frame.origin.y = 30.0 let timing = UICubicTimingParameters(animationCurve: .easeInOut) let animator = UIViewPropertyAnimator(duration: 0.3, timingParameters: timing) animator.addAnimations { childVC.view.frame.origin.y = 0.0 childVC.view.alpha = 1.0 } animator.startAnimation() } private func isMountedViewController (vc : UIViewController?) -> Bool { return vc?.parent != nil } func navigateBalance(account : Account) { performSegue(withIdentifier: "main_to_balance", sender: account) } private func add (viewController : UIViewController) { addChildViewController(viewController) viewController.view.frame = view.frame viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] view.addSubview(viewController.view) viewController.didMove(toParentViewController: self) } private func remove (viewController : UIViewController) { viewController.willMove(toParentViewController: nil) viewController.view.removeFromSuperview() viewController.removeFromParentViewController() } // MARK: Storyboard navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard sender is Account else { return } if let layout = segue.destination as? BalanceVC { layout.setAccount(account: sender as! Account) } } }
29.146154
86
0.619425
ef76530a7a9d4111b82d5afe0209a440b0383e27
1,248
// // Corona-Warn-App // // SAP SE and all other contributors // copyright owners license this file to you under the Apache // License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // import Foundation struct Risk { let level: RiskLevel let details: Details let riskLevelHasChanged: Bool } extension Risk { struct Details { var numberOfExposures: Int? var numberOfHoursWithActiveTracing: Int var numberOfDaysWithActiveTracing: Int { numberOfHoursWithActiveTracing / 24 } var exposureDetectionDate: Date } } #if UITESTING extension Risk { static let mocked = Risk( level: .low, details: Risk.Details( numberOfExposures: 0, numberOfHoursWithActiveTracing: 336, // two weeks exposureDetectionDate: Date()), riskLevelHasChanged: true ) } #endif
25.469388
80
0.745994
1c7ac896f302155249d9964fa1d8200396e640f6
3,120
import Cocoa import RFSupport @NSApplicationMain class ApplicationDelegate: NSObject, NSApplicationDelegate { static let githubURL = "https://github.com/andrews05/ResForge" // Don't configure prefs controller until needed private lazy var prefsController: NSWindowController = { ValueTransformer.setValueTransformer(LaunchActionTransformer(), forName: .launchActionTransformerName) let prefs = NSWindowController(windowNibName: "PrefsWindow") prefs.window?.center() return prefs }() override init() { NSApp.registerServicesMenuSendTypes([.string], returnTypes: [.string]) UserDefaults.standard.register(defaults: [ RFDefaults.confirmChanges: false, RFDefaults.deleteResourceWarning: true, RFDefaults.launchAction: RFDefaults.LaunchActions.displayOpenPanel, RFDefaults.showSidebar: true ]) } func applicationDidFinishLaunching(_ notification: Notification) { SupportRegistry.scanForResources() // Load plugins NotificationCenter.default.addObserver(PluginRegistry.self, selector: #selector(PluginRegistry.bundleLoaded(_:)), name: Bundle.didLoadNotification, object: nil) let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .allDomainsMask) if let plugins = Bundle.main.builtInPlugInsURL { self.scanForPlugins(folder: plugins) } for url in appSupport { self.scanForPlugins(folder: url.appendingPathComponent("ResForge/Plugins")) } } func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool { let launchAction = UserDefaults.standard.string(forKey: RFDefaults.launchAction) switch launchAction { case RFDefaults.LaunchActions.openUntitledFile: return true case RFDefaults.LaunchActions.displayOpenPanel: NSDocumentController.shared.openDocument(sender) return false default: return false } } @IBAction func showInfo(_ sender: Any) { let info = InfoWindowController.shared if info.window?.isKeyWindow == true { info.close() } else { info.showWindow(sender) } } @IBAction func showPrefs(_ sender: Any) { self.prefsController.showWindow(sender) } @IBAction func viewWebsite(_ sender: Any) { if let url = URL(string: Self.githubURL) { NSWorkspace.shared.open(url) } } private func scanForPlugins(folder: URL) { let items: [URL] do { items = try FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) } catch { return } for item in items where item.pathExtension == "plugin" { guard let plugin = Bundle(url: item) else { continue } SupportRegistry.scanForResources(in: plugin) plugin.load() } } }
35.862069
168
0.644231
1ea49007dda71a979c66449e54aec6c385e1a76c
757
// RUN: %target-swift-frontend -module-name specialize_self_conforming -emit-sil -O -primary-file %s | %FileCheck %s // REQUIRES: objc_interop import Foundation @objc protocol P {} @_optimize(none) func takesP<T : P>(_: T) {} @inline(__always) func callsTakesP<T : P>(_ t: T) { takesP(t) } // CHECK-LABEL: sil hidden @$s26specialize_self_conforming16callsTakesPWithPyyAA1P_pF : $@convention(thin) (@guaranteed P) -> () { // CHECK: [[FN:%.*]] = function_ref @$s26specialize_self_conforming6takesPyyxAA1PRzlF : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@guaranteed τ_0_0) -> () // CHECK: apply [[FN]]<P>(%0) : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@guaranteed τ_0_0) -> () // CHECK: return func callsTakesPWithP(_ p: P) { callsTakesP(p) }
29.115385
156
0.688243
3a8b76346de8525d0e58c5dc19ac6191ec86e63d
2,592
// // LoginOrRegisterViewController.swift // Expedia // // Created by YooBin Jo on 03/04/2019. // Copyright © 2019 YooBin Jo. All rights reserved. // import UIKit import XLPagerTabStrip class LoginOrRegisterViewController: ButtonBarPagerTabStripViewController { @IBAction func closeButton(_ sender: Any) { dismiss(animated: true, completion: nil) } func configureButtonBar() { // Sets the background colour of the pager strip and the pager strip item settings.style.buttonBarBackgroundColor = .white settings.style.buttonBarItemBackgroundColor = .white // Sets the pager strip item font and font color settings.style.buttonBarItemFont = UIFont(name: "Helvetica", size: 16.0)! settings.style.buttonBarItemTitleColor = .gray // Sets the pager strip item offsets settings.style.buttonBarMinimumLineSpacing = 0 settings.style.buttonBarItemsShouldFillAvailableWidth = true settings.style.buttonBarLeftContentInset = 0 settings.style.buttonBarRightContentInset = 0 // Sets the height and colour of the slider bar of the selected pager tab settings.style.selectedBarHeight = 3.0 settings.style.selectedBarBackgroundColor = .blue // Changing item text color on swipe changeCurrentIndexProgressive = { [weak self] (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in guard changeCurrentIndex == true else { return } oldCell?.label.textColor = .gray newCell?.label.textColor = .blue } } override func viewDidLoad() { // 네비게이션 바 하단 경계선 지우기 self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() configureButtonBar() super.viewDidLoad() // Do any additional setup after loading the view. } override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { let child1 = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "loginVC") as! LoginViewController let child2 = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "registerVC") as! RegisterViewController return [child1, child2] } } //extension LoginOrRegisterViewController: Pager
40.5
194
0.695988
21c96adef9e4df2f541d773e71fcac8b8ff5004c
2,078
import CoreData import Combine final class ViaplayDataBase: NSObject, ViaplayDataBaseProtocol { private(set) var sectionsPublisher = CurrentValueSubject<[ViaplaySection], Never>([]) private let coreDataManager: CoreDataManager private var fetchedResultsController: NSFetchedResultsController<ViaplaySection>! init(coreDataManager: CoreDataManager) { self.coreDataManager = coreDataManager super.init() setupFetchedResultsController() } func updateSection( id: String, _ configurationsHandler: @escaping (ViaplaySection) -> Void ) { let fetchRequest: NSFetchRequest<ViaplaySection> = ViaplaySection.fetchRequest() fetchRequest.predicate = NSPredicate(format: "id == %@", id) coreDataManager .viewContext .perform { [unowned self] in do { let note = try coreDataManager .viewContext .fetch(fetchRequest).first ?? ViaplaySection(context: coreDataManager.viewContext) configurationsHandler(note) } catch { print("Error occured while updating notes: \(error.localizedDescription)") } } } } // MARK: - NSFetchedResultsController extension ViaplayDataBase: NSFetchedResultsControllerDelegate { private func setupFetchedResultsController() { let fetchRequest = ViaplaySection.fetchRequest() as NSFetchRequest fetchRequest.sortDescriptors = [] fetchedResultsController = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: coreDataManager.viewContext, sectionNameKeyPath: nil, cacheName: nil ) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() syncList() } catch { print(error.localizedDescription) } } func controllerDidChangeContent( _ controller: NSFetchedResultsController<NSFetchRequestResult> ) { syncList() } private func syncList() { fetchedResultsController .fetchedObjects .map { sections in sectionsPublisher.send(sections) } } }
29.685714
94
0.71078
75d177f592e8064b62cf23a12f4d9e4355334d4e
449
// // RequestTokenResponse.swift // TheMovieManager // // Created by Owen LaRosa on 8/13/18. // Copyright © 2018 Udacity. All rights reserved. // import Foundation struct RequestTokenResponse: Codable { let success: Bool let expiresAt: String let requestToken: String enum CodingKeys: String, CodingKey { case success case expiresAt = "expires_at" case requestToken = "request_token" } }
18.708333
50
0.66147
9be04663d1a72e24b6757aca93dc8c3db998a42c
438
// // Cornucopia – (C) Dr. Lauer Information Technology // import Crypto import Foundation public extension String { /// Returns the content's MD5 sum. var CC_md5: String { guard let data = self.data(using: .utf8) else { return "<can't convert string to utf8>" } let digest = Insecure.MD5.hash(data: data) let md5Hex = digest.map { String(format: "%02hhX", $0) }.joined() return md5Hex } }
24.333333
97
0.627854
189985663e8df9fd3753693158001b2726eba305
166
//:[Previous](@previous) /*: # Hashable * Used for quick O(1) lookup in Dictionaries and Sets * A type that is Hashable is able Equatable */ //: [Next](@next)
15.090909
54
0.644578
09e8ddac79bfc73acf19758ce66fb33a38d56b36
2,165
// // FavoriteEstablishmentCollectionViewCell.swift // ChowTown // // Created by Jordain Gijsbertha on 15/11/2019. // Copyright © 2019 Jordain Gijsbertha. All rights reserved. // import UIKit class FavoriteEstablishmentCollectionViewCell: UICollectionViewCell { @IBOutlet weak var image: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var address: UIButton! @IBOutlet weak var about: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code // image.makeRounded() } // Reuser identifier class func reuseIdentifier() -> String { return "FavoriteEstablishmentCollectionViewCellID" } // Nib name class func nibName() -> String { return "FavoriteEstablishmentCollectionViewCell" } func configure(with establishment: FavoriteRestaurant?){ name.text = establishment?.name address.setTitle(establishment?.address, for: .normal) // about.setTitle(establishment?.about, for: .normal) } @IBAction func favoriteButtonTapped(_ sender: UIButton) { sender.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) UIView.animate(withDuration: 2.0, delay: 0, usingSpringWithDamping: CGFloat(0.20), initialSpringVelocity: CGFloat(6.0), options: UIView.AnimationOptions.allowUserInteraction, animations: { sender.transform = CGAffineTransform.identity //check current value if (sender.imageView?.image == UIImage(systemName: "star")) { //set default sender.setImage(UIImage(systemName: "star.fill"), for: .normal) } else{ // set like sender.setImage(UIImage(systemName: "star"), for: .normal) } }, completion: { Void in() } ) } }
30.492958
91
0.552887
6a4ac1c7ab653e747c4d9e8675bc8148f5deb0f3
2,064
// // GATTDayOfWeek.swift // Bluetooth // // Created by Carlos Duclos on 7/5/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** Day of Week - SeeAlso: [Day of Week](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.day_of_week.xml) */ @frozen public struct GATTDayOfWeek: GATTCharacteristic { public static var uuid: BluetoothUUID { return .dayOfWeek } internal static let length = MemoryLayout<UInt8>.size public var day: Day public init(day: Day) { self.day = day } public init?(data: Data) { guard data.count == type(of: self).length else { return nil } guard let day = Day(rawValue: data[0]) else { return nil } self.init(day: day) } public var data: Data { return Data([day.rawValue]) } } extension GATTDayOfWeek: Equatable { public static func == (lhs: GATTDayOfWeek, rhs: GATTDayOfWeek) -> Bool { return lhs.day == rhs.day } } extension GATTDayOfWeek: CustomStringConvertible { public var description: String { return day.description } } extension GATTDayOfWeek { public enum Day: UInt8, BluetoothUnit { public static var unitType: UnitIdentifier { return .day } case unknown = 0 case monday = 1 case tuesday = 2 case wednesday = 3 case thursday = 4 case friday = 5 case saturday = 6 case sunday = 7 } } extension GATTDayOfWeek.Day: Equatable { public static func == (lhs: GATTDayOfWeek.Day, rhs: GATTDayOfWeek.Day) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTDayOfWeek.Day: CustomStringConvertible { public var description: String { return rawValue.description } }
19.657143
141
0.569283
18ac057f5d75a6d0d9c08bbfa6f53d6629f572bf
2,839
// // CreateTweetViewController.swift // ATwitter // // Created by Jeremiah Lee on 2/21/16. // Copyright © 2016 Jeremiah Lee. All rights reserved. // import UIKit class CreateTweetViewController: UIViewController, UITextViewDelegate { var tweet: Tweet? var createdTweet: Tweet? @IBOutlet weak var charactersLeftLabel: UILabel! @IBOutlet weak var tweetTextView: UITextView! @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screennameLabel: UILabel! override func viewDidLoad() { tweetTextView.delegate = self tweetTextView.becomeFirstResponder() if let user = User.currentUser { screennameLabel.text = "@" + (user.screenname)! nameLabel.text = user.name! let avatarImageRequest = NSURLRequest(URL: (user.profileImageURL)!) avatarImageView.setImageWithURLRequest(avatarImageRequest, placeholderImage: nil, success: { (request:NSURLRequest,response:NSHTTPURLResponse?, image:UIImage) -> Void in self.avatarImageView.image = image }, failure: { (request, response,error) -> Void in print("Something went wrong with the image load") } ) } if tweet != nil { tweetTextView.text = "@\((tweet?.user?.screenname)!) " } updateTwitterCharacterCount() } @IBAction func sendTweet(sender: AnyObject) { var replyId: Int? = nil if tweet != nil { replyId = (tweet?.id)! } TwitterClient.sharedInstance.tweet(tweetTextView.text, inReplyToStatusId: replyId, completion: { (tweet: Tweet?, error: NSError?) -> Void in if tweet != nil { self.createdTweet = tweet self.navigationController?.popToRootViewControllerAnimated(true) } else { //show error here } } ) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let vc = segue.destinationViewController as! TweetsViewController vc.sentTweet = tweet } func textViewDidChange(textView: UITextView) { updateTwitterCharacterCount() } func updateTwitterCharacterCount(){ let TWITTER_CHARS = 140 let current_length = tweetTextView.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) let remaining = TWITTER_CHARS - current_length if remaining > 0 { charactersLeftLabel.textColor = UIColor.blackColor() } else { charactersLeftLabel.textColor = UIColor.redColor() } charactersLeftLabel.text = "\(remaining) characters left" } }
33.4
103
0.616062
c1b48a085ebc6c0194c39340c947a6bcbed3be34
2,725
// SPDX-License-Identifier: MIT // Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. import UserNotifications class NotificationService: UNNotificationServiceExtension { let imageKey = AnyHashable("image") var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let imageUrl = request.content.userInfo[imageKey] as? String { print("imageurl under notification",imageUrl) // imageUrl = "http://asta.b4live.com/images/cropped-131239288.jpg" let session = URLSession(configuration: URLSessionConfiguration.default) let task = session.dataTask(with: URL(string: imageUrl)!, completionHandler: { [weak self] (data, response, error) in if let data = data { do { let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("push.png") try data.write(to: writePath) guard let wself = self else { return } if let bestAttemptContent = wself.bestAttemptContent { let attachment = try UNNotificationAttachment(identifier: "nnsnodnb_demo", url: writePath, options: nil) bestAttemptContent.attachments = [attachment] contentHandler(bestAttemptContent) } } catch let error as NSError { print(error.localizedDescription) guard let wself = self else { return } if let bestAttemptContent = wself.bestAttemptContent { contentHandler(bestAttemptContent) } } } else if let error = error { print(error.localizedDescription) } }) task.resume() } else { if let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } override func serviceExtensionTimeWillExpire() { if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } }
43.253968
142
0.572477
f8eedf263deab4617b78e4c47f55124c77aaab41
14,510
// // Copyright © 2019 Essential Developer. All rights reserved. // import XCTest import UIKit import MVP import FeedFeature final class FeedUIIntegrationTests: XCTestCase { func test_feedView_hasTitle() { let (sut, _) = makeSUT() sut.loadViewIfNeeded() XCTAssertEqual(sut.title, localized("FEED_VIEW_TITLE")) } func test_loadFeedActions_requestFeedFromLoader() { let (sut, loader) = makeSUT() XCTAssertEqual(loader.loadFeedCallCount, 0, "Expected no loading requests before view is loaded") sut.loadViewIfNeeded() XCTAssertEqual(loader.loadFeedCallCount, 1, "Expected a loading request once view is loaded") sut.simulateUserInitiatedFeedReload() XCTAssertEqual(loader.loadFeedCallCount, 2, "Expected another loading request once user initiates a reload") sut.simulateUserInitiatedFeedReload() XCTAssertEqual(loader.loadFeedCallCount, 3, "Expected yet another loading request once user initiates another reload") } func test_loadingFeedIndicator_isVisibleWhileLoadingFeed() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() XCTAssertTrue(sut.isShowingLoadingIndicator, "Expected loading indicator once view is loaded") loader.completeFeedLoading(at: 0) XCTAssertFalse(sut.isShowingLoadingIndicator, "Expected no loading indicator once loading completes successfully") sut.simulateUserInitiatedFeedReload() XCTAssertTrue(sut.isShowingLoadingIndicator, "Expected loading indicator once user initiates a reload") loader.completeFeedLoadingWithError(at: 1) XCTAssertFalse(sut.isShowingLoadingIndicator, "Expected no loading indicator once user initiated loading completes with error") } func test_loadFeedCompletion_rendersSuccessfullyLoadedFeed() { let image0 = makeImage(description: "a description", location: "a location") let image1 = makeImage(description: nil, location: "another location") let image2 = makeImage(description: "another description", location: nil) let image3 = makeImage(description: nil, location: nil) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() assertThat(sut, isRendering: []) loader.completeFeedLoading(with: [image0], at: 0) assertThat(sut, isRendering: [image0]) sut.simulateUserInitiatedFeedReload() loader.completeFeedLoading(with: [image0, image1, image2, image3], at: 1) assertThat(sut, isRendering: [image0, image1, image2, image3]) } func test_loadFeedCompletion_NoRendersErrorMessageOnSuccessfullyLoadedFeed() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() XCTAssertNil(sut.errorMessage) loader.completeFeedLoading(with: [makeImage()], at: 0) XCTAssertNil(sut.errorMessage) } func test_loadFeedCompletion_doesNotAlterCurrentRenderingStateOnError() { let image0 = makeImage() let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0], at: 0) assertThat(sut, isRendering: [image0]) sut.simulateUserInitiatedFeedReload() loader.completeFeedLoadingWithError(at: 1) assertThat(sut, isRendering: [image0]) } func test_loadFeedCompletion_rendersErrorMessageOnErrorUntilNextReload() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() XCTAssertEqual(sut.errorMessage, nil) loader.completeFeedLoadingWithError(at: 0) XCTAssertEqual(sut.errorMessage, localized("FEED_VIEW_CONNECTION_ERROR")) sut.simulateUserInitiatedFeedReload() XCTAssertEqual(sut.errorMessage, nil) } func test_errorView_dismissesErrorMessageOnTap() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() XCTAssertEqual(sut.errorMessage, nil) loader.completeFeedLoadingWithError(at: 0) XCTAssertEqual(sut.errorMessage, localized("FEED_VIEW_CONNECTION_ERROR")) sut.simulateTapOnErrorMessage() XCTAssertEqual(sut.errorMessage, nil) } func test_feedImageView_loadsImageURLWhenVisible() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) XCTAssertEqual(loader.loadedImageURLs, [], "Expected no image URL requests until views become visible") sut.simulateFeedImageViewVisible(at: 0) XCTAssertEqual(loader.loadedImageURLs, [image0.url], "Expected first image URL request once first view becomes visible") sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected second image URL request once second view also becomes visible") } func test_feedImageView_cancelsImageLoadingWhenNotVisibleAnymore() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) XCTAssertEqual(loader.cancelledImageURLs, [], "Expected no cancelled image URL requests until image is not visible") sut.simulateFeedImageViewNotVisible(at: 0) XCTAssertEqual(loader.cancelledImageURLs, [image0.url], "Expected one cancelled image URL request once first image is not visible anymore") sut.simulateFeedImageViewNotVisible(at: 1) XCTAssertEqual(loader.cancelledImageURLs, [image0.url, image1.url], "Expected two cancelled image URL requests once second image is also not visible anymore") } func test_feedImageViewLoadingIndicator_isVisibleWhileLoadingImage() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage(), makeImage()]) let view0 = sut.simulateFeedImageViewVisible(at: 0) let view1 = sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(view0?.isShowingImageLoadingIndicator, true, "Expected loading indicator for first view while loading first image") XCTAssertEqual(view1?.isShowingImageLoadingIndicator, true, "Expected loading indicator for second view while loading second image") loader.completeImageLoading(at: 0) XCTAssertEqual(view0?.isShowingImageLoadingIndicator, false, "Expected no loading indicator for first view once first image loading completes successfully") XCTAssertEqual(view1?.isShowingImageLoadingIndicator, true, "Expected no loading indicator state change for second view once first image loading completes successfully") loader.completeImageLoadingWithError(at: 1) XCTAssertEqual(view0?.isShowingImageLoadingIndicator, false, "Expected no loading indicator state change for first view once second image loading completes with error") XCTAssertEqual(view1?.isShowingImageLoadingIndicator, false, "Expected no loading indicator for second view once second image loading completes with error") } func test_feedImageView_rendersImageLoadedFromURL() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage(), makeImage()]) let view0 = sut.simulateFeedImageViewVisible(at: 0) let view1 = sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(view0?.renderedImage, .none, "Expected no image for first view while loading first image") XCTAssertEqual(view1?.renderedImage, .none, "Expected no image for second view while loading second image") let imageData0 = UIImage.make(withColor: .red).pngData()! loader.completeImageLoading(with: imageData0, at: 0) XCTAssertEqual(view0?.renderedImage, imageData0, "Expected image for first view once first image loading completes successfully") XCTAssertEqual(view1?.renderedImage, .none, "Expected no image state change for second view once first image loading completes successfully") let imageData1 = UIImage.make(withColor: .blue).pngData()! loader.completeImageLoading(with: imageData1, at: 1) XCTAssertEqual(view0?.renderedImage, imageData0, "Expected no image state change for first view once second image loading completes successfully") XCTAssertEqual(view1?.renderedImage, imageData1, "Expected image for second view once second image loading completes successfully") } func test_feedImageViewRetryButton_isVisibleOnImageURLLoadError() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage(), makeImage()]) let view0 = sut.simulateFeedImageViewVisible(at: 0) let view1 = sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action for first view while loading first image") XCTAssertEqual(view1?.isShowingRetryAction, false, "Expected no retry action for second view while loading second image") let imageData = UIImage.make(withColor: .red).pngData()! loader.completeImageLoading(with: imageData, at: 0) XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action for first view once first image loading completes successfully") XCTAssertEqual(view1?.isShowingRetryAction, false, "Expected no retry action state change for second view once first image loading completes successfully") loader.completeImageLoadingWithError(at: 1) XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action state change for first view once second image loading completes with error") XCTAssertEqual(view1?.isShowingRetryAction, true, "Expected retry action for second view once second image loading completes with error") } func test_feedImageViewRetryButton_isVisibleOnInvalidImageData() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage()]) let view = sut.simulateFeedImageViewVisible(at: 0) XCTAssertEqual(view?.isShowingRetryAction, false, "Expected no retry action while loading image") let invalidImageData = Data("invalid image data".utf8) loader.completeImageLoading(with: invalidImageData, at: 0) XCTAssertEqual(view?.isShowingRetryAction, true, "Expected retry action once image loading completes with invalid image data") } func test_feedImageViewRetryAction_retriesImageLoad() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) let view0 = sut.simulateFeedImageViewVisible(at: 0) let view1 = sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected two image URL request for the two visible views") loader.completeImageLoadingWithError(at: 0) loader.completeImageLoadingWithError(at: 1) XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected only two image URL requests before retry action") view0?.simulateRetryAction() XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url, image0.url], "Expected third imageURL request after first view retry action") view1?.simulateRetryAction() XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url, image0.url, image1.url], "Expected fourth imageURL request after second view retry action") } func test_feedImageView_preloadsImageURLWhenNearVisible() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) XCTAssertEqual(loader.loadedImageURLs, [], "Expected no image URL requests until image is near visible") sut.simulateFeedImageViewNearVisible(at: 0) XCTAssertEqual(loader.loadedImageURLs, [image0.url], "Expected first image URL request once first image is near visible") sut.simulateFeedImageViewNearVisible(at: 1) XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected second image URL request once second image is near visible") } func test_feedImageView_cancelsImageURLPreloadingWhenNotNearVisibleAnymore() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) XCTAssertEqual(loader.cancelledImageURLs, [], "Expected no cancelled image URL requests until image is not near visible") sut.simulateFeedImageViewNotNearVisible(at: 0) XCTAssertEqual(loader.cancelledImageURLs, [image0.url], "Expected first cancelled image URL request once first image is not near visible anymore") sut.simulateFeedImageViewNotNearVisible(at: 1) XCTAssertEqual(loader.cancelledImageURLs, [image0.url, image1.url], "Expected second cancelled image URL request once second image is not near visible anymore") } func test_feedImageView_doesNotRenderLoadedImageWhenNotVisibleAnymore() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage()]) let view = sut.simulateFeedImageViewNotVisible(at: 0) loader.completeImageLoading(with: anyImageData()) XCTAssertNil(view?.renderedImage, "Expected no rendered image when an image load finishes after the view is not visible anymore") } func test_loadFeedCompletion_dispatchesFromBackgroundToMainThread() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() let exp = expectation(description: "Wait for background queue") DispatchQueue.global().async { loader.completeFeedLoading(at: 0) exp.fulfill() } wait(for: [exp], timeout: 1.0) } func test_loadImageDataCompletion_dispatchesFromBackgroundToMainThread() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage()]) _ = sut.simulateFeedImageViewVisible(at: 0) let exp = expectation(description: "Wait for background queue") DispatchQueue.global().async { loader.completeImageLoading(with: self.anyImageData(), at: 0) exp.fulfill() } wait(for: [exp], timeout: 1.0) } // MARK: - Helpers private func makeSUT(file: StaticString = #filePath, line: UInt = #line) -> (sut: FeedViewController, loader: LoaderSpy) { let loader = LoaderSpy() let sut = FeedUIComposer.feedComposedWith(feedLoader: loader, imageLoader: loader) trackForMemoryLeaks(loader, file: file, line: line) trackForMemoryLeaks(sut, file: file, line: line) return (sut, loader) } private func makeImage(description: String? = nil, location: String? = nil, url: URL = URL(string: "http://any-url.com")!) -> FeedImage { return FeedImage(id: UUID(), description: description, location: location, url: url) } private func anyImageData() -> Data { return UIImage.make(withColor: .red).pngData()! } }
43.05638
171
0.776775
09638d7a0cf57aaf140830f0ecc323a3994ddf18
4,386
// // BBVideoUtils.swift // BBVideoUtils // // Created by Blake Barrett on 2/28/18. // import Foundation import AVFoundation import MediaPlayer public protocol Video { var videoUrl: URL? { get set } var asset: AVAsset? { get set } var duration: CMTime? { get set } var thumbnail: UIImage? { get set } var muted: Bool { get set } } public class BBVideoUtils { public static let exportCompleteNotification = Notification.Name(rawValue: "videoExportComplete") public static let exportProgressNotification = Notification.Name(rawValue: "videoExportProgress") // MARK: AVFoundation Video Manipulation Code public static func merge(_ assets: [Video], andExportTo outputUrl: URL, with backgroundAudio: MPMediaItem? = nil) -> Bool { let mixComposition = AVMutableComposition() let videoTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) let audioTrack = mixComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) // var maxWidth: CGFloat = 0; // var maxHeight: CGFloat = 0; // // run through all the assets selected assets.reversed().forEach {(video) in guard let asset = video.asset, let duration = video.duration else { return } let timeRange = CMTimeRangeMake(kCMTimeZero, duration) // add all video tracks in asset let videoMediaTracks = asset.tracks(withMediaType: .video) videoMediaTracks.forEach{ (videoMediaTrack) in // maxWidth = max(videoMediaTrack.naturalSize.width, maxWidth) // maxHeight = max(videoMediaTrack.naturalSize.height, maxHeight) try? videoTrack?.insertTimeRange(timeRange, of: videoMediaTrack, at: kCMTimeZero) } if video.muted { return } // add all audio tracks in asset let audioMediaTracks = asset.tracks(withMediaType: .audio) audioMediaTracks.forEach {(audioMediaTrack) in try? audioTrack?.insertTimeRange(timeRange, of: audioMediaTrack, at: kCMTimeZero) } } // TODO: check this shit out for video rotation. // http://stackoverflow.com/questions/12136841/avmutablevideocomposition-rotated-video-captured-in-portrait-mode // http://stackoverflow.com/questions/27627610/video-not-rotating-using-avmutablevideocompositionlayerinstruction // And where would we be w/o Ray Wenderlich? // https://www.raywenderlich.com/13418/how-to-play-record-edit-videos-in-ios let notificationCenter = NotificationCenter.default guard let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) else { return false } exporter.outputURL = outputUrl exporter.outputFileType = .mov exporter.shouldOptimizeForNetworkUse = true exporter.exportAsynchronously(completionHandler: { switch exporter.status { case .completed: // we can be confident that there is a URL because // we got this far. Otherwise it would've failed. if let url = exporter.outputURL { print("exportVideo SUCCESS!") notificationCenter.post(name: BBVideoUtils.exportCompleteNotification, object: url) } else { notificationCenter.post(name: BBVideoUtils.exportCompleteNotification, object: exporter.error) } case .exporting: let progress = exporter.progress print("exportVideo \(progress)") notificationCenter.post(name: BBVideoUtils.exportProgressNotification, object: progress) case .failed: notificationCenter.post(name: BBVideoUtils.exportCompleteNotification, object: exporter) default: break } }) return true } }
41.771429
127
0.606931
6968bf66b201fba18457f3a97fa24036f6336186
21,465
// // PeopleDiversityScene.swift // wwdcWinningProject // // Created by Luis Gustavo Avelino de Lima Jacinto on 26/03/18. // Copyright © 2018 Luis Gustavo Avelino de Lima Jacinto. All rights reserved. // import SpriteKit enum Balloon: String { case pink = "pinkballoon" case rainbow = "rainbowballoon" case brown = "brownballoon" } class PeopleDiversityScene: SKScene{ var balloonsHit = [false, false, false] ///MARK: - Propertys let backgroundSceneColor = UIColor(red: 197/255, green: 240/255, blue: 164/255, alpha: 1.0) let lgbtqColor = UIColor(red: 169/255, green: 241/255, blue: 225/255, alpha: 1.0) ///MARK: - didMove override func didMove(to view: SKView) { super.didMove(to: view) backgroundColor = backgroundSceneColor setupScene() setupBalloon(getRandomBallon()!) setupGraph() setupCircle() setupFlag() } ///MARK: - Methods func moveUpAnimation(_ y: CGFloat, _ duration: TimeInterval) -> SKAction{ let moveUp = SKAction.moveTo(y: y, duration: duration) return moveUp } func newBalloon(node: SKSpriteNode, balloon: Balloon) -> SKSpriteNode{ let randomBallon = self.getRandomBallon() if randomBallon?.rawValue == "pinkballoon"{ node.name = "pinkBalloon" node.texture = SKTexture(imageNamed: (randomBallon?.rawValue)!) node.position = self.randomXPosition(y: -500) }else if randomBallon?.rawValue == "rainbowballoon"{ node.name = "rainbowBalloon" node.texture = SKTexture(imageNamed: (randomBallon?.rawValue)!) node.position = self.randomXPosition(y: -500) }else if randomBallon?.rawValue == "brownballoon"{ node.name = "brownBalloon" node.texture = SKTexture(imageNamed: (randomBallon?.rawValue)!) node.position = self.randomXPosition(y: -500) } return node } func createNextButton(){ let nextButton = SKSpriteNode(imageNamed: "nextButton") nextButton.name = "nextButton" nextButton.position = CGPoint(x: self.size.width - 100, y: 25) for subview in (view?.subviews)!{ if subview.restorationIdentifier == "circleView" || subview.restorationIdentifier == "circleViewBrown"{ subview.removeFromSuperview() } } self.addChild(nextButton) } func allTrue() -> Bool{ for value in balloonsHit{ if value == false{ return false } } return true } func animateGraph(){ let pinkGraph = childNode(withName: "pinkGraph") as? SKSpriteNode let graphTextures = [SKTexture(imageNamed: "pinkgraph2"), SKTexture(imageNamed: "pinkgraph3"), SKTexture(imageNamed: "pinkgraph4"), SKTexture(imageNamed: "pinkgraph5")] let customPink = UIColor(red: 241/255, green: 198/255, blue: 222/255, alpha: 1.0) run(.colorize(with: customPink, colorBlendFactor: 1.0, duration: 1.0)) let appearGraphLabelBlock = SKAction.run { let graphLabel = self.childNode(withName: "graphLabel") graphLabel?.run(.fadeAlpha(to: 1.0, duration: 0.5), withKey: "graphLabelAction") } let appearFemaleLabelBlock = SKAction.run { let femaleLabel = self.childNode(withName: "femaleLabel") femaleLabel?.run(.fadeAlpha(to: 1.0, duration: 1.0), withKey: "femaleLabelAction") } let appearArrow = SKAction.run { let arrowNode = self.childNode(withName: "arrowNode") let femalePercentLabel = self.childNode(withName: "femalePercentLabel") arrowNode?.run(.fadeAlpha(to: 1.0, duration: 1.0), withKey: "arrowNodeAction") femalePercentLabel?.run(.fadeAlpha(to: 1.0, duration: 1.0), withKey: "femalePercentLabelAction") } let animateLabels = SKAction.run { let femaleLabel = self.childNode(withName: "femaleLabel") let arrowNode = self.childNode(withName: "arrowNode") let femalePercentLabel = self.childNode(withName: "femalePercentLabel") arrowNode?.run(.scale(to: 2.0, duration: 1.0), withKey: "arrowNodeAction") femaleLabel?.run(.moveTo(y: (femaleLabel?.position.y)! + 12, duration: 1.0), withKey: "femaleLabelAction") let block = SKAction.run { (femalePercentLabel as? SKLabelNode)?.text = "36%" } femalePercentLabel?.run(.sequence([.moveTo(y: (femalePercentLabel?.position.y)! - 5, duration: 1.0), block]), withKey: "femalePercentLabelAction") } let wait = SKAction.wait(forDuration: 1.0) let block = SKAction.run { self.checkHittedBalloons() } let fadeOutBlock = SKAction.run { let allTrue = self.allTrue() if allTrue == true{ }else{ pinkGraph?.run(.fadeAlpha(to: 0.0, duration: 1.0)) let femaleLabel = self.childNode(withName: "femaleLabel") femaleLabel?.run(.fadeAlpha(to: 0.0, duration: 1.0)) let arrowNode = self.childNode(withName: "arrowNode") arrowNode?.run(.fadeAlpha(to: 0.0, duration: 1.0)) let femalePercentLabel = self.childNode(withName: "femalePercentLabel") femalePercentLabel?.run(.fadeAlpha(to: 0.0, duration: 1.0)) let graphLabel = self.childNode(withName: "graphLabel") graphLabel?.run(.fadeAlpha(to: 0.0, duration: 1.0)) } } let sequence = SKAction.sequence([.fadeAlpha(to: 1.0, duration: 0.5), .animate(with: graphTextures, timePerFrame: 0.5), appearGraphLabelBlock, wait, appearFemaleLabelBlock, appearArrow, wait, animateLabels, .wait(forDuration: 5.0), fadeOutBlock, block]) pinkGraph?.run(sequence, withKey: "pinkGraphAction") } func removeBalloon(_ balloon: SKSpriteNode){ balloon.removeAllActions() let alphaAction = SKAction.fadeAlpha(to: 0.0, duration: 0.5) let block = SKAction.run { balloon.removeFromParent() } balloon.run(.sequence([alphaAction, block]), withKey: "\(balloon.name!)Action") } func addCircleView(x: CGFloat, y: CGFloat, color: UIColor, endAngle: CGFloat = CGFloat(.pi * 2.0), identifier: String = "circleView", alpha: CGFloat) { let circleWidth = CGFloat(110) let circleHeight = circleWidth let circleView = CircleView(frame: CGRect(x: x, y: y, width: circleWidth, height: circleHeight), color: color, endAngle: endAngle) circleView.restorationIdentifier = identifier view?.addSubview(circleView) circleView.animateCircle(duration: 1.0) circleView.alpha = alpha } func animateMinoriesCircle(){ let purple = UIColor(red: 201/255, green: 169/255, blue: 241/255, alpha: 1.0) run(.colorize(with: purple, colorBlendFactor: 1.0, duration: 1.0)) for subview in (view?.subviews)!{ if subview.restorationIdentifier == "circleView"{ subview.alpha = 1 } } let customBrown = UIColor(red: 171/255, green: 113/255, blue: 83/255, alpha: 1.0) let circleViewBlock = SKAction.run { self.addCircleView(x: self.size.width * 0.5 - 57, y: self.size.height * 0.23, color: customBrown, endAngle: .pi/2, identifier: "circleViewBrown", alpha: 1) } let percentLabel = childNode(withName: "percentLabel") as? SKLabelNode let block = SKAction.run { percentLabel?.text = "50%" } let textBlock = SKAction.run { let minoriesLabel = self.childNode(withName: "minoriesLabel") minoriesLabel?.run(.fadeAlpha(to: 1.0, duration: 1.0), withKey: "minoriesLabelAction") } let rainbowBallonBlock = SKAction.run { self.checkHittedBalloons() } let fadeOutBlock = SKAction.run { let allTrue = self.allTrue() if allTrue{ }else{ for subview in (self.view?.subviews)!{ if subview.restorationIdentifier == "circleView" || subview.restorationIdentifier == "circleViewBrown"{ SKView.animate(withDuration: 1.0, animations: { subview.alpha = 0 }) } } percentLabel?.run(.fadeAlpha(to: 0.0, duration: 1.0)) let minoriesLabel = self.childNode(withName: "minoriesLabel") minoriesLabel?.run(.fadeAlpha(to: 0.0, duration: 1.0)) } } percentLabel?.run(.sequence([.fadeAlpha(to: 1.0, duration: 0.5), circleViewBlock, .wait(forDuration: 1.0), block, textBlock, .wait(forDuration: 5.0), fadeOutBlock, rainbowBallonBlock]), withKey: "percentLabelAction") } func animateFlag(){ let flagNode = childNode(withName: "flagNode") let flagText = childNode(withName: "flagText") let flagTitle = childNode(withName: "flagTitle") let flagNodeBlock = SKAction.run { flagNode?.run(.fadeAlpha(to: 1.0, duration: 1.0)) self.run(.colorize(with: self.lgbtqColor, colorBlendFactor: 1.0, duration: 0.5)) } let flagTitleBlock = SKAction.run { flagTitle?.run(.fadeAlpha(to: 1.0, duration: 1.0)) } let flagTextBlock = SKAction.run { flagText?.run(.fadeAlpha(to: 1.0, duration: 1.0)) } let nextButtonBlock = SKAction.run { self.checkHittedBalloons() } let fadeOutBlock = SKAction.run { let allTrue = self.allTrue() if allTrue{ }else{ flagNode?.run(.fadeAlpha(to: 0.0, duration: 1.0)) flagText?.run(.fadeAlpha(to: 0.0, duration: 1.0)) flagTitle?.run(.fadeAlpha(to: 0.0, duration: 1.0)) } } run(.sequence([flagNodeBlock, .wait(forDuration: 1.5), flagTitleBlock, .wait(forDuration: 1.0), flagTextBlock, .wait(forDuration: 5.0), fadeOutBlock, nextButtonBlock])) } func getRandomBallon() -> Balloon?{ if balloonsHit[0] == false && balloonsHit[1] == false && balloonsHit[2] == false{ let randomNumber = arc4random_uniform(3) return randomNumber == 0 ? .pink : (randomNumber == 1 ? .rainbow : .brown) }else if balloonsHit[0] == false && balloonsHit[1] == false{ let randomNumber = arc4random_uniform(2) return randomNumber == 0 ? .pink : .rainbow }else if balloonsHit[0] == false && balloonsHit[2] == false{ let randomNumber = arc4random_uniform(2) return randomNumber == 0 ? .pink : .brown }else if balloonsHit[1] == false && balloonsHit[2] == false{ let randomNumber = arc4random_uniform(2) return randomNumber == 0 ? .rainbow : .brown }else if balloonsHit[0] == false{ return .pink }else if balloonsHit[1] == false{ return .rainbow }else if balloonsHit[2] == false{ return .brown }else{ return nil } } func randomXPosition(y: CGFloat) -> CGPoint{ return CGPoint(x: CGFloat(arc4random_uniform(UInt32(size.width * 0.6) + UInt32(size.width * 0.2))), y: y) } func checkHittedBalloons(){ let randomBalloon = getRandomBallon() if randomBalloon == nil{ createNextButton() }else{ setupBalloon(randomBalloon!) } } } ///Mark: - Touches methods extension extension PeopleDiversityScene{ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) let touchNode = atPoint(location) if touchNode.name == "nextButton"{ let scene = PeopleSupplyScene(size: size) scene.scaleMode = .aspectFill let transition = SKTransition.reveal(with: .left, duration: 1.0) view?.presentScene(scene, transition: transition) }else if touchNode.name == "pinkBalloon"{ touchNode.removeAllActions() removeBalloon((childNode(withName: touchNode.name!) as? SKSpriteNode)!) balloonsHit[0] = true animateGraph() }else if touchNode.name == "rainbowBalloon"{ touchNode.removeAllActions() removeBalloon((childNode(withName: touchNode.name!) as? SKSpriteNode)!) balloonsHit[1] = true animateFlag() }else if touchNode.name == "brownBalloon"{ touchNode.removeAllActions() removeBalloon((childNode(withName: touchNode.name!) as? SKSpriteNode)!) balloonsHit[2] = true animateMinoriesCircle() }else{ //Do nothing } } } } ///MARK: - Setup methods extension extension PeopleDiversityScene{ func setupScene(){ let titleLabel = SKSpriteNode(imageNamed: "hit") titleLabel.position = CGPoint(x: size.width/2, y: size.height - 25) addChild(titleLabel) } func setupBalloon(_ type: Balloon){ switch type { case .pink: var pinkBalloon = SKSpriteNode(imageNamed: type.rawValue) pinkBalloon.name = "pinkBalloon" pinkBalloon.position = randomXPosition(y: -500) pinkBalloon.zPosition = 1 addChild(pinkBalloon) let moveAction = moveUpAnimation(size.height + 500, 4.0) let block = SKAction.run{ pinkBalloon = self.newBalloon(node: pinkBalloon, balloon: .pink) } let sequence = SKAction.sequence([moveAction, block]) let repeatForever = SKAction.repeatForever(sequence) pinkBalloon.run(repeatForever) case .rainbow: var rainbowBalloon = SKSpriteNode(imageNamed: type.rawValue) rainbowBalloon.name = "rainbowBalloon" rainbowBalloon.position = randomXPosition(y: -500) rainbowBalloon.zPosition = 1 addChild(rainbowBalloon) let moveAction = moveUpAnimation(size.height + 500, 4.0) let block = SKAction.run{ rainbowBalloon = self.newBalloon(node: rainbowBalloon, balloon: .rainbow) } let sequence = SKAction.sequence([moveAction, block]) let repeatForever = SKAction.repeatForever(sequence) rainbowBalloon.run(repeatForever) case .brown: var brownBalloon = SKSpriteNode(imageNamed: type.rawValue) brownBalloon.name = "brownBalloon" brownBalloon.position = randomXPosition(y: -500) brownBalloon.zPosition = 1 addChild(brownBalloon) let moveAction = moveUpAnimation(size.height + 500, 4.0) let block = SKAction.run{ brownBalloon = self.newBalloon(node: brownBalloon, balloon: .brown) } let sequence = SKAction.sequence([moveAction, block]) let repeatForever = SKAction.repeatForever(sequence) brownBalloon.run(repeatForever) } } func setupGraph(){ let pinkGraph = SKSpriteNode(imageNamed: "pinkgraph1") pinkGraph.name = "pinkGraph" pinkGraph.position = CGPoint(x: size.width/2 - 50, y: size.height/2) addChild(pinkGraph) pinkGraph.alpha = 0 pinkGraph.xScale = 1.5 pinkGraph.yScale = 1.5 let graphLabel = SKLabelNode(fontNamed: UIFont.systemFont(ofSize: 10, weight: .light).fontName) graphLabel.text = " Woman in\napple(under 30)" graphLabel.fontSize = 8 graphLabel.fontColor = .black graphLabel.name = "graphLabel" graphLabel.numberOfLines = 2 graphLabel.position = CGPoint(x: pinkGraph.frame.maxX - 10, y: pinkGraph.frame.minY - 30) addChild(graphLabel) graphLabel.alpha = 0 let paragraph = NSMutableParagraphStyle() paragraph.alignment = .center let femaleLabel = SKLabelNode(fontNamed: UIFont.systemFont(ofSize: 10, weight: .light).fontName) femaleLabel.text = "Female\nrepresentation\nis steadily\nincreasing" let attributedText = NSMutableAttributedString.init(string: femaleLabel.text!) attributedText.setAttributes([NSAttributedStringKey.paragraphStyle: paragraph, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20, weight: .light)], range: NSMakeRange(0, (femaleLabel.text?.count)!)) femaleLabel.attributedText = attributedText femaleLabel.name = "femaleLabel" femaleLabel.fontColor = .black femaleLabel.fontSize = 20 femaleLabel.position = CGPoint(x: pinkGraph.frame.maxX + 70, y: graphLabel.position.y + 60) femaleLabel.numberOfLines = 4 addChild(femaleLabel) femaleLabel.alpha = 0 let arrowNode = SKSpriteNode(imageNamed: "pinkarrow") arrowNode.name = "arrowNode" arrowNode.position = CGPoint(x: femaleLabel.position.x, y: femaleLabel.frame.minY - 15) addChild(arrowNode) arrowNode.alpha = 0 let femalePercentLabel = SKLabelNode(fontNamed: UIFont.systemFont(ofSize: 20, weight: .light).fontName) femalePercentLabel.text = "31%" femalePercentLabel.name = "femalePercentLabel" femalePercentLabel.fontColor = .black femalePercentLabel.fontSize = 16 femalePercentLabel.position = CGPoint(x: arrowNode.position.x + 30, y: arrowNode.position.y - 10) addChild(femalePercentLabel) femalePercentLabel.alpha = 0 } func setupCircle(){ let paragraph = NSMutableParagraphStyle() paragraph.alignment = .center let minoriesLabel = SKLabelNode(fontNamed: UIFont.systemFont(ofSize: 20, weight: .light).fontName) minoriesLabel.text = "From July 2016 to July 2017\n50% of apple's new\nhires were from historically\nunderrepresented groups\nin tech" let attributedText = NSMutableAttributedString.init(string: minoriesLabel.text!) attributedText.setAttributes([NSAttributedStringKey.paragraphStyle: paragraph, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18, weight: .light)], range: NSMakeRange(0, (minoriesLabel.text?.count)!)) minoriesLabel.attributedText = attributedText minoriesLabel.name = "minoriesLabel" minoriesLabel.fontColor = .black minoriesLabel.fontSize = 18 minoriesLabel.numberOfLines = 5 minoriesLabel.position = CGPoint(x: size.width/2, y: size.height * 0.15) let percentLabel = SKLabelNode(fontNamed: UIFont.systemFont(ofSize: 20, weight: .bold).fontName) percentLabel.text = "0%" percentLabel.name = "percentLabel" percentLabel.position = CGPoint(x: size.width/2, y: size.height * 0.6) percentLabel.fontColor = .black percentLabel.fontSize = 28 let customBlue = UIColor(red: 114/255, green: 131/255, blue: 191/255, alpha: 1.0) addCircleView(x: size.width * 0.5 - 57, y: size.height * 0.23, color: customBlue, alpha: 0) addChild(minoriesLabel) addChild(percentLabel) minoriesLabel.alpha = 0 percentLabel.alpha = 0 } func setupFlag(){ let flagNode = SKSpriteNode(imageNamed: "flag") flagNode.name = "flagNode" flagNode.position = CGPoint(x: size.width/2, y: size.height * 0.6) addChild(flagNode) flagNode.alpha = 0 let flagTitle = SKLabelNode(fontNamed: UIFont.systemFont(ofSize: 8, weight: .bold).fontName) flagTitle.text = "LGBTQ rights are human rights" flagTitle.fontColor = .black flagTitle.fontSize = 18 flagTitle.name = "flagTitle" flagTitle.position = CGPoint(x: flagNode.position.x, y: flagNode.frame.minY - 30) addChild(flagTitle) flagTitle.alpha = 0 let paragraph = NSMutableParagraphStyle() paragraph.alignment = .center let flagText = SKLabelNode(fontNamed: UIFont.systemFont(ofSize: 4, weight: .light).fontName) flagText.text = "For 15 consecutive years apple had a\nperfect score on Human Rights\nCampaign Corporate Equality Index" let attributedText = NSMutableAttributedString.init(string: flagText.text!) attributedText.setAttributes([NSAttributedStringKey.paragraphStyle: paragraph, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14, weight: .light)], range: NSMakeRange(0, (flagText.text?.count)!)) flagText.attributedText = attributedText flagText.name = "flagText" flagText.position = CGPoint(x: flagNode.position.x, y: flagTitle.frame.minY - 60) flagText.fontSize = 14 flagText.numberOfLines = 3 flagText.fontColor = .black addChild(flagText) flagText.alpha = 0 } }
44.71875
261
0.60997
f8a3d4908a1362b69063e7e59ff5bddf27b292b2
158
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(NetswiftTests.allTests), ] } #endif
15.8
45
0.670886
fc2ecedc124aef40af012b601a7afdc0766c56ca
6,632
// Copyright 2016 Google 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 // // 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 /// Env var used to specify a path for logging RPC messages. /// These logs can be used for profiling & debugging. let XI_RPC_LOG = "XI_CLIENT_RPC_LOG" /// Error tolerant wrapper for append-writing to a file. struct FileWriter { let path: URL let handle: FileHandle init?(path: String) { let path = NSString(string: path).expandingTildeInPath if FileManager.default.fileExists(atPath: path) { print("file exists at \(path), will not overwrite") return nil } self.path = URL(fileURLWithPath: path) FileManager.default.createFile(atPath: self.path.path, contents: nil, attributes: nil) do { try self.handle = FileHandle(forWritingTo: self.path) } catch let err as NSError { print("error opening log file \(err)") return nil } } func write(bytes: Data) { handle.write(bytes) } } class CoreConnection { var inHandle: FileHandle // stdin of core process var recvBuf: Data var callback: (Any) -> Any? let rpcLogWriter: FileWriter? // RPC state var queue = DispatchQueue(label: "com.levien.xi.CoreConnection", attributes: []) var rpcIndex = 0 var pending = Dictionary<Int, (Any?) -> ()>() init(path: String, callback: @escaping (Any) -> Any?) { if let rpcLogPath = ProcessInfo.processInfo.environment[XI_RPC_LOG] { self.rpcLogWriter = FileWriter(path: rpcLogPath) if self.rpcLogWriter != nil { print("logging client RPC to \(rpcLogPath)") } } else { self.rpcLogWriter = nil } let task = Process() task.launchPath = path task.arguments = [] let outPipe = Pipe() task.standardOutput = outPipe let inPipe = Pipe() task.standardInput = inPipe inHandle = inPipe.fileHandleForWriting recvBuf = Data() self.callback = callback outPipe.fileHandleForReading.readabilityHandler = { handle in let data = handle.availableData self.recvHandler(data) } task.launch() } func recvHandler(_ data: Data) { if data.count == 0 { print("eof") return } let scanStart = recvBuf.count recvBuf.append(data) let recvBufLen = recvBuf.count recvBuf.withUnsafeMutableBytes { (recvBufBytes: UnsafeMutablePointer<UInt8>) -> Void in var i = 0 for j in scanStart..<recvBufLen { // TODO: using memchr would probably be faster if recvBufBytes[j] == UInt8(ascii:"\n") { let dataPacket = recvBuf.subdata(in: i ..< j + 1) handleRaw(dataPacket) i = j + 1 } } if i < recvBufLen { memmove(recvBufBytes, recvBufBytes + i, recvBufLen - i) } recvBuf.count = recvBufLen - i } } func sendJson(_ json: Any) { do { let data = try JSONSerialization.data(withJSONObject: json, options: []) let mutdata = NSMutableData() mutdata.append(data) let nl = [0x0a as UInt8] mutdata.append(nl, length: 1) rpcLogWriter?.write(bytes: mutdata as Data) inHandle.write(mutdata as Data) } catch _ { print("error serializing to json") } } func handleRaw(_ data: Data) { do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) // print("got \(json)") handleRpc(json as Any) } catch { print("json error \(error.localizedDescription)") } } /// handle a JSON RPC call. Determines whether it is a request, response or notifcation /// and executes/responds accordingly func handleRpc(_ json: Any) { if let obj = json as? [String: Any], let index = obj["id"] as? Int { if let result = obj["result"] { // is response var callback: ((Any?) -> ())? queue.sync { callback = self.pending.removeValue(forKey: index) } callback?(result) } else { // is request DispatchQueue.main.async { let result = self.callback(json as AnyObject) let resp = ["id": index, "result": result] as [String : Any?] self.sendJson(resp as Any) } } } else { // is notification DispatchQueue.main.async { let _ = self.callback(json as AnyObject) } } } /// send an RPC request, returning immediately. The callback will be called when the /// response comes in, likely from a different thread func sendRpcAsync(_ method: String, params: Any, callback: ((Any?) -> ())? = nil) { var req = ["method": method, "params": params] as [String : Any] if let callback = callback { queue.sync { let index = self.rpcIndex req["id"] = index self.rpcIndex += 1 self.pending[index] = callback } } sendJson(req as Any) } /// send RPC synchronously, blocking until return. Note: there is no ordering guarantee on /// when this function may return. In particular, an async notification sent by the core after /// a response to a synchronous RPC may be delivered before it. func sendRpc(_ method: String, params: Any) -> Any? { let semaphore = DispatchSemaphore(value: 0) var result: Any? = nil sendRpcAsync(method, params: params) { r in result = r semaphore.signal() } let _ = semaphore.wait(timeout: DispatchTime.distantFuture) return result } }
35.089947
98
0.570115
0aaea957cadce96ba4f70c0139b37a83f5087b7e
273
//: [Previous](@previous) //: 用数组[15,58,510] 输出一个新数组 ["OneSix","FiveEight","FiveOneZero"] //: let numbers = [15,68,510] let digitName = [0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine"] let numberStrings = [""] //: [Next](@next)
27.3
107
0.593407
def29d61bfcc962582b5af7f13c1f5a592810c32
2,485
//===----------------------------------------------------------------------===// // // This source file is part of the fishy-actor-transport open source project // // Copyright (c) 2021 Apple Inc. and the fishy-actor-transport project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of fishy-actor-transport project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation import ArgumentParser // very naive pretty printing let Bold = "\u{001B}[0;1m" let Reset = "\u{001B}[0;0m" struct FishyActorsGeneratorMain: ParsableCommand { @Flag(help: "Print verbose logs") var verbose: Bool = false @Option(help: "'Sources/' directory") var sourceDirectory: String @Option(help: "Target directory for generated sources") var targetDirectory: String @Option(help: "How many files to spread the generated files into") var buckets: Int = 1 mutating func run() throws { // Step 1: Analyze all files looking for `distributed actor` decls let analysis = Analysis(sourceDirectory: sourceDirectory, verbose: verbose) analysis.run() // Optimization: If nothing changed since our last run, just return // Step 2: Source generate necessary bits for every decl if verbose { print("Generate extensions...") } let sourceGen = SourceGen(buckets: buckets) // TODO: Don't do this // Just make sure all "buckets" exist (don't remove this // until you can honor the requested ammount of buckets) for i in (0..<buckets) { let path = targetFilePath(targetDirectory: targetDirectory, i: i) try! "".write(to: path, atomically: true, encoding: .utf8) } for decl in analysis.decls { let source = try sourceGen.generate(decl: decl) let filePath = targetFilePath(targetDirectory: targetDirectory, i: source.bucket) if verbose { print(" Generated 'FishyActorTransport' extensions for 'distributed actor \(decl.name)' -> \(filePath)") } try source.text.write(to: filePath, atomically: true, encoding: .utf8) } } } func targetFilePath(targetDirectory: String, i: Int) -> URL { URL(fileURLWithPath: "\(targetDirectory)/GeneratedFishyActors_\(i).swift") } if #available(macOS 12.0, /* Linux */ *) { FishyActorsGeneratorMain.main() } else { fatalError("Unsupported platform") }
31.858974
113
0.649095
767aa5d0ac186e061577ec7b936c391ae00f9d9b
5,830
//// // 🦠 Corona-Warn-App // import UIKit import OpenCombine /** If the ViewController and the FooterViewController are composed inside a TopBottomContainer, ViewController that implement this protocol get called if a button gets tapped in the footerViewController */ protocol FooterViewHandling { var footerView: FooterViewUpdating? { get } func didTapFooterViewButton(_ type: FooterViewModel.ButtonType) } extension FooterViewHandling where Self: UIViewController { var footerView: FooterViewUpdating? { return parent as? FooterViewUpdating } } class FooterViewController: UIViewController { // MARK: - Init init( _ viewModel: FooterViewModel, didTapPrimaryButton: @escaping () -> Void = {}, didTapSecondaryButton: @escaping () -> Void = {} ) { self.viewModel = viewModel self.didTapPrimaryButton = didTapPrimaryButton self.didTapSecondaryButton = didTapSecondaryButton super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() setupPrimaryButton() setupSecondaryButton() view.backgroundColor = viewModel.backgroundColor view.insetsLayoutMarginsFromSafeArea = false view.preservesSuperviewLayoutMargins = false view.layoutMargins = UIEdgeInsets( top: viewModel.topBottomInset, left: viewModel.leftRightInset, bottom: viewModel.topBottomInset, right: viewModel.leftRightInset ) view.addSubview(primaryButton) view.addSubview(secondaryButton) primaryButton.translatesAutoresizingMaskIntoConstraints = false secondaryButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ primaryButton.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor), primaryButton.leftAnchor.constraint(equalTo: view.layoutMarginsGuide.leftAnchor), primaryButton.rightAnchor.constraint(equalTo: view.layoutMarginsGuide.rightAnchor), primaryButton.heightAnchor.constraint(equalToConstant: viewModel.buttonHeight), secondaryButton.topAnchor.constraint(equalTo: primaryButton.bottomAnchor, constant: viewModel.spacer), secondaryButton.centerXAnchor.constraint(equalTo: primaryButton.centerXAnchor), secondaryButton.widthAnchor.constraint(equalTo: primaryButton.widthAnchor), secondaryButton.heightAnchor.constraint(equalToConstant: viewModel.buttonHeight) ]) // hide and show buttons by alpha to make it animatable viewModel.$height .receive(on: DispatchQueue.main.ocombine) .sink { height in let alpha: CGFloat = height > 0.0 ? 1.0 : 0.0 let animator = UIViewPropertyAnimator(duration: 0.35, curve: .easeInOut) { [weak self] in guard let self = self else { return } self.primaryButton.alpha = alpha self.secondaryButton.alpha = alpha } animator.startAnimation() } .store(in: &subscription) // update loading indicators on model change viewModel.$isPrimaryLoading .receive(on: DispatchQueue.main.ocombine) .sink { [weak self] show in self?.primaryButton.isLoading = show } .store(in: &subscription) viewModel.$isSecondaryLoading .receive(on: DispatchQueue.main.ocombine) .sink { [weak self] show in self?.secondaryButton.isLoading = show } .store(in: &subscription) // update enabled state on model change viewModel.$isPrimaryButtonEnabled .receive(on: DispatchQueue.main.ocombine) .sink { [weak self] isEnabled in self?.primaryButton.isEnabled = isEnabled } .store(in: &subscription) viewModel.$isSecondaryButtonEnabled .receive(on: DispatchQueue.main.ocombine) .sink { [weak self] isEnabled in self?.secondaryButton.isEnabled = isEnabled } .store(in: &subscription) viewModel.$backgroundColor .receive(on: DispatchQueue.main.ocombine) .sink { [weak self] color in self?.view.backgroundColor = color } .store(in: &subscription) } // MARK: - Internal let viewModel: FooterViewModel // MARK: - Private private let didTapPrimaryButton: () -> Void private let didTapSecondaryButton: () -> Void private let primaryButton: ENAButton = ENAButton(type: .custom) private let secondaryButton: ENAButton = ENAButton(type: .custom) private var subscription: [AnyCancellable] = [] private func setupPrimaryButton() { if let primaryButtonColor = viewModel.primaryButtonColor { primaryButton.color = primaryButtonColor } primaryButton.setTitle(viewModel.primaryButtonName, for: .normal) primaryButton.hasBackground = true primaryButton.addTarget(self, action: #selector(didHitPrimaryButton), for: .primaryActionTriggered) primaryButton.accessibilityIdentifier = viewModel.primaryIdentifier primaryButton.alpha = viewModel.isPrimaryButtonHidden ? 0.0 : 1.0 primaryButton.isHidden = !viewModel.isPrimaryButtonEnabled } private func setupSecondaryButton() { secondaryButton.setTitle(viewModel.secondaryButtonName, for: .normal) secondaryButton.hasBackground = true secondaryButton.addTarget(self, action: #selector(didHitSecondaryButton), for: .primaryActionTriggered) secondaryButton.accessibilityIdentifier = viewModel.secondaryIdentifier secondaryButton.alpha = viewModel.isSecondaryButtonHidden ? 0.0 : 1.0 secondaryButton.isHidden = !viewModel.isSecondaryButtonEnabled } @objc private func didHitPrimaryButton() { guard let footerViewHandler = (parent as? FooterViewUpdating)?.footerViewHandler else { didTapPrimaryButton() return } footerViewHandler.didTapFooterViewButton(.primary) } @objc private func didHitSecondaryButton() { guard let footerViewHandler = (parent as? FooterViewUpdating)?.footerViewHandler else { didTapPrimaryButton() return } footerViewHandler.didTapFooterViewButton(.secondary) } }
31.176471
107
0.765523
d98f2638125c8962f6d4f98e8f95d3956a303a4c
2,929
// // HRVProvider.swift // AnyRing // // Created by Dmitriy Loktev on 21.12.2020. // import Foundation import HealthKit import Combine //class HRVProvider: RingProvider { // // // struct Configuration: HealthKitConfiguration { // var provider: RingProvider.Type { HRVProvider.self } // // var minValue: Double = 0 // var maxValue: Double = 100 // // var appearance: RingAppearance // } // // let name = "Latest HRV" // let description = """ // Last available value for Heart Rate Variability // """ // let units = "MS" // // private let dataSource: HealthKitDataSource // // let config: ProviderConfiguration // let configPersistence: ConfigurationPersistence // // required init(dataSource: HealthKitDataSource, config: ProviderConfiguration, configPersistence: ConfigurationPersistence) { // self.dataSource = dataSource // self.config = config // self.configPersistence = configPersistence // } // // private let unit = HKUnit.secondUnit(with: .milli) // // func calculateProgress(providerConfig: ProviderConfiguration, globalConfig: GlobalConfiguration) -> AnyPublisher<Progress, Error> { // return fetchSamples(numberOfNights: globalConfig.days).tryMap { (sample: HKSample?) -> Progress in // if let sample = sample as? HKQuantitySample { // return Progress(absolute: sample.quantity.doubleValue(for: self.unit), // maxAbsolute: providerConfig.maxValue, // minAbsolute: providerConfig.minValue, // reversed: false) // } else { // return Progress(absolute: providerConfig.minValue, maxAbsolute: providerConfig.maxValue, minAbsolute: providerConfig.minValue) // } // }.eraseToAnyPublisher() // } // // private var cancellable: AnyCancellable? // // func viewModel(globalConfig: GlobalConfiguration) -> RingViewModel { // RingViewModel(provider: self, globalConfig: globalConfig) // } // // private let hrvType = HKObjectType.quantityType(forIdentifier: .heartRateVariabilitySDNN)! // // var requiredHKPermission: HKSampleType? { hrvType } // // private func fetchSamples(numberOfNights: Int) -> AnyPublisher<HKSample?, Error> { // let m = dataSource.fetchSamples( // withStart: Date().addingTimeInterval(TimeInterval(-Double(numberOfNights) * secondsInDayApprox)), // to: Date(), // ofType: hrvType) // .tryMap { results -> HKSample? in // let latestHRV = results.min { (sample1, sample2) -> Bool in // (sample1 as! HKQuantitySample).endDate > (sample2 as! HKQuantitySample).endDate // } // return latestHRV // }.eraseToAnyPublisher() // return m // } //}
36.6125
144
0.618641
462f85d0b80676bbe2d4e602eb02b25f89d6c60f
6,563
// // MockIdentityAPIClient.swift // StripeIdentity // // Created by Mel Ludowise on 11/4/21. // import Foundation import UIKit @_spi(STP) import StripeCore /** Mock API client that returns responses from local JSON files instead of actual API endpoints. TODO(mludowise|IDPROD-2542): Delete this class when endpoints are live. */ class MockIdentityAPIClient { let verificationPageDataFileURL: URL let responseDelay: TimeInterval private(set) var displayErrorOnScreen: Int private var cachedVerificationPageDataResponse: VerificationPageData? private lazy var queue = DispatchQueue(label: "com.stripe.StripeIdentity.MockIdentityAPIClient", qos: .userInitiated) init( verificationPageDataFileURL: URL, displayErrorOnScreen: Int?, responseDelay: TimeInterval ) { self.verificationPageDataFileURL = verificationPageDataFileURL self.displayErrorOnScreen = displayErrorOnScreen ?? -1 self.responseDelay = responseDelay } /** Generic helper to mock API requests. - Parameters: - fileURL: JSON file to load response from - cachedResponse: If this file has already been loaded, use a cached response rather than re-loading it. - saveCachedResponse: Closure that saves the response fetched from the file system and updates the local cache. - transformResponse: Closure that transformes the fetched or cached response before returning it */ private func mockRequest<ResponseType: StripeDecodable>( fileURL: URL, cachedResponse: ResponseType?, saveCachedResponse: @escaping (ResponseType) -> Void, transformResponse: ((ResponseType) -> ResponseType)? = nil ) -> Promise<ResponseType> { let transform: (ResponseType) -> ResponseType = { transformResponse?($0) ?? $0 } let promise = Promise<ResponseType>() queue.asyncAfter(deadline: .now() + responseDelay, execute: { // Return cached value if possible if let cachedResponse = cachedResponse { promise.resolve(with: transform(cachedResponse)) return } do { let mockData = try Data(contentsOf: fileURL) let result: Result<ResponseType, Error> = STPAPIClient.decodeResponse(data: mockData, error: nil) switch result { case .success(let response): saveCachedResponse(response) promise.resolve(with: transform(response)) case .failure(let error): promise.reject(with: error) } } catch { promise.reject(with: error) } }) return promise } /** Modify a mock response from the `VerificationPageData` endpoint such that missing requirements will naively contain the exact set of fields not yet input by the user. This method should only be used for mocking responses and will be removed when */ static func modifyVerificationPageDataResponse( originalResponse: VerificationPageData, updating verificationData: VerificationPageDataUpdate, shouldDisplayError: Bool ) -> VerificationPageData { let requirementErrors = shouldDisplayError ? originalResponse.requirements.errors : [] var missing = Set(VerificationPageRequirements.Missing.allCases) if verificationData.collectedData.consent?.biometric != nil { missing.remove(.biometricConsent) } if verificationData.collectedData.idDocument?.back != nil { missing.remove(.idDocumentBack) } if verificationData.collectedData.idDocument?.front != nil { missing.remove(.idDocumentFront) // If user is uploading passport, we wouldn't require a back photo if verificationData.collectedData.idDocument?.type == .passport { missing.remove(.idDocumentBack) } } if verificationData.collectedData.idDocument?.type != nil { missing.remove(.idDocumentType) } return .init( id: originalResponse.id, requirements: VerificationPageDataRequirements( errors: requirementErrors, missing: Array(missing), _allResponseFieldsStorage: nil ), status: originalResponse.status, submitted: originalResponse.submitted, _allResponseFieldsStorage: nil ) } } extension MockIdentityAPIClient: IdentityAPIClient { func getIdentityVerificationPage( id: String, ephemeralKeySecret: String ) -> Promise<VerificationPage> { return STPAPIClient.shared.getIdentityVerificationPage(id: id, ephemeralKeySecret: ephemeralKeySecret) } func updateIdentityVerificationPageData( id: String, updating verificationData: VerificationPageDataUpdate, ephemeralKeySecret: String ) -> Promise<VerificationPageData> { let shouldDisplayError = displayErrorOnScreen == 0 self.displayErrorOnScreen -= 1 return mockRequest( fileURL: verificationPageDataFileURL, cachedResponse: cachedVerificationPageDataResponse, saveCachedResponse: { [weak self] response in self?.cachedVerificationPageDataResponse = response }, transformResponse: { response in MockIdentityAPIClient.modifyVerificationPageDataResponse( originalResponse: response, updating: verificationData, shouldDisplayError: shouldDisplayError ) } ) } func submitIdentityVerificationPage( id: String, ephemeralKeySecret: String ) -> Promise<VerificationPageData> { return STPAPIClient.shared.submitIdentityVerificationPage(id: id, ephemeralKeySecret: ephemeralKeySecret) } func uploadImage( _ image: UIImage, compressionQuality: CGFloat, purpose: String, fileName: String, ownedBy: String?, ephemeralKeySecret: String? ) -> Promise<StripeFile> { return STPAPIClient.shared.uploadImage( image, compressionQuality: compressionQuality, purpose: purpose, fileName: fileName, ownedBy: ownedBy, ephemeralKeySecret: ephemeralKeySecret ) } }
35.284946
121
0.645437
0960ea162eb0c2bfe82f614ddddc0ecffd5e0010
1,546
// // AssignedToMeViewController.swift // BugTracker // // Created by Charles-Olivier Demers on 2015-09-21. // Copyright (c) 2015 Charles-Olivier Demers. All rights reserved. // import UIKit class AppIdeaViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! private var refresher: UIRefreshControl! override func viewDidLoad() { super.viewDidLoad() refresher = UIRefreshControl() refresher.attributedTitle = NSAttributedString(string: "Tirez pour raffraîchir") refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) self.tableView.addSubview(refresher) } func refresh() { self.refresher.endRefreshing() } // Table View func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! AppIdeaTableViewCell cell.ideaNameLabel.text = globalAppIdea[indexPath.row].title() return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return globalAppIdea.count } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
30.313725
109
0.69599
1c65756de96d4d23a3a8dad154e57f9a35b75f28
1,362
// // IncidentAppTests.swift // IncidentAppTests // // Created by Shubham Kumar on 20/03/20. // Copyright © 2020 Shubham Kumar. All rights reserved. // import XCTest @testable import IncidentApp class IncidentAppTests: XCTestCase { var validation:Validation? override func setUp() { validation = Validation() // Put setup code here. This method is called before the invocation oeach test method in the class. } override func tearDown() { super.tearDown() validation = nil // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { let boolName = validation?.validateName(name: "johnkerry") XCTAssertEqual(boolName!, true, "name is not valid"); let boolPassword = validation?.validatePassword(password: "john@0012") XCTAssertEqual(boolPassword!, true, "password is not valid"); // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
28.978723
111
0.637298
0e2fc3cdedda4b2d393c0122c96bee16ad79e7c8
2,738
// // DislikePopView.swift // TodayNews // // Created by 杨蒙 on 2017/8/13. // Copyright © 2017年 hrscy. All rights reserved. // import UIKit import SVProgressHUD class DislikePopView: UIView { var filterWords = [WTTFilterWord]() { didSet { // 40 + 40 + 1 self.popViewHeight.constant = 81 + CGFloat(filterWords.count * 40) self.layoutIfNeeded() tableView.reloadData() } } @IBOutlet weak var bottomMargin: NSLayoutConstraint! @IBOutlet weak var popViewHeight: NSLayoutConstraint! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var finishButton: UIButton! override func awakeFromNib() { super.awakeFromNib() self.width = screenWidth self.height = screenHeight tableView.delegate = self tableView.dataSource = self tableView.register(UINib(nibName: String(describing: DislikeCell.self), bundle: nil), forCellReuseIdentifier: String(describing: DislikeCell.self)) } class func popView() -> DislikePopView { return Bundle.main.loadNibNamed(String(describing: self), owner: nil, options: nil)?.last as! DislikePopView } func show() { UIView.animate(withDuration: 0.25, animations: { self.bottomMargin.constant = 0 self.layoutIfNeeded() }) } func dismiss() { UIView.animate(withDuration: 0.25, animations: { self.bottomMargin.constant = -self.popViewHeight.constant self.layoutIfNeeded() }) { (_) in self.removeFromSuperview() } } /// 完成按钮点击 @IBAction func finishButtonClicked(_ sender: UIButton) { dismiss() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { dismiss() } } extension DislikePopView: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filterWords.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: DislikeCell.self), for: indexPath) as! DislikeCell let word = filterWords[indexPath.row] cell.wordLabel.text = word.name! return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: DislikeCell.self), for: indexPath) as! DislikeCell SVProgressHUD.showInfo(withStatus: cell.wordLabel.text!) dismiss() } }
31.471264
155
0.648283
dee313f440bf38078d728f8cfcc29a37405f7e9b
9,417
import UIKit protocol VideoProgressViewDelegate: class { func videoProgressViewDidBeginSeeking(_ videoProgressView: VideoProgressView) func videoProgressViewDidSeek(_ videoProgressView: VideoProgressView, toDuration duration: Double) func videoProgressViewDidEndSeeking(_ videoProgressView: VideoProgressView) } class VideoProgressView: UIView { weak var delegate: VideoProgressViewDelegate? #if os(iOS) static let height = CGFloat(55.0) private static let progressBarYMargin = CGFloat(23.0) private static let progressBarHeight = CGFloat(6.0) private static let textLabelHeight = CGFloat(18.0) private static let textLabelMargin = CGFloat(18.0) private static let seekViewHeight = CGFloat(45.0) private static let seekViewWidth = CGFloat(45.0) private static let font = UIFont.systemFont(ofSize: 14) #else static let height = CGFloat(110.0) private static let progressBarYMargin = CGFloat(46.0) private static let progressBarHeight = CGFloat(23.0) private static let textLabelHeight = CGFloat(36.0) private static let textLabelMargin = CGFloat(36.0) private static let seekViewHeight = CGFloat(90.0) private static let seekViewWidth = CGFloat(90.0) private static let font = UIFont.systemFont(ofSize: 28) #endif var duration = 0.0 { didSet { if self.duration != oldValue { self.durationTimeLabel.text = self.duration.timeString() self.layoutSubviews() } } } var progress = 0.0 { didSet { self.currentTimeLabel.text = self.progress.timeString() self.layoutSubviews() } } var progressPercentage: Double { guard self.progress != 0.0 && self.duration != 0.0 else { return 0.0 } return self.progress / self.duration } lazy var progressBarMask: UIView = { let maskView = UIView() maskView.backgroundColor = .clear maskView.layer.cornerRadius = VideoProgressView.progressBarHeight / 2 maskView.clipsToBounds = true maskView.layer.masksToBounds = true return maskView }() lazy var backgroundBar: UIView = { let backgroundBar = UIView() backgroundBar.backgroundColor = .white backgroundBar.alpha = 0.2 return backgroundBar }() lazy var progressBar: UIView = { let progressBar = UIView() progressBar.backgroundColor = .white return progressBar }() lazy var currentTimeLabel: UILabel = { let label = UILabel() label.font = VideoProgressView.font label.textColor = .white label.textAlignment = .center return label }() lazy var durationTimeLabel: UILabel = { let label = UILabel() label.font = VideoProgressView.font label.textColor = .white label.textAlignment = .center return label }() lazy var seekView: UIImageView = { let view = UIImageView() view.isUserInteractionEnabled = true view.image = UIImage(named: "seek") view.contentMode = .scaleAspectFit return view }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.progressBarMask) self.progressBarMask.addSubview(self.backgroundBar) self.progressBarMask.addSubview(self.progressBar) self.addSubview(self.seekView) self.addSubview(self.currentTimeLabel) self.addSubview(self.durationTimeLabel) let panGesture = UIPanGestureRecognizer(target: self, action: #selector(seek(gestureRecognizer:))) self.seekView.addGestureRecognizer(panGesture) #if os(tvOS) self.seekView.isHidden = true #endif } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() var currentTimeLabelFrame: CGRect { let width = self.currentTimeLabel.width() + VideoProgressView.textLabelMargin return CGRect(x: 0, y: VideoProgressView.textLabelMargin, width: width, height: VideoProgressView.textLabelHeight) } self.currentTimeLabel.frame = currentTimeLabelFrame var durationTimeLabelFrame: CGRect { let width = self.durationTimeLabel.width() + VideoProgressView.textLabelMargin let x = self.bounds.width - width return CGRect(x: x, y: VideoProgressView.textLabelMargin, width: width, height: VideoProgressView.textLabelHeight) } self.durationTimeLabel.frame = durationTimeLabelFrame var maskBarForRoundedCornersFrame: CGRect { let x = self.currentTimeLabel.frame.width let width = self.bounds.width - self.currentTimeLabel.frame.width - self.durationTimeLabel.frame.width return CGRect(x: x, y: VideoProgressView.progressBarYMargin, width: width, height: VideoProgressView.progressBarHeight) } self.progressBarMask.frame = maskBarForRoundedCornersFrame var backgroundBarFrame: CGRect { let width = self.progressBarMask.frame.width return CGRect(x: 0, y: 0, width: width, height: VideoProgressView.progressBarHeight) } self.backgroundBar.frame = backgroundBarFrame var progressBarFrame: CGRect { let width = self.progressBarMask.frame.width * CGFloat(self.progressPercentage) return CGRect(x: 0, y: 0, width: width, height: VideoProgressView.progressBarHeight) } self.progressBar.frame = progressBarFrame var seekViewFrame: CGRect { let x = self.progressBarMask.frame.origin.x + (self.progressBarMask.frame.size.width * CGFloat(self.progressPercentage)) - (VideoProgressView.seekViewWidth / 2) return CGRect(x: x, y: VideoProgressView.textLabelMargin, width: VideoProgressView.seekViewWidth, height: VideoProgressView.textLabelHeight) } self.seekView.frame = seekViewFrame } @objc func seek(gestureRecognizer: UIPanGestureRecognizer) { switch gestureRecognizer.state { case .began: self.delegate?.videoProgressViewDidBeginSeeking(self) case .changed: var pannableFrame = self.progressBarMask.frame pannableFrame.size.height = self.frame.height let translation = gestureRecognizer.translation(in: self.seekView) let newCenter = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y) let newX = newCenter.x - (VideoProgressView.seekViewWidth / 2) var progressPercentage = Double((-(self.progressBarMask.frame.origin.x - (VideoProgressView.seekViewWidth / 2) - newX)) / self.progressBarMask.frame.size.width) if progressPercentage < 0 { progressPercentage = 0 } else if progressPercentage > 1 { progressPercentage = 1 } if progressPercentage == 0 || progressPercentage == 1 { let x = self.progressBarMask.frame.origin.x + (self.progressBarMask.frame.size.width * CGFloat(progressPercentage)) - (VideoProgressView.seekViewWidth / 2) var frame = self.seekView.frame frame.origin.x = x self.seekView.frame = frame return } var progress = progressPercentage * self.duration if progress < 0 { progress = 0 } else if progress > self.duration { progress = self.duration } self.progress = progress gestureRecognizer.view!.center = newCenter gestureRecognizer.setTranslation(CGPoint.zero, in: self.seekView) self.delegate?.videoProgressViewDidSeek(self, toDuration: progress) case .ended: self.delegate?.videoProgressViewDidEndSeeking(self) default: break } } } public extension UILabel { func width() -> CGFloat { let rect = (self.attributedText ?? NSAttributedString()).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil) return rect.width } } extension Double { func timeString() -> String { let remaining = floor(self) let hours = Int(remaining / 3600) let minutes = Int(remaining / 60) - hours * 60 let seconds = Int(remaining) - hours * 3600 - minutes * 60 let formatter = NumberFormatter() formatter.minimumIntegerDigits = 2 let secondsString = String(format: "%02d", seconds) if hours > 0 { let hoursString = formatter.string(from: NSNumber(value: hours)) if let hoursString = hoursString { let minutesString = String(format: "%02d", minutes) return "\(hoursString):\(minutesString):\(secondsString)" } } else { if let minutesString = formatter.string(from: NSNumber(value: minutes)) { return "\(minutesString):\(secondsString)" } } return "" } }
36.08046
220
0.641499
e586e75731583ca8fb2e9004f72fce85c7e9048c
1,600
// 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 SoftwareUpdateConfigurationListResultData : SoftwareUpdateConfigurationListResultProtocol { public var value: [SoftwareUpdateConfigurationCollectionItemProtocol?]? enum CodingKeys: String, CodingKey {case value = "value" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.value) { self.value = try container.decode([SoftwareUpdateConfigurationCollectionItemData?]?.self, forKey: .value) } 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 { var container = encoder.container(keyedBy: CodingKeys.self) if self.value != nil {try container.encode(self.value as! [SoftwareUpdateConfigurationCollectionItemData?]?, forKey: .value)} } } extension DataFactory { public static func createSoftwareUpdateConfigurationListResultProtocol() -> SoftwareUpdateConfigurationListResultProtocol { return SoftwareUpdateConfigurationListResultData() } }
40
130
0.73625
ff777deceb054c816981de77407e1216da31b0c4
2,014
// // DemoViewModel.swift // // Created by Mike MacDougall on 1/20/17. // Copyright © 2017 Etsy. All rights reserved. // import UIKit enum DemoItemActionType { case pushViewController case invertColor } extension Collection { subscript (safe index: Index) -> Element? { return indices.contains(index) ? self[index] : nil } } class DemoViewModel { private var items: [DemoItem] init(numberOfItems: Int) { var tempItems = [DemoItem]() if numberOfItems > 0 { for i in 0...numberOfItems-1 { let isEven = i % 2 == 0 let color = isEven ? UIColor.green : UIColor.blue let actionType: DemoItemActionType = isEven ? .invertColor : .pushViewController let item = DemoItem(color: color, actionType: actionType) tempItems.append(item) } } items = tempItems } func numberOfItems() -> Int { return items.count } func item(index: Int) -> DemoItem? { return items[safe: index] } func invertColorAtIndex(index: Int) { guard let existingItem = items[safe: index] else { return } let newColor = existingItem.color == UIColor.blue ? UIColor.green : UIColor.blue let item = DemoItem(color: newColor, actionType: existingItem.actionType) if index < items.count && index >= 0 { items[index] = item } } } class DemoItem { let color: UIColor let titleColor: UIColor let actionType: DemoItemActionType init(color: UIColor, actionType: DemoItemActionType) { self.color = color self.actionType = actionType self.titleColor = color == UIColor.green ? UIColor.black : UIColor.white } func actionDescription() -> String { switch actionType { case .invertColor: return "Invert Color" case .pushViewController: return "Push View Controller" } } }
27.216216
96
0.595829
f87b05d18072341caef1186544934fe60013b937
2,373
// // Created by Mengyu Li on 2020/7/29. // import Foundation extension Data { mutating func nullify(range: Range<Int>) { let nullReplacement = Data(repeating: 0, count: range.count) replaceSubrange(range, with: nullReplacement) } } extension Data { mutating func replaceString(range: Range<Int>, filter: (String) -> Bool = { _ in true }, mapping: (String) -> String) { func stringRanges(in range: Range<Int>) -> [String: [Range<Int>]] { let enumeratedBytes: ArraySlice<(offset: Int, element: UInt8)> = Array(enumerated())[range] let chunksOfEnumeratedBytes = enumeratedBytes.split { _, data in data == 0 } let stringWithRangePairs: [(String, Range<Int>)] = chunksOfEnumeratedBytes.compactMap { chunk in let chunkBytes = chunk.map { _, data in data } guard let string = String(bytes: chunkBytes, encoding: .utf8) else { return nil } let chunkArray = Array(chunk) let range = (chunkArray.first!.offset..<(chunkArray.last!.offset + 1)) return (string, range) } return Dictionary(grouping: stringWithRangePairs) { string, _ in string } .mapValues { $0.map { _, range in range } } } let rangesPerString = stringRanges(in: range) rangesPerString.filter { filter($0.key) } .forEach { (originalString: String, ranges: [Range<Int>]) -> () in let mappedString = mapping(originalString) precondition(originalString.utf8.count >= mappedString.utf8.count) guard let mappedData = mappedString.data(using: .utf8) else { return } ranges.forEach { replaceWithPadding(range: $0, data: mappedData) } } } } extension Data { mutating func replaceWithPadding(range: Range<Int>, data: Data) { precondition(range.count >= data.count) let targetDataWithPadding = data + Array(repeating: UInt8(0), count: range.count - data.count) assert(range.count == targetDataWithPadding.count) replaceSubrange(range, with: targetDataWithPadding) } mutating func replaceWithPadding(range: Range<Int>, string: String) { guard let data = string.data(using: .utf8) else { fatalError() } replaceWithPadding(range: range, data: data) } }
43.944444
123
0.623262
e96e1a8f5dfee59188318d3c9ec6f85fdcedc3b8
754
import XCTest import gender_classifier 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. } } }
26
111
0.604775
ef93a39c25d84d12eca7cb32cae1cc786126e877
1,207
// // File.swift // // // Created by Denis Koryttsev on 10.05.2022. // extension BlendMode { /// The Core Image filter name for this `BlendMode`, that can be applied to a `CALayer`'s `compositingFilter`. /// Supported compositing filters are defined here: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP30000136-SW71 var filterName: String? { switch self { case .normal: return nil case .multiply: return "multiplyBlendMode" case .screen: return "screenBlendMode" case .overlay: return "overlayBlendMode" case .darken: return "darkenBlendMode" case .lighten: return "lightenBlendMode" case .colorDodge: return "colorDodgeBlendMode" case .colorBurn: return "colorBurnBlendMode" case .hardLight: return "hardLightBlendMode" case .softLight: return "softLightBlendMode" case .difference: return "differenceBlendMode" case .exclusion: return "exclusionBlendMode" case .hue: return "hueBlendMode" case .saturation: return "saturationBlendMode" case .color: return "colorBlendMode" case .luminosity: return "luminosityBlendMode" } } }
37.71875
209
0.73488
9019e21a402e0c6a836f6ff3e6c63a32e4365a84
819
// // BaseViewModel.swift // TasCar // // Created by Enrique Canedo on 09/07/2019. // Copyright © 2019 Enrique Canedo. All rights reserved. // import RxSwift import Action class BaseViewModel { let wireframe = BaseWireframe() let errorAction: ActionError = Action { element in return Observable.create({ (observer) -> Disposable in observer.onNext(element) observer.onCompleted() return Disposables.create() }) } var disposeBag = DisposeBag() // MARK: - Setups func setup(withPresenter presenter: UIViewController) { wireframe.presenterViewController = presenter } /// Override this method if you want to do something in the viewWillAppear of the ViewController func onViewWillAppear() { } }
24.088235
100
0.648352
f7a752a16f5d15fd1adb3c8e5d65888df69c7611
2,376
// // SceneDelegate.swift // ubble integration ios 12 // // Created by Sam on 10/01/2020. // Copyright © 2020 Ubbleai. All rights reserved. // import UIKit @available(iOS 13.0, *) class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.2
147
0.712542
dd8f56d074127ba8a0cb0ce26ccf298184354e21
5,273
// // helpers.swift // Stats // // Created by Serhiy Mytrovtsiy on 13/07/2020. // Using Swift 5.0. // Running on macOS 10.15. // // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // import Cocoa import os.log import StatsKit extension AppDelegate { internal func parseArguments() { let args = CommandLine.arguments if args.contains("--reset") { os_log(.debug, log: log, "Receive --reset argument. Reseting store (UserDefaults)...") Store.shared.reset() } if let disableIndex = args.firstIndex(of: "--disable") { if args.indices.contains(disableIndex+1) { let disableModules = args[disableIndex+1].split(separator: ",") disableModules.forEach { (moduleName: Substring) in if let module = modules.first(where: { $0.config.name.lowercased() == moduleName.lowercased()}) { module.unmount() } } } } if let mountIndex = args.firstIndex(of: "--mount-path") { if args.indices.contains(mountIndex+1) { let mountPath = args[mountIndex+1] asyncShell("/usr/bin/hdiutil detach \(mountPath)") asyncShell("/bin/rm -rf \(mountPath)") os_log(.debug, log: log, "DMG was unmounted and mountPath deleted") } } if let dmgIndex = args.firstIndex(of: "--dmg-path") { if args.indices.contains(dmgIndex+1) { asyncShell("/bin/rm -rf \(args[dmgIndex+1])") os_log(.debug, log: log, "DMG was deleted") } } } internal func parseVersion() { let key = "version" let currentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String if !Store.shared.exist(key: key) { Store.shared.reset() os_log(.debug, log: log, "Previous version not detected. Current version (%s) set", currentVersion) } else { let prevVersion = Store.shared.string(key: key, defaultValue: "") if prevVersion == currentVersion { return } if isNewestVersion(currentVersion: prevVersion, latestVersion: currentVersion) { _ = showNotification( title: localizedString("Successfully updated"), subtitle: localizedString("Stats was updated to v", currentVersion), id: "updated-from-\(prevVersion)-to-\(currentVersion)" ) } os_log(.debug, log: log, "Detected previous version %s. Current version (%s) set", prevVersion, currentVersion) } Store.shared.set(key: key, value: currentVersion) } internal func defaultValues() { if !Store.shared.exist(key: "runAtLoginInitialized") { Store.shared.set(key: "runAtLoginInitialized", value: true) LaunchAtLogin.isEnabled = true } if Store.shared.exist(key: "dockIcon") { let dockIconStatus = Store.shared.bool(key: "dockIcon", defaultValue: false) ? NSApplication.ActivationPolicy.regular : NSApplication.ActivationPolicy.accessory NSApp.setActivationPolicy(dockIconStatus) } if Store.shared.string(key: "update-interval", defaultValue: AppUpdateInterval.atStart.rawValue) != AppUpdateInterval.never.rawValue { self.checkForNewVersion() } } internal func checkForNewVersion() { updater.check { result, error in if error != nil { os_log(.error, log: log, "error updater.check(): %s", "\(error!.localizedDescription)") return } guard error == nil, let version: version_s = result else { os_log(.error, log: log, "download error(): %s", "\(error!.localizedDescription)") return } DispatchQueue.main.async(execute: { if version.newest { os_log(.debug, log: log, "show update window because new version of app found: %s", "\(version.latest)") self.updateNotification.identifier = "new-version-\(version.latest)" self.updateNotification.title = localizedString("New version available") self.updateNotification.subtitle = localizedString("Click to install the new version of Stats") self.updateNotification.soundName = NSUserNotificationDefaultSoundName self.updateNotification.hasActionButton = true self.updateNotification.actionButtonTitle = localizedString("Install") self.updateNotification.userInfo = ["url": version.url] NSUserNotificationCenter.default.delegate = self NSUserNotificationCenter.default.deliver(self.updateNotification) } }) } } }
40.251908
172
0.554144
507df4b81d382d20052bc57b8c288a0b93e44f17
1,491
// // RemoveCharacterUseCaseUnitTests.swift // MyComicsTests // // Created by Xavi on 28/10/21. // import XCTest @testable import MyComics class RemoveCharacterUseCaseUnitTests: XCTestCase { var sut: RemoveCharacterUseCase? override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. try super.setUpWithError() } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. sut = nil try super.tearDownWithError() } func testRemoveCharacterIsCalled(){ //GIVEN let repository = MockCharacterRepository() sut = RemoveCharacterUseCase(repository: repository) let character = Character(id: 1, name: "name", realName: "real_name", aliases: "aliases", image: nil, birth: "birth", deck: "deck", gender: .other, origin: "origin", powers: []) //WHEN sut!.execute(character : character) //THEN XCTAssertTrue(repository.isRemoveCharacterCalled) } }
29.82
111
0.519785
fc3ed6d5460f175af9d4d156761c9e824b0fec57
317
// // BuildUtil.swift // Pods // // Created by Levi Bostian on 12/29/16. // // import Foundation public class BuildUtil { public class func getVersionName() -> String { return Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String // swiftlint:disable:this force_cast } }
17.611111
120
0.665615
331c71037b92a93f668f04b4181ab506e28c2c07
7,153
// // MessageManager.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/14/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift public typealias MessagesHistoryCompletion = (Date?) -> Void struct MessageManager { static let historySize = 60 } let kBlockedUsersIndentifiers = "kBlockedUsersIndentifiers" extension MessageManager { static var blockedUsersList = UserDefaults.group.value(forKey: kBlockedUsersIndentifiers) as? [String] ?? [] static func getHistory(_ subscription: Subscription, lastMessageDate: Date?, completion: @escaping MessagesHistoryCompletion) { var lastDate: Any! if let lastMessageDate = lastMessageDate { lastDate = ["$date": lastMessageDate.timeIntervalSince1970 * 1000] } else { lastDate = NSNull() } let request = [ "msg": "method", "method": "loadHistory", "params": ["\(subscription.rid)", lastDate, historySize] ] as [String: Any] var lastMessageDate: Date? let currentRealm = Realm.current SocketManager.send(request) { response in guard !response.isError() else { return Log.debug(response.result.string) } let list = response.result["result"]["messages"].array let subscriptionIdentifier = subscription.identifier currentRealm?.execute({ (realm) in guard let detachedSubscription = realm.object(ofType: Subscription.self, forPrimaryKey: subscriptionIdentifier ?? "") else { return } list?.forEach { object in let mockNewMessage = Message() mockNewMessage.map(object, realm: realm) if let existingMessage = realm.object(ofType: Message.self, forPrimaryKey: object["identifier"].stringValue) { if existingMessage.updatedAt?.timeIntervalSince1970 == mockNewMessage.updatedAt?.timeIntervalSince1970 { return } } let message = Message.getOrCreate(realm: realm, values: object, updates: { (object) in object?.subscription = detachedSubscription }) realm.add(message, update: true) lastMessageDate = message.createdAt } }, completion: { completion(lastMessageDate) }) } } static func changes(_ subscription: Subscription) { let eventName = "\(subscription.rid)" let request = [ "msg": "sub", "name": "stream-room-messages", "id": eventName, "params": [eventName, false] ] as [String: Any] let currentRealm = Realm.current let subscriptionIdentifier = subscription.rid SocketManager.subscribe(request, eventName: eventName) { response in guard !response.isError() else { return Log.debug(response.result.string) } let object = response.result["fields"]["args"][0] currentRealm?.execute({ (realm) in guard let detachedSubscription = Subscription.find(rid: subscriptionIdentifier, realm: realm) else { return } let message = Message.getOrCreate(realm: realm, values: object, updates: { (object) in object?.subscription = detachedSubscription }) message.temporary = false realm.add(message, update: true) }) } } static func subscribeSystemMessages() { guard let userIdentifier = AuthManager.currentUser()?.identifier else { return } let eventName = "\(userIdentifier)/message" let request = [ "msg": "sub", "name": "stream-notify-user", "id": eventName, "params": [eventName, false] ] as [String: Any] let currentRealm = Realm.current SocketManager.subscribe(request, eventName: eventName) { response in guard !response.isError() else { return Log.debug(response.result.string) } if let object = response.result["fields"]["args"].array?.first?.dictionary { createSystemMessage(from: object, realm: currentRealm) } } } static func subscribeDeleteMessage(_ subscription: Subscription, completion: @escaping (_ msgId: String) -> Void) { let eventName = "\(subscription.rid)/deleteMessage" let request = [ "msg": "sub", "name": "stream-notify-room", "id": eventName, "params": [eventName, false] ] as [String: Any] let currentRealm = Realm.current SocketManager.subscribe(request, eventName: eventName) { response in guard !response.isError() else { return Log.debug(response.result.string) } if let msgId = response.result["fields"]["args"][0]["_id"].string { currentRealm?.execute({ realm in guard let message = realm.object(ofType: Message.self, forPrimaryKey: msgId) else { return } realm.delete(message) completion(msgId) }) } } } static func report(_ message: Message, completion: @escaping MessageCompletion) { guard let messageIdentifier = message.identifier else { return } let request = [ "msg": "method", "method": "reportMessage", "params": [messageIdentifier, "Message reported by user."] ] as [String: Any] SocketManager.send(request) { response in guard !response.isError() else { return Log.debug(response.result.string) } completion(response) } } static func react(_ message: Message, emoji: String, completion: @escaping MessageCompletion) { guard let messageIdentifier = message.identifier else { return } let request = [ "msg": "method", "method": "setReaction", "params": [emoji, messageIdentifier] ] as [String: Any] SocketManager.send(request, completion: completion) } static func blockMessagesFrom(_ user: User, completion: @escaping VoidCompletion) { guard let userIdentifier = user.identifier else { return } var blockedUsers: [String] = UserDefaults.group.value(forKey: kBlockedUsersIndentifiers) as? [String] ?? [] blockedUsers.append(userIdentifier) UserDefaults.group.setValue(blockedUsers, forKey: kBlockedUsersIndentifiers) self.blockedUsersList = blockedUsers Realm.execute({ (realm) in let messages = realm.objects(Message.self).filter("user.identifier = '\(userIdentifier)'") for message in messages { message.userBlocked = true } realm.add(messages, update: true) }, completion: completion) } }
35.765
149
0.585209
46d6ee3dc577930925630553f6e746657ce3478b
744
// // Analytics.swift // Analytics // // Created by minsone on 2019/09/28. // Copyright © 2019 minsone. All rights reserved. // import Foundation import Firebase public class DCAnalytics { public static func initialze() { guard let filePath = Bundle(for: DCAnalytics.self).path(forResource: "GoogleService-Info", ofType: "plist"), let fileopts = FirebaseOptions(contentsOfFile: filePath) else { return } FirebaseApp.configure(options: fileopts) Analytics.logEvent(AnalyticsEventSelectContent, parameters: [ AnalyticsParameterItemID: "id-111", AnalyticsParameterItemName: "title", AnalyticsParameterContentType: "cont" ]) } }
27.555556
114
0.653226
e5171eecba20fb17e2b6ab3345e8f109d36ffb11
316
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [Void{ } { deinit { func b { let end = [[Void{ case c, { return m(v: b { func a<T where B : Any)? } ((((v: b { func a: Any)? class case c, class c
15.047619
87
0.667722
d74677faeb3625a2901885c36c430f339659deef
941
// // Copyright © 2019 Essential Developer. All rights reserved. // import UIKit public final class ErrorView: UIView { @IBOutlet private var label: UILabel! public var message: String? { get { return isVisible ? label.text : nil } set { setMessageAnimated(newValue) } } public override func awakeFromNib() { super.awakeFromNib() label.text = nil alpha = 0 } private var isVisible: Bool { return alpha > 0 } private func setMessageAnimated(_ message: String?) { if let message = message { showAnimated(message) } else { hideMessageAnimated() } } private func showAnimated(_ message: String) { label.text = message UIView.animate(withDuration: 0.25) { self.alpha = 1 } } @IBAction private func hideMessageAnimated() { UIView.animate( withDuration: 0.25, animations: { self.alpha = 0 }, completion: { completed in if completed { self.label.text = nil } }) } }
18.45098
62
0.669501
4a5855023b78780bb7d2b6a4c06886bf9448263b
7,091
// // InAppNotificationManager.swift // ChatterBox // // Created by Roman Mizin on 8/21/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit import FirebaseDatabase import FirebaseAuth import AudioToolbox import SafariServices import CropViewController class InAppNotificationManager: NSObject { fileprivate var notificationReference: DatabaseReference! fileprivate var notificationHandle = [(handle: DatabaseHandle, chatID: String)]() fileprivate var conversations = [Conversation]() func updateConversations(to conversations: [Conversation]) { self.conversations = conversations } func removeAllObservers() { guard let currentUserID = Auth.auth().currentUser?.uid, notificationReference != nil else { return } let reference = Database.database().reference() for handle in notificationHandle { notificationReference = reference.child("user-messages").child(currentUserID).child(handle.chatID).child(messageMetaDataFirebaseFolder) notificationReference.removeObserver(withHandle: handle.handle) } notificationHandle.removeAll() } func observersForNotifications(conversations: [Conversation]) { removeAllObservers() updateConversations(to: conversations) for conversation in self.conversations { guard let currentUserID = Auth.auth().currentUser?.uid, let chatID = conversation.chatID else { continue } let handle = DatabaseHandle() let element = (handle: handle, chatID: chatID) notificationHandle.insert(element, at: 0) notificationReference = Database.database().reference().child("user-messages").child(currentUserID).child(chatID).child(messageMetaDataFirebaseFolder) notificationHandle[0].handle = notificationReference.observe(.childChanged, with: { (snapshot) in guard snapshot.key == "lastMessageID" else { return } guard let messageID = snapshot.value as? String else { return } guard let oldMessageID = conversation.lastMessageID, messageID > oldMessageID else { return } let lastMessageReference = Database.database().reference().child("messages").child(messageID) lastMessageReference.observeSingleEvent(of: .value, with: { (snapshot) in guard var dictionary = snapshot.value as? [String: AnyObject] else { return } dictionary.updateValue(messageID as AnyObject, forKey: "messageUID") let message = Message(dictionary: dictionary) guard let uid = Auth.auth().currentUser?.uid, message.fromId != uid else { return } self.handleInAppSoundPlaying(message: message, conversation: conversation, conversations: self.conversations) }) }) } } func handleInAppSoundPlaying(message: Message, conversation: Conversation, conversations: [Conversation]) { if UIApplication.topViewController() is SFSafariViewController || UIApplication.topViewController() is CropViewController || UIApplication.topViewController() is INSPhotosViewController { return } if DeviceType.isIPad { if let chatLogController = UIApplication.topViewController() as? ChatLogViewController, let currentOpenedChat = chatLogController.conversation?.chatID, let conversationID = conversation.chatID { if currentOpenedChat == conversationID { return } } } else { if UIApplication.topViewController() is ChatLogViewController { return } } if let index = conversations.firstIndex(where: { (conv) -> Bool in return conv.chatID == conversation.chatID }) { let isGroupChat = conversations[index].isGroupChat.value ?? false if let muted = conversations[index].muted.value, !muted, let chatName = conversations[index].chatName { self.playNotificationSound() if userDefaults.currentBoolObjectState(for: userDefaults.inAppNotifications) { self.showInAppNotification(conversation: conversations[index], title: chatName, subtitle: self.subtitleForMessage(message: message), resource: conversationAvatar(resource: conversations[index].chatThumbnailPhotoURL, isGroupChat: isGroupChat), placeholder: conversationPlaceholder(isGroupChat: isGroupChat) ) } } else if let chatName = conversations[index].chatName, conversations[index].muted.value == nil { self.playNotificationSound() if userDefaults.currentBoolObjectState(for: userDefaults.inAppNotifications) { self.showInAppNotification(conversation: conversations[index], title: chatName, subtitle: self.subtitleForMessage(message: message), resource: conversationAvatar(resource: conversations[index].chatThumbnailPhotoURL, isGroupChat: isGroupChat), placeholder: conversationPlaceholder(isGroupChat: isGroupChat)) } } } } fileprivate func subtitleForMessage(message: Message) -> String { if (message.imageUrl != nil || message.localImage != nil) && message.videoUrl == nil { return MessageSubtitle.image } else if (message.imageUrl != nil || message.localImage != nil) && message.videoUrl != nil { return MessageSubtitle.video } else if message.voiceEncodedString != nil { return MessageSubtitle.audio } else { return message.text ?? "" } } fileprivate func conversationAvatar(resource: String?, isGroupChat: Bool) -> Any { let placeHolderImage = isGroupChat ? UIImage(named: "GroupIcon") : UIImage(named: "UserpicIcon") guard let imageURL = resource, imageURL != "" else { return placeHolderImage! } return URL(string: imageURL)! } fileprivate func conversationPlaceholder(isGroupChat: Bool) -> Data? { let placeHolderImage = isGroupChat ? UIImage(named: "GroupIcon") : UIImage(named: "UserpicIcon") guard let data = placeHolderImage?.asJPEGData else { return nil } return data } fileprivate func showInAppNotification(conversation: Conversation, title: String, subtitle: String, resource: Any?, placeholder: Data?) { let notification: InAppNotification = InAppNotification(resource: resource, title: title, subtitle: subtitle, data: placeholder) InAppNotificationDispatcher.shared.show(notification: notification) { (_) in guard let controller = UIApplication.shared.keyWindow?.rootViewController else { return } guard let id = conversation.chatID, let realmConversation = RealmKeychain.defaultRealm.objects(Conversation.self).filter("chatID == %@", id).first else { chatLogPresenter.open(conversation, controller: controller) return } chatLogPresenter.open(realmConversation, controller: controller) } } fileprivate func playNotificationSound() { if userDefaults.currentBoolObjectState(for: userDefaults.inAppSounds) { SystemSoundID.playFileNamed(fileName: "notification", withExtenstion: "caf") } if userDefaults.currentBoolObjectState(for: userDefaults.inAppVibration) { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } } }
48.568493
317
0.72176
b979fe39201157c32906e913fbc8a36c6628b665
12,706
import UIKit import MBProgressHUD public typealias HUDMode = MBProgressHUDMode public typealias HUDAnimation = MBProgressHUDAnimation public typealias HUDBackgroundStyle = MBProgressHUDBackgroundStyle public typealias HUDCompletionBlock = MBProgressHUDCompletionBlock public enum HUDStatus { case success case error case info case star case hollowStar case waitting } public struct HUDConfig { public static var imageSucess: UIImage? = HUD.bundleImage(by: "ic_tips_sucess")?.template public static var imageInfo: UIImage? = HUD.bundleImage(by: "ic_tips_info")?.template public static var imageError: UIImage? = HUD.bundleImage(by: "ic_tips_error")?.template public static var textColor: UIColor = UIColor.white public static var textFont: UIFont = .boldSystemFont(ofSize: 16) public static var contentColor: UIColor = UIColor.white public static var defaultDismissDuration: TimeInterval = 2.0 public static var offSetY: CGFloat = 0 public static var margin: CGFloat = 20 public static var isSquare: Bool = true public static var minSize: CGSize = CGSize(width: 100, height: 100) public static var cornerRadius: CGFloat = 5.0 public static var animationType: HUDAnimation = .zoom public static var backgroundStyle: HUDBackgroundStyle = .solidColor public static var backgroundColor: UIColor = UIColor.black public static var defaultWindow: UIWindow? public static var defaultLoadingText: String = "加载中..." public static var defaultToastInteraction: Bool = true public static var defaultHUDInteraction: Bool = false } open class HUD: MBProgressHUD { // MARK: - 在 window 上添加一个 HUD public static let shared = HUD(view: HUD.defaultWindow()) // MARK: - 在 window 上添加一个 HUD @discardableResult public static func showStatus(status: HUDStatus, text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return HUD.defaultWindow().showStatus(status: status, text: text, duration: duration, interaction: interaction) } // MARK: - 在 window 上添加一个只显示文字的 HUD @discardableResult public static func showMessage( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultToastInteraction ) -> HUD? { return HUD.defaultWindow().showMessage(text: text, duration: duration, interaction: interaction) } // MARK: - 在 window 上添加一个提示`信息`的 HUD @discardableResult public static func showInfoMsg( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return HUD.defaultWindow().showStatus(status: .info, text: text, duration: duration, interaction: interaction) } // MARK: - 在 window 上添加一个提示`失败`的 HUD @discardableResult public static func showFailure( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return HUD.defaultWindow().showStatus(status: .error, text: text, duration: duration, interaction: interaction) } // MARK: - 在 window 上添加一个提示`成功`的 HUD @discardableResult public static func showSuccess( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return HUD.defaultWindow().showStatus(status: .success, text: text, duration: duration, interaction: interaction) } // MARK: - 在 window 上添加一个提示`收藏成功`的 HUD @discardableResult public static func showAddFavorites( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return HUD.defaultWindow().showStatus(status: .star, text: text, duration: duration, interaction: interaction) } // MARK: - 在 window 上添加一个提示`取消收藏`的 HUD @discardableResult public static func showRemoveFavorites( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return HUD.defaultWindow().showStatus(status: .hollowStar, text: text, duration: duration, interaction: interaction) } // MARK: - 在 window 上添加一个提示`等待`的 HUD, 需要手动关闭 @discardableResult public static func showLoading( text: String?, duration: TimeInterval? = nil, interaction: Bool = false ) -> HUD? { return HUD.defaultWindow().showStatus(status: .waitting, text: text, duration: duration, interaction: interaction) } // MARK: - 手动隐藏 HUD public static func hide() { HUD.defaultWindow().hide() } public static func hideAllHUD() { HUD.hideAllHUD(for: HUD.defaultWindow()) } public static func hideAllHUD(for view: UIView) { for subview in view.subviews { guard let hud = subview as? MBProgressHUD else { continue } hud.removeFromSuperViewOnHide = true hud.hide(animated: true) } } // MARK: - private methods fileprivate static func defaultWindow() -> UIWindow { if let defaultWindow = HUDConfig.defaultWindow { return defaultWindow } guard let keywindow = UIApplication.shared.keyWindow else { assert(false, "application no key window") return UIWindow() } return keywindow } fileprivate static func bundleImage(by name: String) -> UIImage? { let resource_bundle = Bundle(path: Bundle(for: HUD.self).resourcePath ?? "") return UIImage(named: name, in: resource_bundle, compatibleWith: nil) } } public extension UIView { // MARK: - 在 view 上添加一个 HUD @discardableResult func showStatus(status: HUDStatus, text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { let hud = HUD.shared hud.removeFromSuperview() hud.frame = self.bounds hud.show(animated: true) hud.label.text = text hud.removeFromSuperViewOnHide = true hud.label.font = HUDConfig.textFont hud.label.textColor = HUDConfig.textColor hud.label.numberOfLines = 0 hud.contentColor = HUDConfig.contentColor hud.bezelView.style = HUDConfig.backgroundStyle hud.bezelView.backgroundColor = HUDConfig.backgroundColor hud.bezelView.cornerRadius = HUDConfig.cornerRadius hud.animationType = HUDConfig.animationType hud.isUserInteractionEnabled = !interaction hud.isSquare = HUDConfig.isSquare hud.margin = HUDConfig.margin hud.minSize = .zero addSubview(hud) switch status { case .success: hud.mode = .customView hud.hide(animated: true, afterDelay: duration ?? HUDConfig.defaultDismissDuration) let imageView = UIImageView(image: HUDConfig.imageSucess) imageView.tintColor = HUDConfig.contentColor hud.customView = imageView case .error: hud.mode = .customView hud.hide(animated: true, afterDelay: duration ?? HUDConfig.defaultDismissDuration) let imageView = UIImageView(image: HUDConfig.imageError) imageView.tintColor = HUDConfig.contentColor hud.customView = imageView case .info: hud.mode = .customView hud.hide(animated: true, afterDelay: duration ?? HUDConfig.defaultDismissDuration) let imageView = UIImageView(image: HUDConfig.imageInfo) imageView.tintColor = HUDConfig.contentColor hud.customView = imageView case .star: hud.mode = .customView hud.hide(animated: true, afterDelay: duration ?? HUDConfig.defaultDismissDuration) let imageView = UIImageView(image: HUDConfig.imageInfo) imageView.tintColor = HUDConfig.contentColor hud.customView = imageView case .hollowStar: hud.mode = .customView hud.hide(animated: true, afterDelay: duration ?? HUDConfig.defaultDismissDuration) let imageView = UIImageView(image: HUDConfig.imageInfo) imageView.tintColor = HUDConfig.contentColor hud.customView = imageView case .waitting: hud.mode = .indeterminate hud.isUserInteractionEnabled = false } return hud } // MARK: - 在 view 上添加一个只显示文字的 HUD @discardableResult func showMessage( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultToastInteraction ) -> HUD? { guard let text = text, !text.isEmpty else { return nil } let hud = HUD.showAdded(to: self, animated: true) hud.minSize = .zero hud.mode = .text hud.removeFromSuperViewOnHide = true hud.label.text = text hud.label.textColor = HUDConfig.textColor hud.label.font = HUDConfig.textFont hud.label.numberOfLines = 0 hud.isUserInteractionEnabled = !interaction hud.contentColor = HUDConfig.contentColor hud.bezelView.style = HUDConfig.backgroundStyle hud.bezelView.backgroundColor = HUDConfig.backgroundColor hud.bezelView.cornerRadius = HUDConfig.cornerRadius hud.animationType = HUDConfig.animationType hud.margin = HUDConfig.margin hud.isSquare = false hud.minSize = .zero hud.hide(animated: true, afterDelay: duration ?? HUDConfig.defaultDismissDuration) return hud } // MARK: - 在 view 上添加一个提示`信息`的 HUD @discardableResult func showInfoMsg( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return self.showStatus(status: .info, text: text, duration: duration, interaction: interaction) } // MARK: - 在 view 上添加一个提示`失败`的 HUD @discardableResult func showFailure( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return self.showStatus(status: .error, text: text, duration: duration, interaction: interaction) } // MARK: - 在 view 上添加一个提示`成功`的 HUD @discardableResult func showSuccess( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return self.showStatus(status: .success, text: text, duration: duration, interaction: interaction) } // MARK: - 在 view 上添加一个提示`收藏成功`的 HUD @discardableResult func showAddFavorites( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return self.showStatus(status: .star, text: text, duration: duration, interaction: interaction) } // MARK: - 在 view 上添加一个提示`取消收藏`的 HUD @discardableResult func showRemoveFavorites( text: String?, duration: TimeInterval? = nil, interaction: Bool = HUDConfig.defaultHUDInteraction ) -> HUD? { return self.showStatus(status: .hollowStar, text: text, duration: duration, interaction: interaction) } // MARK: - 在 view 上添加一个提示`等待`的 HUD, 需要手动关闭 @discardableResult func showLoading( text: String?, duration: TimeInterval? = nil, interaction: Bool = false ) -> HUD? { return self.showStatus(status: .waitting, text: text, duration: duration, interaction: interaction) } // MARK: - 手动隐藏 HUD func hide() { HUD.hide(for: self, animated: true) } }
31.528536
124
0.611916
9122b22bcdf809ab7e9242690d40bf089f8f4270
1,326
//// Created by Cihat Gündüz on 11.02.16. // //@testable import BartyCrouchKit //import XCTest // //class IBToolCommanderTests: XCTestCase { // func testiOSExampleStoryboard() { // let storyboardPath = "\(BASE_DIR)/Tests/Resources/Storyboards/iOS/base.lproj/Example.storyboard" // let stringsFilePath = storyboardPath + ".strings" // // let exportSuccess = IBToolCommander.shared.export(stringsFileToPath: stringsFilePath, fromIbFileAtPath: storyboardPath) // // XCTAssertTrue(exportSuccess) // } // // func testOSXExampleStoryboard() { // let storyboardPath = "\(BASE_DIR)/Tests/Resources/Storyboards/macOS/base.lproj/Example.storyboard" // let stringsFilePath = storyboardPath + ".strings" // // let exportSuccess = IBToolCommander.shared.export(stringsFileToPath: stringsFilePath, fromIbFileAtPath: storyboardPath) // // XCTAssertTrue(exportSuccess) // } // // func testtvOSExampleStoryboard() { // let storyboardPath = "\(BASE_DIR)/Tests/Resources/Storyboards/tvOS/base.lproj/Example.storyboard" // let stringsFilePath = storyboardPath + ".strings" // // let exportSuccess = IBToolCommander.shared.export(stringsFileToPath: stringsFilePath, fromIbFileAtPath: storyboardPath) // // XCTAssertTrue(exportSuccess) // } //}
39
129
0.707391
d75fb15d1319585b5aebc45705e5783faa65e639
1,889
// // PlaylistDetailService.swift // MusicApp // // Created by Hưng Đỗ on 6/18/17. // Copyright © 2017 HungDo. All rights reserved. // import RxSwift protocol PlaylistDetailService { var repository: PlaylistRepository { get } var notification: PlaylistNotification { get } var songCoordinator: SongCoordinator { get } // MARK: Repository func getPlaylist(_ playlist: Playlist) -> Observable<PlaylistDetailInfo> // MARK: Coordinator func openContextMenu(_ song: Song, in controller: UIViewController) -> Observable<Void> // MARK: Notification func play(tracks: [Track], selectedTrack: Track) -> Observable<Void> } class MAPlaylistDetailService: PlaylistDetailService { let repository: PlaylistRepository let notification: PlaylistNotification let songCoordinator: SongCoordinator init(repository: PlaylistRepository, notification: PlaylistNotification, songCoordinator: SongCoordinator) { self.repository = repository self.notification = notification self.songCoordinator = songCoordinator } // MARK: Repository func getPlaylist(_ playlist: Playlist) -> Observable<PlaylistDetailInfo> { return self.repository.getPlaylist(playlist) .map { detailTuple in let (tracks, playlists) = detailTuple return PlaylistDetailInfo(tracks: tracks, playlists: playlists) } } // MARK: Coordinator func openContextMenu(_ song: Song, in controller: UIViewController) -> Observable<Void> { return songCoordinator.openContextMenu(song, in: controller) } // MARK: Music Center func play(tracks: [Track], selectedTrack: Track) -> Observable<Void> { return notification.play(tracks: tracks, selectedTrack: selectedTrack) } }
28.621212
112
0.672843