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
9c932b5dc4e59a601aa3dfadf844bf723d648138
2,590
// // Copyright © 2019 Essential Developer. All rights reserved. // import UIKit import EssentialFeed public protocol FeedViewControllerDelegate { func didRequestFeedRefresh() } public final class FeedViewController: UITableViewController, UITableViewDataSourcePrefetching, FeedLoadingView, FeedErrorView { @IBOutlet private(set) public var errorView: ErrorView? private var loadingControllers = [IndexPath: FeedImageCellController]() private var tableModel = [FeedImageCellController]() { didSet { tableView.reloadData() } } public var delegate: FeedViewControllerDelegate? public override func viewDidLoad() { super.viewDidLoad() refresh() } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.sizeTableHeaderToFit() } @IBAction private func refresh() { delegate?.didRequestFeedRefresh() } public func display(_ cellControllers: [FeedImageCellController]) { loadingControllers = [:] tableModel = cellControllers } public func display(_ viewModel: FeedLoadingViewModel) { refreshControl?.update(isRefreshing: viewModel.isLoading) } public func display(_ viewModel: FeedErrorViewModel) { errorView?.message = viewModel.message } public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableModel.count } public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return cellController(forRowAt: indexPath).view(in: tableView) } public override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { cancelCellControllerLoad(forRowAt: indexPath) } public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { indexPaths.forEach { indexPath in cellController(forRowAt: indexPath).preload() } } public func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) { indexPaths.forEach(cancelCellControllerLoad) } public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { cellController(forRowAt: indexPath).selected() } private func cellController(forRowAt indexPath: IndexPath) -> FeedImageCellController { let controller = tableModel[indexPath.row] loadingControllers[indexPath] = controller return controller } private func cancelCellControllerLoad(forRowAt indexPath: IndexPath) { loadingControllers[indexPath]?.cancelLoad() loadingControllers[indexPath] = nil } }
29.101124
130
0.779923
2895610e9fccab852c818da814626318710b16e8
3,189
public struct Validations { var storage: [Validation] public init() { self.storage = [] } public mutating func add<T>( _ key: ValidationKey, as type: T.Type = T.self, is validator: Validator<T> = .valid, required: Bool = true, customFailureDescription: String? = nil ) { let validation = Validation(key: key, required: required, validator: validator, customFailureDescription: customFailureDescription) self.storage.append(validation) } public mutating func add( _ key: ValidationKey, result: ValidatorResult, customFailureDescription: String? = nil ) { let validation = Validation(key: key, result: result, customFailureDescription: customFailureDescription) self.storage.append(validation) } public mutating func add( _ key: ValidationKey, required: Bool = true, customFailureDescription: String? = nil, _ nested: (inout Validations) -> () ) { var validations = Validations() nested(&validations) let validation = Validation(nested: key, required: required, keyed: validations, customFailureDescription: customFailureDescription) self.storage.append(validation) } public mutating func add( each key: ValidationKey, required: Bool = true, customFailureDescription: String? = nil, _ handler: @escaping (Int, inout Validations) -> () ) { let validation = Validation(nested: key, required: required, unkeyed: handler, customFailureDescription: customFailureDescription) self.storage.append(validation) } public func validate(request: Request) throws -> ValidationsResult { guard let contentType = request.headers.contentType else { throw Abort(.unprocessableEntity, reason: "Missing \"Content-Type\" header") } guard let body = request.body.data else { throw Abort(.unprocessableEntity, reason: "Empty Body") } let contentDecoder = try ContentConfiguration.global.requireDecoder(for: contentType) let decoder = try contentDecoder.decode(DecoderUnwrapper.self, from: body, headers: request.headers) return try self.validate(decoder.decoder) } public func validate(query: URI) throws -> ValidationsResult { let urlDecoder = try ContentConfiguration.global.requireURLDecoder() let decoder = try urlDecoder.decode(DecoderUnwrapper.self, from: query) return try self.validate(decoder.decoder) } public func validate(json: String) throws -> ValidationsResult { let decoder = try JSONDecoder().decode(DecoderUnwrapper.self, from: Data(json.utf8)) return try self.validate(decoder.decoder) } public func validate(_ decoder: Decoder) throws -> ValidationsResult { try self.validate(decoder.container(keyedBy: ValidationKey.self)) } internal func validate(_ decoder: KeyedDecodingContainer<ValidationKey>) -> ValidationsResult { .init(results: self.storage.map { $0.run(decoder) }) } }
37.964286
140
0.658827
febfe2c15caed3bfae9caeb3e8dd90328eea6e75
4,146
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftCrypto open source project // // Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.md for the list of SwiftCrypto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @_exported import CryptoKit #else import Foundation extension ASN1 { // A PKCS#8 private key is one of two formats, depending on the version: // // For PKCS#8 we need the following for the private key: // // PrivateKeyInfo ::= SEQUENCE { // version Version, // privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, // privateKey PrivateKey, // attributes [0] IMPLICIT Attributes OPTIONAL } // // Version ::= INTEGER // // PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier // // PrivateKey ::= OCTET STRING // // Attributes ::= SET OF Attribute // // We disregard the attributes because we don't support them anyway. // // The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the // ASN.1 parser and go again. struct PKCS8PrivateKey: ASN1Parseable, ASN1Serializable { var algorithm: RFC5480AlgorithmIdentifier var privateKey: ASN1.SEC1PrivateKey init(asn1Encoded rootNode: ASN1.ASN1Node) throws { self = try ASN1.sequence(rootNode) { nodes in let version = try Int(asn1Encoded: &nodes) guard version == 0 else { throw CryptoKitASN1Error.invalidASN1Object } let algorithm = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes) let privateKeyBytes = try ASN1.ASN1OctetString(asn1Encoded: &nodes) // We ignore the attributes _ = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in } let sec1PrivateKeyNode = try ASN1.parse(privateKeyBytes.bytes) let sec1PrivateKey = try ASN1.SEC1PrivateKey(asn1Encoded: sec1PrivateKeyNode) if let innerAlgorithm = sec1PrivateKey.algorithm, innerAlgorithm != algorithm { throw CryptoKitASN1Error.invalidASN1Object } return try .init(algorithm: algorithm, privateKey: sec1PrivateKey) } } private init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: ASN1.SEC1PrivateKey) throws { self.privateKey = privateKey self.algorithm = algorithm } init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: [UInt8], publicKey: [UInt8]) { self.algorithm = algorithm // We nil out the private key here. I don't really know why we do this, but OpenSSL does, and it seems // safe enough to do: it certainly avoids the possibility of disagreeing on what it is! self.privateKey = ASN1.SEC1PrivateKey(privateKey: privateKey, algorithm: nil, publicKey: publicKey) } func serialize(into coder: inout ASN1.Serializer) throws { try coder.appendConstructedNode(identifier: .sequence) { coder in try coder.serialize(0) // version try coder.serialize(self.algorithm) // Here's a weird one: we recursively serialize the private key, and then turn the bytes into an octet string. var subCoder = ASN1.Serializer() try subCoder.serialize(self.privateKey) let serializedKey = ASN1.ASN1OctetString(contentBytes: subCoder.serializedBytes[...]) try coder.serialize(serializedKey) } } } } #endif // Linux or !SwiftPM
41.46
126
0.612156
d7f63ec8ff0f8e4c2fb9198e29db527cb0fe5862
2,164
// // DefaultEvent.swift // BaseApplication // // Created by Dang Huu Tri on 1/15/20. // Copyright © 2020 Dang Huu Tri. All rights reserved // import Foundation public enum DefaultEvent : String { // Common events from Firebase SDK: //* Retail/Ecommerce/travel case addPaymentInfo = "AnalyticalAddPaymentInfo" case checkoutProgress = "AnalyticalCheckoutProgress" case checkoutOption = "AnalyticalCheckoutOption" case addToCart = "AnalyticalAddToCart" case addToWishList = "AnalyticalAddToWishList" case beginCheckout = "AnalyticalBeginCheckout" case ecomPurchase = "AnalyticalaEcomPurchase" case generateLead = "AnalyticalGenerateLead" case purchase = "AnalyticalPurchase" case purchaseRefund = "AnalyticalPurchaseRefund" case viewItem = "AnalyticalViewItem" case viewItemList = "AnalyticalViewItemList" case viewSearchResult = "AnalyticalViewSearchResult" case search = "AnalyticalSearch" case earnVirtualCurrency = "AnalyticalEarnVirtualCurrency" case joinGroup = "AnalyticalJoinGroup" case levelUp = "AnalyticalLevelUp" case postScore = "AnalyticalPostScore" case selectContent = "AnalyticalSelectContent" case spendVirtualCurrency = "AnalyticalSpendVirtualCurrency" case tutorialBegin = "AnalyticalTutorialBegin" case tutorialComplete = "AnalyticalTutorialComplete" case tutorialUnlockAchievement = "AnalyticalTutorialUnlockAchievement" case pushNotification = "AnalyticalEventPushNotification" case campaignDetail = "AnalyticalCampaignDetail" case signUp = "AnalyticalSignUp" case presentOffer = "AnalyticalPresentOffer" case removeFromCart = "AnalyticalRemoveOffer" case share = "AnalyticalShare" case completedRegistration = "AnalyticalCompletedRegistration" } //public extension DefaultEvent { // func event() -> AnalyticalEvent { // return AnalyticalEvent(type: .default, name: self.rawValue, properties: nil) // } //}
41.615385
86
0.691774
6a885d57b031bd042bc03802b0d47fdbd463b6b0
1,289
// // Scopable.swift // Tiv Bible SwiftUI // // Created by Isaac Iniongun on 18/06/2021. // import Foundation protocol Scopable {} extension Scopable { @discardableResult @inline(__always) func apply(block: (Self) -> ()) -> Self { block(self) return self } @inline(__always) func `do`(block: (Self) -> ()) { block(self) } @inline(__always) func `let`<R>(block: (Self) -> R) -> R { return block(self) } @inline(__always) func also(block: (Self) -> ()) -> Self { block(self) return self } @inline(__always) func takeIf(predicate: (Self) -> Bool) -> Self? { if (predicate(self)) { return self } else { return nil } } @inline(__always) func takeUnless(predicate: (Self) -> Bool) -> Self? { if (!predicate(self)) { return self } else { return nil } } @inline(__always) func `repeat`(times: Int, action: (Int) -> ()) -> () { for index in (0...times-1) { action(index) } } } extension NSObject: Scopable {} extension String: Scopable {} @discardableResult func with<T>(_ it: T, f:(T) -> ()) -> T { f(it) return it }
20.460317
82
0.505818
79d565d513efebe0725b5bad3e19639ae4270022
447
// // AppController+SetupRoutes.swift // Freetime // // Created by Ryan Nystrom on 10/7/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import Foundation extension AppController { func setupRoutes() { register(route: BookmarkShortcutRoute.self) register(route: SwitchAccountShortcutRoute.self) register(route: SearchShortcutRoute.self) register(route: IssueNotificationRoute.self) } }
21.285714
56
0.702461
e2ed6a4fcdc54d92622e1766435459c8a962b3a1
2,525
import TuistCore import TuistSupport import XCTest @testable import TuistDependencies @testable import TuistSupportTesting final class CarthageCommandGeneratorTests: TuistUnitTestCase { private var subject: CarthageCommandGenerator! override func setUp() { super.setUp() subject = CarthageCommandGenerator() } override func tearDown() { subject = nil super.tearDown() } func test_command() throws { // Given let stubbedPath = try temporaryPath() let expected = "carthage bootstrap --project-directory \(stubbedPath.pathString) --use-netrc --cache-builds --new-resolver" // When let got = subject .command(path: stubbedPath, platforms: nil, options: nil) .joined(separator: " ") // Then XCTAssertEqual(got, expected) } func test_command_with_platforms() throws { // Given let stubbedPath = try temporaryPath() let expected = "carthage bootstrap --project-directory \(stubbedPath.pathString) --platform iOS --use-netrc --cache-builds --new-resolver" // When let got = subject .command(path: stubbedPath, platforms: [.iOS], options: nil) .joined(separator: " ") // Then XCTAssertEqual(got, expected) } func test_command_with_platforms_and_xcframeworks() throws { // Given let stubbedPath = try temporaryPath() let expected = "carthage bootstrap --project-directory \(stubbedPath.pathString) --platform iOS,macOS,tvOS,watchOS --use-netrc --cache-builds --new-resolver --use-xcframeworks" // When let got = subject .command(path: stubbedPath, platforms: [.iOS, .tvOS, .macOS, .watchOS], options: [.useXCFrameworks]) .joined(separator: " ") // Then XCTAssertEqual(got, expected) } func test_command_with_platforms_and_xcframeworks_and_noUseBinaries() throws { // Given let stubbedPath = try temporaryPath() let expected = "carthage bootstrap --project-directory \(stubbedPath.pathString) --platform iOS,macOS,tvOS,watchOS --use-netrc --cache-builds --new-resolver --use-xcframeworks --no-use-binaries" // When let got = subject .command(path: stubbedPath, platforms: [.iOS, .tvOS, .macOS, .watchOS], options: [.useXCFrameworks, .noUseBinaries]) .joined(separator: " ") // Then XCTAssertEqual(got, expected) } }
32.792208
202
0.637228
3aebeb387864acd84b8f0c8cc8ed89e2e4e98ae1
8,124
// // WalletConnectTransactionBuilder.swift // Tangem Tap // // Created by Andrew Son on 17/05/21. // Copyright © 2021 Tangem AG. All rights reserved. // import Foundation import BlockchainSdk import Combine import WalletConnectSwift class WalletConnectTransactionHandler: TangemWalletConnectRequestHandler { unowned var assembly: Assembly unowned var scannedCardsRepo: ScannedCardsRepository unowned var delegate: WalletConnectHandlerDelegate? unowned var dataSource: WalletConnectHandlerDataSource? let signer: TangemSigner var action: WalletConnectAction { fatalError("Subclass must implement") } var bag: Set<AnyCancellable> = [] init(signer: TangemSigner, delegate: WalletConnectHandlerDelegate, dataSource: WalletConnectHandlerDataSource, assembly: Assembly, scannedCardsRepo: ScannedCardsRepository) { self.assembly = assembly self.scannedCardsRepo = scannedCardsRepo self.signer = signer self.delegate = delegate self.dataSource = dataSource } func canHandle(request: Request) -> Bool { action.rawValue == request.method } func handle(request: Request) { fatalError("Subclass must implement") } func handleTransaction(from request: Request) -> (session: WalletConnectSession, tx: WalletConnectEthTransaction)? { do { let transaction = try request.parameter(of: WalletConnectEthTransaction.self, at: 0) guard let session = dataSource?.session(for: request, address: transaction.from) else { delegate?.sendReject(for: request, with: WalletConnectServiceError.sessionNotFound, for: action) return nil } return (session, transaction) } catch { delegate?.sendInvalid(request) return nil } } func sendReject(for request: Request, error: Error?) { delegate?.sendReject(for: request, with: error ?? WalletConnectServiceError.cancelled, for: action) bag = [] } func buildTx(in session: WalletConnectSession, _ transaction: WalletConnectEthTransaction) -> AnyPublisher<(WalletModel, Transaction), Error> { let wallet = session.wallet guard let card = scannedCardsRepo.cards[wallet.cid] else { return .anyFail(error: WalletConnectServiceError.cardNotFound) } let blockchain = Blockchain.ethereum(testnet: wallet.isTestnet) let walletModels = assembly.makeWallets(from: CardInfo(card: card, artworkInfo: nil, twinCardInfo: nil), blockchains: [blockchain]) guard let ethWalletModel = walletModels.first(where: { $0.wallet.address.lowercased() == transaction.from.lowercased() }), let gasLoader = ethWalletModel.walletManager as? EthereumGasLoader, let value = try? EthereumUtils.parseEthereumDecimal(transaction.value, decimalsCount: blockchain.decimalCount), let gas = transaction.gas?.hexToInteger ?? transaction.gasLimit?.hexToInteger else { return .anyFail(error: WalletConnectServiceError.failedToBuildTx) } let valueAmount = Amount(with: blockchain, address: wallet.address, type: .coin, value: value) ethWalletModel.update() // This zip attempting to load gas price and update wallet balance. // In some cases (ex. when swapping currencies on OpenSea) dApp didn't send gasPrice, that why we need to load this data from blockchain // Also we must identify that wallet failed to update balance. // If we couldn't get gasPrice and can't update wallet balance reject message will be send to dApp return Publishers.Zip(getGasPrice(for: valueAmount, tx: transaction, txSender: gasLoader, decimalCount: blockchain.decimalCount), ethWalletModel .$state .setFailureType(to: Error.self) .tryMap { state -> WalletModel.State in switch state { case .failed(let error): throw error case .noAccount(let message): throw message default: return state } } .filter { $0 == .idle }) .flatMap { (gasPrice, state) -> AnyPublisher<Transaction, Error> in Future { [weak self] promise in let gasAmount = Amount(with: blockchain, address: wallet.address, type: .coin, value: Decimal(gas * gasPrice) / blockchain.decimalValue) let totalAmount = valueAmount + gasAmount let balance = ethWalletModel.wallet.amounts[.coin] ?? .zeroCoin(for: blockchain, address: transaction.from) let dApp = session.session.dAppInfo let message: String = { var m = "" m += String(format: "wallet_connect_create_tx_message".localized, TapCardIdFormatter(cid: wallet.cid).formatted(), dApp.peerMeta.name, dApp.peerMeta.url.absoluteString, valueAmount.description, gasAmount.description, totalAmount.description, ethWalletModel.getBalance(for: .coin)) if (balance < totalAmount) { m += "wallet_connect_create_tx_not_enough_funds".localized } return m }() let alert = WalletConnectUIBuilder.makeAlert(for: .sendTx, message: message, onAcceptAction: { switch ethWalletModel.walletManager.createTransaction(amount: valueAmount, fee: gasAmount, destinationAddress: transaction.to, sourceAddress: transaction.from) { case .success(var tx): let contractDataString = transaction.data.drop0xPrefix let wcTxData = Data(hexString: String(contractDataString)) tx.params = EthereumTransactionParams(data: wcTxData, gasLimit: gas, nonce: transaction.nonce?.hexToInteger) promise(.success(tx)) case .failure(let error): promise(.failure(error)) } }, isAcceptEnabled: (balance >= totalAmount), onReject: { promise(.failure(WalletConnectServiceError.cancelled)) }) self?.presentOnMain(vc: alert) } .eraseToAnyPublisher() } .map { (ethWalletModel, $0) } .eraseToAnyPublisher() } func presentOnMain(vc: UIViewController, delay: Double = 0) { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { UIApplication.modalFromTop(vc) } } private func getGasPrice(for amount: Amount, tx: WalletConnectEthTransaction, txSender: EthereumGasLoader, decimalCount: Int) -> AnyPublisher<Int, Error> { guard let gasPriceString = tx.gasPrice, let gasPrice = gasPriceString.hexToInteger else { return txSender.getGasPrice() .flatMap { (gasPrice) -> AnyPublisher<Int, Error> in .justWithError(output: Int(gasPrice)) } .eraseToAnyPublisher() } return .justWithError(output: gasPrice) } }
48.071006
185
0.566224
4b8fa05ac7d1feceab0711d75273aebb9b5d87e7
4,126
// // Book.swift // NYT Best // // Created by Ishan Handa on 21/09/16. // Copyright © 2016 Ishan Handa. All rights reserved. // import Foundation /// Model to store Books fetched from api struct Book { var amazonProductURLString: String? var bestsellersDate: Date var title: String var description: String var contributor: String? var author: String? var publisher: String? var primaryISBN13: String? var primaryISBN10: String? var publishedDate: Date var rank: Int var rankLastWeek: Int var bookReviewURLString: String? var sundayReviewURLSring: String? var weeksOnList: Int var otherIsbn13: [String]? /// Computed NSURL to guess the image url for the book from the ISBN number returned from api. var imageURL: URL? { if let isbn13 = self.primaryISBN13 { if let url = URL(string: "https://s1.nyt.com/du/books/images/\(isbn13).jpg") { return url } else { return nil } } else { return nil } } /// Computed NSURLs to guess the image url for the book from other ISBN numbers returned from api. var otherImageURLs: [URL]? { if let otherISBNS = self.otherIsbn13, otherISBNS.count > 0 { var urls = [URL]() otherISBNS.forEach({ (isbn) in if let url = URL(string: "https://s1.nyt.com/du/books/images/\(isbn).jpg") { urls.append(url) } }) return urls.count > 0 ? urls : nil } else { return nil } } } extension Book: DictionaryInitializable { init?(dictionary: Dictionary<String, AnyObject>) { guard let bestsellersDate = dictionary["bestsellers_date"] as? String, let bookDetails = dictionary["book_details"] as? [Dictionary<String, AnyObject>], let publishedDate = dictionary["published_date"] as? String, let rank = dictionary["rank"] as? Int, let rankLastWeek = dictionary["rank_last_week"] as? Int, let weeksOnList = dictionary["weeks_on_list"] as? Int else { return nil } guard let detail = bookDetails.first else { return nil } guard let title = detail["title"] as? String, let description = detail["description"] as? String else { return nil } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY-mm-dd" self.bestsellersDate = dateFormatter.date(from: bestsellersDate)! self.title = title.capitalized self.description = description self.author = detail["author"] as? String self.publishedDate = dateFormatter.date(from: publishedDate)! self.rank = rank self.rankLastWeek = rankLastWeek self.weeksOnList = weeksOnList if let otherISBNS = dictionary["isbns"] as? [[String: String]] { var isbns = [String]() otherISBNS.forEach({ (aDict) in if let isbn13 = aDict["isbn13"] { isbns.append(isbn13) } }) self.otherIsbn13 = isbns } self.amazonProductURLString = dictionary["amazon_product_url"] as? String self.contributor = detail["contributor"] as? String self.publisher = detail["publisher"] as? String self.primaryISBN13 = detail["primary_isbn13"] as? String self.primaryISBN10 = detail["primary_isbn10"] as? String self.author = detail["author"] as? String if self.author == "" { self.author = nil } if let reviewsArray = dictionary["reviews"] as? [Dictionary<String, String>] { if let first = reviewsArray.first { self.bookReviewURLString = first["book_review_link"] self.sundayReviewURLSring = first["sunday_review_link"] } } } }
32.746032
102
0.569801
8aefabc69ee4a96849f202ff21902fd259c41b68
2,133
import Foundation import Cache extension View { /// Set image with url /// /// - Parameters: /// - url: The url to fetch /// - placeholder: Placeholder if any /// - option: Customise this specific fetching /// - completion: Called after done public func setImage(url: URL, placeholder: Image? = nil, option: Option = Option(), completion: Completion? = nil) { if let placeholder = placeholder { option.imageDisplayer.display(placeholder: placeholder, onto: self) } cancelImageFetch() self.imageFetcher = ImageFetcher( downloader: option.downloaderMaker(), storage: option.storageMaker() ) self.imageFetcher?.fetch(url: url, completion: { [weak self] result in guard let `self` = self else { return } self.handle(url: url, result: result, option: option, completion: completion) }) } /// Cancel active image fetch public func cancelImageFetch() { if let imageFetcher = imageFetcher { imageFetcher.cancel() self.imageFetcher = nil } } private func handle(url: URL, result: Result, option: Option, completion: Completion?) { defer { DispatchQueue.main.async { completion?(result) } } switch result { case .value(let image): let processedImage = option.imagePreprocessor?.process(image: image) ?? image DispatchQueue.main.async { option.imageDisplayer.display(image: processedImage, onto: self) } case .error(let error): Configuration.trackError?(url, error) } } private var imageFetcher: ImageFetcher? { get { return objc_getAssociatedObject( self, &AssociateKey.fetcher) as? ImageFetcher } set { objc_setAssociatedObject( self, &AssociateKey.fetcher, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } /// Used to associate ImageFetcher with ImageView private struct AssociateKey { static var fetcher = 0 }
25.094118
83
0.615565
1683435d27a8ebb45831b850865cfef72070f242
7,871
// // KMRecommendViewController.swift // KMLive // // Created by 联合创想 on 16/12/16. // Copyright © 2016年 KMXC. All rights reserved. // 关注 import UIKit fileprivate let kNormalItemW = (UIScreen.main.bounds.width - 3 * 10) / 2 fileprivate let kNormalItemH = kNormalItemW * 3 / 4 fileprivate let kPrettyItemH = kNormalItemW * 4 / 3 fileprivate let kCycleViewH = UIScreen.main.bounds.width * 3 / 8 fileprivate let KMRecommendNormalCellIdentifier = "KMRecommendNormalCellIdentifier" fileprivate let KMRecommendPrettyCellIdentifier = "KMRecommendPrettyCellIdentifier" fileprivate let KMRecommendHeaderIdentifier = "KMRecommendHeaderIdentifier" class KMRecommendViewController: UIViewController { //MARK:-- 定义属性 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupUI() view.backgroundColor = UIColor.yellow loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ //MARK:--懒加载 fileprivate lazy var collectionView:UICollectionView = { let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) let collection = UICollectionView(frame:frame, collectionViewLayout: KMRecommendViewLayout()) collection.delegate = self collection.dataSource = self collection.autoresizingMask = [.flexibleHeight, .flexibleWidth] collection.register(KMRecommandNormalCell.self, forCellWithReuseIdentifier: KMRecommendNormalCellIdentifier) collection.register(KMRecommandPrettyCell.self, forCellWithReuseIdentifier: KMRecommendPrettyCellIdentifier) collection.register(KMRecommendHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KMRecommendHeaderIdentifier) collection.backgroundColor = UIColor.white return collection }() fileprivate lazy var recomendVM:KMRecomandViewModel = KMRecomandViewModel() fileprivate lazy var cycleView:KMRecommandCycleView = { let cycleView = KMRecommandCycleView() cycleView.frame = CGRect(x: 0, y: -kCycleViewH, width: UIScreen.main.bounds.width, height: kCycleViewH) return cycleView }() } //MARK:-- extension KMRecommendViewController{ fileprivate func setupUI(){ view.addSubview(collectionView) collectionView.addSubview(cycleView) collectionView.contentInset = UIEdgeInsets(top: kCycleViewH, left: 0, bottom: 0, right: 0) } } extension KMRecommendViewController{ func loadData() { recomendVM.requestData { self.collectionView.reloadData() } recomendVM.requestCycleViewData { self.cycleView.cycleModels = self.recomendVM.kmCycleModels } } } //MARK:--UICollectionViewDelegate,UICollectionViewDataSource extension KMRecommendViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return recomendVM.kmAnchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return recomendVM.kmAnchorGroups[section].anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let anchor = recomendVM.kmAnchorGroups[indexPath.section].anchors[indexPath.item] if indexPath.section == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KMRecommendPrettyCellIdentifier, for: indexPath) as! KMRecommandPrettyCell cell.anchor = anchor cell.backgroundColor = UIColor.white return cell }else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KMRecommendNormalCellIdentifier, for: indexPath) as! KMRecommandNormalCell cell.anchor = anchor cell.backgroundColor = UIColor.white return cell } } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: KMRecommendHeaderIdentifier, for: indexPath) headerView.backgroundColor = UIColor.yellow return headerView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kNormalItemW, height: kPrettyItemH) } return CGSize(width: kNormalItemW, height: kNormalItemH) } } //MARK:-- class KMRecommendViewLayout: UICollectionViewFlowLayout { override func prepare() { super.prepare() let itemW = (UIScreen.main.bounds.width - 30) * 0.5 let itemH = itemW * 3 / 4 itemSize = CGSize(width: itemW, height: itemH) minimumLineSpacing = 0 minimumInteritemSpacing = 10 headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: 50) sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) } } //MARK:-- KMRecommendHeaderView class KMRecommendHeaderView: UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:-- fileprivate lazy var sectionLine:UIView = { let line = UIView() line.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 10) line.backgroundColor = UIColor.lightGray return line }() fileprivate lazy var iconImage:UIImageView = { let iconImage = UIImageView() iconImage.image = UIImage(named: "home_header_phone") iconImage.frame = CGRect(x: 10, y: 15, width: 18, height: 20) return iconImage }() fileprivate lazy var sectionLabel:UILabel = { let label = UILabel() label.frame = CGRect(x: self.iconImage.km_Right + 10, y: self.iconImage.km_Top, width: 50, height: 20) label.text = "颜值" return label }() fileprivate lazy var moreButton:UIButton = { let button = UIButton() button.setTitle("更多 >", for: .normal) button.setTitleColor(UIColor.lightGray, for: .normal) button.sizeToFit() button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0) return button }() } extension KMRecommendHeaderView { fileprivate func setupUI(){ addSubview(sectionLine) addSubview(iconImage) addSubview(sectionLabel) addSubview(moreButton) _ = moreButton.xmg_AlignInner(type: .TopRight, referView: self, size: nil,offset:CGPoint(x: -10, y: 10)) } }
31.995935
171
0.668403
ab6c551f783454ea6c941f9c2a7104dfdce8cfb5
1,048
@testable import PersistQL import XCTest class GraphQLDescriptionTests: XCTestCase { func test() { let operations = [ GraphQL.Operation( type: .query, name: "foo", selectionSet: [ .field(GraphQL.Field(name: "name")) ] ), GraphQL.Operation( type: .query, name: "bar", selectionSet: [ .fragment("baz") ] ) ] let fragments = [ GraphQL.Fragment( name: "baz", type: "User", selectionSet: [ .field(GraphQL.Field(name: "id")), .field(GraphQL.Field(name: "name")), ] ) ] let graphQL = GraphQL(operations: operations, fragments: fragments) XCTAssertEqual(graphQL.description, "query foo { name } query bar { ...baz } fragment baz on User { id name }") } }
29.111111
119
0.432252
b99001e97641a11fc2348bd3bf8013459be42bed
58
import Foundation class DataEntryTablePresenter { }
9.666667
31
0.758621
e219df675e431cbaa8531670230d398dca2c2c2d
1,285
// // VisualRecognitionUITests.swift // VisualRecognitionUITests // // Created by Nicholas Bourdakos on 6/23/17. // Copyright © 2017 Nicholas Bourdakos. All rights reserved. // import XCTest class VisualRecognitionUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.72973
182
0.673152
e60784d8a0e6462f8cc9a36cab9d86b7b6ae728b
255
// // SpokenLanguages.swift // TheMovieAppSample // // Created by Juan Garcia on 1/6/19. // Copyright © 2019 Juan Garcia. All rights reserved. // import Foundation struct SpokenLanguages: Codable { let iso_639_1: String? let name: String? }
17
54
0.694118
f4c44854eaa437068e6cdc17fbef4f9549bb8eda
2,698
// // SceneDelegate.swift // ArunCard // // Created by M_243704 on 1/14/21. // import UIKit import SwiftUI 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). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } 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. } }
42.15625
147
0.704967
def0e532063914b121e427ff1c1b5e339a9c2d3c
1,151
/// Reports violations as JUnit XML. public struct JUnitReporter: Reporter { // MARK: - Reporter Conformance public static let identifier = "junit" public static let isRealtime = false public var description: String { return "Reports violations as JUnit XML." } public static func generateReport(_ violations: [StyleViolation]) -> String { return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<testsuites><testsuite>\n" + violations.map({ violation -> String in let fileName = (violation.location.relativeFile ?? "<nopath>").escapedForXML() let severity = violation.severity.rawValue + ":\n" let message = severity + "Line:" + String(violation.location.line ?? 0) + " " let reason = violation.reason.escapedForXML() return [ "\t<testcase classname='SwiftLint' name='\(fileName)\'>\n", "\t\t<failure message='\(reason)\'>" + message + "</failure>\n", "\t</testcase>\n" ].joined() }).joined() + "</testsuite></testsuites>" } }
42.62963
94
0.565595
6736d36b025b2c8d98d77dc03ea05934e321371c
605
// 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 // InconsistentVmDetailsProtocol is this class stores the monitoring details for consistency check of inconsistent // Protected Entity. public protocol InconsistentVmDetailsProtocol : Codable { var vmName: String? { get set } var cloudName: String? { get set } var details: [String]? { get set } var errorIds: [String]? { get set } }
43.214286
115
0.72562
8a28d60227d1b697fcdf8424378692dcfbedf399
3,769
// // JKRepostCell.swift // sinaWeibo // // Created by 张俊凯 on 16/7/17. // Copyright © 2016年 张俊凯. All rights reserved. // import UIKit import KILabel class JKRepostCell: JKHomeCell { override var status: JKStatus? { didSet{ let name = status?.retweeted_status?.user?.name ?? "" let text = status?.retweeted_status?.text ?? "" forwardLabel.attributedText = EmoticonPackage.emoticonString("@" + name + ": " + text) } } //父类的设置子视图方法,重写 override func setupUI() { super.setupUI() //1.添加子控件 //1.1按钮在配图下面 contentView.insertSubview(forwardButton, belowSubview: pictureView) //1.2正文在按钮上面 contentView.insertSubview(forwardLabel, aboveSubview: forwardButton) // 2.布局子控件 // 2.1布局转发背景 forwardButton.jk_AlignVertical(type: JK_AlignType.BottomLeft, referView: contentLabel, size: nil, offset: CGPoint(x: -10, y: 10)) forwardButton.jk_AlignVertical(type: JK_AlignType.TopRight, referView: footerView, size: nil) // 2.2布局转发正文 forwardLabel.text = "fjdskljflkdsjflksdjlkfdsjlfjdslfjlkds" forwardLabel.jk_AlignInner(type: JK_AlignType.TopLeft, referView: forwardButton, size: nil, offset: CGPoint(x: 10, y: 10)) // 2.3重新调整转发配图的位置,配图放到转发的正文下面 let cons = pictureView.jk_AlignVertical(type: JK_AlignType.BottomLeft, referView: forwardLabel, size: CGSize(width: 290, height: 290), offset: CGPoint(x: 0, y: 10)) pictureWidthCons = pictureView.jk_Constraint(cons, attribute: NSLayoutAttribute.Width) pictureHeightCons = pictureView.jk_Constraint(cons, attribute: NSLayoutAttribute.Height) pictureTopCons = pictureView.jk_Constraint(cons, attribute: NSLayoutAttribute.Top) } // MARK: - 懒加载 //转发内容label显示正文 // private lazy var forwardLabel: UILabel = { // let label = UILabel.createLabel(UIColor.darkGrayColor(), fontSize: 15) // label.numberOfLines = 0 // label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 20 // return label // }() //可以实现label内容点击网页链接和高亮 private lazy var forwardLabel: UILabel = { let label = KILabel() label.textColor = UIColor.darkGrayColor() label.font = UIFont.systemFontOfSize(15) label.numberOfLines = 0 label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 20 // 监听URL label.urlLinkTapHandler = { (label, string, range) in // //只能调用类方法,静态方法 // JKRepostCell.openWebView(string) } return label }() //找view的所在控制器 func parentViewController() -> UIViewController? { for (let next = self.superview; next != nil; next?.superview) { let ctr = next?.nextResponder() if (ctr is UIViewController) { return ctr as? UIViewController } } return nil } //接受KILabel的字符串,弹出控制器 func openWebView(string : String) { let vc = parentViewController() let webVC = JKWelcomVC() vc?.navigationController?.pushViewController(webVC, animated: true) } //整个cell是一个button,可以点击 private lazy var forwardButton: UIButton = { let btn = UIButton() btn.backgroundColor = UIColor(white: 0.9, alpha: 1.0) return btn }() }
31.408333
172
0.570708
1cddb8368199fd129b2814e90fdcb071d2c4a0bf
14,149
// // PlayerDetailsView.swift // iPod cast // // Created by wiz on 9/7/20. // Copyright © 2020 Codelife studio. All rights reserved. // import UIKit import AVKit import MediaPlayer class PlayerDetailsView: UIView { var episode: Episode! { didSet { episodeTitleLabel.text = episode.title authorLabel.text = episode.author miniTitleLabel.text = episode.title setupAudioSession() setupNowPlaytingInfo() playEpisode() guard let url = URL(string: episode.imageUrl ?? "") else {return } episodeImageView.sd_setImage(with: url, completed: nil) miniEpisodeImageView.sd_setImage(with: url) miniEpisodeImageView.sd_setImage(with: url) { (image, _, _, _) in guard let image = image else { return } let artworkItem = MPMediaItemArtwork(boundsSize: .zero, requestHandler: { (size) -> UIImage in return image }) MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyArtwork] = artworkItem } } } fileprivate func setupNowPlaytingInfo(){ var nowPlayingInfo = [String: Any]() nowPlayingInfo[MPMediaItemPropertyTitle] = episode.title nowPlayingInfo[MPMediaItemPropertyArtist] = episode.author MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } fileprivate func playEpisode(){ if episode.fileUrl != nil { guard let fileURL = URL(string: episode.fileUrl ?? "") else { return } let fileName = fileURL.lastPathComponent guard var trueLocation = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } trueLocation.appendPathComponent(fileName) playEpisodeUsing(urlString: trueLocation.absoluteString) }else{ playEpisodeUsing(urlString: episode.streamUrl) // guard let url = URL(string: episode.streamUrl) else { return } // let playerItem = AVPlayerItem(url: url) // player.replaceCurrentItem(with: playerItem) // player.play() } } fileprivate func playEpisodeUsing(urlString: String){ guard let url = URL(string: urlString ) else { return } let playerItem = AVPlayerItem(url: url) player.replaceCurrentItem(with: playerItem) player.play() self.playPauseTapped.setImage(#imageLiteral(resourceName: "pause"), for: .normal) self.miniPlayPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal) } let player: AVPlayer = { let avPlayer = AVPlayer() avPlayer.automaticallyWaitsToMinimizeStalling = false return avPlayer }() fileprivate func observePlayerCurrentTime() { let interval = CMTimeMake(value: 1, timescale: 2) player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] (time) in self?.currentTImeLabel.text = time.toDisplayString() let durationTime = self?.player.currentItem?.duration self?.durationTimeLabel.text = durationTime?.toDisplayString() self?.updateCurrentTimeSlider() } } fileprivate func updateCurrentTimeSlider(){ let currentTimeSeconds = CMTimeGetSeconds(player.currentTime()) let durationSeconds = CMTimeGetSeconds(player.currentItem?.duration ?? CMTimeMake(value: 1, timescale: 1)) let percentage = currentTimeSeconds / durationSeconds self.currentTimeSlider.value = Float(percentage) } var panGesture: UIPanGestureRecognizer! fileprivate func setupGestures() { addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapMaximize))) //observePlayerCurrentTime() panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan)) miniPlayerView.addGestureRecognizer(panGesture) maximizedStackView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handleDismissalPan))) //addGestureRecognizer(panGesture) } @objc func handleDismissalPan(gesture: UIPanGestureRecognizer){ print("maximized SV dismissal") if gesture.state == .changed { let translation = gesture.translation(in: superview) maximizedStackView.transform = CGAffineTransform(translationX: 0, y: translation.y) }else if gesture.state == .ended { let translation = gesture.translation(in: superview) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.maximizedStackView.transform = .identity if translation.y > 50 { UIApplication.mainTabBarController()?.minimizePlayerDetails() //gesture.isEnabled = false } }) } } private func setupAudioSession(){ do{ try AVAudioSession.sharedInstance().setCategory(.playback) try AVAudioSession.sharedInstance().setActive(true) }catch let sessionErr { print("fail to active session error:", sessionErr) } } private func setupRemoteControl(){ UIApplication.shared.beginReceivingRemoteControlEvents() let commandCenter = MPRemoteCommandCenter.shared() commandCenter.playCommand.isEnabled = true commandCenter.playCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in self.player.play() self.playPauseTapped.setImage(#imageLiteral(resourceName: "pause"), for: .normal) self.miniPlayPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal) self.setupElapsedTime(playbackRate: 1) return .success } commandCenter.pauseCommand.isEnabled = true commandCenter.pauseCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in self.player.pause() self.playPauseTapped.setImage(#imageLiteral(resourceName: "play"), for: .normal) self.miniPlayPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal) self.setupElapsedTime(playbackRate: 0) return .success } commandCenter.togglePlayPauseCommand.isEnabled = true commandCenter.togglePlayPauseCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in self.handlePlayPause() return .success } commandCenter.nextTrackCommand.addTarget(self, action: #selector(handleNextTrack)) //commandCenter.previousTrackCommand.isEnabled = true commandCenter.previousTrackCommand.addTarget(self, action: #selector(previousNextTrack)) } var playlistEpisodes = [Episode]() @objc fileprivate func handleNextTrack() -> MPRemoteCommandHandlerStatus{ print("Play next episode....") if playlistEpisodes.count == 0 { return .success } let currentEpisodeIndex = playlistEpisodes.firstIndex { (ep) -> Bool in return self.episode.title == ep.title && self.episode.author == ep.author } guard let index = currentEpisodeIndex else { return .success } let nextEpisode: Episode if index == playlistEpisodes.count - 1 { nextEpisode = playlistEpisodes[0] }else{ nextEpisode = playlistEpisodes[index + 1] } self.episode = nextEpisode return .success } @objc fileprivate func previousNextTrack() -> MPRemoteCommandHandlerStatus { print("Play previous episode....") //check if playlistEpisodes.count == 0 then return //find out current episode inx //if episode index is 0 then wrap to end of list somehow.. //otherwise play episode index -1 if playlistEpisodes.isEmpty { return .success } let currentEpisodeIndex = playlistEpisodes.firstIndex { (ep) -> Bool in return self.episode.title == ep.title && self.episode.author == ep.author } guard let index = currentEpisodeIndex else { return .success } let prevEpisode: Episode if index == 0 { let count = playlistEpisodes.count prevEpisode = playlistEpisodes[count - 1] } else { prevEpisode = playlistEpisodes[index - 1] } self.episode = prevEpisode return .success } fileprivate func setupElapsedTime(playbackRate: Float){ let elapsedTime = CMTimeGetSeconds(player.currentTime()) MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyElapsedPlaybackTime] = elapsedTime MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = playbackRate } fileprivate func observeBoundaryTime() { let time = CMTimeMake(value: 1, timescale: 3) let times = [NSValue(time: time)] //Player has a reference to self //self has a reference to player player.addBoundaryTimeObserver(forTimes: times, queue: .main) { [weak self] in print("Episode started playing") self?.enlargeEpisodeImageView() //self?.setupLockscreenCurrentTime() self?.setupLockscreenDuration() } } fileprivate func setupLockscreenDuration() { guard let duration = player.currentItem?.duration else { return } let durationSeconds = CMTimeGetSeconds(duration) MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyPlaybackDuration] = durationSeconds } fileprivate func setupInterruptionObserver(){ NotificationCenter.default.addObserver(self, selector: #selector(handleInterrruption), name: .AVCaptureSessionWasInterrupted, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleInterrruption), name: .AVCaptureSessionInterruptionEnded, object: nil) } @objc fileprivate func handleInterrruption(notification: Notification){ print("Interruption observed") guard let userInfo = notification.userInfo else { return } guard let type = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt else { return } if type == AVAudioSession.InterruptionType.began.rawValue { playPauseTapped.setImage(#imageLiteral(resourceName: "play"), for: .normal) miniPlayPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal) }else { guard let options = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else { return } if options == AVAudioSession.InterruptionOptions.shouldResume.rawValue { player.play() playPauseTapped.setImage(#imageLiteral(resourceName: "pause"), for: .normal) miniPlayPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal) } } } override func awakeFromNib() { super.awakeFromNib() setupRemoteControl() setupGestures() setupInterruptionObserver() observePlayerCurrentTime() observeBoundaryTime() } static func initFromNib() -> PlayerDetailsView { return Bundle.main.loadNibNamed("PlayerDetailsView", owner: self, options: nil)?.first as! PlayerDetailsView } deinit { print("PlayerDetailsView memory being reclaimed") } //MARK:- IB Actions and Outlets @IBOutlet weak var miniEpisodeImageView: UIImageView! @IBOutlet weak var miniTitleLabel: UILabel! @IBOutlet weak var miniPlayPauseButton: UIButton! { didSet { miniPlayPauseButton.addTarget(self, action: #selector(handlePlayPause), for: .touchUpInside) miniPlayPauseButton.imageView?.contentMode = .scaleAspectFit miniPlayPauseButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) } } @IBOutlet weak var miniFastForwardButton: UIButton! { didSet { miniFastForwardButton.imageView?.contentMode = .scaleAspectFit miniFastForwardButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) } } @IBOutlet weak var miniPlayerView: UIView! @IBOutlet weak var maximizedStackView: UIStackView! @IBOutlet weak var currentTimeSlider: UISlider! @IBOutlet weak var durationTimeLabel: UILabel! @IBOutlet weak var currentTImeLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var episodeImageView: UIImageView! { didSet { episodeImageView.layer.cornerRadius = 5 episodeImageView.clipsToBounds = true episodeImageView.transform = self.shrunkenTransform } } @IBOutlet weak var playPauseTapped: UIButton!{ didSet { playPauseTapped.setImage(#imageLiteral(resourceName: "pause"), for: .normal) playPauseTapped.addTarget(self, action: #selector(handlePlayPause), for: .touchUpInside) } } @objc func handlePlayPause(){ if player.timeControlStatus == .paused { playPauseTapped.setImage(#imageLiteral(resourceName: "pause"), for: .normal) miniPlayPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal) player.play() enlargeEpisodeImageView() self.setupElapsedTime(playbackRate: 1) }else{ playPauseTapped.setImage(#imageLiteral(resourceName: "play"), for: .normal) miniPlayPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal) player.pause() shrinkEpisodeImageView() self.setupElapsedTime(playbackRate: 0) } } @IBOutlet weak var episodeTitleLabel: UILabel! { didSet { episodeTitleLabel.numberOfLines = 0 } } fileprivate let shrunkenTransform = CGAffineTransform(scaleX: 0.7, y: 0.7) fileprivate func shrinkEpisodeImageView(){ UIView.animate(withDuration: 0.75, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.episodeImageView.transform = self.shrunkenTransform }) } fileprivate func enlargeEpisodeImageView(){ UIView.animate(withDuration: 0.75, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.episodeImageView.transform = .identity }) } @IBAction func dismissTapped(_ sender: Any) { //self.removeFromSuperview() UIApplication.mainTabBarController()?.minimizePlayerDetails() //panGesture.isEnabled = true } @IBAction func handleCurrentTimeSliderChanged(_ sender: UISlider) { let percentage = currentTimeSlider.value guard let duration = player.currentItem?.duration else { return } let durationInSeconds = CMTimeGetSeconds(duration) let seekTimeInSeconds = Float64(percentage) * durationInSeconds //Int32(NSEC_PER_SEC) let seekTime = CMTimeMakeWithSeconds(seekTimeInSeconds, preferredTimescale: 1) MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyElapsedPlaybackTime] = seekTimeInSeconds player.seek(to: seekTime) } @IBAction func handleRewind(_ sender: UIButton) { seekToCurrentTime(delta: -15) } fileprivate func seekToCurrentTime(delta: Int64) { let fifteenSeconds = CMTimeMake(value: delta,timescale: 1) let seekTime = CMTimeAdd(player.currentTime(), fifteenSeconds) player.seek(to: seekTime) } @IBAction func handleFastForward(_ sender: UIButton) { seekToCurrentTime(delta: 15) } @IBAction func handleVolumeChangeSlider(_ sender: UISlider) { player.volume = sender.value } }
34.342233
143
0.752067
8a55a5bdf9575205e8e1fda3e21a02d37175bb83
2,677
// // Copyright © 2019 Essential Developer. All rights reserved. // import UIKit import CoreData import EssentialFeed import EssentialFeediOS import Combine class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? lazy var httpClient: HTTPClient = { URLSessionHTTPClient(session: URLSession(configuration: .ephemeral)) }() lazy var store: FeedStore & FeedImageDataStore = { try! CoreDataFeedStore( storeURL: NSPersistentContainer .defaultDirectoryURL() .appendingPathComponent("feed-store.sqlite")) }() private lazy var localFeedLoader: LocalFeedLoader = { LocalFeedLoader(store: store, currentDate: Date.init) }() convenience init(httpClient: HTTPClient, store: FeedStore & FeedImageDataStore) { self.init() self.httpClient = httpClient self.store = store } func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let scene = (scene as? UIWindowScene) else { return } window = UIWindow(windowScene: scene) configureWindow() } func configureWindow() { window?.rootViewController = UINavigationController(rootViewController: FeedUIComposer.feedComposedWith( feedLoader: makeRemoteFeedLoaderWithLocalFallBack, imageLoader: makeLocalImageLoaderWithRemoteFallBack)) window?.makeKeyAndVisible() } func sceneWillResignActive(_ scene: UIScene) { localFeedLoader.validateCache { _ in } } private func makeRemoteFeedLoaderWithLocalFallBack() -> AnyPublisher<[FeedImage], Error> { let remoteURL = URL(string: "https://static1.squarespace.com/static/5891c5b8d1758ec68ef5dbc2/t/5db4155a4fbade21d17ecd28/1572083034355/essential_app_feed.json")! return httpClient .getPublisher(url: remoteURL) .tryMap(FeedItemsMapper.map) .caching(to: localFeedLoader) .fallback(to: localFeedLoader.loadPublisher) } private func makeLocalImageLoaderWithRemoteFallBack(url: URL) -> FeedImageDataLoader.Publisher { let remoteImageLoader = RemoteFeedImageDataLoader(client: httpClient) let localImageLoader = LocalFeedImageDataLoader(store: store) return localImageLoader .loadImageDataPublisher(from: url) .fallback(to: { remoteImageLoader .loadImageDataPublisher(from: url) .caching(to: localImageLoader, using: url) }) } }
34.320513
168
0.669406
08e3af0c1a25357cfd74eb5784321677014169aa
3,100
// // StaffHomeViewController.swift // Projet12 // // Created by Elodie-Anne Parquer on 26/03/2020. // Copyright © 2020 Elodie-Anne Parquer. All rights reserved. // import UIKit final class StaffHomeViewController: UIViewController { // MARK: - Outlets @IBOutlet private weak var bordeauxTempLabel: UILabel! @IBOutlet private weak var bordeauxImageView: UIImageView! @IBOutlet private weak var bordeauxInfoLabel: UILabel! @IBOutlet private weak var quoteLabel: UILabel! @IBOutlet private weak var authorLabel: UILabel! @IBOutlet private weak var navSecondView: UIView! // MARK: - Properties private var city: WeatherData? private let weatherService = WeatherService() private var quote: QuoteData? private let quoteService = QuoteService() private let authService: AuthService = AuthService() // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureNavigationBar() weatherData() quoteData() navSecondView.configureNavSecondView() } // MARK: - Actions @IBAction private func logOutButtonTapped(_ sender: Any) { authService.signOut { (isSucceded) in if isSucceded { self.navigationController?.popToRootViewController(animated: true) } else { self.presentAlert(titre: "Erreur", message: "La déconnexion a échoué") } } } // MARK: - Methods /// method that manages the data of the network call private func weatherData() { weatherService.getWeather { result in switch result { case .success(let weatherData): DispatchQueue.main.sync { self.updateWeather(data: weatherData) } case .failure(let error): DispatchQueue.main.sync { self.presentAlert(titre: "Error", message: "Service non disponible") print(error) } } } } /// method that manages the data of the network call private func quoteData() { quoteService.getQuote { result in switch result { case .success(let quoteData): DispatchQueue.main.sync { self.updateQuote(data: quoteData) } case .failure(let error): DispatchQueue.main.sync { self.presentAlert(titre: "Error", message: "Service non disponible") print(error) } } } } private func updateWeather(data: WeatherData) { bordeauxTempLabel.text = String(data.main.temp.rounded()) + "°" bordeauxInfoLabel.text = data.weather[0].weatherDescription bordeauxImageView.image = UIImage(named: data.weather[0].icon ?? "09n") } private func updateQuote(data: QuoteData) { quoteLabel.text = data.quoteText authorLabel.text = data.quoteAuthor } }
31.313131
88
0.591613
6a6833e5aed8727caf0449952e7db13756d6f447
1,743
// // Network.swift // BillionWallet // // Created by Evolution Group Ltd on 31/07/2017. // Copyright © 2017 Evolution Group Ltd. All rights reserved. // import Foundation enum NetworkError: LocalizedError, CustomStringConvertible { case unknown case invalidResponse case httpFailure(Int) case statusFailed var errorDescription: String? { return self.description } var description: String { switch self { case .unknown: return "An unknown error occurred" case .invalidResponse: return "Received an invalid response" case .statusFailed: return "Status Failed" case .httpFailure(let code): return "HTTP failure \(code)" } } } protocol NetworkCancelable { func cancel() } extension URLSessionDataTask: NetworkCancelable { } protocol Network { func stopAllOperations() @discardableResult func makeRequest(_ networkRequest: NetworkRequest, resultQueue: DispatchQueue, completion: @escaping (Result<JSON>) -> Void) -> NetworkCancelable? @discardableResult func makeRequest(_ networkRequest: NetworkRequest, resultQueue: DispatchQueue, completion: @escaping (Result<Data>) -> Void) -> NetworkCancelable? } extension Network { @discardableResult func makeRequest(_ networkRequest: NetworkRequest, completion: @escaping (Result<JSON>) -> Void) -> NetworkCancelable? { return makeRequest(networkRequest, resultQueue: .main, completion: completion) } @discardableResult func makeRequest(_ networkRequest: NetworkRequest, completion: @escaping (Result<Data>) -> Void) -> NetworkCancelable? { return makeRequest(networkRequest, resultQueue: .main, completion: completion) } }
31.690909
150
0.707975
6a4ae0c73a75aa274add2d730c1b83e00b7d9cc5
2,447
// // SugarRecordResults.swift // project // // Created by Pedro Piñera Buendía on 25/12/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation public class SugarRecordResults: SequenceType { //MARK: - Attributes var results: SugarRecordResultsProtocol private var finder: SugarRecordFinder //MARK: - Constructors /** Initializes SRResults passing an object that conforms the protocol SRResultsProtocol :param: results Original results :returns: Initialized SRResults */ internal init(results: SugarRecordResultsProtocol, finder: SugarRecordFinder) { self.results = results self.finder = finder } //MARK: - Public methods /// Returns the number of elements public var count:Int { get { return results.count(finder: finder) } } /** Returns the object at a given index :param: index Index of the object :returns: Object at the passed index (if exists) */ public func objectAtIndex(index: UInt) -> AnyObject! { return results.objectAtIndex(index, finder: finder) } /** Returns the first object of the results :returns: First object (if exists) */ public func firstObject() -> AnyObject! { return results.firstObject(finder: finder) } /** Returns the last object of the results :returns: Last object (if exists) */ public func lastObject() -> AnyObject! { return results.lastObject(finder: finder) } /** * Access to the element at a given index */ public subscript (index: Int) -> AnyObject! { get { return results.objectAtIndex(UInt(index), finder: finder) } } //MARK: SequenceType Protocol public func generate() -> SRResultsGenerator { return SRResultsGenerator(results: self) } } //MARK: Generator public class SRResultsGenerator: GeneratorType { private var results: SugarRecordResults private var nextIndex: Int init(results: SugarRecordResults) { self.results = results nextIndex = results.count - 1 } public func next() -> AnyObject? { if (nextIndex < 0) { return nil } return self.results[nextIndex++] } }
20.563025
88
0.599918
768ce697ed2bb4a8fb006aa62dc6357ba141ff4f
4,577
import Dispatch /// A DatabaseSnapshot sees an unchanging database content, as it existed at the /// moment it was created. /// /// See DatabasePool.makeSnapshot() /// /// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html> public class DatabaseSnapshot: DatabaseReader { private var serializedDatabase: SerializedDatabase /// The database configuration public var configuration: Configuration { serializedDatabase.configuration } #if SQLITE_ENABLE_SNAPSHOT // Support for ValueObservation in DatabasePool private(set) var version: UnsafeMutablePointer<sqlite3_snapshot>? #endif init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { var configuration = DatabasePool.readerConfiguration(configuration) configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction serializedDatabase = try SerializedDatabase( path: path, configuration: configuration, defaultLabel: defaultLabel, purpose: purpose) try serializedDatabase.sync { db in // Assert WAL mode let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode") guard journalMode == "wal" else { throw DatabaseError(message: "WAL mode is not activated at path: \(path)") } // Open transaction try db.beginTransaction(.deferred) // Acquire snapshot isolation try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() #if SQLITE_ENABLE_SNAPSHOT // We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html // > At least one transaction must be written to it first. version = try? db.takeVersionSnapshot() #endif } } deinit { // Leave snapshot isolation serializedDatabase.reentrantSync { db in #if SQLITE_ENABLE_SNAPSHOT if let version = version { sqlite3_snapshot_free(version) } #endif try? db.commit() } } } // DatabaseReader extension DatabaseSnapshot { // MARK: - Interrupting Database Operations public func interrupt() { serializedDatabase.interrupt() } // MARK: - Reading from Database /// Synchronously executes a read-only block that takes a database /// connection, and returns its result. /// /// let players = try snapshot.read { db in /// try Player.fetchAll(...) /// } /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func read<T>(_ block: (Database) throws -> T) rethrows -> T { try serializedDatabase.sync(block) } /// Asynchronously executes a read-only block in a protected dispatch queue. /// /// let players = try snapshot.asyncRead { dbResult in /// do { /// let db = try dbResult.get() /// let count = try Player.fetchCount(db) /// } catch { /// // Handle error /// } /// } /// /// - parameter block: A block that accesses the database. public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) { serializedDatabase.async { block(.success($0)) } } /// :nodoc: public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) { serializedDatabase.weakAsync { block($0.map { .success($0) }) } } /// :nodoc: public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T { try serializedDatabase.sync(block) } /// :nodoc: public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T { try serializedDatabase.reentrantSync(block) } // MARK: - Database Observation /// :nodoc: public func _add<Reducer: ValueReducer>( observation: ValueObservation<Reducer>, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { _addReadOnly( observation: observation, scheduling: scheduler, onChange: onChange) } }
33.654412
118
0.599956
0933bc22c9c074cf7b0a49e066aefacb01e23311
23,714
/** * Copyright (c) 2022 Dustin Collins (Strega's Gate) * All Rights Reserved. * Licensed under MIT License * * http://stregasgate.com */ import _RaylibC //------------------------------------------------------------------------------------ // Texture Loading and Drawing Functions (Module: textures) //------------------------------------------------------------------------------------ //MARK: - Image loading functions // NOTE: This functions do not require GPU access public extension Raylib { /// Load image from file into CPU memory (RAM) @inlinable static func loadImage(_ fileName: String) -> Image { return fileName.withCString { cString in return _RaylibC.LoadImage(cString) } } /// Load image from RAW file data @inlinable static func loadImageRaw(_ fileName: String, _ width: Int32, _ height: Int32, _ format: PixelFormat, _ headerSize: Int32) -> Image { return fileName.withCString { cString in return _RaylibC.LoadImageRaw(cString, width, height, format.rawValue, headerSize) } } /// Load image sequence from file (frames appended to image.data) @inlinable static func loadImageAnim(_ fileName: String, _ frames: inout Int32) -> Image { return fileName.withCString { cString in return _RaylibC.LoadImageAnim(cString, &frames) } } /// Load image from memory buffer, fileType refers to extension: i.e. `.png` @inlinable static func loadImageFromMemory(_ fileType: String, _ fileData: UnsafePointer<UInt8>!, _ dataSize: Int32) -> Image { return fileType.withCString { cString in return _RaylibC.LoadImageFromMemory(cString, fileData, dataSize) } } /// Load image from GPU texture data @inlinable static func loadImageFromTexture(_ texture: Texture2D) -> Image { return _RaylibC.LoadImageFromTexture(texture) } // Load image from screen buffer and (screenshot) @inlinable static func loadImageFromScreen() -> Image { return _RaylibC.LoadImageFromScreen() } /// Unload image from CPU memory (RAM) @inlinable static func unloadImage(_ image: Image) { _RaylibC.UnloadImage(image) } /// Export image data to file, returns true on success @inlinable static func exportImage(_ image: Image, _ fileName: String) -> Bool { return fileName.withCString { cString in let result = _RaylibC.ExportImage(image, cString) #if os(Windows) return result.rawValue != 0 #else return result #endif } } /// Export image as code file defining an array of bytes, returns true on success @inlinable static func exportImageAsCode(_ image: Image, _ fileName: String) -> Bool { return fileName.withCString { cString in let result = _RaylibC.ExportImageAsCode(image, cString) #if os(Windows) return result.rawValue != 0 #else return result #endif } } } //MARK: - Image generation functions public extension Raylib { /// Generate image: plain color @inlinable static func genImageColor(_ width: Int32, _ height: Int32, _ color: Color) -> Image { return _RaylibC.GenImageColor(width, height, color) } /// Generate image: vertical gradient @inlinable static func genImageGradientV(_ width: Int32, _ height: Int32, _ top: Color, _ bottom: Color) -> Image { return _RaylibC.GenImageGradientV(width, height, top, bottom) } /// Generate image: horizontal gradient @inlinable static func genImageGradientH(_ width: Int32, _ height: Int32, _ left: Color, _ right: Color) -> Image { return _RaylibC.GenImageGradientH(width, height, left, right) } /// Generate image: radial gradient @inlinable static func genImageGradientRadial(_ width: Int32, _ height: Int32, _ density: Float, _ inner: Color, _ outer: Color) -> Image { return _RaylibC.GenImageGradientRadial(width, height, density, inner, outer) } /// Generate image: checked @inlinable static func genImageChecked(_ width: Int32, _ height: Int32, _ checksX: Int32, _ checksY: Int32, _ col1: Color, _ col2: Color) -> Image { return _RaylibC.GenImageChecked(width, height, checksX, checksY, col1, col2) } /// Generate image: white noise @inlinable static func genImageWhiteNoise(_ width: Int32, _ height: Int32, _ factor: Float) -> Image { return _RaylibC.GenImageWhiteNoise(width, height, factor) } /// Generate image: cellular algorithm, bigger tileSize means bigger cells @inlinable static func genImageCellular(_ width: Int32, _ height: Int32, _ tileSize: Int32) -> Image { return _RaylibC.GenImageCellular(width, height, tileSize) } } //MARK: - Image manipulation functions public extension Raylib { /// Create an image duplicate (useful for transformations) @inlinable static func imageCopy(_ image: Image) -> Image { return _RaylibC.ImageCopy(image) } /// Create an image from another image piece @inlinable static func imageFromImage(_ image: Image, _ rec: Rectangle) -> Image { return _RaylibC.ImageFromImage(image, rec) } /// Create an image from text (default font) @inlinable static func imageText(_ text: String, _ fontSize: Int32, _ color: Color) -> Image { return text.withCString { cString in return _RaylibC.ImageText(cString, fontSize, color) } } /// Create an image from text (custom sprite font) @inlinable static func imageTextEx(_ font: Font, _ text: String, _ fontSize: Float, _ spacing: Float, _ tint: Color) -> Image { return text.withCString { cString in return _RaylibC.ImageTextEx(font, cString, fontSize, spacing, tint) } } /// Convert image data to desired format @inlinable static func imageFormat(_ image: inout Image, _ newFormat: PixelFormat) { _RaylibC.ImageFormat(&image, newFormat.rawValue) } /// Convert image to POT (power-of-two) @inlinable static func imageToPOT(_ image: inout Image, _ fill: Color) { _RaylibC.ImageToPOT(&image, fill) } /// Crop an image to a defined rectangle @inlinable static func imageCrop(_ image: inout Image, _ crop: Rectangle) { _RaylibC.ImageCrop(&image, crop) } /// Crop image depending on alpha value @inlinable static func imageAlphaCrop(_ image: inout Image, _ threshold: Float) { _RaylibC.ImageAlphaCrop(&image, threshold) } /// Clear alpha channel to desired color @inlinable static func imageAlphaClear(_ image: inout Image, _ color: Color, _ threshold: Float) { _RaylibC.ImageAlphaClear(&image, color, threshold) } /// Apply alpha mask to image @inlinable static func imageAlphaMask(_ image: inout Image, _ alphaMask: Image) { _RaylibC.ImageAlphaMask(&image, alphaMask) } /// Premultiply alpha channel @inlinable static func imageAlphaPremultiply(_ image: inout Image) { _RaylibC.ImageAlphaPremultiply(&image) } /// Resize image (Bicubic scaling algorithm) @inlinable static func imageResize(_ image: inout Image, _ newWidth: Int32, _ newHeight: Int32) { _RaylibC.ImageResize(&image, newWidth, newHeight) } /// Resize image (Nearest-Neighbor scaling algorithm) @inlinable static func imageResizeNN(_ image: inout Image, _ newWidth: Int32, _ newHeight: Int32) { _RaylibC.ImageResizeNN(&image, newWidth, newHeight) } /// Resize canvas and fill with color @inlinable static func imageResizeCanvas(_ image: inout Image, _ newWidth: Int32, _ newHeight: Int32, _ offsetX: Int32, _ offsetY: Int32, _ fill: Color) { _RaylibC.ImageResizeCanvas(&image, newWidth, newHeight, offsetX, offsetY, fill) } /// Compute all mipmap levels for a provided image @inlinable static func imageMipmaps(_ image: inout Image) { _RaylibC.ImageMipmaps(&image) } /// Dither image data to 16bpp or lower (Floyd-Steinberg dithering) @inlinable static func imageDither(_ image: inout Image, _ rBpp: Int32, _ gBpp: Int32, _ bBpp: Int32, _ aBpp: Int32) { _RaylibC.ImageDither(&image, rBpp, gBpp, bBpp, aBpp) } /// Flip image vertically @inlinable static func imageFlipVertical(_ image: inout Image) { _RaylibC.ImageFlipVertical(&image) } /// Flip image horizontally @inlinable static func imageFlipHorizontal(_ image: inout Image) { _RaylibC.ImageFlipHorizontal(&image) } /// Rotate image clockwise 90deg @inlinable static func imageRotateCW(_ image: inout Image) { _RaylibC.ImageRotateCW(&image) } /// Rotate image counter-clockwise 90deg @inlinable static func imageRotateCCW(_ image: inout Image) { _RaylibC.ImageRotateCCW(&image) } /// Modify image color: tint @inlinable static func imageColorTint(_ image: inout Image, _ color: Color) { _RaylibC.ImageColorTint(&image, color) } /// Modify image color: invert @inlinable static func imageColorInvert(_ image: inout Image) { _RaylibC.ImageColorInvert(&image) } /// Modify image color: grayscale @inlinable static func imageColorGrayscale(_ image: inout Image) { _RaylibC.ImageColorGrayscale(&image) } /// Modify image color: contrast (-100 to 100) @inlinable static func imageColorContrast(_ image: inout Image, _ contrast: Float) { _RaylibC.ImageColorContrast(&image, contrast) } /// Modify image color: brightness (-255 to 255) @inlinable static func imageColorBrightness(_ image: inout Image, _ brightness: Int32) { _RaylibC.ImageColorBrightness(&image, brightness) } /// Modify image color: replace color @inlinable static func imageColorReplace(_ image: inout Image, _ color: Color, _ replace: Color) { _RaylibC.ImageColorReplace(&image, color, replace) } /// Load color data from image as a Color array (RGBA - 32bit) @inlinable static func loadImageColors(_ image: Image) -> [Color] { let count = image.width * image.height * 4 let result = _RaylibC.LoadImageColors(image) let buffer = UnsafeMutableBufferPointer(start: result, count: Int(count)) return Array(buffer) } /// Load colors palette from image as a Color array (RGBA - 32bit) @inlinable static func loadImagePalette(_ image: Image, _ maxPaletteSize: Int32) -> [Color] { var colorsCount: Int32 = 0 let result = _RaylibC.LoadImagePalette(image, maxPaletteSize, &colorsCount) let buffer = UnsafeMutableBufferPointer(start: result, count: Int(colorsCount)) return Array(buffer) } /// Unload color data loaded with LoadImageColors() @inlinable @available(*, unavailable, message: "No need to do this in swift.") static func unloadImageColors(_ colors: [Color]) { var _colors = colors _RaylibC.UnloadImageColors(&_colors) } /// Unload colors palette loaded with LoadImagePalette() @inlinable @available(*, unavailable, message: "No need to do this in swift.") static func unloadImagePalette(_ colors: [Color]) { var _colors = colors _RaylibC.UnloadImagePalette(&_colors) } /// Get image alpha border rectangle @inlinable static func getImageAlphaBorder(_ image: Image, _ threshold: Float) -> Rectangle { return _RaylibC.GetImageAlphaBorder(image, threshold) } /// Get image pixel color at (x, y) position @inlinable static func getImageColor(_ image: Image, _ x: Int32, _ y: Int32) -> Color { return _RaylibC.GetImageColor(image, x, y) } } //MARK: - Image drawing functions // NOTE: Image software-rendering functions (CPU) public extension Raylib { /// Clear image background with given color @inlinable static func imageClearBackground(_ dst: inout Image, _ color: Color) { _RaylibC.ImageClearBackground(&dst, color) } /// Draw pixel within an image @inlinable static func imageDrawPixel(_ dst: inout Image, _ posX: Int32, _ posY: Int32, _ color: Color) { _RaylibC.ImageDrawPixel(&dst, posX, posY, color) } /// Draw pixel within an image (Vector version) @inlinable static func imageDrawPixelV(_ dst: inout Image, _ position: Vector2, _ color: Color) { _RaylibC.ImageDrawPixelV(&dst, position, color) } /// Draw line within an image @inlinable static func imageDrawLine(_ dst: inout Image, _ startPosX: Int32, _ startPosY: Int32, _ endPosX: Int32, _ endPosY: Int32, _ color: Color) { _RaylibC.ImageDrawLine(&dst, startPosX, startPosY, endPosX, endPosY, color) } /// Draw line within an image (Vector version) @inlinable static func imageDrawLineV(_ dst: inout Image, _ start: Vector2, _ end: Vector2, _ color: Color) { _RaylibC.ImageDrawLineV(&dst, start, end, color) } /// Draw circle within an image @inlinable static func imageDrawCircle(_ dst: inout Image, _ centerX: Int32, _ centerY: Int32, _ radius: Int32, _ color: Color) { _RaylibC.ImageDrawCircle(&dst, centerX, centerY, radius, color) } /// Draw circle within an image (Vector version) @inlinable static func imageDrawCircleV(_ dst: inout Image, _ center: Vector2, _ radius: Int32, _ color: Color) { _RaylibC.ImageDrawCircleV(&dst, center, radius, color) } /// Draw rectangle within an image @inlinable static func imageDrawRectangle(_ dst: inout Image, _ posX: Int32, _ posY: Int32, _ width: Int32, _ height: Int32, _ color: Color) { _RaylibC.ImageDrawRectangle(&dst, posX, posY, width, height, color) } /// Draw rectangle within an image (Vector version) @inlinable static func imageDrawRectangleV(_ dst: inout Image, _ position: Vector2, _ size: Vector2, _ color: Color) { _RaylibC.ImageDrawRectangleV(&dst, position, size, color) } /// Draw rectangle within an image @inlinable static func imageDrawRectangleRec(_ dst: inout Image, _ rec: Rectangle, _ color: Color) { _RaylibC.ImageDrawRectangleRec(&dst, rec, color) } /// Draw rectangle lines within an image @inlinable static func imageDrawRectangleLines(_ dst: inout Image, _ rec: Rectangle, _ thick: Int32, _ color: Color) { _RaylibC.ImageDrawRectangleLines(&dst, rec, thick, color) } /// Draw a source image within a destination image (tint applied to source) @inlinable static func imageDraw(_ dst: inout Image, _ src: Image, _ srcRec: Rectangle, _ dstRec: Rectangle, _ tint: Color) { _RaylibC.ImageDraw(&dst, src, srcRec, dstRec, tint) } /// Draw text (using default font) within an image (destination) @inlinable static func imageDrawText(_ dst: inout Image, _ text: String, _ posX: Int32, _ posY: Int32, _ fontSize: Int32, _ color: Color) { text.withCString { cString in _RaylibC.ImageDrawText(&dst, cString, posX, posY, fontSize, color) } } /// Draw text (custom sprite font) within an image (destination) @inlinable static func imageDrawTextEx(_ dst: inout Image, _ font: Font, _ text: String, _ position: Vector2, _ fontSize: Float, _ spacing: Float, _ tint: Color) { text.withCString { cString in _RaylibC.ImageDrawTextEx(&dst, font, cString, position, fontSize, spacing, tint) } } } //MARK: - Texture loading functions // NOTE: These functions require GPU access public extension Raylib { /// Load texture from file into GPU memory (VRAM) @inlinable static func loadTexture(_ fileName: String) -> Texture2D { return fileName.withCString { cString in return _RaylibC.LoadTexture(cString) } } /// Load texture from image data @inlinable static func loadTextureFromImage(_ image: Image) -> Texture2D { return _RaylibC.LoadTextureFromImage(image) } /// Load cubemap from image, multiple image cubemap layouts supported @inlinable static func loadTextureCubemap(_ image: Image, _ layout: CubemapLayout) -> TextureCubemap { return _RaylibC.LoadTextureCubemap(image, layout.rawValue) } /// Load texture for rendering (framebuffer) @inlinable static func loadRenderTexture(_ width: Int32, _ height: Int32) -> RenderTexture2D { return _RaylibC.LoadRenderTexture(width, height) } /// Unload texture from GPU memory (VRAM) @inlinable static func unloadTexture(_ texture: Texture2D) { return _RaylibC.UnloadTexture(texture) } /// Unload render texture from GPU memory (VRAM) @inlinable static func unloadRenderTexture(_ target: RenderTexture2D) { return _RaylibC.UnloadRenderTexture(target) } /// Update GPU texture with new data @inlinable static func updateTexture(_ texture: Texture2D, _ pixels: UnsafeRawPointer!) { _RaylibC.UpdateTexture(texture, pixels) } /// Update GPU texture rectangle with new data @inlinable static func updateTextureRec(_ texture: Texture2D, _ rec: Rectangle, _ pixels: UnsafeRawPointer!) { _RaylibC.UpdateTextureRec(texture, rec, pixels) } } //MARK: - Texture configuration functions public extension Raylib { /// Generate GPU mipmaps for a texture @inlinable static func genTextureMipmaps(_ texture: inout Texture2D) { _RaylibC.GenTextureMipmaps(&texture) } /// Set texture scaling filter mode @inlinable static func setTextureFilter(_ texture: Texture2D, _ filter: TextureFilter) { _RaylibC.SetTextureFilter(texture, filter.rawValue) } /// Set texture wrapping mode @inlinable static func setTextureWrap(_ texture: Texture2D, _ wrap: TextureWrap) { _RaylibC.SetTextureWrap(texture, wrap.rawValue) } } //MARK: - Texture drawing functions public extension Raylib { /// Draw a Texture2D @inlinable static func drawTexture(_ texture: Texture2D, _ posX: Int32, _ posY: Int32, _ tint: Color) { return _RaylibC.DrawTexture(texture, posX, posY, tint) } /// Draw a Texture2D with position defined as Vector2 @inlinable static func drawTextureV(_ texture: Texture2D, _ position: Vector2, _ tint: Color) { _RaylibC.DrawTextureV(texture, position, tint) } //// Draw a Texture2D with extended parameters @inlinable static func drawTextureEx(_ texture: Texture2D, _ position: Vector2, _ rotation: Float, _ scale: Float, _ tint: Color) { _RaylibC.DrawTextureEx(texture, position, rotation, scale, tint) } /// Draw a part of a texture defined by a rectangle @inlinable static func drawTextureRec(_ texture: Texture2D, _ source: Rectangle, _ position: Vector2, _ tint: Color) { _RaylibC.DrawTextureRec(texture, source, position, tint) } /// Draw texture quad with tiling and offset parameters @inlinable static func drawTextureQuad(_ texture: Texture2D, _ tiling: Vector2, _ offset: Vector2, _ quad: Rectangle, _ tint: Color) { _RaylibC.DrawTextureQuad(texture, tiling, offset, quad, tint) } /// Draw part of a texture (defined by a rectangle) with rotation and scale tiled into dest. @inlinable static func drawTextureTiled(_ texture: Texture2D, _ source: Rectangle, _ dest: Rectangle, _ origin: Vector2, _ rotation: Float, _ scale: Float, _ tint: Color) { _RaylibC.DrawTextureTiled(texture, source, dest, origin, rotation, scale, tint) } /// Draw a part of a texture defined by a rectangle with 'pro' parameters @inlinable static func drawTexturePro(_ texture: Texture2D, _ source: Rectangle, _ dest: Rectangle, _ origin: Vector2, _ rotation: Float, _ tint: Color) { _RaylibC.DrawTexturePro(texture, source, dest, origin, rotation, tint) } /// Draws a texture (or part of it) that stretches or shrinks nicely @inlinable static func drawTextureNPatch(_ texture: Texture2D, _ nPatchInfo: NPatchInfo, _ dest: Rectangle, _ origin: Vector2, _ rotation: Float, _ tint: Color) { _RaylibC.DrawTextureNPatch(texture, nPatchInfo, dest, origin, rotation, tint) } /// Draw a textured polygon @inlinable static func drawTexturePoly(_ texture: Texture2D, _ center: Vector2, _ points: [Vector2], _ texcoords: [Vector2], _ tint: Color) { var _points = points var _texcoords = texcoords _RaylibC.DrawTexturePoly(texture, center, &_points, &_texcoords, Int32(points.count), tint) } } //MARK: - Color/pixel related functions public extension Raylib { /// Get color with alpha applied, alpha goes from 0.0f to 1.0f @inlinable static func fade(_ color: Color, _ alpha: Float) -> Color { return _RaylibC.Fade(color, alpha) } /// Get hexadecimal value for a Color @inlinable static func colorToInt(_ color: Color) -> Int32 { return _RaylibC.ColorToInt(color) } /// Get Color normalized as float [0..1] static func colorNormalize(_ color: Color) -> Vector4 { return _RaylibC.ColorNormalize(color) } /// Get Color from normalized values [0..1] @inlinable static func colorFromNormalized(_ normalized: Vector4) -> Color { return _RaylibC.ColorFromNormalized(normalized) } /// Get HSV values for a Color, hue [0..360], saturation/value [0..1] @inlinable static func colorToHSV(_ color: Color) -> Vector3 { return _RaylibC.ColorToHSV(color) } /// Get a Color from HSV values, hue [0..360], saturation/value [0..1] @inlinable static func colorFromHSV(_ hue: Float, _ saturation: Float, _ value: Float) -> Color { return _RaylibC.ColorFromHSV(hue, saturation, value) } /// Get color with alpha applied, alpha goes from 0.0f to 1.0f @inlinable static func colorAlpha(_ color: Color, _ alpha: Float) -> Color { return _RaylibC.ColorAlpha(color, alpha) } /// Get src alpha-blended into dst color with tint @inlinable static func colorAlphaBlend(_ dst: Color, _ src: Color, _ tint: Color) -> Color { return _RaylibC.ColorAlphaBlend(dst, src, tint) } /// Get Color structure from hexadecimal value @inlinable static func getColor(_ hexValue: UInt32) -> Color { return _RaylibC.GetColor(hexValue) } /// Get Color from a source pixel pointer of certain format @inlinable static func getPixelColor(_ srcPtr: UnsafeMutableRawPointer!, _ format: PixelFormat) -> Color { return _RaylibC.GetPixelColor(srcPtr, format.rawValue) } /// Set color formatted into destination pixel pointer @inlinable static func setPixelColor(_ dstPtr: UnsafeMutableRawPointer!, _ color: Color, _ format: PixelFormat) { return _RaylibC.SetPixelColor(dstPtr, color, format.rawValue) } /// Get pixel data size in bytes for certain format @inlinable static func getPixelDataSize(_ width: Int32, _ height: Int32, _ format: PixelFormat) -> Int32 { return _RaylibC.GetPixelDataSize(width, height, format.rawValue) } }
36.371166
165
0.660665
fc62af3e923bb282a41b9d53abe7790fab229d1b
488
// // AmuseViewModel.swift // DYZB // // Created by admin on 17/8/18. // Copyright © 2017年 smartFlash. All rights reserved. // import UIKit class AmuseViewModel { } extension AmuseViewModel { func loadAmuseData(finishedCllback : @escaping () -> ()) { NetworkTools.requestData(tape: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotRoom/2") { (result) in //1.对结果进行处理 guard let resultDict = result as? [String : Any] else { return } } } }
21.217391
112
0.639344
fb93cf189e78034d1cccfa0034ef0811fc80bcd9
4,620
// // ParallaxIntroCollectionViewCell.swift // PDAnimator-Demo // // Created by Anton Doudarev on 3/30/18. // Copyright © 2018 ELEPHANT. All rights reserved. // import UIKit import Elephant_Parade #if ENV_TEST import PDAnimator #endif class ParallaxIntroCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) setupInterface() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupInterface() } func setupInterface() { clipsToBounds = false contentView.clipsToBounds = false contentView.backgroundColor = defaultBlackColor contentView.addSubview(logoImageView) contentView.addSubview(progressView) contentView.addSubview(arrowImageView) // Not the most efficient way to layout // content, but good enough for a demo logoImageView.frame = CGRect(origin: CGPoint(x: (contentView.bounds.width / 2.0) - 120, y: 130), size: CGSize(width: 240, height : 240)) arrowImageView.frame = CGRect(origin: CGPoint(x: (contentView.bounds.width / 2.0) - 40, y: (contentView.bounds.height) - 130), size: CGSize(width: 80, height : 46)) progressView.frame = CGRect(origin: CGPoint(x: (contentView.bounds.width / 2.0) - 2, y: contentView.bounds.height - 254), size: CGSize(width: 4, height : 80)) } // MARK: Lazy Loaded Views lazy var logoImageView : UIImageView = { [unowned self] in let image: UIImageView = UIImageView(image : preloadedImageCache["elephant_logo"]!) image.backgroundColor = UIColor.clear image.contentMode = .scaleAspectFit return image }() lazy var progressView : ProgressDotView = { [unowned self] in let view = ProgressDotView(frame:CGRect.zero) view.backgroundColor = UIColor.clear return view }() lazy var arrowImageView : UIImageView = { [unowned self] in let image: UIImageView = UIImageView(image :UIImage(named: "down_arrow")) image.backgroundColor = UIColor.clear image.contentMode = .scaleAspectFit image.alpha = 0.8 return image }() } // MARK: - PDAnimatableType extension ParallaxIntroCollectionViewCell: PDAnimatableType { func configuredAnimator() -> PDAnimator { // The logo transform for appearence / disappearance let offScreenLogoTransform = CGAffineTransform.identity.scaledBy(x: 1.6, y: 1.6).translatedBy(x: 0, y: 50.0) // The arrow transform for appearence / disappearance let offScreenArrowTransform = CGAffineTransform.identity.scaledBy(x: 0.1, y: 0.1).translatedBy(x: 0, y: 160.0) // The progress dots view transform for appearence / disappearance let offScreenDotsViewTransform = CGAffineTransform.identity.translatedBy(x: 0, y: -10.0).scaledBy(x: 0.8, y: 1.0) // The alpha for appearence / disappearance of all elements let offScreenAlpha = CGFloat(0.0) // The size for dots view for appearence / disappearance // Size is used so that it redraws the view and does not stretch it let offScreenDotViewSize = progressView.bounds.size.scaledValue(width: 0.8, height : 3.0) return PDAnimator.newVerticalAnimator { (animator) in animator.endState(for: logoImageView, { (s) in s.alpha(offScreenAlpha).easing(.inSine) s.transform(offScreenLogoTransform) }).endState(for: arrowImageView, { (s) in s.alpha(offScreenAlpha).easing(.inSine) s.transform(offScreenArrowTransform) }).endState(for: contentView, { (s) in s.backgroundColor(transitioningBackgroundColor) }).endState(for: progressView, { (s) in s.alpha(offScreenAlpha).easing(.inSine) s.transform(offScreenDotsViewTransform).easing(.inSine) }).startEndState(for: progressView, { (s) in s.size(offScreenDotViewSize).easing(.inSine) }) } } }
34.222222
129
0.581602
e23502e4aa5c13f7e185970650c4f048811cea18
1,409
// // Tests_iOS.swift // Tests iOS // // Created by Amr Aboelela on 6/14/21. // import XCTest class Tests_iOS: 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, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
32.767442
182
0.650816
d5db91e9e666496712e2eb8b093bcf80ac3645ce
299
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { for in{ var [{{ (((({ (({ { {{(( { [[{{ [{{{ { [((( { {{ {{{ { { { { " class case,
10.310345
87
0.598662
e2e3714acc37d1d24a4cc8d394408f8c71a5c9db
861
// // AltarStudiosEndpoint.swift // AT_Test_Task // // Created by Vasile Morari on 24.09.2020. // import Foundation enum AltarStudiosEndpoint { case auth(username: String, password: String) case data } extension AltarStudiosEndpoint: Endpoint { var host: String { return "http://www.alarstudios.com" } var basePath: String { return "/test" } var path: String { switch self { case .auth: return "/auth.cgi" case .data: return "/data.cgi" } } var queryItems: [URLQueryItem]? { switch self { case .auth(let username, let password): return [ .init(name: "username", value: username), .init(name: "password", value: password) ] case .data: return nil } } }
20.023256
57
0.542393
9160b754cc679cd2de9c209078dc5bdc861dc142
978
import Darwin public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } // DFS, top -> down, 484 ms func isBalanced(root: TreeNode?) -> Bool { let left = height(root?.left) let right = height(root?.right) return root == nil ? true : abs(left-right) <= 1 && isBalanced(root?.left) && isBalanced(root?.right) } func height(root: TreeNode?) -> Int { return root == nil ? 0 : max(height(root?.left),height(root?.right)) + 1 } // DFS, bottom up, 444 ms, a little bit faster func isBalanced(root: TreeNode?) -> Bool { return height(root) != -1 } func height(root: TreeNode?) -> Int { if root == nil { return 0 } let left = height(root?.left) let right = height(root?.right) if left == -1 || right == -1 || abs(left - right) > 1 { return -1 } return max(left, right) + 1 }
23.853659
105
0.596115
e48a5895628a593c82d1391dfc4b673766750855
278
// // ScoreKeys.swift // labs-ios-starter // // Created by Kelson Hartle on 2/16/21. // Copyright © 2021 Spencer Curtis. All rights reserved. // import Foundation enum ScoreKeys { case rent case walk case crime case air case life case population }
14.631579
57
0.654676
910d19b7e2c45c8bb214de9fe27046b67f87f5a7
2,039
// Webservice.swift import Foundation enum WebserviceError: Error { case networkError(Error) case serverError case requestError(Int, String) case invalidResponse case decodingError(Error) } final class Webservice { private let session: URLSession! private let baseURL = URL(string: "https://jsonplaceholder.typicode.com")! init(session: URLSession = .shared) { self.session = session } func load<T>(resource: Resource<T>, completion: @escaping (Result<T?, WebserviceError>) -> ()) { var urlComponents = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)! urlComponents.path = resource.path urlComponents.queryItems = resource.queryItems let request = URLRequest(url: urlComponents.url!) session.dataTask(with: request) { (data, response, error) in if let error = error { DispatchQueue.main.async { completion(Result.failure(.networkError(error))) } return } guard let http = response as? HTTPURLResponse else { DispatchQueue.main.async { completion(.failure(.invalidResponse)) } return } switch http.statusCode { case 200: DispatchQueue.main.async { completion(.success((data.flatMap(resource.parse)))) } case 400...499: if let data = data, let body = String(data: data, encoding: .utf8) { DispatchQueue.main.async { completion(.failure(.requestError(http.statusCode, body))) } } case 500...599: DispatchQueue.main.async { completion(.failure(.serverError)) } default: fatalError("Unhandeled HTTP status code: \(http.statusCode)") } }.resume() } }
31.859375
100
0.545365
4be017a9c8ceee73b360c6f3458bb866f298bde7
3,862
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // LinuxMain.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// #if os(Linux) || os(FreeBSD) @testable import NIOConcurrencyHelpersTests @testable import NIOHTTP1Tests @testable import NIOTLSTests @testable import NIOTests @testable import NIOWebSocketTests XCTMain([ testCase(AcceptBackoffHandlerTest.allTests), testCase(AdaptiveRecvByteBufferAllocatorTest.allTests), testCase(ApplicationProtocolNegotiationHandlerTests.allTests), testCase(Base64Test.allTests), testCase(BaseObjectTest.allTests), testCase(BlockingIOThreadPoolTest.allTests), testCase(BootstrapTest.allTests), testCase(ByteBufferTest.allTests), testCase(ByteBufferUtilsTest.allTests), testCase(ByteToMessageDecoderTest.allTests), testCase(ChannelNotificationTest.allTests), testCase(ChannelOptionStorageTest.allTests), testCase(ChannelPipelineTest.allTests), testCase(ChannelTests.allTests), testCase(CircularBufferTests.allTests), testCase(CompositeErrorTests.allTests), testCase(CustomChannelTests.allTests), testCase(DatagramChannelTests.allTests), testCase(EchoServerClientTest.allTests), testCase(EmbeddedChannelTest.allTests), testCase(EmbeddedEventLoopTest.allTests), testCase(EndToEndTests.allTests), testCase(EventLoopFutureTest.allTests), testCase(EventLoopTest.allTests), testCase(FileRegionTest.allTests), testCase(GetaddrinfoResolverTest.allTests), testCase(HTTPDecoderLengthTest.allTests), testCase(HTTPDecoderTest.allTests), testCase(HTTPHeadersTest.allTests), testCase(HTTPRequestEncoderTests.allTests), testCase(HTTPResponseEncoderTests.allTests), testCase(HTTPServerClientTest.allTests), testCase(HTTPServerPipelineHandlerTest.allTests), testCase(HTTPServerProtocolErrorHandlerTest.allTests), testCase(HTTPTest.allTests), testCase(HTTPUpgradeTestCase.allTests), testCase(HappyEyeballsTest.allTests), testCase(HeapTests.allTests), testCase(IdleStateHandlerTest.allTests), testCase(IntegerTypesTest.allTests), testCase(MarkedCircularBufferTests.allTests), testCase(MessageToByteEncoderTest.allTests), testCase(MulticastTest.allTests), testCase(NIOAnyDebugTest.allTests), testCase(NIOConcurrencyHelpersTests.allTests), testCase(NonBlockingFileIOTest.allTests), testCase(PendingDatagramWritesManagerTests.allTests), testCase(PriorityQueueTest.allTests), testCase(SNIHandlerTest.allTests), testCase(SelectorTest.allTests), testCase(SocketAddressTest.allTests), testCase(SocketChannelTest.allTests), testCase(SocketOptionProviderTest.allTests), testCase(SystemTest.allTests), testCase(ThreadTest.allTests), testCase(TypeAssistedChannelHandlerTest.allTests), testCase(UtilitiesTest.allTests), testCase(WebSocketFrameDecoderTest.allTests), testCase(WebSocketFrameEncoderTest.allTests), ]) #endif
41.085106
87
0.690316
f5a72667dd0b1397ed7846e3538c0b823aba40a0
21,154
// // NBSideTabBarController.swift // SideTabBar // // Created by Nicolas Barbara on 7/25/18. // Copyright © 2018 Nicolas Barbara. All rights reserved. // import Foundation import UIKit class NBSideTabBarController:UIViewController,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate{ var tableViewCells:[NBSideTableViewCell] var views:[NBView] var colorList:[UIColor]? var leftTableViewWidth:CGFloat var tableViewAnchor:NBSideTabBarAnchor init(dataSource:[NBSideTabBarControllerDataSource],width:CGFloat,anchor:NBSideTabBarAnchor,colors:[UIColor]?){ self.colorList = colors self.tableViewAnchor = anchor self.leftTableViewWidth = width self.tableViewCells = dataSource.map({ (i) -> NBSideTableViewCell in return i.tableViewCell }) self.views = dataSource.map({ (i) -> NBView in return i.view }) super.init(nibName: nil, bundle: nil) views.forEach { (i) in i.sideTabBarController = self } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var selectorView = UIView() var leftTableViewBackgroundView = UIView() lazy var tableView:UITableView = { let t = UITableView() t.delegate = self t.dataSource = self t.separatorStyle = .none t.isScrollEnabled = false t.backgroundColor = .clear t.translatesAutoresizingMaskIntoConstraints = false return t }() lazy var scrollView1:UIScrollView = { let s = UIScrollView() s.delegate = self s.backgroundColor = .white s.isPagingEnabled = true s.bounces = false s.translatesAutoresizingMaskIntoConstraints = false s.canCancelContentTouches = true return s }() override func viewDidLoad() { super.viewDidLoad() leftTableViewBackgroundView.backgroundColor = UIColor.gray leftTableViewBackgroundView.translatesAutoresizingMaskIntoConstraints = false selectorView.translatesAutoresizingMaskIntoConstraints = false selectorView.backgroundColor = .red if self.colorList != nil{ if self.colorList?.count != 0{ selectorView.backgroundColor = self.colorList![0] } } setupTableViews() for i in 0...self.views.count-1{ self.scrollView1.addSubview(views[i]) if i == 0{ views[i].topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true views[i].bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true views[i].widthAnchor.constraint(equalToConstant: self.view.frame.width-self.leftTableViewWidth).isActive = true views[i].leftAnchor.constraint(equalTo: self.scrollView1.leftAnchor).isActive = true } else if i == self.views.count-1{ views[i].topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true views[i].bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true views[i].widthAnchor.constraint(equalToConstant: self.view.frame.width-self.leftTableViewWidth).isActive = true views[i].leftAnchor.constraint(equalTo: views[i-1].rightAnchor).isActive = true } else{ views[i].topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true views[i].bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true views[i].widthAnchor.constraint(equalToConstant: self.view.frame.width-self.leftTableViewWidth).isActive = true views[i].leftAnchor.constraint(equalTo: views[i-1].rightAnchor).isActive = true } scrollView1.contentSize.width = (self.view.frame.width-self.leftTableViewWidth)*CGFloat(self.views.count) } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableViewCells.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableViewCells[indexPath.row] } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.view.frame.height/CGFloat(tableViewCells.count) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //scrollView1.scrollToItem(at: indexPath, at: .left, animated: true) let x = self.scrollView1.frame.width*CGFloat(indexPath.row) let p = CGPoint(x: x, y: 0) scrollView1.setContentOffset(p, animated: true) } func setupTableViews(){ view.addSubview(leftTableViewBackgroundView) view.addSubview(selectorView) view.addSubview(scrollView1) view.addSubview(tableView) if self.tableViewAnchor == .left{ selectorView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true selectorView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true selectorView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true selectorView.heightAnchor.constraint(equalToConstant: view.frame.height/CGFloat(tableViewCells.count)).isActive = true leftTableViewBackgroundView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true leftTableViewBackgroundView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true leftTableViewBackgroundView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true leftTableViewBackgroundView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true tableView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true scrollView1.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true scrollView1.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true scrollView1.leftAnchor.constraint(equalTo: self.tableView.rightAnchor).isActive = true scrollView1.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } else{ selectorView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true selectorView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true selectorView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true selectorView.heightAnchor.constraint(equalToConstant: view.frame.height/CGFloat(tableViewCells.count)).isActive = true leftTableViewBackgroundView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true leftTableViewBackgroundView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true leftTableViewBackgroundView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true leftTableViewBackgroundView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true tableView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true scrollView1.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true scrollView1.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true scrollView1.rightAnchor.constraint(equalTo: self.tableView.leftAnchor).isActive = true scrollView1.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.views.count } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == scrollView1{ selectorView.frame.origin.y = scrollView.contentOffset.x / scrollView.contentSize.width * tableView.frame.height } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == scrollView1{ if let cl = self.colorList{ let index = Int(scrollView.contentOffset.x / scrollView.contentSize.width * CGFloat(cl.count)) if cl.count > index{ selectorView.backgroundColor = cl[index] } } } } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { if scrollView == scrollView1{ if let cl = self.colorList{ let index = Int(scrollView.contentOffset.x / scrollView.contentSize.width * CGFloat(cl.count)) if cl.count > index{ selectorView.backgroundColor = cl[index] } } } } } enum NBSideTabBarAnchor{ case left case right } struct NBSideTabBarControllerDataSource { let tableViewCell:NBSideTableViewCell let view:NBView } class NBView:UIView{ var sideTabBarController:NBSideTabBarController! init() { super.init(frame:.zero) translatesAutoresizingMaskIntoConstraints = false } required init?(coder aDecoder: NSCoder) { fatalError("error") } } class NBSideCollectionViewCell:UICollectionViewCell{ var view:NBView!{ didSet{ addSubview(view) view.topAnchor.constraint(equalTo: self.topAnchor).isActive = true view.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true view.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true } } } class NBSideTableViewCell:UITableViewCell{ let label:UILabel = { let l = UILabel() l.textColor = .white l.textAlignment = .center l.adjustsFontSizeToFitWidth = true l.translatesAutoresizingMaskIntoConstraints = false return l }() let imageView1:UIImageView = { let i = UIImageView() i.backgroundColor = .clear i.clipsToBounds = true i.contentMode = .scaleAspectFit return i }() init(text:String) { super.init(style: UITableViewCellStyle.default, reuseIdentifier: nil) selectionStyle = .none backgroundColor = .clear label.text = text addSubview(label) label.topAnchor.constraint(equalTo: self.topAnchor).isActive = true label.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true label.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true label.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true } init(image:UIImage) { super.init(style: UITableViewCellStyle.default, reuseIdentifier: nil) selectionStyle = .none backgroundColor = .clear imageView1.image = image addSubview(imageView1) imageView1.topAnchor.constraint(equalTo: self.topAnchor).isActive = true imageView1.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true imageView1.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true imageView1.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true } init() { super.init(style: UITableViewCellStyle.default, reuseIdentifier: nil) selectionStyle = .none backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /*class NBSideTabBarController:UIViewController,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{ var tableViewCells:[NBSideTableViewCell] var views:[NBView] var colorList:[UIColor]? var leftTableViewWidth:CGFloat var tableViewAnchor:NBSideTabBarAnchor init(dataSource:[NBSideTabBarControllerDataSource],width:CGFloat,anchor:NBSideTabBarAnchor,colors:[UIColor]?){ self.colorList = colors self.tableViewAnchor = anchor self.leftTableViewWidth = width self.tableViewCells = dataSource.map({ (i) -> NBSideTableViewCell in return i.tableViewCell }) self.views = dataSource.map({ (i) -> NBView in return i.view }) super.init(nibName: nil, bundle: nil) views.forEach { (i) in i.sideTabBarController = self } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var selectorView = UIView() var leftTableViewBackgroundView = UIView() lazy var tableView:UITableView = { let t = UITableView() t.delegate = self t.dataSource = self t.separatorStyle = .none t.isScrollEnabled = false t.backgroundColor = .clear t.translatesAutoresizingMaskIntoConstraints = false return t }() lazy var collectionView:UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 let c = UICollectionView(frame: .zero, collectionViewLayout: layout) c.delegate = self c.dataSource = self c.backgroundColor = .white c.isPagingEnabled = true c.bounces = false c.showsHorizontalScrollIndicator = false c.translatesAutoresizingMaskIntoConstraints = false c.register(NBSideCollectionViewCell.self, forCellWithReuseIdentifier: "ID") return c }() override func viewDidLoad() { super.viewDidLoad() leftTableViewBackgroundView.backgroundColor = UIColor.gray leftTableViewBackgroundView.translatesAutoresizingMaskIntoConstraints = false selectorView.translatesAutoresizingMaskIntoConstraints = false selectorView.backgroundColor = .red if self.colorList != nil{ if self.colorList?.count != 0{ selectorView.backgroundColor = self.colorList![0] } } setupTableViews() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableViewCells.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableViewCells[indexPath.row] } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.view.frame.height/CGFloat(tableViewCells.count) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { collectionView.scrollToItem(at: indexPath, at: .left, animated: true) } func setupTableViews(){ view.addSubview(leftTableViewBackgroundView) view.addSubview(selectorView) view.addSubview(collectionView) view.addSubview(tableView) if self.tableViewAnchor == .left{ selectorView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true selectorView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true selectorView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true selectorView.heightAnchor.constraint(equalToConstant: view.frame.height/CGFloat(tableViewCells.count)).isActive = true leftTableViewBackgroundView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true leftTableViewBackgroundView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true leftTableViewBackgroundView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true leftTableViewBackgroundView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true tableView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true collectionView.leftAnchor.constraint(equalTo: self.tableView.rightAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } else{ selectorView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true selectorView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true selectorView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true selectorView.heightAnchor.constraint(equalToConstant: view.frame.height/CGFloat(tableViewCells.count)).isActive = true leftTableViewBackgroundView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true leftTableViewBackgroundView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true leftTableViewBackgroundView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true leftTableViewBackgroundView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true tableView.widthAnchor.constraint(equalToConstant: self.leftTableViewWidth).isActive = true tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true collectionView.rightAnchor.constraint(equalTo: self.tableView.leftAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.views.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ID", for: indexPath) as! NBSideCollectionViewCell cell.view = views[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.width, height: collectionView.frame.height) } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == collectionView{ selectorView.frame.origin.y = scrollView.contentOffset.x / scrollView.contentSize.width * tableView.frame.height } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == collectionView{ if let cl = self.colorList{ let index = Int(scrollView.contentOffset.x / scrollView.contentSize.width * CGFloat(cl.count)) if cl.count > index{ selectorView.backgroundColor = cl[index] } } } } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { if scrollView == collectionView{ if let cl = self.colorList{ let index = Int(scrollView.contentOffset.x / scrollView.contentSize.width * CGFloat(cl.count)) if cl.count > index{ selectorView.backgroundColor = cl[index] } } } } } */
48.629885
177
0.681101
08fd8a1c0ad8092196eccbe504fb4d46cea2bc44
1,224
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Tracing open source project // // Copyright (c) 2020 Moritz Lang and the Swift Tracing project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // HeaderInjectingHTTPClientHandlerTests+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension HeaderInjectingHTTPClientHandlerTests { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (HeaderInjectingHTTPClientHandlerTests) -> () throws -> Void)] { return [ ("test_injects_baggage_into_http_request_headers", test_injects_baggage_into_http_request_headers), ("test_forwards_all_write_events", test_forwards_all_write_events), ] } }
36
162
0.639706
4853bd4e0a52eabcf74c0471d068d283c466babc
7,693
// // eNotesNetworkManager.swift // eNotes // // Created by Smiacter on 2018/8/23. // Copyright © 2018 eNotes. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import Alamofire class eNotesNetworkManager: NSObject { static let shared = eNotesNetworkManager() private override init() { } } // MARK: Universal extension eNotesNetworkManager { func getBalance(blockchain: Blockchain, network: Network, address: String, closure: balanceClosure) { let request = eNotesArrayPostRequest() request.path = "/get_address_balance" request.anyKey = [["blockchain": blockchain.eNotesString, "network": network.eNotesString, "address": address]] eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: [eNotesBalanceRaw].self) { closure?(model.toBalance(), response.error) } else { closure?("", error ?? response.error) } } } func sendTransaction(blockchain: Blockchain, network: Network, rawtx: String, closure: txIdClosure) { let request = eNotesArrayPostRequest() request.path = "/send_raw_transaction" request.anyKey = [["blockchain": blockchain.eNotesString, "network": network.eNotesString, "rawtx": rawtx]] eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: [eNotesTxidRaw].self), !model.toTxId().isEmpty { closure?(model.toTxId(), response.error) } else { closure?("", error ?? response.error) } } } func getTxReceipt(blockchain: Blockchain, network: Network, txid: String, closure: txReceiptClosure) { let request = eNotesArrayPostRequest() request.path = "/get_transaction_receipt" request.anyKey = [["blockchain": blockchain.eNotesString, "network": network.eNotesString, "txid": txid]] eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: [[eNotesTxReceiptRaw]].self) { closure?(model.toConfirmStatus(), response.error) } else { closure?(.none, error ?? response.error) } } } /// subscribe Notification /// clientId: Getui Client id func subscribeNotification(blockchain: Blockchain, clientId: String, network: Network, txid: String) { let request = eNotesArrayPostRequest() request.path = "/subscribe_notification" request.anyKey = [["blockchain": blockchain.eNotesString, "network": network.eNotesString, "txid": txid, "event": "txreceipt", "cid": clientId]] eNotesNetwork.request(request) { (response) in } } } // MARK: Btc extension eNotesNetworkManager { func getUtxos(network: Network, address: String, closure: btcUtxosClosure) { let request = eNotesUtxosRequest() request.path = "/get_address_utxos/bitcoin/\(network.network(api: .eNotes))/?address=\(address)" eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: eNotesUtxosRaw.self) { closure?(model.toUtxos(), response.error) } else { closure?([], error ?? response.error) } } } func getTxFee(api: ApiType, network: Network, closure: btcTxFeeClosure) { let request = eNotesEstimateFeeRequest() request.path = "/estimate_fee/bitcoin/\(network.network(api: api))/?blocks=1" eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: eNotesEstimateFeeRaw.self) { closure?(model.toBtcTxFee(), nil, response.error) } else { closure?(0, nil, error ?? response.error) } } } } // MARK: Eth extension eNotesNetworkManager { func getGasPrice(api: ApiType, network: Network, closure: ethGasPriceClosure) { let request = eNotesGasPriceRequest() request.path = "/get_gas_price/ethereum/\(network.network(api: api))" eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: eNotesGasPriceRaw.self) { closure?(model.toGasPrice(), nil, response.error) } else { closure?("", nil, error ?? response.error) } } } func call(api: ApiType, network: Network, toAddress: String, dataStr: String, closure: ethCallClosure) { let request = eNotesCallRequest() request.path = "/eth_call/ethereum/\(network.network(api: api))/?to=\(toAddress)&data=\(dataStr.addHexPrefix())" eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: eNotesCallRaw.self) { closure?(model.data.result, response.error) } else { closure?("", error ?? response.error) } } } func getNonce(api: ApiType, network: Network, address: String, closure: ethNonceClosure) { let request = eNotesNonceRequest() request.path = "/get_address_nonce/ethereum/\(network.network(api: api))/?address=\(address)" eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: eNotesNonceRaw.self) { closure?(model.toNonce(), response.error) } else { closure?(0, error ?? response.error) } } } func getEstimateGas(api: ApiType, network: Network, from: String, to address: String, value: String, data: String? = nil, closure: ethEstimateGasClosure) { let dataStr = data != nil ? "&data=\(data!)" : "" let request = eNotesEstimateGasRequest() request.path = "/estimate_gas/ethereum/\(network.network(api: api))/?from=\(from)&to=\(address)&value=\(value)\(dataStr)" eNotesNetwork.request(request) { (response) in let error = response.error if let model = response.decode(to: eNotesEstimateGasRaw.self) { closure?(model.toEstimateGas(), response.error) } else { closure?("", error ?? response.error) } } } }
40.920213
159
0.621864
48c6a83143dcdacccfee84d1453ad8282d0c8cdf
617
// // UserRouter.swift // CodeEditModules/GitAccounts // // Created by Nanashi Li on 2022/03/31. // import Foundation enum UserRouter: Router { case readAuthenticatedUser(Configuration) var configuration: Configuration? { switch self { case .readAuthenticatedUser(let config): return config } } var method: HTTPMethod { .GET } var encoding: HTTPEncoding { .url } var path: String { switch self { case .readAuthenticatedUser: return "user" } } var params: [String: Any] { [:] } }
16.236842
62
0.570502
f87b570e27d1aebae56577df68dec27c0d5d8c9f
1,687
// // MainTabViewController.swift // YDNYNAB // // Created by Justin Hill on 9/1/18. // Copyright © 2018 Justin Hill. All rights reserved. // import Cocoa protocol MainTabViewControllerDelegate: class { func mainTabViewControllerItemsDidChange(_ tabViewController: NSTabViewController) } class MainTabViewController: NSTabViewController { enum Constant { static let toolbarIdentifier = NSToolbar.Identifier("BudgetWindowToolbar") static let budgetItemIdentifier = NSToolbarItem.Identifier("BudgetItem") } lazy var contentViewController = BudgetOverviewViewController(budgetContext: self.budgetContext) lazy var allTransactionsRegister = RegisterViewController(mode: .full, budgetContext: self.budgetContext) let budgetContext: BudgetContext var delegate: MainTabViewControllerDelegate? required init?(coder: NSCoder) { fatalError("not implemented") } init(budgetContext: BudgetContext) { self.budgetContext = budgetContext super.init(nibName: nil, bundle: nil) } override func loadView() { self.tabView = NSTabView() self.view = NSView() } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(self.tabView) self.tabView.makeEdgesEqual(to: self.view) self.view.wantsLayer = true self.tabView.tabPosition = .none } override func viewWillAppear() { super.viewWillAppear() self.addChild(self.contentViewController) self.addChild(self.allTransactionsRegister) self.delegate?.mainTabViewControllerItemsDidChange(self) } }
29.596491
109
0.692353
bbb1aa74eb50c30ff7a4b04a578b0b72f33c1147
1,023
/** * Copyright IBM Corporation 2019 * * 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 /** Relevant text that contributed to the categorization. */ public struct CategoriesRelevantText: Codable, Equatable { /** Text from the analyzed source that supports the categorization. */ public var text: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case text = "text" } }
29.228571
82
0.72043
169fbf43a223127e2afbbb5fe79b7fa76ff603e0
1,159
// // AppDelegate+OAuthSupport.swift // LinkDemo-Swift // // Copyright © 2020 Plaid Inc. All rights reserved. // import UIKit extension AppDelegate { // MARK: Re-initialize Plaid Link for iOS to complete OAuth authentication flow // <!-- SMARTDOWN_OAUTH_SUPPORT --> func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let webpageURL = userActivity.webpageURL else { return false } #warning("Replace the example oauthRedirectUri below with your oauthRedirectUri, which should be configured as a universal link and must be whitelisted through Plaid's developer dashboard") let oauthRedirectUri = URL(string: "https://example.net/plaid-oauth")! if webpageURL.host == oauthRedirectUri.host && webpageURL.path == oauthRedirectUri.path { // Pass the webpageURL to your code responsible for re-initalizing Plaid Link for iOS } return true } // <!-- SMARTDOWN_OAUTH_SUPPORT --> }
38.633333
197
0.707506
215e8e0c52a8a8e66bf55eb78e60e549d75dc241
1,100
// // HomeView.swift // tourist // // Created by 唐烁 on 2021/10/18. // import SwiftUI struct HomeView: View { @State var selectedView = 1 var body: some View { TabView(selection: $selectedView) { WeatherView() .tabItem { Image(systemName: "cloud") Text("天气预报") } .tag(1) ScenicView() .tabItem { Image(systemName: "giftcard") Text("信息查询") } .tag(2) HistoryTodayView() .tabItem { Image(systemName: "book.closed") Text("那年今日") } .tag(2) CookBookView() .tabItem { Image(systemName: "book") Text("菜谱大全") } .tag(2) } .accentColor(.black) .edgesIgnoringSafeArea(.top) } } struct HomeView_Previews: PreviewProvider { static var previews: some View { HomeView() } }
21.568627
52
0.417273
6a6f34b38e6cb3c9fd51507f6c8ecbc1de709ac5
2,124
// // TweetsViewController.swift // SwifterDemoiOS // // Copyright (c) 2014 Matt Donnelly. // // 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 import SwifteriOS class TweetsViewController: UITableViewController { var tweets : [JSONValue] = [] override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.tableView.contentInset = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, 0, 0) self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, 0, 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil) cell.textLabel.text = tweets[indexPath.row]["text"].string return cell } }
37.263158
118
0.728814
eddc8b28dcae2222852a5e205fabbcef2992335b
1,529
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class ShowMagnifierViewController: UIViewController { @IBOutlet private weak var mapView:AGSMapView! private var map:AGSMap! override func viewDidLoad() { super.viewDidLoad() //instantiate map with topographic basemap self.map = AGSMap(basemap: AGSBasemap.imagery()) //asssign map to the map view self.mapView.map = self.map //enable magnifier self.mapView.interactionOptions.isMagnifierEnabled = true //zoom to custom viewpoint let viewpoint = AGSViewpoint(center: AGSPoint(x: -110.8258 , y: 32.1545089, spatialReference: AGSSpatialReference.wgs84()), scale: 2e4) self.mapView.setViewpoint(viewpoint) //setup source code BBI (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ShowMagnifierViewController"] } }
33.977778
143
0.689993
0a22bf9e9ed0d9f5496077676bcb587fa7a51392
3,620
// The MIT License (MIT) // Copyright © 2020 Ivan Vorobei ([email protected]) // // 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 #if os(iOS) @available(iOSApplicationExtension, unavailable) public class SPPermissionsActionButton: UIButton { var permission: SPPermissions.Permission? public var allowTitle: String = Texts.allow_permission_action public var allowTitleColor: UIColor = UIColor.tint public var allowBackgroundColor: UIColor = UIColor.buttonArea public var allowedTitle: String = Texts.allowed_permission_action public var allowedTitleColor: UIColor = UIColor.white public var allowedBackgroundColor: UIColor = UIColor.tint public var deniedTitle: String = Texts.denied_permission_action public var deniedTitleColor: UIColor = UIColor.tint public var deniedBackgroundColor: UIColor = UIColor.buttonArea // MARK: - Init init() { super.init(frame: .zero) contentEdgeInsets = UIEdgeInsets.init(top: 5, left: 13, bottom: 5, right: 13) titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .bold) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Helpers func updateInterface() { guard let permission = self.permission else { return } switch permission.status { case .notDetermined, .notSupported: setTitle(allowTitle, for: .normal) setTitleColor(allowTitleColor, for: .normal) setTitleColor(allowTitleColor.withAlphaComponent(0.7), for: .highlighted) backgroundColor = allowBackgroundColor case .authorized: setTitle(allowedTitle, for: .normal) backgroundColor = allowedBackgroundColor setTitleColor(allowedTitleColor, for: .normal) setTitleColor(allowedTitleColor.withAlphaComponent(0.7), for: .highlighted) case .denied: setTitle(deniedTitle, for: .normal) backgroundColor = deniedBackgroundColor setTitleColor(deniedTitleColor, for: .normal) setTitleColor(deniedTitleColor.withAlphaComponent(0.7), for: .highlighted) } } // MARK: - Layout override public func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = self.frame.height / 2 } // MARK: - Ovveride override public func setTitle(_ title: String?, for state: UIControl.State) { super.setTitle(title?.uppercased(), for: state) } } #endif
39.347826
87
0.697238
62a35df94c02d29e5a217a9c5e11d305678faf66
16,142
// // AvatarHelper.swift // CDDGroupAvatarSwift // // Created by 陈甸甸 on 2020/3/9. // Copyright © 2020 RocketsChen. All rights reserved. // import UIKit import CommonCrypto struct AvatarHelper<T> { // MARK: - 获取群头像最大数组数量 public static func getTypefMaxCount(_ groupSource: [T], _ groupAvatarType: DCGroupAvatarType) -> [T] { var newSource = [T]() var count: Int switch groupAvatarType { case .WeChat: count = AvatarConfig.DCMaxWeChatCount case .QQ: count = AvatarConfig.DCMaxQQCount case .WeiBo: count = AvatarConfig.DCMaxWeiBoCount } for i in 0..<min(count, groupSource.count) { newSource.append(groupSource[i]) } return newSource } } struct AvatarHelperTool { // MARK: - 计算Type_QQ头像尺寸 public static func calculateSizeQQAvatarGroup(_ groupCount: Int, _ index: Int, _ containerSize: CGSize, _ distance: CGFloat) -> CGSize { var avatarSize: CGSize = CGSize.zero let wholeSize = containerSize if groupCount == DCNumberOfGroupAvatarType.One.description() { avatarSize = wholeSize }else if groupCount == DCNumberOfGroupAvatarType.Two.description() { avatarSize = CGSize(width: (wholeSize.width - distance) / 2, height: wholeSize.height) }else if groupCount == DCNumberOfGroupAvatarType.Three.description() , index == 0 { avatarSize = CGSize(width: (wholeSize.width - distance) / 2, height: wholeSize.height) }else { avatarSize = CGSize(width: (wholeSize.width - distance) / 2, height: (wholeSize.height - distance) / 2) } return avatarSize } // MARK: - 计算Type_WeChat头像尺寸 public static func calculateSizeWeChatAvatarGroup(_ groupCount: Int, _ containerSize: CGSize, _ distance: CGFloat) -> CGSize { var avatarSize: CGSize = CGSize.zero let wholeSize = containerSize if groupCount < DCNumberOfGroupAvatarType.Five.description() { avatarSize = CGSize(width: (wholeSize.width - (3 * distance)) / 2, height: (wholeSize.height - (3 * distance)) / 2) }else { avatarSize = CGSize(width: (wholeSize.width - (4 * distance)) / 3, height: (wholeSize.height - (4 * distance)) / 3) } return avatarSize } // MARK: - 计算TypeWeiBo头像尺寸 public static func calculateRadiusWeiBoAvatarGroup(_ groupCount: Int, _ containerSize: CGSize, _ distance: CGFloat) -> CGFloat { let bigRadius: CGFloat = containerSize.width / 2 var radius: CGFloat = 0 switch groupCount { case DCNumberOfGroupAvatarType.One.description(): radius = bigRadius case DCNumberOfGroupAvatarType.Two.description(): radius = bigRadius / 2 + (distance / 2) case DCNumberOfGroupAvatarType.Three.description(): radius = (2 * sqrt(3) - 3) * bigRadius + (distance / 3) case DCNumberOfGroupAvatarType.Four.description(): radius = bigRadius / 2 - (distance / 2) default: radius = 0 } return radius } // MARK: - 计算Type_WeiBo小头像位置 public static func calculateWeiBoAvatarGroup(_ groupCount: Int, _ index: Int, _ containerSize: CGSize, _ distance: CGFloat) -> CGPoint { var avatarPoint = CGPoint.zero var avatarDiameter: CGFloat = calculateRadiusWeiBoAvatarGroup(groupCount, containerSize, distance) var radiusOffset: CGFloat = 0 let bigRadius: CGFloat = containerSize.width / 2 let shrinkage: CGFloat = groupCount == DCNumberOfGroupAvatarType.Four.description() ? distance : -2 * distance let indexFloat = CGFloat(index) let groupCountFloat = CGFloat(groupCount) let piFloat = CGFloat.pi if (groupCount == DCNumberOfGroupAvatarType.One.description()) { avatarPoint = CGPoint(x: containerSize.width * 0.5, y: containerSize.height * 0.5) } else if (groupCount == DCNumberOfGroupAvatarType.Three.description()) { let difference: CGFloat = (bigRadius - avatarDiameter) if (index == 1) { avatarDiameter = avatarDiameter - shrinkage avatarPoint = CGPoint(x: bigRadius, y: avatarDiameter + distance) }else{ avatarDiameter = avatarDiameter + shrinkage radiusOffset = indexFloat * -0.5 * piFloat let pX: CGFloat = avatarDiameter * CGFloat(cosf(Float(radiusOffset))) avatarPoint = CGPoint(x: bigRadius + pX, y: bigRadius + (difference / 2) + distance) } }else{ avatarDiameter = avatarDiameter + shrinkage radiusOffset = -0.75 * piFloat let content: Float = Float(2 * piFloat * indexFloat / groupCountFloat + radiusOffset) let pX: CGFloat = avatarDiameter * CGFloat(cosf(content)) let pY: CGFloat = avatarDiameter * CGFloat(sinf(content)) avatarPoint = CGPoint(x: bigRadius + pX, y: bigRadius + pY) } return avatarPoint } // MARK: - 计算Type_WeChat/QQ小头像位置 public static func calculatePointAvatarGroup(_ groupCount: Int, _ index: Int, _ containerSize: CGSize, _ distance: CGFloat, _ avatarType: DCGroupAvatarType) -> CGPoint { var avatarPoint = CGPoint.zero let wcSize: CGSize = calculateSizeWeChatAvatarGroup(groupCount, containerSize, distance) let qqSize: CGSize = calculateSizeQQAvatarGroup(groupCount, index, containerSize, distance) let avatarSize: CGSize = (avatarType == .WeChat) ? wcSize : qqSize var currentIndex = index let avaWidth = avatarSize.width let avaHeight = avatarSize.height let currentIndexFloat = CGFloat(currentIndex) var row: CGFloat = 0 var column: CGFloat = 0 let maxWeiChatCount = CGFloat(AvatarConfig.DCMaxWeChatColumn) switch groupCount { case DCNumberOfGroupAvatarType.One.description(): if avatarType == .WeChat { avatarPoint = CGPoint(x: (containerSize.width - avaWidth) * 0.5, y: (containerSize.height - avaHeight) * 0.5) } case DCNumberOfGroupAvatarType.Two.description(): if avatarType == .WeChat { avatarPoint = CGPoint(x: currentIndexFloat * (avaWidth + distance) + distance, y: (containerSize.height - avaHeight) / 2) }else if avatarType == .QQ { avatarPoint = CGPoint(x: currentIndexFloat * (avaWidth + distance), y: 0) } case DCNumberOfGroupAvatarType.Three.description(): if avatarType == .WeChat { if currentIndex == 0 { avatarPoint = CGPoint(x: (containerSize.width - avaWidth) / 2, y: distance) }else { avatarPoint = CGPoint(x: (currentIndexFloat - 1) * (avaWidth + distance) + distance, y: avaHeight + 2 * distance) } }else if avatarType == .QQ { if currentIndex == 0 { avatarPoint = CGPoint(x: 0, y: 0); }else { if currentIndex == 2 { currentIndex = currentIndex + 1 } column = CGFloat(currentIndex / 2) avatarPoint = CGPoint(x: avaWidth + distance, y: column * (avaHeight + distance)) } } case DCNumberOfGroupAvatarType.Four.description(): column = computing(currentIndexFloat, 2).column row = computing(currentIndexFloat, 2).row if avatarType == .WeChat { avatarPoint = CGPoint(x: row * (avaWidth + distance) + distance, y: column * (avaHeight + distance) + distance) }else if avatarType == .QQ { avatarPoint = CGPoint(x: row * (avaWidth + distance), y: column * (avaHeight + distance)) } case DCNumberOfGroupAvatarType.Five.description(): if avatarType == .WeChat { let tempPoint = CGPoint(x: (containerSize.width - distance - (2 * avaWidth)) / 2, y: (containerSize.height - distance - (2 * avaHeight)) / 2) if currentIndex <= 1 { avatarPoint = CGPoint(x: currentIndexFloat * (distance + avaWidth) + tempPoint.x , y: tempPoint.y) }else { avatarPoint = CGPoint(x: (currentIndexFloat - 2) * (avaWidth + distance) + distance, y: tempPoint.y + avaHeight + distance) } } case DCNumberOfGroupAvatarType.Six.description(): let tempPointY: CGFloat = (containerSize.height - distance - (2 * avaHeight)) / 2 if avatarType == .WeChat { column = computing(currentIndexFloat, maxWeiChatCount).column row = computing(currentIndexFloat, maxWeiChatCount).row avatarPoint = CGPoint(x: row * (avaWidth + distance) + distance, y: column * (avaHeight + distance) + tempPointY) } case DCNumberOfGroupAvatarType.Seven.description(): if avatarType == .WeChat { if currentIndex == 0 { avatarPoint = CGPoint(x: (containerSize.width - avaWidth) / 2, y: distance) }else { column = computing(currentIndexFloat + 2, maxWeiChatCount).column row = computing(currentIndexFloat + 2, maxWeiChatCount).row avatarPoint = CGPoint(x: row * (avaWidth + distance) + distance, y: column * (avaHeight + distance) + distance) } } case DCNumberOfGroupAvatarType.Eight.description(): if avatarType == .WeChat { if currentIndex < 2 { let tempPointX = (containerSize.width - 2 * avaWidth - distance) / 2 avatarPoint = CGPoint(x: currentIndexFloat * (avaWidth + distance) + tempPointX, y: distance) }else { column = computing(currentIndexFloat + 1, maxWeiChatCount).column row = computing(currentIndexFloat + 1, maxWeiChatCount).row avatarPoint = CGPoint(x: row * (avaWidth + distance) + distance, y: column * (avaHeight + distance) + distance) } } case DCNumberOfGroupAvatarType.Nine.description(): if avatarType == .WeChat { column = computing(currentIndexFloat, maxWeiChatCount).column row = computing(currentIndexFloat, maxWeiChatCount).row avatarPoint = CGPoint(x: row * (avaWidth + distance) + distance, y: column * (avaHeight + distance) + distance) } default: break } return avatarPoint } } extension AvatarHelperTool { // MARK: - 计算行和列 private static func computing(_ current: CGFloat , _ operation: CGFloat) -> (column: CGFloat, row: CGFloat) { let columnInt = Int(current) / Int(operation) let rowInt = Int(current) % Int(operation) return(column: CGFloat(columnInt), row: CGFloat(rowInt)) } } extension String { public var md5: String? { let str = self.cString(using: String.Encoding.utf8) let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0 ..< digestLen { hash.appendFormat("%02x", result[i]) } free(result) return String(format: hash as String) } } extension UIColor { // MARK: - 颜色转字符串 public var hexString: String? { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 let multiplier = CGFloat(255.999999) guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return nil } if alpha == 1.0 { return String( format: "#%02lX%02lX%02lX", Int(red * multiplier), Int(green * multiplier), Int(blue * multiplier) ) } else { return String( format: "#%02lX%02lX%02lX%02lX", Int(red * multiplier), Int(green * multiplier), Int(blue * multiplier), Int(alpha * multiplier) ) } } } extension UIImage { // MARK: - 裁剪图片 public func cutImageView(_ size: CGSize, _ rect: CGRect) -> UIImage { var clipImage: UIImage = self let scaleWidth: CGFloat = self.size.width / size.width let scaleHeight: CGFloat = self.size.height / size.height let clipRect = CGRect(x: rect.origin.x * scaleWidth, y: rect.origin.y * scaleHeight, width: rect.size.width * scaleWidth, height: rect.size.height * scaleHeight) UIGraphicsBeginImageContext(clipRect.size) clipImage.draw(at: CGPoint(x: -clipRect.origin.x, y: -clipRect.origin.y)) clipImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return clipImage } // MARK: - 画圆 public func cgContextAddArcToPointImage(_ borderWidth: CGFloat, _ borderColor: UIColor) -> UIImage { var avatarImage: UIImage = self let size: CGSize = CGSize(width: avatarImage.size.width + 2 * borderWidth, height: avatarImage.size.height + 2 * borderWidth) UIGraphicsBeginImageContextWithOptions(size, false, 0) var path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: size.width, height: size.height)) borderColor.set() path.fill() path = UIBezierPath(ovalIn: CGRect(x: borderWidth, y: borderWidth, width: avatarImage.size.width, height: avatarImage.size.height)) path.addClip() avatarImage.draw(in: CGRect(x: borderWidth, y: borderWidth, width: avatarImage.size.width, height: avatarImage.size.height)) avatarImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return avatarImage } // MARK: - 返回占位 public func backItemPlaceholderImage(_ placeholder: [UIImage]? = nil, _ groupCount: Int, _ groupIndex: Int) -> UIImage{ var itemPlaceholder = self guard let placeholderArray = placeholder else { return itemPlaceholder } if placeholderArray.count > 0 && placeholderArray.count >= groupCount { let item = placeholderArray[groupIndex] itemPlaceholder = item } return itemPlaceholder } }
38.160757
173
0.551419
e49858e2ee16434a129a4c480d75cbbdb435b107
467
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class B<T where g:a{class n{func a{class C<w{func b{{class c{func e<Tt{b=a
46.7
78
0.743041
e8a44ff81531de81acc4cf1f07697179506811fd
3,525
// 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 RunbookCreateOrUpdatePropertiesData : RunbookCreateOrUpdatePropertiesProtocol { public var logVerbose: Bool? public var logProgress: Bool? public var runbookType: RunbookTypeEnumEnum public var draft: RunbookDraftProtocol? public var publishContentLink: ContentLinkProtocol? public var description: String? public var logActivityTrace: Int32? enum CodingKeys: String, CodingKey {case logVerbose = "logVerbose" case logProgress = "logProgress" case runbookType = "runbookType" case draft = "draft" case publishContentLink = "publishContentLink" case description = "description" case logActivityTrace = "logActivityTrace" } public init(runbookType: RunbookTypeEnumEnum) { self.runbookType = runbookType } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.logVerbose) { self.logVerbose = try container.decode(Bool?.self, forKey: .logVerbose) } if container.contains(.logProgress) { self.logProgress = try container.decode(Bool?.self, forKey: .logProgress) } self.runbookType = try container.decode(RunbookTypeEnumEnum.self, forKey: .runbookType) if container.contains(.draft) { self.draft = try container.decode(RunbookDraftData?.self, forKey: .draft) } if container.contains(.publishContentLink) { self.publishContentLink = try container.decode(ContentLinkData?.self, forKey: .publishContentLink) } if container.contains(.description) { self.description = try container.decode(String?.self, forKey: .description) } if container.contains(.logActivityTrace) { self.logActivityTrace = try container.decode(Int32?.self, forKey: .logActivityTrace) } 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.logVerbose != nil {try container.encode(self.logVerbose, forKey: .logVerbose)} if self.logProgress != nil {try container.encode(self.logProgress, forKey: .logProgress)} try container.encode(self.runbookType, forKey: .runbookType) if self.draft != nil {try container.encode(self.draft as! RunbookDraftData?, forKey: .draft)} if self.publishContentLink != nil {try container.encode(self.publishContentLink as! ContentLinkData?, forKey: .publishContentLink)} if self.description != nil {try container.encode(self.description, forKey: .description)} if self.logActivityTrace != nil {try container.encode(self.logActivityTrace, forKey: .logActivityTrace)} } } extension DataFactory { public static func createRunbookCreateOrUpdatePropertiesProtocol(runbookType: RunbookTypeEnumEnum) -> RunbookCreateOrUpdatePropertiesProtocol { return RunbookCreateOrUpdatePropertiesData(runbookType: runbookType) } }
47
146
0.721986
e2b48a54e84517887c1a029e27cff4314bc9ed51
1,385
// // AmuseViewController.swift // DouYuZB // // Created by HCL黄 on 2016/12/21. // Copyright © 2016年 HCL黄. All rights reserved. // import UIKit private let kMenuViewH : CGFloat = 200 class AmuseViewController: BaseAnchorViewController { fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel() fileprivate lazy var menuView : AmuseMenuView = { let menuView = AmuseMenuView.amuseMenuView() menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH) return menuView; }() override func viewDidLoad() { super.viewDidLoad() } } // MARK:- 设置UI界面 extension AmuseViewController { override func setupUI() { super.setupUI() // 将菜单的view添加到collectionView中 collectionView.addSubview(menuView) collectionView.contentInset = UIEdgeInsetsMake(kMenuViewH, 0, 0, 0) } } // MARK:- 请求数据 extension AmuseViewController { override func loadData(){ // 1.给父类中ViewModel进行赋值 baseVM = amuseVM // 2. 请求数据 amuseVM.loadAmuseData { self.collectionView.reloadData() var tempGroups = self.amuseVM.anchorGroups tempGroups.removeFirst() self.menuView.groups = tempGroups self.loadDataFinshed() } } }
21.984127
90
0.611552
d7343c0a3ba84f0d042efa46fcf1314c843181a0
1,344
// // Minute.swift // Adhan // // Copyright © 2018 Batoul Apps. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public typealias Minute = Int internal extension Minute { var timeInterval: TimeInterval { return TimeInterval(self * 60) } }
38.4
81
0.741071
ff79b7feb87621af30147604040e96ccaa1ce5a9
6,427
// // Router.swift // EurosportPlayer // // Created by Alexander Edge on 14/05/2016. import Foundation import CoreData public protocol URLRequestConvertible { var request: URLRequest { get } } struct Router { fileprivate static func standardRequest(_ url: URL) -> URLRequest { var req = URLRequest(url: url) req.setValue("EurosportPlayer PROD/5.2.2 (iPad; iOS 10.2; Scale/2.00)", forHTTPHeaderField: "User-Agent") return req } enum User: URLRequestConvertible { case login(email: String, password: String) fileprivate var baseURL: URL { return URL(string : "https://crm-partners.eurosportplayer.com/")! } var path: String { return "JsonPlayerCrmApi.svc/login" } var request: URLRequest { switch self { case .login(let email, let password): var params = [String: String]() let contextData = try! JSONSerialization.data(withJSONObject: ["g": "GB", "p": 9, "l": "EN", "d": 2, "mn": "iPad", "v": "5.2.2", "tt": "Pad", "li": 2, "s": 1, "b": 7], options: []) params["context"] = String(data: contextData, encoding: .utf8) let identifier = UIDevice.current.identifierForVendor!.uuidString let data = try! JSONSerialization.data(withJSONObject: ["email": email, "password": password, "udid": identifier], options: []) params["data"] = String(data: data, encoding: .utf8) var URLComponents = Foundation.URLComponents(url: URL(string: path, relativeTo: baseURL)!, resolvingAgainstBaseURL: true)! URLComponents.queryItems = params.map({URLQueryItem(name: $0, value: $1)}) let url = URLComponents.url! return Router.standardRequest(url) } } } enum AuthToken: URLRequestConvertible { case fetch(userId: String, hkey: String) fileprivate var baseURL: URL { return URL(string : "https://videoshop-partners.eurosportplayer.com/")! } var path: String { return "JsonProductService.svc/GetToken" } var request: URLRequest { switch self { case .fetch(let userId, let hkey): var params = [String: String]() let contextData = try! JSONSerialization.data(withJSONObject: ["g": "GB", "d": 2], options: []) params["context"] = String(data: contextData, encoding: String.Encoding.utf8) let data = try! JSONSerialization.data(withJSONObject: ["userid": userId, "hkey": hkey], options: []) params["data"] = String(data: data, encoding: String.Encoding.utf8) var URLComponents = Foundation.URLComponents(url: URL(string: path, relativeTo: baseURL)!, resolvingAgainstBaseURL: true)! URLComponents.queryItems = params.map({URLQueryItem(name: $0, value: $1)}) let url = URLComponents.url! return Router.standardRequest(url) } } } fileprivate enum Language: String { case German = "de" case English = "en" case French = "fr" fileprivate var identifier: Int { switch self { case .German: return 1 case .English: return 2 case .French: return 3 } } static var preferredLanguage: Language { guard let preferredLanguage = Locale.preferredLanguages.first, let language = Language(rawValue: preferredLanguage) else { return .English } return language } } enum Catchup: URLRequestConvertible { case fetch fileprivate var baseURL: URL { return URL(string : "https://videoshop-partners.eurosportplayer.com/")! } var path: String { return "JsonProductService.svc/GetAllCatchupCache" } var request: URLRequest { switch self { case .fetch: var params = [String: String]() let contextData = try! JSONSerialization.data(withJSONObject: ["g": "GB", "d": 2], options: []) params["context"] = String(data: contextData, encoding: .utf8) let data = try! JSONSerialization.data(withJSONObject: ["languageid": Language.preferredLanguage.identifier], options: []) params["data"] = String(data: data, encoding: String.Encoding.utf8) var URLComponents = Foundation.URLComponents(url: URL(string: path, relativeTo: baseURL)!, resolvingAgainstBaseURL: true)! URLComponents.queryItems = params.map({URLQueryItem(name: $0, value: $1)}) let url = URLComponents.url! return Router.standardRequest(url) } } } enum Channel: URLRequestConvertible { case fetch fileprivate var baseURL: URL { return URL(string : "https://videoshop-partners.eurosportplayer.com/")! } var path: String { return "JsonProductService.svc/GetAllChannelsCache" } var request: URLRequest { switch self { case .fetch: var params = [String: String]() let contextData = try! JSONSerialization.data(withJSONObject: ["g": "GB", "d": 2], options: []) params["context"] = String(data: contextData, encoding: .utf8) let data = try! JSONSerialization.data(withJSONObject: ["languageid": Language.preferredLanguage.identifier, "isfullaccess": 0, "withouttvscheduleliveevents": "true", "groupchannels": "true", "pictureformatids": "[87]", "isbroadcasted": 1], options: []) params["data"] = String(data: data, encoding: .utf8) var URLComponents = Foundation.URLComponents(url: URL(string: path, relativeTo: baseURL)!, resolvingAgainstBaseURL: true)! URLComponents.queryItems = params.map({URLQueryItem(name: $0, value: $1)}) let url = URLComponents.url! return Router.standardRequest(url) } } } }
32.790816
196
0.564182
b94cb0d0be0d3be32d4d5f55828068420ca5921f
1,345
// // Copyright (c) 2018 KxCoding <[email protected]> // // 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. // //: [Previous](@previous) import Foundation /*: ## forEach */ // 함수형 페러다임응로 실행할때 자주 사용된다고 한다. let array = [1,2,3] array.forEach { (num) in print(num) } // for in 반복문과 같은 결과를 내게 함
29.888889
81
0.726394
79db961f2231b32e00c20995d711569446b0dc13
997
/* This source file is part of the Swift.org open source project Copyright (c) 2021 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 Swift project authors */ extension SymbolGraph { /** The operating system intended for a ``Module-swift.struct``'s deployment. */ public struct OperatingSystem: Codable { /** The name of the operating system, such as `macOS` or `Linux`. */ public var name: String /** The intended minimum version of the operating system. If no specific version is required, this may be undefined. */ public var minimumVersion: SemanticVersion? public init(name: String, minimumVersion: SemanticVersion? = nil) { self.name = name self.minimumVersion = minimumVersion } } }
30.212121
85
0.656971
20718a2620e824c430708c94a350588fde604922
1,353
// // AppDelegate.swift // 04_Scene-MultiUnwind // // Created by 한상혁 on 2021/10/14. // import UIKit @main 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. } }
36.567568
179
0.746489
184869cee7a385b427da5de905e30b767e183de4
715
// // ViewController.swift // NLSwiftSuger // // Created by NealWills on 08/29/2021. // Copyright (c) 2021 NealWills. All rights reserved. // import UIKit import SnapKit import NLSwiftSuger class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let btn = UIButton.newItem() .nl .set(superView: self.view) .set(frame: CGRect.init(x: 100, y: 150, width: 50, height: 50)) .set(backgroundColor: UIColor.red) .item() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
21.029412
75
0.605594
2f4c0f99230c77c597695f6d01305e0473eed428
5,742
/* Copyright (c) 2019, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreData import Foundation class OCKCDVersionedObject: OCKCDObject, OCKCDManageable { @NSManaged var id: String @NSManaged var previous: OCKCDVersionedObject? @NSManaged var allowsMissingRelationships: Bool @NSManaged var effectiveDate: Date @NSManaged var deletedDate: Date? @NSManaged private(set) weak var next: OCKCDVersionedObject? var nextVersionID: OCKLocalVersionID? { return next?.localDatabaseID } var previousVersionID: OCKLocalVersionID? { return previous?.localDatabaseID } func validateRelationships() throws { } static var defaultSortDescriptors: [NSSortDescriptor] { return [NSSortDescriptor(keyPath: \OCKCDVersionedObject.effectiveDate, ascending: false)] } static func fetchHeads<T: OCKCDVersionedObject>(ids: [String], in context: NSManagedObjectContext) -> [T] { return fetchFromStore(in: context, where: headerPredicate(for: ids)) { request in request.fetchLimit = ids.count request.returnsObjectsAsFaults = false }.compactMap { $0 as? T } } static var notDeletedPredicate: NSPredicate { NSPredicate(format: "%K == nil", #keyPath(OCKCDVersionedObject.deletedDate)) } static func headerPredicate(for ids: [String]) -> NSPredicate { return NSCompoundPredicate(andPredicateWithSubpredicates: [ NSPredicate(format: "%K IN %@", #keyPath(OCKCDVersionedObject.id), ids), headerPredicate() ]) } static func headerPredicate() -> NSPredicate { return NSCompoundPredicate(andPredicateWithSubpredicates: [ notDeletedPredicate, NSPredicate(format: "%K == nil", #keyPath(OCKCDVersionedObject.next)) ]) } static func newestVersionPredicate(in interval: DateInterval) -> NSPredicate { let startsBeforeEndOfQuery = NSPredicate(format: "%K < %@", #keyPath(OCKCDVersionedObject.effectiveDate), interval.end as NSDate) let noNextVersion = NSPredicate(format: "%K == nil OR %K.effectiveDate >= %@", #keyPath(OCKCDVersionedObject.next), #keyPath(OCKCDVersionedObject.next), interval.end as NSDate) return NSCompoundPredicate(andPredicateWithSubpredicates: [ startsBeforeEndOfQuery, noNextVersion ]) } static func validateNewIDs(_ ids: [String], in context: NSManagedObjectContext) throws { guard Set(ids).count == ids.count else { throw OCKStoreError.invalidValue(reason: "Identifiers contains duplicate values! [\(ids)]") } let existingPredicate = NSPredicate(format: "%K IN %@", #keyPath(OCKCDVersionedObject.id), ids) let existingIDs = fetchFromStore(in: context, where: existingPredicate, configureFetchRequest: { request in request.propertiesToFetch = [#keyPath(OCKCDVersionedObject.id)] }).map { $0.id } guard existingIDs.isEmpty else { let objectClass = String(describing: type(of: self)) throw OCKStoreError.invalidValue(reason: "\(objectClass) with IDs [\(Set(existingIDs))] already exists!") } } static func validateUpdateIdentifiers(_ ids: [String], in context: NSManagedObjectContext) throws { guard Set(ids).count == ids.count else { throw OCKStoreError.invalidValue(reason: "Identifiers contains duplicate values! [\(ids)]") } } override func validateForInsert() throws { try super.validateForInsert() try validateRelationships() } override func validateForUpdate() throws { try super.validateForUpdate() try validateRelationships() } func copyVersionInfo(from other: OCKVersionedObjectCompatible) { id = other.id deletedDate = other.deletedDate effectiveDate = other.effectiveDate copyValues(from: other) } }
41.912409
117
0.686172
bfb7f01c54667d8ecd62948f31636b1f58666c10
4,467
// // Core+RemoveTorrent.swift // iTorrent // // Created by Daniil Vinogradov on 03.04.2020. // Copyright © 2020  XITRIX. All rights reserved. // import UIKit extension Core { func removeTorrentsUI(hashes: [String], sender: Any, direction: UIPopoverArrowDirection = .any, completionAction: (()->())? = nil) { let torrents = hashes.compactMap({Core.shared.torrents[$0]}) var title: String? var message: String? let isMagnet = torrents.count == 1 && !torrents[0].hasMetadata if isMagnet { title = nil message = Localize.get("Are you sure to remove this magnet torrent?") } else { title = "\(Localize.get("Are you sure to remove"))" title! += torrents.count > 1 ? " \(torrents.count) \(Localize.get("torrents"))?" : "?" message = torrents.map({$0.title}).joined(separator: "\n") } let removeController = ThemedUIAlertController(title: title, message: message, preferredStyle: .actionSheet) let removeAll = UIAlertAction(title: NSLocalizedString("Yes and remove data", comment: ""), style: .destructive) { _ in for torrent in torrents { self.removeTorrent(hash: torrent.hash, removeData: true, notify: false) } completionAction?() NotificationCenter.default.post(name: .torrentRemoved, object: torrents.map({$0.hash})) } let removeTorrent = UIAlertAction(title: NSLocalizedString("Yes but keep data", comment: ""), style: .default) { _ in for torrent in torrents { self.removeTorrent(hash: torrent.hash, removeData: false, notify: false) } completionAction?() NotificationCenter.default.post(name: .torrentRemoved, object: torrents.map({$0.hash})) } let removeMagnet = UIAlertAction(title: NSLocalizedString("Remove", comment: ""), style: .destructive) { _ in self.removeTorrent(hash: torrents[0].hash, removeData: false, notify: false) completionAction?() } let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel) if isMagnet { removeController.addAction(removeMagnet) } else { removeController.addAction(removeAll) removeController.addAction(removeTorrent) } removeController.addAction(cancel) if removeController.popoverPresentationController != nil { if let bb = sender as? UIBarButtonItem { removeController.popoverPresentationController?.barButtonItem = bb } else if let view = sender as? UIView { removeController.popoverPresentationController?.sourceView = view removeController.popoverPresentationController?.sourceRect = view.bounds } removeController.popoverPresentationController?.permittedArrowDirections = direction } Utils.topViewController?.present(removeController, animated: true) } func removeTorrent(hash: String, removeData: Bool = false, notify: Bool = true) { guard let torrent = torrents[hash] else { return } TorrentSdk.removeTorrent(hash: torrent.hash, withFiles: removeData) if torrent.hasMetadata { removeTorrentFile(hash: torrent.hash) if removeData { do { try FileManager.default.removeItem(atPath: Core.rootFolder + "/" + torrent.title) } catch { print("MainController: removeTorrent()") print(error.localizedDescription) } } } torrents[hash] = nil if notify { NotificationCenter.default.post(name: .torrentRemoved, object: [hash]) } } private func removeTorrentFile(hash: String) { let files = try? FileManager.default.contentsOfDirectory(atPath: Core.configFolder).filter { $0.hasSuffix(".torrent") } for file in files ?? [] { if hash == TorrentSdk.getTorrentFileHash(torrentPath: Core.configFolder + "/" + file) { try? FileManager.default.removeItem(atPath: Core.configFolder + "/" + file) break } } } }
41.747664
136
0.591225
ffc0e89685189deb7c4398e9cf61b696d4372a63
238
// // EmptyParser.swift // Pods-RTFView_Example // // Created by Marco Seidel on 07.05.20. // import Foundation struct SimpleParser: RTFParser { func parse(input: String) -> [Token] { [Token(text: input, tags: [])] } }
15.866667
75
0.62605
5b7c3960307a4a9a5929dc3e159e56e258dcee1e
3,467
// // Operators.swift // RxExample // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // // swiftlint:disable identifier_name // swiftlint:disable orphaned_doc_comment // swiftlint:disable line_length import RxSwift import RxCocoa import UIKit // Two way binding operator between control property and variable, that's all it takes { infix operator <-> : DefaultPrecedence public func nonMarkedText(_ textInput: UITextInput) -> String? { let start = textInput.beginningOfDocument let end = textInput.endOfDocument guard let rangeAll = textInput.textRange(from: start, to: end), let text = textInput.text(in: rangeAll) else { return nil } guard let markedTextRange = textInput.markedTextRange else { return text } guard let startRange = textInput.textRange(from: start, to: markedTextRange.start), let endRange = textInput.textRange(from: markedTextRange.end, to: end) else { return text } return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "") } public func <-> <Base>(textInput: TextInput<Base>, variable: BehaviorRelay<String>) -> Disposable { let bindToUIDisposable = variable.asObservable() .bind(to: textInput.text) let bindToVariable = textInput.text .subscribe(onNext: { [weak base = textInput.base] _ in guard let base = base else { return } let nonMarkedTextValue = nonMarkedText(base) /** In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know. The can be reproed easily if replace bottom code with if nonMarkedTextValue != variable.value { variable.value = nonMarkedTextValue ?? "" } and you hit "Done" button on keyboard. */ if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value { variable.accept(nonMarkedTextValue) } }, onCompleted: { bindToUIDisposable.dispose() }) return Disposables.create(bindToUIDisposable, bindToVariable) } public func <-> <T>(property: ControlProperty<T>, variable: BehaviorRelay<T>) -> Disposable { if T.self == String.self { #if DEBUG fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx.text` property directly to variable.\n" + "That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" + "REMEDY: Just use `textField <-> variable` instead of `textField.rx.text <-> variable`.\n" + "Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n" ) #endif } let bindToUIDisposable = variable.asObservable() .bind(to: property) let bindToVariable = property .subscribe(onNext: { n in variable.accept(n) }, onCompleted: { bindToUIDisposable.dispose() }) return Disposables.create(bindToUIDisposable, bindToVariable) }
36.494737
207
0.652149
ccbe0c474525ceca2e7c55b566436552736255ad
1,499
// // SimpleToastModifier.swift // // // Created by Martin Albrecht on 17.08.20. // Copyright © 2020 Martin Albrecht. All rights reserved. // // Licensed under Apache License v2.0 // import SwiftUI public enum SimpleToastModifierType { case fade, slide } protocol SimpleToastModifier: ViewModifier { var showToast: Bool { get set } var options: SimpleToastOptions? { get set } } public struct SimpleToastSlide: SimpleToastModifier { @Binding var showToast: Bool var options: SimpleToastOptions? private var transitionEdge: Edge { if let pos = options?.alignment ?? nil { switch pos { case .top, .topLeading, .topTrailing: return .top case .bottom, .bottomLeading, .bottom: return .bottom default: return .top } } return .top } public func body(content: Content) -> some View { return content .transition(AnyTransition.move(edge: transitionEdge).combined(with: .opacity)) .animation(options?.animation ?? .default) .zIndex(1) } } public struct SimpleToastFade: SimpleToastModifier { @Binding var showToast: Bool var options: SimpleToastOptions? public func body(content: Content) -> some View { content .transition(AnyTransition.opacity.animation(options?.animation ?? .linear)) .opacity(showToast ? 1 : 0) } }
23.061538
90
0.612408
fefdd813f6f886526a0208772bc0ea1dc6c9da2b
1,248
// // PrimerAppUITests.swift // PrimerAppUITests // // Created by d182_raul_j on 16/02/18. // Copyright © 2018 d182_raul_j. All rights reserved. // import XCTest class PrimerAppUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.72973
182
0.665064
1a9c36bdd711e2461c9ef7933934ce2779c4aeab
696
// // MovieListScreen.swift // MoviesApp // // Created by Mohammad Azam on 7/31/20. // Copyright © 2020 Mohammad Azam. All rights reserved. // import SwiftUI struct MovieListScreen: View { @ObservedObject private var movieListVM: MovieListViewModel init() { self.movieListVM = MovieListViewModel() self.movieListVM.searchByName("batman") } var body: some View { VStack { MovieListView(movies: self.movieListVM.movies) .navigationBarTitle("Movies") }.embedNavigationView() } } struct MovieListScreen_Previews: PreviewProvider { static var previews: some View { MovieListScreen() } }
21.090909
63
0.645115
1e3900a8fd1c32d5a0e32278d6cc125c10609561
763
import UIKit import XCTest import mapCounterIos class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.433333
111
0.606815
16409506d0823e47d5d2ec8ab11700bc1b2f5b03
681
// // CalculateGameScore // kata-bowling // // Created by Ondrej Fabian on 01/10/2015. // Copyright © 2015 Ondrej Fabian. All rights reserved. // class CalculateGameScore { let parser: RollsParser init(rollsParser: RollsParser) { parser = rollsParser } func calculateScore(game: Game) -> Int { var score = 0 for (idx, frame) in game.frames.enumerate() { if (idx == Constant.LastFrame) { frame.scoringStrategy = LastFrameScoreCalculationStrategy() } score += frame.getScore(Array(game.frames.suffixFrom(idx+1))) } return score } }
21.967742
75
0.574156
2128e744f565e4517dc3dac4cbc34f60ea76a2e8
546
import UIKit class Dog { var name = "" private var whatADogSays = "woof" func bark() { print(self.whatADogSays) } func nameCat(cat:Cat) { cat.secretName = "Lazybones" // legal: same file let k = Kangaroo() _ = k } func nameCat2(cat:Cat2) { // cat.secretName = "Lazybones" // illegal: different file } } class Cat { fileprivate var secretName : String? private(set) var color : UIColor? fileprivate(set) var length : Double? } private class Kangaroo { }
18.827586
66
0.586081
298fb862cc6315b0e2baeab21b7646002930ac5b
667
// // OnboardingViewController.swift // MC2-Group15 // // Created by Baskoro Indrayana on 05/27/20. // Copyright © 2020 Angela Fanuela. All rights reserved. // import UIKit class OnboardingViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. validateUserDefaults() } // add action // validate from User Defaults, redirect to Helper Login Page func validateUserDefaults(){ let usertype = UserDefaults.standard.string(forKey: "userType") print("Previously Logged In as : \(usertype)") } }
20.84375
71
0.652174
75c7099fd475ecefe31443083138a7e47f94b6e9
27,887
// // ABSteppedProgressBar.swift // ABSteppedProgressBar // // Created by Antonin Biret on 17/02/15. // Copyright (c) 2015 Antonin Biret. All rights reserved. // import UIKit import Foundation import CoreGraphics @objc public protocol FlexibleSteppedProgressBarDelegate { @objc optional func progressBar(_ progressBar: FlexibleSteppedProgressBar, willSelectItemAtIndex index: Int) @objc optional func progressBar(_ progressBar: FlexibleSteppedProgressBar, didSelectItemAtIndex index: Int) @objc optional func progressBar(_ progressBar: FlexibleSteppedProgressBar, canSelectItemAtIndex index: Int) -> Bool @objc optional func progressBar(_ progressBar: FlexibleSteppedProgressBar, textAtIndex index: Int, position: FlexibleSteppedProgressBarTextLocation) -> String } @IBDesignable open class FlexibleSteppedProgressBar: UIView { //MARK: - Public properties /// The number of displayed points in the component @IBInspectable open var numberOfPoints: Int = 3 { didSet { self.setNeedsDisplay() } } /// The current selected index open var currentIndex: Int = 0 { willSet(newValue){ if let delegate = self.delegate { delegate.progressBar?(self, willSelectItemAtIndex: newValue) } } didSet { // animationRendering = true self.setNeedsDisplay() } } open var completedTillIndex: Int = -1 { willSet(newValue){ } didSet { self.setNeedsDisplay() } } open var currentSelectedCenterColor: UIColor = UIColor.black open var currentSelectedTextColor: UIColor! open var viewBackgroundColor: UIColor = UIColor.white open var selectedOuterCircleStrokeColor: UIColor! open var lastStateOuterCircleStrokeColor: UIColor! open var lastStateCenterColor: UIColor! open var centerLayerTextColor: UIColor! open var centerLayerDarkBackgroundTextColor: UIColor = UIColor.white open var useLastState: Bool = false { didSet { if useLastState { self.layer.addSublayer(self.clearLastStateLayer) self.layer.addSublayer(self.lastStateLayer) self.layer.addSublayer(self.lastStateCenterLayer) } self.setNeedsDisplay() } } /// The line height between points @IBInspectable open var lineHeight: CGFloat = 0.0 { didSet { self.setNeedsDisplay() } } open var selectedOuterCircleLineWidth: CGFloat = 3.0 { didSet { self.setNeedsDisplay() } } open var lastStateOuterCircleLineWidth: CGFloat = 5.0 { didSet { self.setNeedsDisplay() } } open var textDistance: CGFloat = 20.0 { didSet { self.setNeedsDisplay() } } fileprivate var _lineHeight: CGFloat { get { if(lineHeight == 0.0 || lineHeight > self.bounds.height) { return self.bounds.height * 0.4 } return lineHeight } } /// The point's radius @IBInspectable open var radius: CGFloat = 0.0 { didSet { self.setNeedsDisplay() } } fileprivate var _radius: CGFloat { get{ if(radius == 0.0 || radius > self.bounds.height / 2.0) { return self.bounds.height / 2.0 } return radius } } /// The progress points's raduis @IBInspectable open var progressRadius: CGFloat = 0.0 { didSet { maskLayer.cornerRadius = progressRadius self.setNeedsDisplay() } } fileprivate var _progressRadius: CGFloat { get { if(progressRadius == 0.0 || progressRadius > self.bounds.height / 2.0) { return self.bounds.height / 2.0 } return progressRadius } } /// The progress line height between points @IBInspectable open var progressLineHeight: CGFloat = 0.0 { didSet { self.setNeedsDisplay() } } fileprivate var _progressLineHeight: CGFloat { get { if(progressLineHeight == 0.0 || progressLineHeight > _lineHeight) { return _lineHeight } return progressLineHeight } } /// The selection animation duration @IBInspectable open var stepAnimationDuration: CFTimeInterval = 0.4 /// True if some text should be rendered in the step points. The text value is provided by the delegate @IBInspectable open var displayStepText: Bool = true { didSet { self.setNeedsDisplay() } } /// The text font in the step points open var stepTextFont: UIFont? { didSet { self.setNeedsDisplay() } } /// The text color in the step points open var stepTextColor: UIColor? { didSet { self.setNeedsDisplay() } } /// The component's background color @IBInspectable open var backgroundShapeColor: UIColor = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 0.8) { didSet { self.setNeedsDisplay() } } /// The component selected background color @IBInspectable open var selectedBackgoundColor: UIColor = UIColor(red: 251.0/255.0, green: 167.0/255.0, blue: 51.0/255.0, alpha: 1.0) { didSet { self.setNeedsDisplay() } } /// The component's delegate open weak var delegate: FlexibleSteppedProgressBarDelegate? //MARK: - Private properties fileprivate var backgroundLayer = CAShapeLayer() fileprivate var progressLayer = CAShapeLayer() fileprivate var selectionLayer = CAShapeLayer() fileprivate var clearSelectionLayer = CAShapeLayer() fileprivate var clearLastStateLayer = CAShapeLayer() fileprivate var lastStateLayer = CAShapeLayer() fileprivate var lastStateCenterLayer = CAShapeLayer() fileprivate var selectionCenterLayer = CAShapeLayer() fileprivate var roadToSelectionLayer = CAShapeLayer() fileprivate var clearCentersLayer = CAShapeLayer() fileprivate var maskLayer = CAShapeLayer() fileprivate var centerPoints = [CGPoint]() fileprivate var _textLayers = [Int:CATextLayer]() fileprivate var _topTextLayers = [Int:CATextLayer]() fileprivate var _bottomTextLayers = [Int:CATextLayer]() fileprivate var previousIndex: Int = 0 fileprivate var animationRendering = false //MARK: - Life cycle public override init(frame: CGRect) { super.init(frame: frame) self.commonInit() self.backgroundColor = UIColor.clear } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } convenience init() { self.init(frame:CGRect.zero) } func commonInit() { if currentSelectedTextColor == nil { currentSelectedTextColor = selectedBackgoundColor } if lastStateCenterColor == nil { lastStateCenterColor = backgroundShapeColor } if stepTextColor == nil { stepTextColor = UIColor.black } if selectedOuterCircleStrokeColor == nil { selectedOuterCircleStrokeColor = selectedBackgoundColor } if lastStateOuterCircleStrokeColor == nil { lastStateOuterCircleStrokeColor = selectedBackgoundColor } if stepTextFont == nil { stepTextFont = UIFont(name: "HelveticaNeue-Medium", size: 14.0) } if centerLayerTextColor == nil { centerLayerTextColor = stepTextColor } let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(FlexibleSteppedProgressBar.gestureAction(_:))) let swipeGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(FlexibleSteppedProgressBar.gestureAction(_:))) self.addGestureRecognizer(tapGestureRecognizer) self.addGestureRecognizer(swipeGestureRecognizer) self.layer.addSublayer(self.clearCentersLayer) self.layer.addSublayer(self.backgroundLayer) self.layer.addSublayer(self.progressLayer) self.layer.addSublayer(self.clearSelectionLayer) self.layer.addSublayer(self.selectionCenterLayer) self.layer.addSublayer(self.selectionLayer) self.layer.addSublayer(self.roadToSelectionLayer) self.progressLayer.mask = self.maskLayer self.contentMode = UIView.ContentMode.redraw } override open func draw(_ rect: CGRect) { super.draw(rect) if !useLastState { completedTillIndex = currentIndex } self.centerPoints.removeAll() let largerRadius = fmax(_radius, _progressRadius) let distanceBetweenCircles = (self.bounds.width - (CGFloat(numberOfPoints) * 2 * largerRadius)) / CGFloat(numberOfPoints - 1) var xCursor: CGFloat = largerRadius for _ in 0...(numberOfPoints - 1) { centerPoints.append(CGPoint(x: xCursor, y: bounds.height / 2)) xCursor += 2 * largerRadius + distanceBetweenCircles } let largerLineWidth = fmax(selectedOuterCircleLineWidth, lastStateOuterCircleLineWidth) if(!animationRendering) { let clearCentersPath = self._shapePath(self.centerPoints, aRadius: largerRadius + largerLineWidth, aLineHeight: _lineHeight) clearCentersLayer.path = clearCentersPath.cgPath clearCentersLayer.fillColor = viewBackgroundColor.cgColor let bgPath = self._shapePath(self.centerPoints, aRadius: _radius, aLineHeight: _lineHeight) backgroundLayer.path = bgPath.cgPath backgroundLayer.fillColor = backgroundShapeColor.cgColor let progressPath = self._shapePath(self.centerPoints, aRadius: _progressRadius, aLineHeight: _progressLineHeight) progressLayer.path = progressPath.cgPath progressLayer.fillColor = selectedBackgoundColor.cgColor let clearSelectedRadius = fmax(_progressRadius, _progressRadius + selectedOuterCircleLineWidth) let clearSelectedPath = self._shapePathForSelected(self.centerPoints[currentIndex], aRadius: clearSelectedRadius) clearSelectionLayer.path = clearSelectedPath.cgPath clearSelectionLayer.fillColor = viewBackgroundColor.cgColor let selectedPath = self._shapePathForSelected(self.centerPoints[currentIndex], aRadius: _radius) selectionLayer.path = selectedPath.cgPath selectionLayer.fillColor = currentSelectedCenterColor.cgColor if !useLastState { let selectedPathCenter = self._shapePathForSelectedPathCenter(self.centerPoints[currentIndex], aRadius: _progressRadius) selectionCenterLayer.path = selectedPathCenter.cgPath selectionCenterLayer.strokeColor = selectedOuterCircleStrokeColor.cgColor selectionCenterLayer.fillColor = UIColor.clear.cgColor selectionCenterLayer.lineWidth = selectedOuterCircleLineWidth selectionCenterLayer.strokeEnd = 1.0 } else { let selectedPathCenter = self._shapePathForSelectedPathCenter(self.centerPoints[currentIndex], aRadius: _progressRadius + selectedOuterCircleLineWidth) selectionCenterLayer.path = selectedPathCenter.cgPath selectionCenterLayer.strokeColor = selectedOuterCircleStrokeColor.cgColor selectionCenterLayer.fillColor = UIColor.clear.cgColor selectionCenterLayer.lineWidth = selectedOuterCircleLineWidth if completedTillIndex >= 0 { let lastStateLayerPath = self._shapePathForLastState(self.centerPoints[completedTillIndex]) lastStateLayer.path = lastStateLayerPath.cgPath lastStateLayer.strokeColor = lastStateOuterCircleStrokeColor.cgColor lastStateLayer.fillColor = viewBackgroundColor.cgColor lastStateLayer.lineWidth = lastStateOuterCircleLineWidth let lastStateCenterLayerPath = self._shapePathForSelected(self.centerPoints[completedTillIndex], aRadius: _radius) lastStateCenterLayer.path = lastStateCenterLayerPath.cgPath lastStateCenterLayer.fillColor = lastStateCenterColor.cgColor } if currentIndex > 0 { let lastPoint = centerPoints[currentIndex-1] let centerCurrent = centerPoints[currentIndex] let xCursor = centerCurrent.x - progressRadius - _radius let routeToSelectedPath = UIBezierPath() routeToSelectedPath.move(to: CGPoint(x: lastPoint.x + progressRadius + selectedOuterCircleLineWidth, y: lastPoint.y)) routeToSelectedPath.addLine(to: CGPoint(x: xCursor, y: centerCurrent.y)) roadToSelectionLayer.path = routeToSelectedPath.cgPath roadToSelectionLayer.strokeColor = selectedBackgoundColor.cgColor roadToSelectionLayer.lineWidth = progressLineHeight } } } self.renderTopTextIndexes() self.renderBottomTextIndexes() self.renderTextIndexes() let progressCenterPoints = Array<CGPoint>(centerPoints[0..<(completedTillIndex+1)]) if let currentProgressCenterPoint = progressCenterPoints.last { let maskPath = self._maskPath(currentProgressCenterPoint) maskLayer.path = maskPath.cgPath CATransaction.begin() let progressAnimation = CABasicAnimation(keyPath: "path") progressAnimation.duration = stepAnimationDuration * CFTimeInterval(abs(completedTillIndex - previousIndex)) progressAnimation.toValue = maskPath progressAnimation.isRemovedOnCompletion = false progressAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) CATransaction.setCompletionBlock { () -> Void in if(self.animationRendering) { if let delegate = self.delegate { delegate.progressBar?(self, didSelectItemAtIndex: self.currentIndex) } self.animationRendering = false } } maskLayer.add(progressAnimation, forKey: "progressAnimation") CATransaction.commit() } self.previousIndex = self.currentIndex } /** Render the text indexes */ fileprivate func renderTextIndexes() { for i in 0...(numberOfPoints - 1) { let centerPoint = centerPoints[i] let textLayer = self._textLayer(atIndex: i) let textLayerFont = UIFont.boldSystemFont(ofSize: 15) textLayer.contentsScale = UIScreen.main.scale textLayer.font = CTFontCreateWithName(textLayerFont.fontName as CFString, textLayerFont.pointSize, nil) textLayer.fontSize = textLayerFont.pointSize if i == currentIndex || i == completedTillIndex { textLayer.foregroundColor = centerLayerDarkBackgroundTextColor.cgColor } else { textLayer.foregroundColor = centerLayerTextColor?.cgColor } if let text = self.delegate?.progressBar?(self, textAtIndex: i, position: FlexibleSteppedProgressBarTextLocation.center) { textLayer.string = text } else { textLayer.string = "\(i)" } textLayer.sizeWidthToFit() textLayer.frame = CGRect(x: centerPoint.x - textLayer.bounds.width/2, y: centerPoint.y - textLayer.bounds.height/2, width: textLayer.bounds.width, height: textLayer.bounds.height) } } /** Render the text indexes */ fileprivate func renderTopTextIndexes() { for i in 0...(numberOfPoints - 1) { let centerPoint = centerPoints[i] let textLayer = self._topTextLayer(atIndex: i) textLayer.contentsScale = UIScreen.main.scale textLayer.font = stepTextFont textLayer.fontSize = (stepTextFont?.pointSize)! if i == currentIndex { textLayer.foregroundColor = currentSelectedTextColor.cgColor } else { textLayer.foregroundColor = stepTextColor!.cgColor } if let text = self.delegate?.progressBar?(self, textAtIndex: i, position: FlexibleSteppedProgressBarTextLocation.top) { textLayer.string = text } else { textLayer.string = "\(i)" } textLayer.sizeWidthToFit() textLayer.frame = CGRect(x: centerPoint.x - textLayer.bounds.width/2, y: centerPoint.y - textLayer.bounds.height/2 - _progressRadius - textDistance, width: textLayer.bounds.width, height: textLayer.bounds.height) } } fileprivate func renderBottomTextIndexes() { for i in 0...(numberOfPoints - 1) { let centerPoint = centerPoints[i] let textLayer = self._bottomTextLayer(atIndex: i) textLayer.contentsScale = UIScreen.main.scale textLayer.font = stepTextFont textLayer.fontSize = (stepTextFont?.pointSize)! if i == currentIndex { textLayer.foregroundColor = currentSelectedTextColor.cgColor } else { textLayer.foregroundColor = stepTextColor!.cgColor } if let text = self.delegate?.progressBar?(self, textAtIndex: i, position: FlexibleSteppedProgressBarTextLocation.bottom) { textLayer.string = text } else { textLayer.string = "\(i)" } textLayer.sizeWidthToFit() textLayer.frame = CGRect(x: centerPoint.x - textLayer.bounds.width/2, y: centerPoint.y - textLayer.bounds.height/2 + _progressRadius + textDistance, width: textLayer.bounds.width, height: textLayer.bounds.height) } } /** Provide a text layer for the given index. If it's not in cache, it'll be instanciated. - parameter index: The index where the layer will be used - returns: The text layer */ fileprivate func _topTextLayer(atIndex index: Int) -> CATextLayer { var textLayer: CATextLayer if let _textLayer = self._topTextLayers[index] { textLayer = _textLayer } else { textLayer = CATextLayer() self._topTextLayers[index] = textLayer } self.layer.addSublayer(textLayer) return textLayer } /** Provide a text layer for the given index. If it's not in cache, it'll be instanciated. - parameter index: The index where the layer will be used - returns: The text layer */ fileprivate func _bottomTextLayer(atIndex index: Int) -> CATextLayer { var textLayer: CATextLayer if let _textLayer = self._bottomTextLayers[index] { textLayer = _textLayer } else { textLayer = CATextLayer() self._bottomTextLayers[index] = textLayer } self.layer.addSublayer(textLayer) return textLayer } /** Provide a text layer for the given index. If it's not in cache, it'll be instanciated. - parameter index: The index where the layer will be used - returns: The text layer */ fileprivate func _textLayer(atIndex index: Int) -> CATextLayer { var textLayer: CATextLayer if let _textLayer = self._textLayers[index] { textLayer = _textLayer } else { textLayer = CATextLayer() self._textLayers[index] = textLayer } self.layer.addSublayer(textLayer) return textLayer } /** Compte a progress path - parameter centerPoints: The center points corresponding to the indexes - parameter aRadius: The index radius - parameter aLineHeight: The line height between each index - returns: The computed path */ fileprivate func _shapePath(_ centerPoints: Array<CGPoint>, aRadius: CGFloat, aLineHeight: CGFloat) -> UIBezierPath { let nbPoint = centerPoints.count let path = UIBezierPath() var distanceBetweenCircles: CGFloat = 0 if let first = centerPoints.first , nbPoint > 2 { let second = centerPoints[1] distanceBetweenCircles = second.x - first.x - 2 * aRadius } let angle = aLineHeight / 2.0 / aRadius; var xCursor: CGFloat = 0 for i in 0...(2 * nbPoint - 1) { var index = i if(index >= nbPoint) { index = (nbPoint - 1) - (i - nbPoint) } let centerPoint = centerPoints[index] var startAngle: CGFloat = 0 var endAngle: CGFloat = 0 if(i == 0) { xCursor = centerPoint.x startAngle = CGFloat.pi endAngle = -angle } else if(i < nbPoint - 1) { startAngle = CGFloat.pi + angle endAngle = -angle } else if(i == (nbPoint - 1)){ startAngle = CGFloat.pi + angle endAngle = 0 } else if(i == nbPoint) { startAngle = 0 endAngle = CGFloat.pi - angle } else if (i < (2 * nbPoint - 1)) { startAngle = angle endAngle = CGFloat.pi - angle } else { startAngle = angle endAngle = CGFloat.pi } path.addArc(withCenter: CGPoint(x: centerPoint.x, y: centerPoint.y), radius: aRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) if(i < nbPoint - 1) { xCursor += aRadius + distanceBetweenCircles path.addLine(to: CGPoint(x: xCursor, y: centerPoint.y - aLineHeight / 2.0)) xCursor += aRadius } else if (i < (2 * nbPoint - 1) && i >= nbPoint) { xCursor -= aRadius + distanceBetweenCircles path.addLine(to: CGPoint(x: xCursor, y: centerPoint.y + aLineHeight / 2.0)) xCursor -= aRadius } } return path } fileprivate func _shapePathForSelected(_ centerPoint: CGPoint, aRadius: CGFloat) -> UIBezierPath { return UIBezierPath(roundedRect: CGRect(x: centerPoint.x - aRadius, y: centerPoint.y - aRadius, width: 2.0 * aRadius, height: 2.0 * aRadius), cornerRadius: aRadius) } fileprivate func _shapePathForLastState(_ center: CGPoint) -> UIBezierPath { // let angle = CGFloat(M_PI)/4 let path = UIBezierPath() // path.addArcWithCenter(center, radius: self._progressRadius + _radius, startAngle: angle, endAngle: 2*CGFloat(M_PI) + CGFloat(M_PI)/4, clockwise: true) path.addArc(withCenter: center, radius: self._progressRadius + lastStateOuterCircleLineWidth, startAngle: 0, endAngle: 4*CGFloat.pi, clockwise: true) return path } fileprivate func _shapePathForSelectedPathCenter(_ centerPoint: CGPoint, aRadius: CGFloat) -> UIBezierPath { return UIBezierPath(roundedRect: CGRect(x: centerPoint.x - aRadius, y: centerPoint.y - aRadius, width: 2.0 * aRadius, height: 2.0 * aRadius), cornerRadius: aRadius) } /** Compute the mask path - parameter currentProgressCenterPoint: The current progress index's center point - returns: The computed mask path */ fileprivate func _maskPath(_ currentProgressCenterPoint: CGPoint) -> UIBezierPath { let angle = self._progressLineHeight / 2.0 / self._progressRadius; let xOffset = cos(angle) * self._progressRadius let maskPath = UIBezierPath() maskPath.move(to: CGPoint(x: 0.0, y: 0.0)) maskPath.addLine(to: CGPoint(x: currentProgressCenterPoint.x + xOffset, y: 0.0)) maskPath.addLine(to: CGPoint(x: currentProgressCenterPoint.x + xOffset, y: currentProgressCenterPoint.y - self._progressLineHeight)) maskPath.addArc(withCenter: currentProgressCenterPoint, radius: self._progressRadius, startAngle: -angle, endAngle: angle, clockwise: true) maskPath.addLine(to: CGPoint(x: currentProgressCenterPoint.x + xOffset, y: self.bounds.height)) maskPath.addLine(to: CGPoint(x: 0.0, y: self.bounds.height)) maskPath.close() return maskPath } /** Respond to the user action - parameter gestureRecognizer: The gesture recognizer responsible for the action */ @objc func gestureAction(_ gestureRecognizer: UIGestureRecognizer) { if(gestureRecognizer.state == UIGestureRecognizer.State.ended || gestureRecognizer.state == UIGestureRecognizer.State.changed ) { let touchPoint = gestureRecognizer.location(in: self) var smallestDistance = CGFloat(Float.infinity) var selectedIndex = 0 for (index, point) in self.centerPoints.enumerated() { let distance = touchPoint.distanceWith(point) if(distance < smallestDistance) { smallestDistance = distance selectedIndex = index } } if(self.currentIndex != selectedIndex) { if let canSelect = self.delegate?.progressBar?(self, canSelectItemAtIndex: selectedIndex) { if (canSelect) { if (selectedIndex > completedTillIndex) { completedTillIndex = selectedIndex } self.currentIndex = selectedIndex self.animationRendering = true } } } } } }
36.216883
224
0.590096
03d35d530cb04f69ccf4ef9d78b2b23a5fa1b524
1,036
// // AppDelegate.swift // RxSwiftMVVMTableView // // Created by tokijh on 2018. 2. 21.. // Copyright © 2018년 tokijh. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var navigationViewController: UINavigationController = { [unowned self] in let navigationViewController = UINavigationController(rootViewController: self.rootViewController) return navigationViewController }() lazy var rootViewController: UIViewController = { let mainViewController = MainViewController.create(with: MainViewModel()) return mainViewController }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = navigationViewController window?.makeKeyAndVisible() return true } }
28.777778
144
0.712355
336159e715ae858822af47d8b3e2789f858723a5
3,429
/* ************************************************************************************************* HTTPETagTests.swift © 2017-2018 YOCKOW. Licensed under MIT License. See "LICENSE.txt" for more information. ************************************************************************************************ */ import XCTest @testable import NetworkGear final class HTTPETagTests: XCTestCase { func test_initialization() { XCTAssertNil(HTTPETag("unquoted")) XCTAssertEqual(HTTPETag("\"STRONG\""), .strong("STRONG")) XCTAssertEqual(HTTPETag("W/\"WEAK\""), .weak("WEAK")) XCTAssertEqual(HTTPETag("*"), .any) } func test_comparison() { let strong = HTTPETag("\"HTTPETag\"")! let weak = HTTPETag("W/\"HTTPETag\"")! XCTAssertTrue(strong =~ weak) XCTAssertFalse(strong == weak) } func test_list() { let trial = { (string:String, expectedError:HTTPETagParseError) -> Void in do { _ = try HTTPETagList(string) } catch { guard case let parseError as HTTPETagParseError = error else { XCTFail("Unexpected Error was thrown.") return } XCTAssertEqual(expectedError, parseError, "Expected Error: \(expectedError); Actual Error: \(parseError)") } } trial(", \"A\"", .extraComma) trial("\"A\", , \"B\"", .extraComma) trial("?", .unexpectedCharacter) trial("W-\"A\"", .unexpectedCharacter) trial("W/'A'", .unexpectedCharacter) trial("\"", .unterminatedTag) trial("W/\"ABCDEFGHIJKLMN", .unterminatedTag) trial("W/\"ABCDEFGHIJKLMN\\\"", .unterminatedTag) do { let list = try HTTPETagList("\"A\", \"B\", W/\"C\", \"D\" ") guard case .list(let array) = list else { XCTFail("Unexpected Error") return } XCTAssertEqual(array[0], .strong("A")) XCTAssertEqual(array[1], .strong("B")) XCTAssertEqual(array[2], .weak("C")) XCTAssertEqual(array[3], .strong("D")) XCTAssertTrue(list.contains(.strong("A"))) XCTAssertTrue(list.contains(.weak("C"))) XCTAssertTrue(list.contains(.strong("C"), weakComparison:true)) XCTAssertTrue(list.contains(.weak("D"), weakComparison:true)) } catch { XCTFail("Unexpected Error: \(error)") } } public func test_headerField() { let eTag1 = HTTPETag("\"SomeETag\"")! let eTag2 = HTTPETag("W/\"SomeWeakETag\"")! var eTagField = HTTPETagHeaderFieldDelegate(eTag1) XCTAssertEqual(type(of:eTagField).name, .eTag) XCTAssertEqual(eTagField.value.rawValue, eTag1.description) eTagField.source = eTag2 XCTAssertEqual(eTagField.value.rawValue, eTag2.description) XCTAssertEqual(type(of:eTagField).type, .single) var ifMatchField = IfMatchHTTPHeaderFieldDelegate(.list([eTag1])) ifMatchField.append(eTag2) XCTAssertEqual(type(of:ifMatchField).name, .ifMatch) XCTAssertEqual(ifMatchField.value.rawValue, "\(eTag1.description), \(eTag2.description)") XCTAssertEqual(type(of:ifMatchField).type, .appendable) var ifNoneMatchField = IfMatchHTTPHeaderFieldDelegate(.list([eTag1])) ifNoneMatchField.append(eTag2) XCTAssertEqual(type(of:ifNoneMatchField).name, .ifMatch) XCTAssertEqual(ifNoneMatchField.value.rawValue, "\(eTag1.description), \(eTag2.description)") XCTAssertEqual(type(of:ifNoneMatchField).type, .appendable) } }
34.636364
100
0.610382
2fc13247c4cbe57b896e23220ffafd02183f4c66
234
// PulseXSmartContractTests.swift // Copyright (c) 2022 Joe Blau import XCTest @testable import UniswapSmartContract final class PulseXSmartContractTests: XCTestCase { func testExample() throws { XCTAssert(true) } }
19.5
50
0.74359
18f4a6f1a2aba3df3efe9fd64b2b906e9211e21f
1,574
extension UIImage { @objc func aspectFill(toSize newSize: CGSize) -> UIImage? { let aspectRatio = size.aspectRatio() let targetAspectRatio = newSize.aspectRatio() let drawSize: CGSize; if (targetAspectRatio > aspectRatio) { // target is to make the image wider -> increase width, possibly crop height drawSize = CGSize(width: newSize.width, height: newSize.width / aspectRatio) } else { // target is to make the image taller -> increase height, possibly crop width drawSize = CGSize(width: newSize.height * aspectRatio, height: newSize.height) } let newImage: UIImage? let clipRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral // perform center cropping by drawing the image outside of clip rect let drawRect = CGRect(x: (drawSize.width >= newSize.width) ? (newSize.width - drawSize.width) / 2 : 0, y: (drawSize.height >= newSize.height) ? (newSize.height - drawSize.height) / 2 : 0, width: drawSize.width, height: drawSize.height) UIGraphicsBeginImageContextWithOptions(newSize, false, 0) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.interpolationQuality = .high context.clip(to: clipRect) draw(in: drawRect) newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
42.540541
114
0.622618
5bae5d2fd22c34a1e820eb716dca3381dfc1fbc0
2,236
// // AnimatedLineView.swift // YoCelsius // // Created by 王伟奇 on 2017/8/17. // Copyright © 2017年 王伟奇. All rights reserved. // import UIKit class AnimatedLineView: UIView { private var startRect: CGRect = CGRect.zero private var midRect: CGRect = CGRect.zero private var endRect: CGRect = CGRect.zero //显示的图片 var image = UIImage() { didSet{ imageView.image = image } } private var imageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) initRects() imageView = UIImageView(frame: startRect) imageView.alpha = 0.0 self.addSubview(imageView) } //重置UIImageView的参数 func resetImageView() { imageView.alpha = 0.0 imageView.frame = startRect } //显示出来 func showWithDuration(duration: TimeInterval, animated: Bool) { resetImageView() if animated { UIView.animate(withDuration: duration, animations: { self.imageView.frame = self.midRect self.imageView.alpha = 1.0 }) }else { self.imageView.frame = self.midRect self.imageView.alpha = 1.0 } } //隐藏 func hideWithDuration(duration: TimeInterval, animated: Bool) { if animated { UIView.animate(withDuration: duration, animations: { self.imageView.frame = self.endRect self.imageView.alpha = 0.0 }) }else { self.imageView.frame = self.endRect self.imageView.alpha = 0.0 } } func initRects() { let width = self.bounds.width let height = self.bounds.height / 2.0 self.startRect = CGRect(x: 0, y: -10, width: width, height: height) self.midRect = CGRect(x: 0, y: 0, width: width, height: height) self.endRect = CGRect(x: 0, y: -5, width: width, height: height) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
24.043011
75
0.535331
488a3f3135165ceaf166efe2146ff97d5d529a05
322
/** * Resolver - это абстракция, которая определяет, * как контейнер будет разрешать зависимость */ public class Resolver<T> { /** * Разрешает зависимость типа [T] * @return - возвращает объект типа [T] */ func resolve() -> T { preconditionFailure("TODO: Need implement Resolver") } }
24.769231
60
0.630435
b92551c042b37b88012c6fcd29d186553d0ff8ef
887
// // ProfileTextFieldTableViewCell.swift // Academia // // Created by Kelly Johnson on 8/30/18. // Copyright © 2018 DunDak, LLC. All rights reserved. // import UIKit class ProfileTextFieldTableViewCell: UITableViewCell { // MARK: - Properties @IBOutlet weak var textFieldOutlet: UITextField! override func awakeFromNib() { super.awakeFromNib() let avenirFont = [ NSAttributedStringKey.foregroundColor: UIColor.gray, NSAttributedStringKey.font: UIFont(name: "Avenir-Medium", size: 24)! ] textFieldOutlet.attributedPlaceholder = NSAttributedString(string: "", attributes: avenirFont) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
25.342857
102
0.655017
bbb3652690f752271e57c17e9699d3c4e8a47636
1,710
// // DeepDatagoTests.swift // DeepDatagoTests // // Created by tnnd on 12/29/18. // Copyright © 2018 com.deepdatago. All rights reserved. // import XCTest @testable import DeepDatago class DeepDatagoTests: 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 system integration test case. The request will be sent to the real dev server // Use XCTAssert and related functions to verify your tests produce the correct results. // SecKeyGeneratePair doesn't work well on XCTest as a known bug (URL cannot be found) var testDeep = DeepDatagoManager.sharedInstance() let groupAddress = "abc" as NSString // let groupKeyFlag = testDeep.getGroupKeyFromServer(groupAddress: groupAddress) let groupKey = testDeep.getGroupKey(group: groupAddress) let groupKey2 = testDeep.getGroupKey(group: groupAddress) var inviteeArray : NSMutableArray = [] inviteeArray.add("invitee1@com") inviteeArray.add("invitee2@com") _ = testDeep.createGroupChat(groupAddress: "abc", inviteeArray: inviteeArray); var a = 3 a = 4 } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
33.529412
113
0.653216
ab3975bc8f4f35ac271d8a47923363fd1ded6e18
12,712
// // LegalViewController.swift // Nano // // Created by Zack Shapiro on 3/22/18. // Copyright © 2018 Nano Wallet Company. All rights reserved. // import Foundation import Cartography import M13Checkbox import ReactiveCocoa import ReactiveSwift import Result protocol LegalViewControllerDelegate: class { func didFinishWithLegalVC() } final class LegalViewController: UIViewController { private let useForLoggedInState: Bool private let userService = UserService() private let credentials: Credentials private let dateFormatter = DateFormatter() private let (lifetime, token) = Lifetime.make() private weak var eulaCheckbox: M13Checkbox? private weak var privacyPolicyCheckbox: M13Checkbox? private weak var agreeButton: NanoButton? var delegate: LegalViewControllerDelegate? private var dateString: String { dateFormatter.dateFormat = "MM/dd/yyyy-HH:mm:ssXXX" return dateFormatter.string(from: Date()) } init(useForLoggedInState: Bool) { self.useForLoggedInState = useForLoggedInState guard let credentials = userService.fetchCredentials() else { fatalError("Should always have credentials") } self.credentials = credentials super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { view.backgroundColor = .white super.viewDidLoad() AnalyticsEvent.legalViewed.track() let disagreeButton = NanoButton(withType: .grey) disagreeButton.addTarget(self, action: #selector(disagreeToLegal), for: .touchUpInside) disagreeButton.setAttributedTitle("Disagree") view.addSubview(disagreeButton) constrain(disagreeButton) { $0.bottom == $0.superview!.bottom - (isiPhoneSE() ? CGFloat(17) : CGFloat(34)) $0.right == $0.superview!.centerX - CGFloat(10) $0.width == $0.superview!.width * CGFloat(0.43) $0.height == CGFloat(55) } let agreeButton = NanoButton(withType: .lightBlue) agreeButton.addTarget(self, action: #selector(agreeToLegal), for: .touchUpInside) agreeButton.setAttributedTitle("Agree") agreeButton.isEnabled = false view.addSubview(agreeButton) constrain(agreeButton, disagreeButton) { $0.bottom == $1.bottom $0.left == $0.superview!.centerX + CGFloat(10) $0.width == $1.width $0.height == $1.height } self.agreeButton = agreeButton let viewTitle = UILabel() viewTitle.text = "Terms and Conditions" viewTitle.font = Styleguide.Fonts.nunitoRegular.font(ofSize: 24) viewTitle.underline() view.addSubview(viewTitle) constrain(viewTitle, disagreeButton) { if isiPhoneSE() { $0.top == $0.superview!.top + CGFloat(33) } else { $0.top == $0.superview!.top + CGFloat(44) } $0.left == $1.left } let viewCopy = UILabel() viewCopy.numberOfLines = 0 if isiPhonePlus() { viewCopy.font = Styleguide.Fonts.nunitoLight.font(ofSize: 18) } else if isiPhoneRegular() { viewCopy.font = Styleguide.Fonts.nunitoLight.font(ofSize: 16) } else { viewCopy.font = Styleguide.Fonts.nunitoLight.font(ofSize: 14) } viewCopy.lineBreakMode = .byWordWrapping viewCopy.text = """ Your use of this CellCoin Wallet mobile application is subject to your agreement to all terms and conditions of the End User License Agreement and Privacy Policy linked below (collectively, the "Terms and Conditions"). \n\nCellCoin Organization (CellCoin.org) cannot take responsibility for third-party providers, such as the listed exchanges, wallets, sites and pools. All links hosted on our domain are by community members and third parties and by clicking on any of the listed links you are accepting the risks of using the third party domain and taking responsibility for any losses, damage or other issues using the said domain. Crypto-currencies are inherently risky and investors and users must remain vigilant. If you do not understand or agree to any of the Terms and Conditions, you are not licensed or authorized to use this application and should delete it from your device. """ view.addSubview(viewCopy) constrain(viewCopy, viewTitle, agreeButton) { if isiPhoneSE() { $0.top == $1.bottom + CGFloat(10) } else { $0.top == $1.bottom + CGFloat(20) } $0.left == $1.left $0.right == $2.right } let eulaCheckbox = createCheckbox() view.addSubview(eulaCheckbox) constrain(eulaCheckbox, viewCopy) { if isiPhoneSE() { $0.top == $1.bottom + CGFloat(30) } else if isiPhoneRegular() { $0.top == $1.bottom + CGFloat(30) } else { $0.top == $1.bottom + CGFloat(40) } $0.left == $1.left $0.width == (isiPhoneSE() ? CGFloat(30) : CGFloat(40)) $0.height == (isiPhoneSE() ? CGFloat(30) : CGFloat(40)) } self.eulaCheckbox = eulaCheckbox let eula = createUnderlinedButton() eula.setTitle("End User License Agreement", for: .normal) eula.addTarget(self, action: #selector(viewEula), for: .touchUpInside) eula.underline() view.addSubview(eula) constrain(eula, eulaCheckbox) { $0.bottom == $1.bottom $0.left == $1.right + CGFloat(20) } let privacyPolicyCheckbox = createCheckbox() view.addSubview(privacyPolicyCheckbox) constrain(privacyPolicyCheckbox, eulaCheckbox) { $0.top == $1.bottom + CGFloat(40) $0.left == $1.left $0.width == (isiPhoneSE() ? CGFloat(30) : CGFloat(40)) $0.height == (isiPhoneSE() ? CGFloat(30) : CGFloat(40)) } self.privacyPolicyCheckbox = privacyPolicyCheckbox let privacyPolicy = createUnderlinedButton() privacyPolicy.setTitle("Privacy Policy", for: .normal) privacyPolicy.addTarget(self, action: #selector(viewPrivacyPolicy), for: .touchUpInside) privacyPolicy.underline() view.addSubview(privacyPolicy) constrain(privacyPolicy, privacyPolicyCheckbox) { $0.bottom == $1.bottom $0.left == $1.right + CGFloat(20) } // MARK: - Reactive SignalProducer(eulaCheckbox.reactive.checkboxTapped) .producer .take(during: lifetime) .startWithValues { _ in if self.eulaCheckbox?.checkState == .checked { self.eulaCheckbox?.toggleAgreement() } self.viewEula() } SignalProducer(privacyPolicyCheckbox.reactive.checkboxTapped) .producer .take(during: lifetime) .startWithValues { _ in if self.privacyPolicyCheckbox?.checkState == .checked { self.privacyPolicyCheckbox?.toggleAgreement() } self.viewPrivacyPolicy() } // MARK: - Reactive For Analytics SignalProducer(eulaCheckbox.reactive.valueChanged) .producer .take(during: lifetime) .startWithValues { _ in guard let checkbox = self.eulaCheckbox else { return } AnalyticsEvent.eulaAgreementToggled.track(customAttributes: [ "device_id": UIDevice.current.identifierForVendor!.uuidString, "accepted": checkbox.checkState.rawValue, "date": self.dateString ]) } SignalProducer(privacyPolicyCheckbox.reactive.valueChanged) .producer .take(during: lifetime) .startWithValues { _ in guard let checkbox = self.privacyPolicyCheckbox else { return } AnalyticsEvent.privacyPolicyAgreementToggled.track(customAttributes: [ "device_id": UIDevice.current.identifierForVendor!.uuidString, "accepted": checkbox.checkState.rawValue, "date": self.dateString ]) } // MARK: - Master Button Enable/Disable Check SignalProducer.combineLatest(SignalProducer(eulaCheckbox.reactive.valueChanged), SignalProducer(privacyPolicyCheckbox.reactive.valueChanged)) .producer .take(during: lifetime) .observe(on: UIScheduler()) .startWithValues { _, _ in if self.eulaCheckbox?.checkState == .checked && self.privacyPolicyCheckbox?.checkState == .checked { self.agreeButton?.isEnabled = true } else { self.agreeButton?.isEnabled = false } } } private func createCheckbox() -> M13Checkbox { let checkbox = M13Checkbox() checkbox.boxType = .square checkbox.markType = .checkmark checkbox.boxLineWidth = 2 checkbox.animationDuration = 0.2 checkbox.tintColor = Styleguide.Colors.lightBlue.color checkbox.secondaryTintColor = Styleguide.Colors.lightBlue.color return checkbox } private func createUnderlinedButton() -> UIButton { let button = UIButton() button.titleLabel?.font = Styleguide.Fonts.nunitoLight.font(ofSize: (isiPhoneSE() ? CGFloat(18) : CGFloat(22))) button.setTitleColor(Styleguide.Colors.darkBlue.color, for: .normal) return button } @objc func viewEula() { AnalyticsEvent.eulaViewed.track(customAttributes: [ "device_id": UIDevice.current.identifierForVendor!.uuidString, "date": dateString ]) let vc = WebViewController(url: URL(string: "https://cellcoin.cc/terms")!, useForLegalPurposes: true, agreement: .eula) vc.delegate = self present(vc, animated: true) } @objc func viewPrivacyPolicy() { AnalyticsEvent.privacyPolicyViewed.track(customAttributes: [ "device_id": UIDevice.current.identifierForVendor!.uuidString, "date": dateString ]) let vc = WebViewController(url: URL(string: "https://cellcoin.cc/privacy")!, useForLegalPurposes: true, agreement: .privacyPolicy) vc.delegate = self present(vc, animated: true) } @objc func disagreeToLegal() { if useForLoggedInState { let ac = UIAlertController(title: "Log Out Warning", message: "Not agreeing will result in logging out of the app.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Log Me Out", style: .destructive) { _ in NotificationCenter.default.post(name: NSNotification.Name(rawValue: "LogOut"), object: nil) }) ac.addAction(UIAlertAction(title: "Cancel", style: .default)) present(ac, animated: true) } else { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "LogOut"), object: nil) } } @objc func agreeToLegal() { userService.updateLegal() self.dismiss(animated: true) { self.delegate?.didFinishWithLegalVC() } } } extension M13Checkbox { @objc func handleLongPress(_ sender: UILongPressGestureRecognizer) { guard sender.state == .ended else { return } sendActions(for: .touchUpInside) } func toggleAgreement() { toggleCheckState(true) sendActions(for: .valueChanged) } } extension LegalViewController: WebViewControllerDelegate { func didDismissWithAcceptance(agreement: Agreement) { switch agreement { case .eula: if self.eulaCheckbox?.checkState == .unchecked { self.eulaCheckbox?.toggleAgreement() } case .privacyPolicy: if self.privacyPolicyCheckbox?.checkState == .unchecked { self.privacyPolicyCheckbox?.toggleAgreement() } } dismiss(animated: true, completion: nil) } } extension Reactive where Base: UIControl { public var checkboxTapped: Signal<Void, NoError> { return mapControlEvents(.touchUpInside) { _ in } } public var valueChanged: Signal<Void, NoError> { return mapControlEvents(.valueChanged) { _ in } } }
36.113636
895
0.616897
f9f900929159d49c3feacf67c0e2bd0a04abfc13
7,344
// // ScrimmageViewController.swift // Huddle // // Created by Sagar Doshi on 7/17/17. // Copyright © 2017 Beroshi Studios. All rights reserved. // import UIKit func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } class ScrimmageViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { var imagesDirectoryPath: URL! var imagePicker: UIImagePickerController! var photoToSave: UIImage! = UIImage(named: "scrimmageImage.png") var compressionMultiplier: CGFloat = 0.25 @IBOutlet weak var overlayView: UIView! @IBOutlet weak var subcontentStackViewToHide: UIStackView! @IBOutlet weak var cameraButton: UIButton! @IBOutlet weak var photoImageView: UIImageView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) cameraButton.imageView?.contentMode = UIViewContentMode.scaleAspectFit } // When an image is "picked" it will return through this function func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { self.dismiss(animated: true, completion: nil) if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { photoImageView.image = image photoToSave = image } else { print("Dunno why, but looks like the chosen image wasn't a UIImage, and it needs to be.") // ERROR MESSAGE } } @IBAction func importImage(_ sender: UIButton) { // Hide text and camera button subcontentStackViewToHide.isHidden = true // Replace with overlay overlayView.isHidden = false // Take image (I think this ultimately calls the imagePickerController function...) imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.camera imagePicker.allowsEditing = true present(imagePicker, animated: true, completion: nil) } func saveImage(imageToSave: UIImage!) { // Get unique name for file path var fileName: String = NSDate().description fileName = fileName.replacingOccurrences(of: " ", with: "") fileName = fileName.replacingOccurrences(of: "/", with: "") fileName = "ImagePicker/\(fileName).png" print("***** Here's fileName after all the string adjustments: " + fileName) imagesDirectoryPath = getDocumentsDirectory() imagesDirectoryPath.appendPathComponent(fileName) print("***** Here's imagesDirectoryPath AFTER appending the fileName: \(imagesDirectoryPath)") print() let finalImagePath = imagesDirectoryPath! // Compress image let thumbnail = imageToSave.compress(toPercentage: compressionMultiplier) var imageData = UIImagePNGRepresentation(thumbnail!) // Fix the error in PNG Representation where its photos are rotated left using updateImageOrientationUpSide() function if let updatedImage = thumbnail?.updateImageOrientionUpSide() { imageData = UIImagePNGRepresentation(updatedImage) } do { try imageData!.write(to: finalImagePath, options: .atomic) print("HOOORAY!!! image as data WAS written to a path: \(finalImagePath)") } catch { print("BOOOO... image as data WAS NOT written to this path: \(finalImagePath)") } } func createImagesFolder () { if(!FileManager.default.fileExists(atPath: imagePickerPath.path)) { print("There was no existing ImagePicker folder.") do { print("I am creating the folder where the images will be stored: \(imagePickerPath.path)") try FileManager.default.createDirectory(at: imagePickerPath, withIntermediateDirectories: true, attributes: nil) print("I have finished creating the folder where the images will be stored: \(imagePickerPath.path)") } catch { print("Something went wrong while creating a new folder to hold the images.") } } else { print("There was an existing ImagePicker folder.") print("Here's the path for the already existing folder: \(imagePickerPath.path)") } } @IBAction func scrimmageComplete(_ sender: Any) { score += 30 level += 1 saveImage(imageToSave: photoToSave!) } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // All below is related to menu animation @IBOutlet weak var menuView: UIView! @IBOutlet weak var menuTopConstraint: NSLayoutConstraint! var menuVisible = false override func viewDidLoad() { super.viewDidLoad() menuView.layer.shadowOpacity = 1 menuView.layer.shadowOffset = CGSize(width: 5, height: 5) menuView.layer.shadowRadius = 5 createImagesFolder() // Creates storage folder if and only if it doesn't already exist } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if menuVisible { toggleMenu(self) } } @IBAction func toggleMenu(_ sender: Any) { menuView.isHidden = false if (!menuVisible) { menuTopConstraint.constant = 0 } else { menuTopConstraint.constant = -300 } UIView.animate(withDuration: 0.3, animations: {self.view.layoutIfNeeded()}) menuVisible = !menuVisible } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // Image extension extension UIImage { func updateImageOrientionUpSide() -> UIImage? { if self.imageOrientation == .up { return self } UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) if let normalizedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() { UIGraphicsEndImageContext() return normalizedImage } UIGraphicsEndImageContext() return nil } func compress(toPercentage percentage: CGFloat) -> UIImage? { let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage) UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: canvasSize)) return UIGraphicsGetImageFromCurrentImageContext() } }
33.081081
128
0.614379
4bcb931e6392c3ad9143ec073d1515dca2fc8077
1,645
import SwiftUI struct FavoritesNewsView: View { @ObservedObject var viewModel : FavoritesNewsViewModel @Binding var showSheetView: Bool var emptyListView: some View { Text("no data...").frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/1.5, alignment: .center) } var NewsListView: some View { List(self.viewModel.newsFavoritesList,id: \.title) { item in VStack { NewsViewCell(item:item) Button(action: { self.viewModel.deleteFevoriteItem(item: item) }) { Text("delete from favorites") .font(.headline) .foregroundColor(Color.blue) .frame(minWidth: 100, maxWidth: UIScreen.main.bounds.size.width/1.2, minHeight: 50) }.background( RoundedRectangle(cornerRadius: 15).shadow(color: Color.gray.opacity(0.35), radius: 15, x: 0, y: 0)) } } } @ViewBuilder var listView: some View { if self.viewModel.newsFavoritesList.isEmpty { emptyListView }else{ NewsListView } } var body: some View { NavigationView { listView .navigationBarTitle(Text("Favorites News"), displayMode: .inline) .navigationBarItems(trailing: Button(action: { print("Dismissing sheet view...") self.showSheetView = false self.viewModel.getFevoriteList() }) { Text("Done").bold() }) } } }
31.037736
128
0.542249
8799ced7c6f56791d5b19d58887189e340390eac
1,026
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "Core", platforms: [ .iOS(.v14), .macOS(.v11) ], products: [ .library( name: "Core", targets: ["Core"]) ], dependencies: [ .package( name: "Injector", path: "../DI"), .package( url: "https://github.com/apple/swift-collections.git", .upToNextMajor(from: "1.0.0")), .package( name: "SwiftProtobuf", url: "https://github.com/apple/swift-protobuf.git", from: "1.18.0") ], targets: [ .target( name: "Core", dependencies: [ "Injector", "SwiftProtobuf", .product(name: "Collections", package: "swift-collections") ], path: "Sources"), .testTarget( name: "CoreTests", dependencies: ["Core"], path: "Tests") ] )
24.428571
75
0.446394
23849b5dc1eb67f89091ce18e17122759416f2a1
332
// // TimeClock.swift // AlarmClock // // Created by lieon on 2019/9/18. // Copyright © 2019 lieon. All rights reserved. // import Foundation struct PopMenuModel { var iconName: String var name: String init(_ iconName: String, name: String) { self.iconName = iconName self.name = name } }
16.6
48
0.623494
4b1274af3d5eab0b8cfa69003266451ffca88a8d
12,552
// // TaskTouchVC.swift // BetterReminders // // Created by Joe Holt on 3/28/17. // Copyright © 2017 Joe Holt. All rights reserved. // import UIKit import UserNotifications enum TaskViewType: String { case NotCompleted = "Not Completed" case Completed = "Completed" case All = "All" } class TaskVC: UITableViewController, AddTaskDelegate, UIPopoverPresentationControllerDelegate, UIGestureRecognizerDelegate, UITextFieldDelegate { // MARK: - Properties let center = UNUserNotificationCenter.current() var schedule: JHSchedule! var clas: JHSchoolClass! var displayTasks: [JHTask]! var displayType: TaskViewType = .NotCompleted var feedbackGenerator: UISelectionFeedbackGenerator? var quickAddTextField: UITextField? // MARK: - View Methods override func viewDidLoad() { super.viewDidLoad() title = clas.name setUp() } // MARK: - TableView methods override func numberOfSections(in tableView: UITableView) -> Int { // 1 - Time left // 2 - Tasks return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: // Time remaining return 1 case 1: //Tasks return displayTasks.count + 1 //THe one extra is the quick add view default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { //Total time left let cell = tableView.dequeueReusableCell(withIdentifier: "timeLeftCell") let (hours, minutes) = clas.timeToCompleteTasks() cell?.textLabel?.text = "\(hours) \(getUnitsStringForHours(hours: hours)) and \(minutes) \(getUnitsStringForMinutes(minutes: minutes))" cell?.selectionStyle = .none cell?.isUserInteractionEnabled = false return cell! } else if indexPath.section == 1 && indexPath.row == displayTasks.count { //Quick add view let cell = tableView.dequeueReusableCell(withIdentifier: "quickAddCell") cell?.selectionStyle = .none let textField = cell?.viewWithTag(5) as! UITextField textField.delegate = self textField.text = "" return cell! } else { //Tasks let task = displayTasks[indexPath.row] let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "taskCell") var displayString = "" cell.textLabel?.text = task.name let outputFormatter = DateFormatter() outputFormatter.dateStyle = .full if let due = task.dueDate { displayString += "\(outputFormatter.string(from: due)) - " } if let (hours, minutes) = task.timeToComplete() { displayString += "\(timeStringFromHoursAndMinutes(hours: hours, minutes: minutes))" } cell.detailTextLabel?.text = displayString if task.completed == true { cell.accessoryType = .checkmark } return cell } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { //Total time left return 44.0 + 15.0 //Where 44 is default } else { return UITableViewAutomaticDimension } } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if indexPath.section == 1 { let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete", handler: { _,_ in self.deleteTask(at: indexPath) }) let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { _,_ in self.editTask(task: self.clas.tasks[indexPath.row]) }) editAction.backgroundColor = UIColor.blue return [deleteAction, editAction] } else { return [] } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section != 0 && indexPath.row != displayTasks.count { let task = displayTasks[indexPath.row] task.completed = !task.completed let cell = tableView.cellForRow(at: indexPath) if cell?.accessoryType == UITableViewCellAccessoryType.none { cell?.accessoryType = UITableViewCellAccessoryType.checkmark } else { cell?.accessoryType = UITableViewCellAccessoryType.none } saveSchedule() } updateTimeLeft() } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 1 { return "Tasks - \(displayType.rawValue)" } else { return "Estimated Time Left" } } // MARK: - Text (quick add) View functions func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) if textField.text?.trimmingCharacters(in: .whitespaces) != "" { print("test") let task = JHTask(name: textField.text!, completed: false, dueDate: nil, estimatedTimeToComplete: nil) schedule.classes[0].tasks.append(task) reloadTasks() } return false } // MARK: - Task Functions /** Removes task - parameter indexPath: Index for task to remove */ private func deleteTask(at indexPath: IndexPath) { //get most recent task list let task = displayTasks[indexPath.row] clas.removeTask(withId: task.id) let requestId = ("TASK_\(clas.tasks[indexPath.row].id)") center.removePendingNotificationRequests(withIdentifiers: [requestId]) reloadTasks() } /** Reloads data */ internal func didAddTask() { reloadTasks() } /** Reloads data */ internal func didEditTask() { //Task was edited reloadTasks() } /** Reloads, saves data */ private func reloadTasks() { //Reloads and saves tasks saveSchedule() loadTasks() print("Rload") UIView.transition(with: tableView, duration: 1.0, options: .transitionCrossDissolve, animations: {self.tableView.reloadData()}, completion: nil) } /** Save classes to defaults */ private func saveSchedule() { let data: Data = NSKeyedArchiver.archivedData(withRootObject: schedule!) UserDefaults.standard.set(data, forKey: "schedule") } /** Displays addTaskPopover in add mode */ @objc private func addTaskButtonTapped() { displayTaskPopover() } /** Displays addTaskPopover in edit mode */ private func editTask(task: JHTask) { //Edit a task displayTaskPopover(editing: true, forTask: task) } /** Sets tasks depending on if displayMode */ private func loadTasks() { //Get tasks to be displayed switch displayType { case .NotCompleted: displayTasks = clas.uncompletedTasks() case .Completed: displayTasks = clas.completedTasks() default: displayTasks = clas.tasks } } // MARK: - TaskPopover /** Displays a popup for adding/editing */ private func displayTaskPopover(editing: Bool = false, forTask: JHTask? = nil) { //Display a popover for editing or creating let storyBoard = UIStoryboard(name: "Main", bundle: nil) let vc = storyBoard.instantiateViewController(withIdentifier: "popoverTaskAdd") as! TaskPopoverVC vc.delegate = self vc.clas = clas vc.forTask = forTask vc.forEditing = editing let nav = UINavigationController(rootViewController: vc) nav.modalPresentationStyle = .popover if let presentationController = nav.popoverPresentationController { presentationController.delegate = self presentationController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0) presentationController.sourceView = self.view let width = self.view.bounds.width let height = UIScreen.main.bounds.height presentationController.sourceRect = CGRect(x: (self.view.bounds.width - width)/2, y: 0.0, width: width, height: height - 150) self.present(nav, animated: true, completion: nil) } } internal func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? { //Gives the view controller to be displayed in the popover view contorller let navigationController = UINavigationController(rootViewController: controller.presentedViewController) let btnDone = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(MainTableViewController.dismissClassPopoverView)) navigationController.topViewController?.navigationItem.rightBarButtonItem = btnDone return navigationController } internal func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { //.none sets the popover style as an actual popover rather than a full screen view return UIModalPresentationStyle.none } /** Hides task popover view */ internal func dismissTaskPopoverView() { self.dismiss(animated: true, completion: nil) } // MARK: - Helper Functions /** Finds units for gives hours - parameter hours: Hours to get units for - returns: Untits for given hours */ private func getUnitsStringForHours(hours: Int) -> String { if hours == 1 { return "Hour" } else { return "Hours" } } /** Finds units for gives minutes - parameter minutes: Minutes to get units for - returns: Untits for given minutes */ private func getUnitsStringForMinutes(minutes: Int) -> String { if minutes == 1 { return "Minute" } else { return "Minutes" } } // MARK: - Display type /** Changes display mode of tasks */ @objc private func navBarLongPress(sender: UILongPressGestureRecognizer? = nil) { feedbackGenerator = UISelectionFeedbackGenerator() feedbackGenerator?.prepare() if sender?.state == UIGestureRecognizerState.began { feedbackGenerator?.selectionChanged() changeDisplayType() } if sender?.state == UIGestureRecognizerState.ended { feedbackGenerator = nil } } /** Changes ui display of tasks */ private func changeDisplayType() { //Changes display type of classes displayed switch displayType { case .NotCompleted: displayType = .Completed case .Completed: displayType = .All default: displayType = .NotCompleted } print(displayType.rawValue) reloadTasks() } /** Updates timeLeft ui */ func updateTimeLeft() { tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) } /** UI set up */ private func setUp() { let button = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTaskButtonTapped)) navigationItem.rightBarButtonItem = button let longPress = UILongPressGestureRecognizer(target: self, action: #selector(navBarLongPress(sender:))) longPress.delegate = self navigationController?.navigationBar.addGestureRecognizer(longPress) loadTasks() } }
31.938931
179
0.602693
7a6db97abbedf4e5a7f5121327b7810630ee97f1
1,096
// // SameNameStoreTests.swift // FluxSwiftTests // // Created by Koji Murata on 2020/01/22. // import XCTest import Foundation @testable import FluxSwift class SameNameStoreTests: XCTestCase { func test() { let a = A.Store().register() let b = B.Store().register() A.Increment().dispatch() B.Increment().dispatch() B.Increment().dispatch() XCTAssertEqual(1, a.entity.x) XCTAssertEqual(2, b.entity.x) } class A { struct Store: FluxSwift.Store { var x: Int = 0 } struct Increment: Action { func reduce(store: Store) -> Store? { var tmp = store tmp.x += 1 return tmp } } } class B { struct Store: FluxSwift.Store { var x: Int = 0 } struct Increment: Action { func reduce(store: Store) -> Store? { var tmp = store tmp.x += 1 return tmp } } } }
20.679245
49
0.468978
4ab9bcf8062e75078e7fe2f1fb44f19a775c22aa
221
// // AsyncDispatchQueue.swift // BreakingBad // // Created by Joshua Simmons on 10/12/2020. // import Foundation protocol AsyncDispatchQueue { func async(execute work: @escaping @convention(block) () -> Void) }
17
69
0.701357
5b6c158b99d9430a91122aca8972b05d114774cd
181
// // NoBody.swift // ParseSwift // // Created by Florent Vilmart on 17-07-24. // Copyright © 2020 Parse. All rights reserved. // internal struct NoBody: ParseType, Codable {}
18.1
48
0.679558
e99f961dde4b1d630b8847da90938e0940f2ae9e
1,051
// // MemoListDatasource.swift // voicy-ios // // Created by Eliel A. Gordon on 1/5/18. // Copyright © 2018 Eliel Gordon. All rights reserved. // import Foundation import UIKit typealias CollectionViewCellCallback = (UICollectionView, IndexPath) -> UICollectionViewCell class GenericCollectionViewDatasource<T>: NSObject, UICollectionViewDataSource { var items: [T] = [] var configureCell: CollectionViewCellCallback? func numberOfSections(in collectionView: UICollectionView) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let configureCell = configureCell else { precondition(false, "You did not pass a configuration closure to configureCell, you must do so") } return configureCell(collectionView, indexPath) } }
30.911765
121
0.710752
e0897253c39d25d85c79c4bc51cb049936dfb4fc
59,955
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import TSCBasic import struct PackageModel.PackageReference import struct TSCUtility.Version import class Foundation.NSDate public enum DependencyResolverError: Error, Equatable, CustomStringConvertible { /// The resolver was unable to find a solution to the input constraints. case unsatisfiable /// The resolver found a dependency cycle. case cycle(PackageReference) /// The resolver encountered a versioned container which has a revision dependency. case incompatibleConstraints( dependency: (PackageReference, String), revisions: [(PackageReference, String)]) /// The resolver found missing versions for the given constraints. case missingVersions([PackageContainerConstraint]) /// A revision-based dependency contains a local package dependency. case revisionDependencyContainsLocalPackage(dependency: String, localPackage: String) /// The resolution was cancelled. case cancelled public static func == (lhs: DependencyResolverError, rhs: DependencyResolverError) -> Bool { switch (lhs, rhs) { case (.unsatisfiable, .unsatisfiable): return true case (.unsatisfiable, _): return false case (.cycle(let lhs), .cycle(let rhs)): return lhs == rhs case (.cycle, _): return false case (.incompatibleConstraints(let lDependency, let lRevisions), .incompatibleConstraints(let rDependency, let rRevisions)): return lDependency == rDependency && lRevisions == rRevisions case (.incompatibleConstraints, _): return false case (.missingVersions(let lhs), .missingVersions(let rhs)): return lhs == rhs case (.missingVersions, _): return false case (.revisionDependencyContainsLocalPackage(let a1, let b1), .revisionDependencyContainsLocalPackage(let a2, let b2)): return a1 == a2 && b1 == b2 case (.revisionDependencyContainsLocalPackage, _): return false case (.cancelled, .cancelled): return true case (.cancelled, _): return false } } public var description: String { switch self { case .cancelled: return "the package resolution operation was cancelled" case .revisionDependencyContainsLocalPackage(let dependency, let localPackage): return "package '\(dependency)' is required using a revision-based requirement and it depends on local package '\(localPackage)', which is not supported" case .unsatisfiable: return "the package dependency graph could not be resolved due to an unknown conflict" case .cycle(let package): return "the package \(package) depends on itself" case let .incompatibleConstraints(dependency, revisions): let stream = BufferedOutputByteStream() stream <<< "the package \(dependency.0) @ \(dependency.1) contains incompatible dependencies:\n" for (i, revision) in revisions.enumerated() { stream <<< " " stream <<< "\(revision.0)" <<< " @ " <<< revision.1 if i != revisions.count - 1 { stream <<< "\n" } } return stream.bytes.description case let .missingVersions(constraints): let stream = BufferedOutputByteStream() stream <<< "the package dependency graph could not be resolved; unable to find any available tag for the following requirements:\n" for (i, constraint) in constraints.enumerated() { stream <<< " " stream <<< "\(constraint.identifier.path)" <<< " @ " switch constraint.requirement { case .versionSet(let set): stream <<< "\(set)" case .revision, .unversioned: assertionFailure("Unexpected requirement type") break } if i != constraints.count - 1 { stream <<< "\n" } } return stream.bytes.description } } } /// A requirement that a package must satisfy. public enum PackageRequirement: Hashable { /// The requirement is specified by the version set. case versionSet(VersionSetSpecifier) /// The requirement is specified by the revision. /// /// The revision string (identifier) should be valid and present in the /// container. Only one revision requirement per container is possible /// i.e. two revision requirements for same container will lead to /// unsatisfiable resolution. The revision requirement can either come /// from initial set of constraints or from dependencies of a revision /// requirement. case revision(String) /// Un-versioned requirement i.e. a version should not resolved. case unversioned } extension PackageRequirement: CustomStringConvertible { public var description: String { switch self { case .versionSet(let versionSet): return versionSet.description case .revision(let revision): return revision case .unversioned: return "unversioned" } } } /// A container of packages. /// /// This is the top-level unit of package resolution, i.e. the unit at which /// versions are associated. /// /// It represents a package container (e.g., a source repository) which can be /// identified unambiguously and which contains a set of available package /// versions and the ability to retrieve the dependency constraints for each of /// those versions. /// /// We use the "container" terminology here to differentiate between two /// conceptual notions of what the package is: (1) informally, the repository /// containing the package, but from which a package cannot be loaded by itself /// and (2) the repository at a particular version, at which point the package /// can be loaded and dependencies enumerated. /// /// This is also designed in such a way to extend naturally to multiple packages /// being contained within a single repository, should we choose to support that /// later. public protocol PackageContainer { /// The identifier for the package. var identifier: PackageReference { get } /// Returns true if the tools version is compatible at the given version. func isToolsVersionCompatible(at version: Version) -> Bool /// Get the list of versions which are available for the package. /// /// The list will be returned in sorted order, with the latest version *first*. /// All versions will not be requested at once. Resolver will request the next one only /// if the previous one did not satisfy all constraints. func versions(filter isIncluded: (Version) -> Bool) -> AnySequence<Version> /// Get the list of versions in the repository sorted in the reverse order, that is the latest /// version appears first. var reversedVersions: [Version] { get } // FIXME: We should perhaps define some particularly useful error codes // here, so the resolver can handle errors more meaningfully. // /// Fetch the declared dependencies for a particular version. /// /// This property is expected to be efficient to access, and cached by the /// client if necessary. /// /// - Precondition: `versions.contains(version)` /// - Throws: If the version could not be resolved; this will abort /// dependency resolution completely. func getDependencies(at version: Version) throws -> [PackageContainerConstraint] /// Fetch the declared dependencies for a particular revision. /// /// This property is expected to be efficient to access, and cached by the /// client if necessary. /// /// - Throws: If the revision could not be resolved; this will abort /// dependency resolution completely. func getDependencies(at revision: String) throws -> [PackageContainerConstraint] /// Fetch the dependencies of an unversioned package container. /// /// NOTE: This method should not be called on a versioned container. func getUnversionedDependencies() throws -> [PackageContainerConstraint] /// Get the updated identifier at a bound version. /// /// This can be used by the containers to fill in the missing information that is obtained /// after the container is available. The updated identifier is returned in result of the /// dependency resolution. func getUpdatedIdentifier(at boundVersion: BoundVersion) throws -> PackageReference /// Hack for the old resolver. Don't use. var _isRemoteContainer: Bool? { get } } extension PackageContainer { public var _isRemoteContainer: Bool? { return nil } } /// An interface for resolving package containers. public protocol PackageContainerProvider { /// Get the container for a particular identifier asynchronously. func getContainer( for identifier: PackageReference, skipUpdate: Bool, completion: @escaping (Result<PackageContainer, AnyError>) -> Void ) } /// An individual constraint onto a container. public struct PackageContainerConstraint: CustomStringConvertible, Equatable, Hashable { /// The identifier for the container the constraint is on. public let identifier: PackageReference /// The constraint requirement. public let requirement: PackageRequirement /// Create a constraint requiring the given `container` satisfying the /// `requirement`. public init(container identifier: PackageReference, requirement: PackageRequirement) { self.identifier = identifier self.requirement = requirement } /// Create a constraint requiring the given `container` satisfying the /// `versionRequirement`. public init(container identifier: PackageReference, versionRequirement: VersionSetSpecifier) { self.init(container: identifier, requirement: .versionSet(versionRequirement)) } public var description: String { return "Constraint(\(identifier), \(requirement))" } } /// Delegate interface for dependency resoler status. public protocol DependencyResolverDelegate { } // FIXME: This should be nested, but cannot be currently. // /// A bound version for a package within an assignment. public enum BoundVersion: Equatable, CustomStringConvertible { /// The assignment should not include the package. /// /// This is different from the absence of an assignment for a particular /// package, which only indicates the assignment is agnostic to its /// version. This value signifies the package *may not* be present. case excluded /// The version of the package to include. case version(Version) /// The package assignment is unversioned. case unversioned /// The package assignment is this revision. case revision(String) public var description: String { switch self { case .excluded: return "excluded" case .version(let version): return version.description case .unversioned: return "unversioned" case .revision(let identifier): return identifier } } } // FIXME: Maybe each package should just return this, instead of a list of // `PackageContainerConstraint`s. That won't work if we decide this should // eventually map based on the `Container` rather than the `Identifier`, though, // so they are separate for now. // /// A container for constraints for a set of packages. /// /// This data structure is only designed to represent satisfiable constraint /// sets, it cannot represent sets including containers which have an empty /// constraint. public struct PackageContainerConstraintSet: Collection, Hashable { public typealias Index = Dictionary<PackageReference, PackageRequirement>.Index public typealias Element = Dictionary<PackageReference, PackageRequirement>.Element /// The set of constraints. private var constraints: [PackageReference: PackageRequirement] /// Create an empty constraint set. public init() { self.constraints = [:] } /// Create an constraint set from known values. /// /// The initial constraints should never be unsatisfiable. init(_ constraints: [PackageReference: PackageRequirement]) { assert(constraints.values.filter({ $0 == .versionSet(.empty) }).isEmpty) self.constraints = constraints } /// The list of containers with entries in the set. var containerIdentifiers: AnySequence<PackageReference> { return AnySequence(constraints.keys) } /// Get the version set specifier associated with the given package `identifier`. public subscript(identifier: PackageReference) -> PackageRequirement { return constraints[identifier] ?? .versionSet(.any) } /// Create a constraint set by merging the `requirement` for container `identifier`. /// /// - Returns: The new set, or nil the resulting set is unsatisfiable. private func merging( requirement: PackageRequirement, for identifier: PackageReference ) -> PackageContainerConstraintSet? { switch (requirement, self[identifier]) { case (.versionSet(let newSet), .versionSet(let currentSet)): // Try to intersect two version set requirements. let intersection = currentSet.intersection(newSet) if intersection == .empty { return nil } var result = self result.constraints[identifier] = .versionSet(intersection) return result case (.unversioned, .unversioned): return self case (.unversioned, _): // Unversioned requirements always *wins*. var result = self result.constraints[identifier] = requirement return result case (_, .unversioned): // Unversioned requirements always *wins*. return self // The revision cases are deliberately placed below the unversioned // cases because unversioned has more priority. case (.revision(let lhs), .revision(let rhs)): // We can merge two revisions if they have the same identifier. if lhs == rhs { return self } return nil // We can merge the revision requiement if it currently does not have a requirement. case (.revision, .versionSet(.any)): var result = self result.constraints[identifier] = requirement return result // Otherwise, we can't merge the revision requirement. case (.revision, _): return nil // Exisiting revision requirements always *wins*. case (_, .revision): return self } } /// Create a constraint set by merging `constraint`. /// /// - Returns: The new set, or nil the resulting set is unsatisfiable. public func merging(_ constraint: PackageContainerConstraint) -> PackageContainerConstraintSet? { return merging(requirement: constraint.requirement, for: constraint.identifier) } /// Create a new constraint set by merging the given constraint set. /// /// - Returns: False if the merger has made the set unsatisfiable; i.e. true /// when the resulting set is satisfiable, if it was already so. func merging( _ constraints: PackageContainerConstraintSet ) -> PackageContainerConstraintSet? { var result = self for (key, requirement) in constraints { guard let merged = result.merging(requirement: requirement, for: key) else { return nil } result = merged } return result } // MARK: Collection Conformance public var startIndex: Index { return constraints.startIndex } public var endIndex: Index { return constraints.endIndex } public func index(after index: Index) -> Index { return constraints.index(after: index) } public subscript(position: Index) -> Element { return constraints[position] } } // FIXME: Actually make efficient. // /// A container for version assignments for a set of packages, exposed as a /// sequence of `Container` to `BoundVersion` bindings. /// /// This is intended to be an efficient data structure for accumulating a set of /// version assignments along with efficient access to the derived information /// about the assignment (for example, the unified set of constraints it /// induces). /// /// The set itself is designed to only ever contain a consistent set of /// assignments, i.e. each assignment should satisfy the induced /// `constraints`, but this invariant is not explicitly enforced. struct VersionAssignmentSet: Equatable, Sequence { // FIXME: Does it really make sense to key on the identifier here. Should we // require referential equality of containers and use that to simplify? // /// The assignment records. fileprivate var assignments: OrderedDictionary<PackageReference, (container: PackageContainer, binding: BoundVersion)> /// Create an empty assignment. init() { assignments = [:] } /// The assignment for the given container `identifier. subscript(identifier: PackageReference) -> BoundVersion? { get { return assignments[identifier]?.binding } } /// The assignment for the given `container`. subscript(container: PackageContainer) -> BoundVersion? { get { return self[container.identifier] } set { // We disallow deletion. let newBinding = newValue! // Validate this is a valid assignment. assert(isValid(binding: newBinding, for: container)) assignments[container.identifier] = (container: container, binding: newBinding) } } /// Create a new assignment set by merging in the bindings from `assignment`. /// /// - Returns: The new assignment, or nil if the merge cannot be made (the /// assignments contain incompatible versions). func merging(_ assignment: VersionAssignmentSet) -> VersionAssignmentSet? { // In order to protect the assignment set, we first have to test whether // the merged constraint sets are satisfiable. // // FIXME: This is very inefficient; we should decide whether it is right // to handle it here or force the main resolver loop to handle the // discovery of this property. guard constraints.merging(assignment.constraints) != nil else { return nil } // The induced constraints are satisfiable, so we *can* union the // assignments without breaking our internal invariant on // satisfiability. var result = self for (container, binding) in assignment { if let existing = result[container] { if existing != binding { return nil } } else { result[container] = binding } } return result } // FIXME: We need to cache this. // /// The combined version constraints induced by the assignment. /// /// This consists of the merged constraints which need to be satisfied on /// each package as a result of the versions selected in the assignment. /// /// The resulting constraint set is guaranteed to be non-empty for each /// mapping, assuming the invariants on the set are followed. var constraints: PackageContainerConstraintSet { // Collect all of the constraints. var result = PackageContainerConstraintSet() /// Merge the provided constraints into result. func merge(constraints: [PackageContainerConstraint]) { for constraint in constraints { guard let merged = result.merging(constraint) else { preconditionFailure("unsatisfiable constraint set") } result = merged } } for (_, (container: container, binding: binding)) in assignments { switch binding { case .unversioned, .excluded: // If the package is unversioned or excluded, it doesn't contribute. continue case .revision(let identifier): // FIXME: Need caching and error handling here. See the FIXME below. merge(constraints: try! container.getDependencies(at: identifier)) case .version(let version): // If we have a version, add the constraints from that package version. // // FIXME: We should cache this too, possibly at a layer // different than above (like the entry record). // // FIXME: Error handling, except that we probably shouldn't have // needed to refetch the dependencies at this point. merge(constraints: try! container.getDependencies(at: version)) } } return result } // FIXME: This is currently very inefficient. // /// Check if the given `binding` for `container` is valid within the assignment. func isValid(binding: BoundVersion, for container: PackageContainer) -> Bool { switch binding { case .excluded: // A package can be excluded if there are no constraints on the // package (it has not been requested by any other package in the // assignment). return constraints[container.identifier] == .versionSet(.any) case .version(let version): // A version is valid if it is contained in the constraints. if case .versionSet(let versionSet) = constraints[container.identifier] { return versionSet.contains(version) } return false case .revision(let identifier): // If we already have a revision constraint, it should be same as // the one we're trying to set. if case .revision(let existingRevision) = constraints[container.identifier] { return existingRevision == identifier } // Otherwise, it is always valid to set a revision binding. Note // that there are rules that prevents versioned constraints from // having revision constraints, but that is handled by the resolver. return true case .unversioned: // An unversioned binding is always valid. return true } } /// Check if the assignment is valid and complete. func checkIfValidAndComplete() -> Bool { // Validity should hold trivially, because it is an invariant of the collection. for (_, assignment) in assignments { if !isValid(binding: assignment.binding, for: assignment.container) { return false } } // Check completeness, by simply looking at all the entries in the induced constraints. for identifier in constraints.containerIdentifiers { // Verify we have a non-excluded entry for this key. switch assignments[identifier]?.binding { case .unversioned?, .version?, .revision?: continue case .excluded?, nil: return false } } return true } // MARK: Sequence Conformance // FIXME: This should really be a collection, but that takes significantly // more work given our current backing collection. typealias Iterator = AnyIterator<(PackageContainer, BoundVersion)> func makeIterator() -> Iterator { var it = assignments.makeIterator() return AnyIterator { if let (_, next) = it.next() { return (next.container, next.binding) } else { return nil } } } } func ==(lhs: VersionAssignmentSet, rhs: VersionAssignmentSet) -> Bool { if lhs.assignments.count != rhs.assignments.count { return false } for (container, lhsBinding) in lhs { switch rhs[container] { case let rhsBinding? where lhsBinding == rhsBinding: continue default: return false } } return true } /// A general purpose package dependency resolver. /// /// This is a general purpose solver for the problem of: /// /// Given an input list of constraints, where each constraint identifies a /// container and version requirements, and, where each container supplies a /// list of additional constraints ("dependencies") for an individual version, /// then, choose an assignment of containers to versions such that: /// /// 1. The assignment is complete: there exists an assignment for each container /// listed in the union of the input constraint list and the dependency list for /// every container in the assignment at the assigned version. /// /// 2. The assignment is correct: the assigned version satisfies each constraint /// referencing its matching container. /// /// 3. The assignment is maximal: there is no other assignment satisfying #1 and /// #2 such that all assigned version are greater than or equal to the versions /// assigned in the result. /// /// NOTE: It does not follow from #3 that this solver attempts to give an /// "optimal" result. There may be many possible solutions satisfying #1, #2, /// and #3, and optimality requires additional information (e.g. a /// prioritization among packages). /// /// As described, this problem is NP-complete (*). This solver currently /// implements a basic depth-first greedy backtracking algorithm, and honoring /// the order of dependencies as specified in the manifest file. The solver uses /// persistent data structures to manage the accumulation of state along the /// traversal, so the backtracking is not explicit, rather it is an implicit /// side effect of the underlying copy-on-write data structures. /// /// The resolver will always merge the complete set of immediate constraints for /// a package (i.e., the version ranges of its immediate dependencies) into the /// constraint set *before* traversing into any dependency. This property allows /// packages to manually work around performance issues in the resolution /// algorithm by _lifting_ problematic dependency constraints up to be immediate /// dependencies. /// /// There is currently no external control offered by the solver over _which_ /// solution satisfying the properties above is selected, if more than one are /// possible. In practice, the algorithm is designed such that it will /// effectively prefer (i.e., optimize for the newest version of) dependencies /// which are earliest in the depth-first, pre-order, traversal. /// /// (*) Via reduction from 3-SAT: Introduce a package for each variable, with /// two versions representing true and false. For each clause `C_n`, introduce a /// package `P(C_n)` representing the clause, with three versions; one for each /// satisfying assignment of values to a literal with the corresponding precise /// constraint on the input packages. Finally, construct an input constraint /// list including a dependency on each clause package `P(C_n)` and an /// open-ended version constraint. The given input is satisfiable iff the input /// 3-SAT instance is. public class DependencyResolver { public typealias Container = PackageContainer public typealias Binding = (container: PackageReference, binding: BoundVersion) /// The container provider used to load package containers. public let provider: PackageContainerProvider /// The resolver's delegate. public let delegate: DependencyResolverDelegate? /// Should resolver prefetch the containers. private let isPrefetchingEnabled: Bool /// Skip updating containers while fetching them. private let skipUpdate: Bool /// Lock used to get and set the error variable. private let errorLock: Lock = Lock() // FIXME: @testable private // /// Contains any error encountered during dependency resolution. var error: Swift.Error? { get { return errorLock.withLock { self.__error } } set { errorLock.withLock { self.__error = newValue } } } var __error: Swift.Error? /// Key used to cache a resolved subtree. private struct ResolveSubtreeCacheKey: Hashable { let container: Container let allConstraints: PackageContainerConstraintSet func hash(into hasher: inout Hasher) { hasher.combine(container.identifier) hasher.combine(allConstraints) } static func ==(lhs: ResolveSubtreeCacheKey, rhs: ResolveSubtreeCacheKey) -> Bool { return lhs.container.identifier == rhs.container.identifier && lhs.allConstraints == rhs.allConstraints } } /// Cache for subtree resolutions. private var _resolveSubtreeCache: [ResolveSubtreeCacheKey: AnySequence<VersionAssignmentSet>] = [:] /// Puts the resolver in incomplete mode. /// /// In this mode, no new containers will be requested from the provider. /// Instead, if a container is not already present in the resolver, it will /// skipped without raising an error. This is useful to avoid cloning /// repositories from network when trying to partially resolve the constraints. /// /// Note that the input constraints will always be fetched. public var isInIncompleteMode = false public init( _ provider: PackageContainerProvider, _ delegate: DependencyResolverDelegate? = nil, isPrefetchingEnabled: Bool = false, skipUpdate: Bool = false ) { self.provider = provider self.delegate = delegate self.isPrefetchingEnabled = isPrefetchingEnabled self.skipUpdate = skipUpdate } /// The dependency resolver result. public enum Result { /// A valid and complete assignment was found. case success([Binding]) /// The dependency graph was unsatisfiable. /// /// The payload may contain conflicting constraints and pins. /// /// - parameters: /// - dependencies: The package dependencies which make the graph unsatisfiable. /// - pins: The pins which make the graph unsatisfiable. case unsatisfiable(dependencies: [PackageContainerConstraint], pins: [PackageContainerConstraint]) /// The resolver encountered an error during resolution. case error(Swift.Error) } /// Cancel the dependency resolution operation. /// /// This method is thread-safe. public func cancel() { self.error = DependencyResolverError.cancelled } /// Execute the resolution algorithm to find a valid assignment of versions. /// /// If a valid assignment is not found, the resolver will go into incomplete /// mode and try to find the conflicting constraints. public func resolve( dependencies: [PackageContainerConstraint], pins: [PackageContainerConstraint] ) -> Result { do { // Reset the incomplete mode and run the resolver. self.isInIncompleteMode = false let constraints = dependencies return try .success(resolve(constraints: constraints, pins: pins)) } catch DependencyResolverError.unsatisfiable { // FIXME: can we avoid this do..catch nesting? do { // If the result is unsatisfiable, try to debug. let debugger = ResolverDebugger(self) let badConstraints = try debugger.debug(dependencies: dependencies, pins: pins) return .unsatisfiable(dependencies: badConstraints.dependencies, pins: badConstraints.pins) } catch { return .error(error) } } catch { return .error(error) } } /// Execute the resolution algorithm to find a valid assignment of versions. /// /// - Parameters: /// - constraints: The contraints to solve. It is legal to supply multiple /// constraints for the same container identifier. /// - Returns: A satisfying assignment of containers and their version binding. /// - Throws: DependencyResolverError, or errors from the underlying package provider. public func resolve( constraints: [PackageContainerConstraint], pins: [PackageContainerConstraint] = [] ) throws -> [(container: PackageReference, binding: BoundVersion)] { return try resolveAssignment(constraints: constraints, pins: pins).map({ assignment in let (container, binding) = assignment let identifier = try self.isInIncompleteMode ? container.identifier : container.getUpdatedIdentifier(at: binding) // Get the updated identifier from the container. return (identifier, binding) }) } /// Execute the resolution algorithm to find a valid assignment of versions. /// /// - Parameters: /// - constraints: The contraints to solve. It is legal to supply multiple /// constraints for the same container identifier. /// - Returns: A satisfying assignment of containers and versions. /// - Throws: DependencyResolverError, or errors from the underlying package provider. func resolveAssignment( constraints: [PackageContainerConstraint], pins: [PackageContainerConstraint] = [] ) throws -> VersionAssignmentSet { // Create a constraint set with the input pins. var allConstraints = PackageContainerConstraintSet() for constraint in pins { if let merged = allConstraints.merging(constraint) { allConstraints = merged } else { // FIXME: We should issue a warning if the pins can't be merged // for some reason. } } // Create an assignment for the input constraints. let mergedConstraints = merge( constraints: constraints, into: VersionAssignmentSet(), subjectTo: allConstraints, excluding: [:]) // Prefetch the pins. if !isInIncompleteMode && isPrefetchingEnabled { prefetch(containers: pins.map({ $0.identifier })) } guard let assignment = mergedConstraints.first(where: { _ in true }) else { // Throw any error encountered during resolution. if let error = error { throw error } // Diagnose any missing versions for the constraints. try diagnoseMissingVersions(for: constraints) throw DependencyResolverError.unsatisfiable } return assignment } /// Diagnoses missing versions for the given constraints. private func diagnoseMissingVersions(for constraints: [RepositoryPackageConstraint]) throws { let constraintsWithNoAvailableVersions = constraints.filter { constraint in if case .versionSet(let versions) = constraint.requirement, let container = try? getContainer(for: constraint.identifier), // FIXME: This is hacky but we should be moving away from this resolver anyway. container._isRemoteContainer == true, !container.versions(filter: versions.contains).contains(where: { _ in true }) { return true } return false } if !constraintsWithNoAvailableVersions.isEmpty { throw DependencyResolverError.missingVersions(constraintsWithNoAvailableVersions) } } // FIXME: This needs to a way to return information on the failure, or we // will need to have it call the delegate directly. // // FIXME: @testable private // /// Resolve an individual container dependency tree. /// /// This is the primary method in our bottom-up algorithm for resolving /// dependencies. The inputs define an active set of constraints and set of /// versions to exclude (conceptually the latter could be merged with the /// former, but it is convenient to separate them in our /// implementation). The result is a sequence of all valid assignments for /// this container's subtree. /// /// - Parameters: /// - container: The container to resolve. /// - constraints: The external constraints which must be honored by the solution. /// - exclusions: The list of individually excluded package versions. /// - Returns: A sequence of feasible solutions, starting with the most preferable. func resolveSubtree( _ container: Container, subjectTo allConstraints: PackageContainerConstraintSet, excluding allExclusions: [PackageReference: Set<Version>] ) -> AnySequence<VersionAssignmentSet> { guard self.error == nil else { return AnySequence([]) } // The key that is used to cache this assignement set. let cacheKey = ResolveSubtreeCacheKey(container: container, allConstraints: allConstraints) // Check if we have a cache hit for this subtree resolution. // // Note: We don't include allExclusions in the cache key so we ignore // the cache if its non-empty. // // FIXME: We can improve the cache miss rate here if we have a cached // entry with a broader constraint set. The cached sequence can be // filtered according to the new narrower constraint set. if allExclusions.isEmpty, let assignments = _resolveSubtreeCache[cacheKey] { return assignments } func validVersions(_ container: Container, in versionSet: VersionSetSpecifier) -> AnySequence<Version> { let exclusions = allExclusions[container.identifier] ?? Set() return AnySequence(container.versions(filter: { versionSet.contains($0) && !exclusions.contains($0) })) } // Helper method to abstract passing common parameters to merge(). // // FIXME: We must detect recursion here. func merge(constraints: [PackageContainerConstraint], binding: BoundVersion) -> AnySequence<VersionAssignmentSet> { guard self.error == nil else { return AnySequence([]) } // Diagnose if this container depends on itself. if constraints.contains(where: { $0.identifier == container.identifier }) { error = DependencyResolverError.cycle(container.identifier) return AnySequence([]) } // Create an assignment for the container. var assignment = VersionAssignmentSet() assignment[container] = binding return AnySequence(self.merge( constraints: constraints, into: assignment, subjectTo: allConstraints, excluding: allExclusions).lazy.map({ result in // We might not have a complete result in incomplete mode. if !self.isInIncompleteMode { assert(result.checkIfValidAndComplete()) } return result })) } var result: AnySequence<VersionAssignmentSet> switch allConstraints[container.identifier] { case .unversioned: guard let constraints = self.safely({ try container.getUnversionedDependencies() }) else { return AnySequence([]) } // Merge the dependencies of unversioned constraint into the assignment. result = merge(constraints: constraints, binding: .unversioned) case .revision(let identifier): guard let constraints = self.safely({ try container.getDependencies(at: identifier) }) else { return AnySequence([]) } // If we have any local packages, set the error and abort. // // We might want to support this in the future if the local package is contained // inside the dependency. That's going to be tricky though since we don't have // concrete checkouts yet. let incompatibleConstraints = constraints.filter{ $0.requirement == .unversioned } guard incompatibleConstraints.isEmpty else { self.error = DependencyResolverError.revisionDependencyContainsLocalPackage( dependency: container.identifier.identity, localPackage: incompatibleConstraints[0].identifier.identity ) return AnySequence([]) } result = merge(constraints: constraints, binding: .revision(identifier)) case .versionSet(let versionSet): // The previous valid version that was picked. var previousVersion: Version? = nil // Attempt to select each valid version in the preferred order. result = AnySequence(validVersions(container, in: versionSet).lazy .flatMap({ version -> AnySequence<VersionAssignmentSet> in assert(previousVersion != nil ? previousVersion! > version : true, "container versions are improperly ordered") previousVersion = version // If we had encountered any error, return early. guard self.error == nil else { return AnySequence([]) } // Get the constraints for this container version and update the assignment to include each one. // FIXME: Making these methods throwing will kill the lazy behavior. guard var constraints = self.safely({ try container.getDependencies(at: version) }) else { return AnySequence([]) } // Since we don't want to request additional containers in incomplete // mode, remove any dependency that we don't already have. if self.isInIncompleteMode { constraints = constraints.filter({ self.containers[$0.identifier] != nil }) } // Since this is a versioned container, none of its // dependencies can have a revision constraints. let incompatibleConstraints: [(PackageReference, String)] incompatibleConstraints = constraints.compactMap({ switch $0.requirement { case .versionSet: return nil case .revision(let revision): return ($0.identifier, revision) case .unversioned: // FIXME: Maybe we should have metadata inside unversion to signify // if its a local or edited dependency. We add edited constraints // as inputs so it shouldn't really matter because an edited // requirement can't be specified in the manifest file. return ($0.identifier, "local") } }) // If we have any revision constraints, set the error and abort. guard incompatibleConstraints.isEmpty else { self.error = DependencyResolverError.incompatibleConstraints( dependency: (container.identifier, version.description), revisions: incompatibleConstraints) return AnySequence([]) } return merge(constraints: constraints, binding: .version(version)) })) } if allExclusions.isEmpty { // Ensure we can cache this sequence. result = AnySequence(CacheableSequence(result)) _resolveSubtreeCache[cacheKey] = result } return result } /// Find all solutions for `constraints` with the results merged into the `assignment`. /// /// - Parameters: /// - constraints: The input list of constraints to solve. /// - assignment: The assignment to merge the result into. /// - allConstraints: An additional set of constraints on the viable solutions. /// - allExclusions: A set of package assignments to exclude from consideration. /// - Returns: A sequence of all valid satisfying assignment, in order of preference. private func merge( constraints: [PackageContainerConstraint], into assignment: VersionAssignmentSet, subjectTo allConstraints: PackageContainerConstraintSet, excluding allExclusions: [PackageReference: Set<Version>] ) -> AnySequence<VersionAssignmentSet> { guard self.error == nil else { return AnySequence([]) } var allConstraints = allConstraints // Never prefetch when running in incomplete mode. if !isInIncompleteMode && isPrefetchingEnabled { prefetch(containers: constraints.map({ $0.identifier })) } // Update the active constraint set to include all active constraints. // // We want to put all of these constraints in up front so that we are // more likely to get back a viable solution. // // FIXME: We should have a test for this, probably by adding some kind // of statistics on the number of backtracks. for constraint in constraints { guard let merged = allConstraints.merging(constraint) else { return AnySequence([]) } allConstraints = merged } // Perform an (eager) reduction merging each container into the (lazy) // sequence of possible assignments. // // NOTE: What we are *accumulating* here is a lazy sequence (of // solutions) satisfying some number of the constraints; the final lazy // sequence is effectively one which has all of the constraints // merged. Thus, the reduce itself can be eager since the result is // lazy. return AnySequence(constraints .map({ $0.identifier }) .reduce(AnySequence([(assignment, allConstraints)]), { (possibleAssignments, identifier) -> AnySequence<(VersionAssignmentSet, PackageContainerConstraintSet)> in // If we had encountered any error, return early. guard self.error == nil else { return AnySequence([]) } // Get the container. // // Failures here will immediately abort the solution, although in // theory one could imagine attempting to find a solution not // requiring this container. It isn't clear that is something we // would ever want to handle at this level. // // FIXME: Making these methods throwing will kill the lazy behavior, guard let container = safely({ try getContainer(for: identifier) }) else { return AnySequence([]) } // Return a new lazy sequence merging all possible subtree solutions into all possible incoming // assignments. return AnySequence(possibleAssignments.lazy.flatMap({ value -> AnySequence<(VersionAssignmentSet, PackageContainerConstraintSet)> in let (assignment, allConstraints) = value let subtree = self.resolveSubtree(container, subjectTo: allConstraints, excluding: allExclusions) return AnySequence(subtree.lazy.compactMap({ subtreeAssignment -> (VersionAssignmentSet, PackageContainerConstraintSet)? in // We found a valid subtree assignment, attempt to merge it with the // current solution. guard let newAssignment = assignment.merging(subtreeAssignment) else { // The assignment couldn't be merged with the current // assignment, or the constraint sets couldn't be merged. // // This happens when (a) the subtree has a package overlapping // with a previous subtree assignment, and (b) the subtrees // needed to resolve different versions due to constraints not // present in the top-down constraint set. return nil } // Update the working assignment and constraint set. // // This should always be feasible, because all prior constraints // were part of the input constraint request (see comment around // initial `merge` outside the loop). guard let merged = allConstraints.merging(subtreeAssignment.constraints) else { preconditionFailure("unsatisfiable constraints while merging subtree") } // We found a valid assignment and updated constraint set. return (newAssignment, merged) })) })) }) .lazy .map({ $0.0 })) } /// Executes the body and return the value if the body doesn't throw. /// Returns nil if the body throws and save the error. private func safely<T>(_ body: () throws -> T) -> T? { do { return try body() } catch { self.error = error } return nil } // MARK: Container Management /// Condition for container management structures. private let fetchCondition = Condition() /// The active set of managed containers. public var containers: [PackageReference: Container] { return fetchCondition.whileLocked({ _fetchedContainers.spm_flatMapValues({ try? $0.get() }) }) } /// The list of fetched containers. private var _fetchedContainers: [PackageReference: Swift.Result<Container, AnyError>] = [:] /// The set of containers requested so far. private var _prefetchingContainers: Set<PackageReference> = [] /// Get the container for the given identifier, loading it if necessary. fileprivate func getContainer(for identifier: PackageReference) throws -> Container { return try fetchCondition.whileLocked { // Return the cached container, if available. if let container = _fetchedContainers[identifier] { return try container.get() } // If this container is being prefetched, wait for that to complete. while _prefetchingContainers.contains(identifier) { fetchCondition.wait() } // The container may now be available in our cache if it was prefetched. if let container = _fetchedContainers[identifier] { return try container.get() } // Otherwise, fetch the container synchronously. let container = try await { provider.getContainer(for: identifier, skipUpdate: skipUpdate, completion: $0) } self._fetchedContainers[identifier] = .success(container) return container } } /// Starts prefetching the given containers. private func prefetch(containers identifiers: [PackageReference]) { fetchCondition.whileLocked { // Process each container. for identifier in identifiers { // Skip if we're already have this container or are pre-fetching it. guard _fetchedContainers[identifier] == nil, !_prefetchingContainers.contains(identifier) else { continue } // Otherwise, record that we're prefetching this container. _prefetchingContainers.insert(identifier) provider.getContainer(for: identifier, skipUpdate: skipUpdate) { container in self.fetchCondition.whileLocked { // Update the structures and signal any thread waiting // on prefetching to finish. self._fetchedContainers[identifier] = container self._prefetchingContainers.remove(identifier) self.fetchCondition.signal() } } } } } } /// The resolver debugger. /// /// Finds the constraints which results in graph being unresolvable. private struct ResolverDebugger { enum Error: Swift.Error { /// Reached the time limit without completing the algorithm. case reachedTimeLimit } /// Reference to the resolver. unowned let resolver: DependencyResolver /// Create a new debugger. init(_ resolver: DependencyResolver) { self.resolver = resolver } /// The time limit in seconds after which we abort finding a solution. let timeLimit = 10.0 /// Returns the constraints which should be removed in order to make the /// graph resolvable. /// /// We use delta debugging algoritm to find the smallest set of constraints /// which can be removed from the input in order to make the graph /// satisfiable. /// /// This algorithm can be exponential, so we abort after the predefined time limit. func debug( dependencies inputDependencies: [PackageContainerConstraint], pins inputPins: [PackageContainerConstraint] ) throws -> (dependencies: [PackageContainerConstraint], pins: [PackageContainerConstraint]) { // Form the dependencies array. // // We iterate over the inputs and fetch all the dependencies for // unversioned requirements as the unversioned requirements are not // relevant to the dependency resolution. var dependencies = [PackageContainerConstraint]() for constraint in inputDependencies { if constraint.requirement == .unversioned { // Ignore the errors here. do { let container = try resolver.getContainer(for: constraint.identifier) dependencies += try container.getUnversionedDependencies() } catch {} } else { dependencies.append(constraint) } } // Form a set of all unversioned dependencies. let unversionedDependencies = Set(inputDependencies.filter({ $0.requirement == .unversioned }).map({ $0.identifier })) // Remove the unversioned constraints from dependencies and pins. dependencies = dependencies.filter({ !unversionedDependencies.contains($0.identifier) }) let pins = inputPins.filter({ !unversionedDependencies.contains($0.identifier) }) // Put the resolver in incomplete mode to avoid cloning new repositories. resolver.isInIncompleteMode = true let deltaAlgo = DeltaAlgorithm<ResolverChange>() let allPackages = Set(dependencies.map({ $0.identifier })) // Compute the set of changes. let allChanges: Set<ResolverChange> = { var set = Set<ResolverChange>() set.formUnion(dependencies.map({ ResolverChange.allowPackage($0.identifier) })) set.formUnion(pins.map({ ResolverChange.allowPin($0.identifier) })) return set }() // Compute the current time. let startTime = NSDate().timeIntervalSince1970 var timeLimitReached = false // Run the delta debugging algorithm. let badChanges = try deltaAlgo.run(changes: allChanges) { changes in // Check if we reached the time limits. timeLimitReached = timeLimitReached || (NSDate().timeIntervalSince1970 - startTime) >= timeLimit // If we reached the time limit, throw. if timeLimitReached { throw Error.reachedTimeLimit } // Find the set of changes we want to allow in this predicate. let allowedChanges = allChanges.subtracting(changes) // Find the packages which are allowed and disallowed to participate // in this changeset. let allowedPackages = Set(allowedChanges.compactMap({ $0.allowedPackage })) let disallowedPackages = allPackages.subtracting(allowedPackages) // Start creating constraints. // // First, add all the package dependencies. var constraints = dependencies // Set all disallowed packages to unversioned, so they stay out of resolution. constraints += disallowedPackages.map({ PackageContainerConstraint(container: $0, requirement: .unversioned) }) let allowedPins = Set(allowedChanges.compactMap({ $0.allowedPin })) // It is always a failure if this changeset contains a pin of // a disallowed package. if allowedPins.first(where: disallowedPackages.contains) != nil { return false } // Finally, add the allowed pins. constraints += pins.filter({ allowedPins.contains($0.identifier) }) return try satisfies(constraints) } // Filter the input with found result and return. let badDependencies = Set(badChanges.compactMap({ $0.allowedPackage })) let badPins = Set(badChanges.compactMap({ $0.allowedPin })) return ( dependencies: dependencies.filter({ badDependencies.contains($0.identifier) }), pins: pins.filter({ badPins.contains($0.identifier) }) ) } /// Returns true if the constraints are satisfiable. func satisfies(_ constraints: [PackageContainerConstraint]) throws -> Bool { do { _ = try resolver.resolve(constraints: constraints, pins: []) return true } catch DependencyResolverError.unsatisfiable { return false } } /// Represents a single change which should introduced during delta debugging. enum ResolverChange: Hashable { /// Allow the package with the given identifier. case allowPackage(PackageReference) /// Allow the pins with the given identifier. case allowPin(PackageReference) /// Returns the allowed pin identifier. var allowedPin: PackageReference? { if case let .allowPin(identifier) = self { return identifier } return nil } // Returns the allowed package identifier. var allowedPackage: PackageReference? { if case let .allowPackage(identifier) = self { return identifier } return nil } } }
41.897275
165
0.632941
9caa237eda02e8043524583da0cbd2e94554becd
2,998
// // main.swift // aoc-day4 // // Created by Frank Guchelaar on 06/12/2016. // Copyright © 2016 Awesomation. All rights reserved. // import Foundation var input = try String(contentsOfFile: "day4/input.txt") var roomStrings = input .trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) .components(separatedBy: CharacterSet.newlines) extension String { func rollCharacters(by: Int) -> String { return self.unicodeScalars.reduce("", { (result, scalar) in // a == 97 let newScalar = (((scalar.value + UInt32(by)) - 97) % 26) + 97 return result + String(Character(UnicodeScalar(newScalar)!)) }) } } struct Room { var encryptedName : [String] let sectorId : Int let checksum : String init(withString string: String) { let charactersRegex = try! NSRegularExpression(pattern: "[a-z]+", options: .caseInsensitive) let matches = charactersRegex.matches(in: string, options: .reportCompletion, range: NSMakeRange(0, string.characters.count)) self.encryptedName = matches.map({ (result) -> String in let range = string.rangeFromNSRange(aRange: result.range) let part = string.substring(with: range) return part }) checksum = self.encryptedName.removeLast() let digitsRegex = try! NSRegularExpression(pattern: "\\d+", options: .caseInsensitive) let match = digitsRegex.firstMatch(in: string, options: .reportCompletion, range: NSMakeRange(0, string.characters.count)) sectorId = Int(string.substring(with: string.rangeFromNSRange(aRange: match!.range)))! } func name() -> String { return self.encryptedName.map { $0.rollCharacters(by: self.sectorId) }.joined(separator: " ") } private func calculateChecksum() -> String { let characterMap = encryptedName.joined().characterMap() let sorted = characterMap.sorted {a,b in return (a.value > b.value) || (a.value == b.value && a.key < b.key) } var cs = "" for idx in 0..<5 { cs.append(sorted[idx].0) } return cs } func isReal() -> Bool { let calculated = self.calculateChecksum() return checksum.localizedCaseInsensitiveCompare(calculated) == .orderedSame } } let rooms = roomStrings.map { (roomString) -> Room in return Room(withString: roomString) } //: ## Part One let realRooms = rooms.reduce(0, { (result, room) in if room.isReal() { return result + room.sectorId } else { return result } }) print (realRooms) //: ## Part Two //: I've checked the results to find the proper room name... let room = rooms.first { (room) -> Bool in return room.name().localizedCaseInsensitiveCompare("northpole object storage") == .orderedSame } print (room!.sectorId)
28.826923
133
0.611741
b963beedec2ba71a7f84a7820041c3c8e42b52fa
2,328
import BuildArtifacts import EmceeLogging import Foundation import PathLib import ResourceLocation import TypedResourceLocation public final class BuildArtifactsPreparerImpl: BuildArtifactsPreparer { private let localTypedResourceLocationPreparer: LocalTypedResourceLocationPreparer private let logger: ContextualLogger public init( localTypedResourceLocationPreparer: LocalTypedResourceLocationPreparer, logger: ContextualLogger ) { self.localTypedResourceLocationPreparer = localTypedResourceLocationPreparer self.logger = logger } public func prepare(buildArtifacts: BuildArtifacts) throws -> BuildArtifacts { try remotelyAccessibleBuildArtifacts(buildArtifacts: buildArtifacts) } private func remotelyAccessibleBuildArtifacts( buildArtifacts: BuildArtifacts ) throws -> BuildArtifacts { let remotelyAccessibleTestBundle = XcTestBundle( location: try localTypedResourceLocationPreparer.generateRemotelyAccessibleTypedResourceLocation(buildArtifacts.xcTestBundle.location), testDiscoveryMode: buildArtifacts.xcTestBundle.testDiscoveryMode ) switch buildArtifacts { case .iosLogicTests: return .iosLogicTests( xcTestBundle: remotelyAccessibleTestBundle ) case .iosApplicationTests(_, let appBundle): return .iosApplicationTests( xcTestBundle: remotelyAccessibleTestBundle, appBundle: try localTypedResourceLocationPreparer.generateRemotelyAccessibleTypedResourceLocation(appBundle) ) case .iosUiTests(_, let appBundle, let runner, let additionalApplicationBundles): return .iosUiTests( xcTestBundle: remotelyAccessibleTestBundle, appBundle: try localTypedResourceLocationPreparer.generateRemotelyAccessibleTypedResourceLocation(appBundle), runner: try localTypedResourceLocationPreparer.generateRemotelyAccessibleTypedResourceLocation(runner), additionalApplicationBundles: try additionalApplicationBundles.map { try localTypedResourceLocationPreparer.generateRemotelyAccessibleTypedResourceLocation($0) } ) } } }
43.111111
147
0.727234
87a61938b18975677161bdfd6157c7bba201e199
13,566
// SPDX-License-Identifier: MIT // Copyright © 2018-2020 WireGuard LLC. All Rights Reserved. import UIKit import SystemConfiguration.CaptiveNetwork import NetworkExtension protocol SSIDOptionEditTableViewControllerDelegate: class { func ssidOptionSaved(option: ActivateOnDemandViewModel.OnDemandSSIDOption, ssids: [String]) } class SSIDOptionEditTableViewController: UITableViewController { private enum Section: Hashable { case ssidOption case selectedSSIDs case addSSIDs } private struct SSIDEntry: Equatable, Hashable { let uuid = UUID().uuidString var string: String func hash(into hasher: inout Hasher) { hasher.combine(uuid) } static func == (lhs: SSIDEntry, rhs: SSIDEntry) -> Bool { return lhs.uuid == rhs.uuid } } private enum Item: Hashable { case ssidOption(ActivateOnDemandViewModel.OnDemandSSIDOption) case selectedSSID(SSIDEntry) case noSSID case addConnectedSSID(String) case addNewSSID } weak var delegate: SSIDOptionEditTableViewControllerDelegate? private var dataSource: TableViewDiffableDataSource<Section, Item>? private let ssidOptionFields: [ActivateOnDemandViewModel.OnDemandSSIDOption] = [ .anySSID, .onlySpecificSSIDs, .exceptSpecificSSIDs ] private var selectedOption: ActivateOnDemandViewModel.OnDemandSSIDOption private var selectedSSIDs: [SSIDEntry] private var connectedSSID: String? init(option: ActivateOnDemandViewModel.OnDemandSSIDOption, ssids: [String]) { selectedOption = option selectedSSIDs = ssids.map { SSIDEntry(string: $0) } super.init(style: .grouped) } private func makeCell(for itemIdentifier: Item, at indexPath: IndexPath) -> UITableViewCell? { guard let dataSource = self.dataSource else { return nil } let sectionIdentifier = dataSource.snapshot().sectionIdentifiers[indexPath.section] switch sectionIdentifier { case .ssidOption: return ssidOptionCell(for: tableView, itemIdentifier: itemIdentifier, at: indexPath) case .selectedSSIDs: switch itemIdentifier { case .noSSID: return noSSIDsCell(for: tableView, at: indexPath) case .selectedSSID(let ssidEntry): return selectedSSIDCell(for: tableView, ssidEntry: ssidEntry, at: indexPath) default: fatalError() } case .addSSIDs: return addSSIDCell(for: tableView, itemIdentifier: itemIdentifier, at: indexPath) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = tr("tunnelOnDemandSSIDViewTitle") dataSource = TableViewDiffableDataSource(tableView: tableView) { [weak self] _, indexPath, item -> UITableViewCell? in return self?.makeCell(for: item, at: indexPath) } tableView.dataSource = self tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableView.automaticDimension tableView.register(CheckmarkCell.self) tableView.register(EditableTextCell.self) tableView.register(TextCell.self) tableView.isEditing = true tableView.allowsSelectionDuringEditing = true tableView.keyboardDismissMode = .onDrag updateDataSource() updateConnectedSSID() } private func updateConnectedSSID() { getConnectedSSID { [weak self] ssid in guard let self = self else { return } self.connectedSSID = ssid self.updateDataSource() } } private func getConnectedSSID(completionHandler: @escaping (String?) -> Void) { #if targetEnvironment(simulator) completionHandler("Simulator Wi-Fi") #else if #available(iOS 14, *) { NEHotspotNetwork.fetchCurrent { hotspotNetwork in completionHandler(hotspotNetwork?.ssid) } } else { if let supportedInterfaces = CNCopySupportedInterfaces() as? [CFString] { for interface in supportedInterfaces { if let networkInfo = CNCopyCurrentNetworkInfo(interface) { if let ssid = (networkInfo as NSDictionary)[kCNNetworkInfoKeySSID as String] as? String { completionHandler(!ssid.isEmpty ? ssid : nil) return } } } } completionHandler(nil) } #endif } private func updateDataSource(completion: (() -> Void)? = nil) { var snapshot = DiffableDataSourceSnapshot<Section, Item>() snapshot.appendSections([.ssidOption]) snapshot.appendItems(ssidOptionFields.map { .ssidOption($0) }, toSection: .ssidOption) if selectedOption != .anySSID { snapshot.appendSections([.selectedSSIDs, .addSSIDs]) if selectedSSIDs.isEmpty { snapshot.appendItems([.noSSID], toSection: .selectedSSIDs) } else { snapshot.appendItems(selectedSSIDs.map { .selectedSSID($0) }, toSection: .selectedSSIDs) } if let connectedSSID = connectedSSID, !selectedSSIDs.contains(where: { $0.string == connectedSSID }) { snapshot.appendItems([.addConnectedSSID(connectedSSID)], toSection: .addSSIDs) } snapshot.appendItems([.addNewSSID], toSection: .addSSIDs) } dataSource?.apply(snapshot, animatingDifferences: true, completion: completion) } override func viewWillDisappear(_ animated: Bool) { delegate?.ssidOptionSaved(option: selectedOption, ssids: selectedSSIDs.map { $0.string }) } } extension SSIDOptionEditTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return dataSource?.numberOfSections(in: tableView) ?? 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource?.tableView(tableView, numberOfRowsInSection: section) ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return dataSource!.tableView(tableView, cellForRowAt: indexPath) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { guard let dataSource = dataSource else { return false } let sectionIdentifier = dataSource.snapshot().sectionIdentifiers[indexPath.section] switch sectionIdentifier { case .ssidOption: return false case .selectedSSIDs: return !selectedSSIDs.isEmpty case .addSSIDs: return true } } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { guard let dataSource = dataSource else { return .none } let sectionIdentifier = dataSource.snapshot().sectionIdentifiers[indexPath.section] switch sectionIdentifier { case .ssidOption: return .none case .selectedSSIDs: return .delete case .addSSIDs: return .insert } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard let dataSource = dataSource else { return nil } let sectionIdentifier = dataSource.snapshot().sectionIdentifiers[section] switch sectionIdentifier { case .ssidOption: return nil case .selectedSSIDs: return tr("tunnelOnDemandSectionTitleSelectedSSIDs") case .addSSIDs: return tr("tunnelOnDemandSectionTitleAddSSIDs") } } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard let dataSource = dataSource else { return } let sectionIdentifier = dataSource.snapshot().sectionIdentifiers[indexPath.section] switch sectionIdentifier { case .ssidOption: assertionFailure() case .selectedSSIDs: assert(editingStyle == .delete) selectedSSIDs.remove(at: indexPath.row) updateDataSource() case .addSSIDs: assert(editingStyle == .insert) let itemIdentifier = dataSource.itemIdentifier(for: indexPath) switch itemIdentifier { case .addConnectedSSID(let connectedSSID): appendSSID(connectedSSID, beginEditing: false) case .addNewSSID: appendSSID("", beginEditing: true) default: fatalError() } } } private func ssidOptionCell(for tableView: UITableView, itemIdentifier: Item, at indexPath: IndexPath) -> UITableViewCell { guard case .ssidOption(let field) = itemIdentifier else { fatalError() } let cell: CheckmarkCell = tableView.dequeueReusableCell(for: indexPath) cell.message = field.localizedUIString cell.isChecked = selectedOption == field cell.isEditing = false return cell } private func noSSIDsCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell: TextCell = tableView.dequeueReusableCell(for: indexPath) cell.message = tr("tunnelOnDemandNoSSIDs") if #available(iOS 13.0, *) { cell.setTextColor(.secondaryLabel) } else { cell.setTextColor(.gray) } cell.setTextAlignment(.center) return cell } private func selectedSSIDCell(for tableView: UITableView, ssidEntry: SSIDEntry, at indexPath: IndexPath) -> UITableViewCell { let cell: EditableTextCell = tableView.dequeueReusableCell(for: indexPath) cell.message = ssidEntry.string cell.placeholder = tr("tunnelOnDemandSSIDTextFieldPlaceholder") cell.isEditing = true cell.onValueBeingEdited = { [weak self] cell, text in guard let self = self else { return } if let row = self.tableView.indexPath(for: cell)?.row { self.selectedSSIDs[row].string = text self.updateDataSource() } } return cell } private func addSSIDCell(for tableView: UITableView, itemIdentifier: Item, at indexPath: IndexPath) -> UITableViewCell { let cell: TextCell = tableView.dequeueReusableCell(for: indexPath) cell.isEditing = true switch itemIdentifier { case .addConnectedSSID(let connectedSSID): cell.message = tr(format: "tunnelOnDemandAddMessageAddConnectedSSID (%@)", connectedSSID) case .addNewSSID: cell.message = tr("tunnelOnDemandAddMessageAddNewSSID") default: fatalError() } return cell } } extension SSIDOptionEditTableViewController { override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { guard let sectionIdentifier = dataSource?.snapshot().sectionIdentifiers[indexPath.section] else { return nil } switch sectionIdentifier { case .ssidOption, .addSSIDs: return indexPath case .selectedSSIDs: return nil } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let dataSource = dataSource else { return } tableView.deselectRow(at: indexPath, animated: true) let itemIdentifier = dataSource.itemIdentifier(for: indexPath) switch itemIdentifier { case .ssidOption(let newOption): setSSIDOption(newOption) case .addConnectedSSID(let connectedSSID): appendSSID(connectedSSID, beginEditing: false) case .addNewSSID: appendSSID("", beginEditing: true) default: break } } private func appendSSID(_ newSSID: String, beginEditing: Bool) { guard let dataSource = dataSource else { return } let newEntry = SSIDEntry(string: newSSID) selectedSSIDs.append(newEntry) updateDataSource { let indexPath = dataSource.indexPath(for: .selectedSSID(newEntry))! if let cell = self.tableView.cellForRow(at: indexPath) as? EditableTextCell, beginEditing { cell.beginEditing() } } } private func setSSIDOption(_ ssidOption: ActivateOnDemandViewModel.OnDemandSSIDOption) { guard let dataSource = dataSource, ssidOption != selectedOption else { return } let prevOption = selectedOption selectedOption = ssidOption // Manually update cells let indexPathForPrevItem = dataSource.indexPath(for: .ssidOption(prevOption))! let indexPathForSelectedItem = dataSource.indexPath(for: .ssidOption(selectedOption))! if let cell = tableView.cellForRow(at: indexPathForPrevItem) as? CheckmarkCell { cell.isChecked = false } if let cell = tableView.cellForRow(at: indexPathForSelectedItem) as? CheckmarkCell { cell.isChecked = true } updateDataSource() } }
35.420366
137
0.645806
8f530e8ecb18e6bc5ac551f5048d8b025983155e
1,096
import Foundation import CoreTelephony @objc(CallHooks) class CallHooks : CDVPlugin { static var callCenter:CTCallCenter = CTCallCenter() @objc(callEnded:) func callEnded(_ command: CDVInvokedUrlCommand) { CallHooks.callCenter.callEventHandler = { (call:CTCall!) in switch call.callState { case CTCallStateConnected: print("CTCallStateConnected") let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "OFFHOOK") pluginResult?.setKeepCallbackAs(true) self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) case CTCallStateDisconnected: print("CTCallStateDisconnected") let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "IDLE") pluginResult?.setKeepCallbackAs(true) self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) default: break } } } }
36.533333
101
0.619526
7a8e3f9eccee4af98a8f1adc88e0fa7f73406cf3
1,336
// // CDAKQRDACustodian.swift // CDAKit // // Created by Eric Whitley on 2/16/16. // Copyright © 2016 Eric Whitley. All rights reserved. // import Foundation import Mustache open class CDAKQRDACustodian { open var ids: [CDAKCDAIdentifier] = [] open var person: CDAKPerson? //I see no cases where this is used in CDA open var organization: CDAKOrganization? } extension CDAKQRDACustodian: CustomStringConvertible { public var description: String { return "CDAKQRDACustodian => ids: \(ids), person:\(person?.description ?? ""), organization:\(organization?.description ?? "nil"))" } } extension CDAKQRDACustodian: MustacheBoxable { var boxedValues: [String:MustacheBox] { return [ "ids" : Box(ids), "person" : Box(person), "organization" : Box(organization) ] } public var mustacheBox: MustacheBox { return Box(boxedValues) } } extension CDAKQRDACustodian: CDAKJSONExportable { public var jsonDict: [String: AnyObject] { var dict: [String: AnyObject] = [:] if ids.count > 0 { dict["ids"] = ids.map({$0.jsonDict}) as AnyObject? } if let person = person { dict["person"] = person.jsonDict as AnyObject? } if let organization = organization { dict["organization"] = organization.jsonDict as AnyObject? } return dict } }
25.207547
135
0.668413
7633aa2ed11be3e1f4c28b5f5a2cd7cbc6c0e530
752
// // NextExample.ViewController.swift // autolayout+viewcode+swift // // Created by João Vitor Duarte Mariucio on 10/02/22. // import Foundation import UIKit extension Module.NextExample { class ViewController: UIViewController { let mainView = View() override func loadView() { view = mainView } override func viewDidLoad() { super.viewDidLoad() mainView.headerView.leftButton.addTarget( self, action: #selector(backButton(_:)), for: .touchUpInside ) } @objc func backButton(_ sender: UIButton) { navigationController?.popViewController(animated: true) } } }
20.324324
67
0.573138
189362e472d8d1c31ebf9d2684d35b9501382fe7
2,552
// // RecipeFactory.swift // CoodingTests // // Created by Kamil Tustanowski on 28/07/2019. // Copyright © 2019 Kamil Tustanowski. All rights reserved. // import Foundation @testable import Core struct RecipeFactory { static func pancakes() -> [Step] { return [Step(description: "Prepare blender", dependencies: [Dependency(name: "blender")], ingredients: nil, duration: .minutes(59)), Step(description: "Add 1.25 glass of buttermilk to the blender", dependencies: [Dependency(name: "blender")], ingredients: [Ingredient(name: "glass off buttermilk", quantity: 1.25)]), Step(description: "Add 0.25 glass of powdered sugar to the blender", dependencies: [Dependency(name: "blender")], ingredients: [Ingredient(name: "glass of powdered sugar", quantity: 0.25)]), Step(description: "Add 1 heaping teaspoon of baking powder to the blender", dependencies: [Dependency(name: "blender")], ingredients: [Ingredient(name: "heaping teaspoon of baking powder", quantity: 1.0)]), Step(description: "Add 1 teaspoon of baking soda to the blender", dependencies: [Dependency(name: "blender")], ingredients: [Ingredient(name: "teaspoon of baking soda", quantity: 1.0)], duration: .minutes(2)), Step(description: "Add 1 pinch of salt to the blender", dependencies: [Dependency(name: "blender")], ingredients: [Ingredient(name: "pinch of salt", quantity: 1.0)]), Step(description: "Blend everything in a blender to a smooth mass with the consistency of thick cream", dependencies: [Dependency(name: "blender")]), Step(description: "Preheat the frying pan", dependencies: [Dependency(name: "frying pan")]), Step(description: "Fry pancakes on both sides in a frying pan over medium heat", dependencies: [Dependency(name: "frying pan")], duration: 256.0)] } static func veryLongDescriptions() -> [Step] { return [Step(description: .loremIpsumLong, dependencies: [Dependency(name: "frying pan")], duration: .hours(3)), Step(description: .loremIpsumMedium, dependencies: [Dependency(name: "frying pan")], duration: .hours(3))] } }
54.297872
119
0.583856
d5176f893d883bdc4b80c326da7b0d7d05796a25
10,544
//===--- main.swift -------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // This is just a driver for performance overview tests. import TestsUtils import DriverUtils import Ackermann import AngryPhonebook import AnyHashableWithAClass import Array2D import ArrayAppend import ArrayInClass import ArrayLiteral import ArrayOfGenericPOD import ArrayOfGenericRef import ArrayOfPOD import ArrayOfRef import ArraySetElement import ArraySubscript import BinaryFloatingPointConversionFromBinaryInteger import BinaryFloatingPointProperties import BitCount import Breadcrumbs import BucketSort import ByteSwap import COWTree import COWArrayGuaranteedParameterOverhead import CString import CSVParsing import Calculator import CaptureProp import ChaCha import ChainedFilterMap import CharacterLiteralsLarge import CharacterLiteralsSmall import CharacterProperties import Chars import ClassArrayGetter import Codable import Combos import DataBenchmarks import DeadArray import DevirtualizeProtocolComposition import DictOfArraysToArrayOfDicts import DictTest import DictTest2 import DictTest3 import DictTest4 import DictTest4Legacy import DictionaryBridge import DictionaryBridgeToObjC import DictionaryCompactMapValues import DictionaryCopy import DictionaryGroup import DictionaryKeysContains import DictionaryLiteral import DictionaryOfAnyHashableStrings import DictionaryRemove import DictionarySubscriptDefault import DictionarySwap import Diffing import DiffingMyers import DropFirst import DropLast import DropWhile import ErrorHandling import Exclusivity import ExistentialPerformance import Fibonacci import FindStringNaive import FlattenList import FloatingPointParsing import FloatingPointPrinting import Hanoi import Hash import Histogram import InsertCharacter import IntegerParsing import Integrate import IterateData import Join import LazyFilter import LinkedList import LuhnAlgoEager import LuhnAlgoLazy import MapReduce import Memset import MonteCarloE import MonteCarloPi import NibbleSort import NIOChannelPipeline import NSDictionaryCastToSwift import NSError #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import NSStringConversion #endif import NopDeinit import ObjectAllocation #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import ObjectiveCBridging import ObjectiveCBridgingStubs #if !(SWIFT_PACKAGE || Xcode) import ObjectiveCNoBridgingStubs #endif #endif import ObserverClosure import ObserverForwarderStruct import ObserverPartiallyAppliedMethod import ObserverUnappliedMethod import OpaqueConsumingUsers import OpenClose import Phonebook import PointerArithmetics import PolymorphicCalls import PopFront import PopFrontGeneric import Prefix import PrefixWhile import Prims import PrimsNonStrongRef import PrimsSplit import ProtocolDispatch import ProtocolDispatch2 import Queue import RC4 import RGBHistogram import Radix2CooleyTukey import RandomShuffle import RandomValues import RangeAssignment import RangeIteration import RangeOverlaps import RangeReplaceableCollectionPlusDefault import RecursiveOwnedParameter import ReduceInto import RemoveWhere import ReversedCollections import RomanNumbers import SequenceAlgos import SetTests import SevenBoom import Sim2DArray import SortArrayInClass import SortIntPyramids import SortLargeExistentials import SortLettersInPlace import SortStrings import StackPromo import StaticArray import StrComplexWalk import StrToInt import StringBuilder import StringComparison import StringEdits import StringEnum import StringInterpolation import StringMatch import StringRemoveDupes import StringReplaceSubrange import StringTests import StringWalk import Substring import Suffix import SuperChars import TwoSum import TypeFlood import UTF8Decode import Walsh import WordCount import XorLoop @inline(__always) private func registerBenchmark(_ bench: BenchmarkInfo) { registeredBenchmarks.append(bench) } @inline(__always) private func registerBenchmark< S : Sequence >(_ infos: S) where S.Element == BenchmarkInfo { registeredBenchmarks.append(contentsOf: infos) } registerBenchmark(Ackermann) registerBenchmark(AngryPhonebook) registerBenchmark(AnyHashableWithAClass) registerBenchmark(Array2D) registerBenchmark(ArrayAppend) registerBenchmark(ArrayInClass) registerBenchmark(ArrayLiteral) registerBenchmark(ArrayOfGenericPOD) registerBenchmark(ArrayOfGenericRef) registerBenchmark(ArrayOfPOD) registerBenchmark(ArrayOfRef) registerBenchmark(ArraySetElement) registerBenchmark(ArraySubscript) registerBenchmark(BinaryFloatingPointConversionFromBinaryInteger) registerBenchmark(BinaryFloatingPointPropertiesBinade) registerBenchmark(BinaryFloatingPointPropertiesNextUp) registerBenchmark(BinaryFloatingPointPropertiesUlp) registerBenchmark(BitCount) registerBenchmark(Breadcrumbs) registerBenchmark(BucketSort) registerBenchmark(ByteSwap) registerBenchmark(COWTree) registerBenchmark(COWArrayGuaranteedParameterOverhead) registerBenchmark(CString) registerBenchmark(CSVParsing) registerBenchmark(Calculator) registerBenchmark(CaptureProp) registerBenchmark(ChaCha) registerBenchmark(ChainedFilterMap) registerBenchmark(CharacterLiteralsLarge) registerBenchmark(CharacterLiteralsSmall) registerBenchmark(CharacterPropertiesFetch) registerBenchmark(CharacterPropertiesStashed) registerBenchmark(CharacterPropertiesStashedMemo) registerBenchmark(CharacterPropertiesPrecomputed) registerBenchmark(Chars) registerBenchmark(Codable) registerBenchmark(Combos) registerBenchmark(ClassArrayGetter) registerBenchmark(DataBenchmarks) registerBenchmark(DeadArray) registerBenchmark(DevirtualizeProtocolComposition) registerBenchmark(DictOfArraysToArrayOfDicts) registerBenchmark(Dictionary) registerBenchmark(Dictionary2) registerBenchmark(Dictionary3) registerBenchmark(Dictionary4) registerBenchmark(Dictionary4Legacy) registerBenchmark(DictionaryBridge) registerBenchmark(DictionaryBridgeToObjC) registerBenchmark(DictionaryCompactMapValues) registerBenchmark(DictionaryCopy) registerBenchmark(DictionaryGroup) registerBenchmark(DictionaryKeysContains) registerBenchmark(DictionaryLiteral) registerBenchmark(DictionaryOfAnyHashableStrings) registerBenchmark(DictionaryRemove) registerBenchmark(DictionarySubscriptDefault) registerBenchmark(DictionarySwap) registerBenchmark(Diffing) registerBenchmark(DiffingMyers) registerBenchmark(DropFirst) registerBenchmark(DropLast) registerBenchmark(DropWhile) registerBenchmark(ErrorHandling) registerBenchmark(Exclusivity) registerBenchmark(ExistentialPerformance) registerBenchmark(Fibonacci) registerBenchmark(FindStringNaive) registerBenchmark(FlattenListLoop) registerBenchmark(FlattenListFlatMap) registerBenchmark(FloatingPointParsing) registerBenchmark(FloatingPointPrinting) registerBenchmark(Hanoi) registerBenchmark(HashTest) registerBenchmark(Histogram) registerBenchmark(InsertCharacter) registerBenchmark(IntegerParsing) registerBenchmark(IntegrateTest) registerBenchmark(IterateData) registerBenchmark(Join) registerBenchmark(LazyFilter) registerBenchmark(LinkedList) registerBenchmark(LuhnAlgoEager) registerBenchmark(LuhnAlgoLazy) registerBenchmark(MapReduce) registerBenchmark(Memset) registerBenchmark(MonteCarloE) registerBenchmark(MonteCarloPi) registerBenchmark(NSDictionaryCastToSwift) registerBenchmark(NSErrorTest) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) registerBenchmark(NSStringConversion) #endif registerBenchmark(NibbleSort) registerBenchmark(NIOChannelPipeline) registerBenchmark(NopDeinit) registerBenchmark(ObjectAllocation) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) registerBenchmark(ObjectiveCBridging) registerBenchmark(ObjectiveCBridgingStubs) #if !(SWIFT_PACKAGE || Xcode) registerBenchmark(ObjectiveCNoBridgingStubs) #endif #endif registerBenchmark(ObserverClosure) registerBenchmark(ObserverForwarderStruct) registerBenchmark(ObserverPartiallyAppliedMethod) registerBenchmark(ObserverUnappliedMethod) registerBenchmark(OpaqueConsumingUsers) registerBenchmark(OpenClose) registerBenchmark(Phonebook) registerBenchmark(PointerArithmetics) registerBenchmark(PolymorphicCalls) registerBenchmark(PopFront) registerBenchmark(PopFrontArrayGeneric) registerBenchmark(Prefix) registerBenchmark(PrefixWhile) registerBenchmark(Prims) registerBenchmark(PrimsNonStrongRef) registerBenchmark(PrimsSplit) registerBenchmark(ProtocolDispatch) registerBenchmark(ProtocolDispatch2) registerBenchmark(QueueGeneric) registerBenchmark(QueueConcrete) registerBenchmark(RC4Test) registerBenchmark(RGBHistogram) registerBenchmark(Radix2CooleyTukey) registerBenchmark(RandomShuffle) registerBenchmark(RandomValues) registerBenchmark(RangeAssignment) registerBenchmark(RangeIteration) registerBenchmark(RangeOverlaps) registerBenchmark(RangeReplaceableCollectionPlusDefault) registerBenchmark(RecursiveOwnedParameter) registerBenchmark(ReduceInto) registerBenchmark(RemoveWhere) registerBenchmark(ReversedCollections) registerBenchmark(RomanNumbers) registerBenchmark(SequenceAlgos) registerBenchmark(SetTests) registerBenchmark(SevenBoom) registerBenchmark(Sim2DArray) registerBenchmark(SortArrayInClass) registerBenchmark(SortIntPyramids) registerBenchmark(SortLargeExistentials) registerBenchmark(SortLettersInPlace) registerBenchmark(SortStrings) registerBenchmark(StackPromo) registerBenchmark(StaticArrayTest) registerBenchmark(StrComplexWalk) registerBenchmark(StrToInt) registerBenchmark(StringBuilder) registerBenchmark(StringComparison) registerBenchmark(StringEdits) registerBenchmark(StringEnum) registerBenchmark(StringHashing) registerBenchmark(StringInterpolation) registerBenchmark(StringInterpolationSmall) registerBenchmark(StringInterpolationManySmallSegments) registerBenchmark(StringMatch) registerBenchmark(StringNormalization) registerBenchmark(StringRemoveDupes) registerBenchmark(StringReplaceSubrange) registerBenchmark(StringTests) registerBenchmark(StringWalk) registerBenchmark(SubstringTest) registerBenchmark(Suffix) registerBenchmark(SuperChars) registerBenchmark(TwoSum) registerBenchmark(TypeFlood) registerBenchmark(UTF8Decode) registerBenchmark(Walsh) registerBenchmark(WordCount) registerBenchmark(XorLoop) main()
28.420485
80
0.879173
0a4ecf646bbfa9e60ff3fc55d204065b0ad31918
1,263
// // TestFrameworkDemoUITests.swift // TestFrameworkDemoUITests // // Created by green on 15/11/5. // Copyright © 2015年 city8.go. All rights reserved. // import XCTest class TestFrameworkDemoUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.135135
182
0.66825
9b14f3670acb1bd6526bc1f419e1b49e89ca187a
690
// // Common.swift // GMDemo // // Created by gavin on 2021/12/22. // import Foundation import UIKit extension UIViewController { public var topPresentedViewController: UIViewController { return presentedViewController?.topPresentedViewController ?? self } public static var rootViewController: UIViewController? { let keyWindow = UIApplication.shared.windows.first { window in return window.isKeyWindow } return keyWindow?.rootViewController?.topPresentedViewController } } extension UIApplication { public var getFirstKeyWindow: UIWindow? { self.windows.first(where: { $0.isKeyWindow }) } }
22.258065
74
0.686957
2f58f8840b0117771514cc112a36377fdfa41135
534
/* Question - Palindrome Permutation Link - > https://leetcode.com/explore/featured/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3588/ */ class Solution { func canPermutePalindrome(_ s: String) -> Bool { if(s.isEmpty) { return true } var dict = [Character:Int]() for i in s { if let entry = dict[i] { dict[i] = nil } else { dict[i] = 1 } } if (dict.count == 1 || dict.count == 0) { return true } return false } }
20.538462
127
0.56367
6998ce32386f397072e9bd7a429e631d50c1c4e1
1,296
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ public struct VCEntitiesConstants { static let SELF_ISSUED = "https://self-issued.me" // TODO: temporary until deterministic key generation is implemented. public static let MASTER_ID = "master" // key actions in a DID Document public static let SIGNING_KEYID_PREFIX = "sign_" public static let UPDATE_KEYID_PREFIX = "update_" public static let RECOVER_KEYID_PREFIX = "recover_" // JWK public key public static let SUPPORTED_PUBLICKEY_TYPE = "EcdsaSecp256k1VerificationKey2019" public static let PUBLICKEY_AUTHENTICATION_PURPOSE_V1 = "authentication" public static let PUBLICKEY_AUTHENTICATION_PURPOSE_V0 = "auth" public static let PUBLICKEY_GENERAL_PURPOSE_V0 = "general" // OIDC Protocol public static let RESPONSE_TYPE = "id_token" public static let RESPONSE_MODE = "form_post" public static let SCOPE = "openid did_authn" public static let PIN = "pin" }
44.689655
95
0.631944
1a0cfafb71656040afff79dbc2b87c1abce121ae
509
// // CryptoCurrency.swift // CurrencyConverter // // Created by Ali Arda İsenkul on 22.01.2022. // import Foundation // MARK: - Welcome struct CryptoCurrency: Codable { let query: Query let data: [String: Double] } // MARK: - Query struct Query: Codable { let apikey: String let timestamp: Int let base_currency: String } struct Crypto : Decodable { var name: String var value : Double } struct Conversion{ var sourceN: Int var SourceT:String var targetT: String }
15.90625
46
0.67387