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
e51851a6324f10180d4a4b40c13ac29fdcb3dc76
17,384
// // EthereumClientTests.swift // web3sTests // // Created by Matt Marshall on 09/03/2018. // Copyright © 2018 Argent Labs Limited. All rights reserved. // import XCTest @testable import web3swift import BigInt struct TransferMatchingSignatureEvent: ABIEvent { public static let name = "Transfer" public static let types: [ABIType.Type] = [ EthereumAddress.self , EthereumAddress.self , BigUInt.self] public static let typesIndexed = [true, true, false] public let log: EthereumLog public let from: EthereumAddress public let to: EthereumAddress public let value: BigUInt public init?(topics: [ABIDecoder.DecodedValue], data: [ABIDecoder.DecodedValue], log: EthereumLog) throws { try TransferMatchingSignatureEvent.checkParameters(topics, data) self.log = log self.from = try topics[0].decoded() self.to = try topics[1].decoded() self.value = try data[0].decoded() } } class EthereumClientTests: XCTestCase { var client: EthereumClient? var account: EthereumAccount? let timeout = 10.0 override func setUp() { super.setUp() self.client = EthereumClient(url: URL(string: TestConfig.clientUrl)!) self.account = try? EthereumAccount(keyStorage: TestEthereumKeyStorage(privateKey: TestConfig.privateKey)) print("Public address: \(self.account?.address ?? "NONE")") } override func tearDown() { super.tearDown() } func testEthGetBalance() { let expectation = XCTestExpectation(description: "get remote balance") client?.eth_getBalance(address: account?.address ?? "", block: .Latest, completion: { (error, balance) in XCTAssertNotNil(balance, "Balance not available: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthGetBalanceIncorrectAddress() { let expectation = XCTestExpectation(description: "get remote balance incorrect") client?.eth_getBalance(address: "0xnig42niog2", block: .Latest, completion: { (error, balance) in XCTAssertNotNil(error, "Balance error not available") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testNetVersion() { let expectation = XCTestExpectation(description: "get net version") client?.net_version(completion: { (error, network) in XCTAssertEqual(network, EthereumNetwork.Ropsten, "Network incorrect: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthGasPrice() { let expectation = XCTestExpectation(description: "get gas price") client?.eth_gasPrice(completion: { (error, gas) in XCTAssertNotNil(gas, "Gas not available: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthBlockNumber() { let expectation = XCTestExpectation(description: "get current block number") client?.eth_blockNumber(completion: { (error, block) in XCTAssertNotNil(block, "Block not available: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthGetCode() { let expectation = XCTestExpectation(description: "get contract code") client?.eth_getCode(address: "0x112234455c3a32fd11230c42e7bccd4a84e02010", completion: { (error, code) in XCTAssertNotNil(code, "Contract code not available: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthSendRawTransaction() { let expectation = XCTestExpectation(description: "send raw transaction") let tx = EthereumTransaction(from: nil, to: EthereumAddress("0x3c1bd6b420448cf16a389c8b0115ccb3660bb854"), value: BigUInt(1600000), data: nil, nonce: 2, gasPrice: BigUInt(4000000), gasLimit: BigUInt(50000), chainId: EthereumNetwork.Ropsten.intValue) self.client?.eth_sendRawTransaction(tx, withAccount: self.account!, completion: { (error, txHash) in XCTAssertNotNil(txHash, "No tx hash, ensure key is valid in TestConfig.swift") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthGetTransactionCount() { let expectation = XCTestExpectation(description: "get transaction receipt") client?.eth_getTransactionCount(address: account!.address, block: .Latest, completion: { (error, count) in XCTAssertNotNil(count, "Transaction count not available: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthGetTransactionCountPending() { let expectation = XCTestExpectation(description: "get transaction receipt") client?.eth_getTransactionCount(address: account!.address, block: .Pending, completion: { (error, count) in XCTAssertNotNil(count, "Transaction count not available: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthGetTransactionReceipt() { let expectation = XCTestExpectation(description: "get transaction receipt") let txHash = "0xc51002441dc669ad03697fd500a7096c054b1eb2ce094821e68831a3666fc878" client?.eth_getTransactionReceipt(txHash: txHash, completion: { (error, receipt) in XCTAssertNotNil(receipt, "Transaction receipt not available: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testEthCall() { let expectation = XCTestExpectation(description: "send raw transaction") let tx = EthereumTransaction(from: nil, to: EthereumAddress("0x3c1bd6b420448cf16a389c8b0115ccb3660bb854"), value: BigUInt(1800000), data: nil, nonce: 2, gasPrice: BigUInt(400000), gasLimit: BigUInt(50000), chainId: EthereumNetwork.Ropsten.intValue) client?.eth_call(tx, block: .Latest, completion: { (error, txHash) in XCTAssertNotNil(txHash, "Transaction hash not available: \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testSimpleEthGetLogs() { let expectation = XCTestExpectation(description: "get logs") client?.eth_getLogs(addresses: ["0x23d0a442580c01e420270fba6ca836a8b2353acb"], topics: nil, fromBlock: .Earliest, toBlock: .Latest, completion: { (error, logs) in XCTAssertNotNil(logs, "Logs not available \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testOrTopicsEthGetLogs() { let expectation = XCTestExpectation(description: "get logs") // Deposit/Withdrawal event to specific address client?.eth_getLogs(addresses: nil, orTopics: [["0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c", "0x7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65"], ["0x000000000000000000000000655ef694b98e55977a93259cb3b708560869a8f3"]], fromBlock: .Number(6540313), toBlock: .Number(6540397), completion: { (error, logs) in XCTAssertEqual(logs?.count, 2) XCTAssertNotNil(logs, "Logs not available \(error?.localizedDescription ?? "no error")") expectation.fulfill() }) wait(for: [expectation], timeout: timeout) } func testGivenGenesisBlock_ThenReturnsByNumber() { let expectation = XCTestExpectation(description: "get block by number") client?.eth_getBlockByNumber(.Number(0)) { error, block in XCTAssertNil(error) XCTAssertEqual(block?.timestamp.timeIntervalSince1970, 0) XCTAssertEqual(block?.transactions.count, 0) XCTAssertEqual(block?.number, .Number(0)) expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenLatestBlock_ThenReturnsByNumber() { let expectation = XCTestExpectation(description: "get block by number") client?.eth_getBlockByNumber(.Latest) { error, block in XCTAssertNil(error) XCTAssertNotNil(block?.number.intValue) expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenExistingBlock_ThenGetsBlockByNumber() { let expectation = XCTestExpectation(description: "get block by number") client?.eth_getBlockByNumber(.Number(3415757)) { error, block in XCTAssertNil(error) XCTAssertEqual(block?.number, .Number(3415757)) XCTAssertEqual(block?.timestamp.timeIntervalSince1970, 1528711895) XCTAssertEqual(block?.transactions.count, 40) XCTAssertEqual(block?.transactions.first, "0x387867d052b3f89fb87937572891118aa704c1ba604c157bbd9c5a07f3a7e5cd") expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenUnexistingBlockNumber_ThenGetBlockByNumberReturnsError() { let expectation = XCTestExpectation(description: "get block by number") client?.eth_getBlockByNumber(.Number(Int.max)) { error, block in XCTAssertNotNil(error) XCTAssertNil(block) expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenMinedTransactionHash_ThenGetsTransactionByHash() { let expectation = XCTestExpectation(description: "get transaction by hash") client?.eth_getTransaction(byHash: "0x014726c783ab2fd6828a9ca556850bccfc66f70926f411274eaf886385c704af") { error, transaction in XCTAssertNil(error) XCTAssertEqual(transaction?.from?.value, "0xbbf5029fd710d227630c8b7d338051b8e76d50b3") XCTAssertEqual(transaction?.to.value, "0x37f13b5ffcc285d2452c0556724afb22e58b6bbe") XCTAssertEqual(transaction?.gas, "30400") XCTAssertEqual(transaction?.gasPrice, BigUInt(hex: "0x9184e72a000")) XCTAssertEqual(transaction?.nonce, 973253) XCTAssertEqual(transaction?.value, BigUInt(hex: "0x56bc75e2d63100000")) XCTAssertEqual(transaction?.blockNumber, EthereumBlock.Number(3439303)) XCTAssertEqual(transaction?.hash?.web3.hexString, "0x014726c783ab2fd6828a9ca556850bccfc66f70926f411274eaf886385c704af") expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenUnexistingTransactionHash_ThenErrorsGetTransactionByHash() { let expectation = XCTestExpectation(description: "get transaction by hash") client?.eth_getTransaction(byHash: "0x01234") { error, transaction in XCTAssertNotNil(error) XCTAssertNil(transaction) expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenNoFilters_WhenMatchingSingleTransferEvents_AllEventsReturned() { let expectation = XCTestExpectation(description: "get events") let to = try! ABIEncoder.encode(EthereumAddress("0x3C1Bd6B420448Cf16A389C8b0115CCB3660bB854")) client?.getEvents(addresses: nil, topics: [try! ERC20Events.Transfer.signature(), nil, to.hexString, nil], fromBlock: .Earliest, toBlock: .Latest, eventTypes: [ERC20Events.Transfer.self]) { (error, events, logs) in XCTAssertNil(error) XCTAssertEqual(events.count, 2) XCTAssertEqual(logs.count, 0) expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenNoFilters_WhenMatchingMultipleTransferEvents_BothEventsReturned() { let expectation = XCTestExpectation(description: "get events") let to = try! ABIEncoder.encode(EthereumAddress("0x3C1Bd6B420448Cf16A389C8b0115CCB3660bB854")) client?.getEvents(addresses: nil, topics: [try! ERC20Events.Transfer.signature(), nil, to.hexString, nil], fromBlock: .Earliest, toBlock: .Latest, eventTypes: [ERC20Events.Transfer.self, TransferMatchingSignatureEvent.self]) { (error, events, logs) in XCTAssertNil(error) XCTAssertEqual(events.count, 4) XCTAssertEqual(logs.count, 0) expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenContractFilter_WhenMatchingSingleTransferEvents_OnlyMatchingSourceEventReturned() { let expectation = XCTestExpectation(description: "get events") let to = try! ABIEncoder.encodeRaw("0x3C1Bd6B420448Cf16A389C8b0115CCB3660bB854", forType: ABIRawType.FixedAddress) let filters = [ EventFilter(type: ERC20Events.Transfer.self, allowedSenders: [EthereumAddress("0xdb0040451f373949a4be60dcd7b6b8d6e42658b6")]) ] client?.getEvents(addresses: nil, topics: [try! ERC20Events.Transfer.signature(), nil, to.hexString, nil], fromBlock: .Earliest, toBlock: .Latest, matching: filters) { (error, events, logs) in XCTAssertNil(error) XCTAssertEqual(events.count, 1) XCTAssertEqual(logs.count, 1) expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func testGivenContractFilter_WhenMatchingMultipleTransferEvents_OnlyMatchingSourceEventsReturned() { let expectation = XCTestExpectation(description: "get events") let to = try! ABIEncoder.encode(EthereumAddress("0x3C1Bd6B420448Cf16A389C8b0115CCB3660bB854")) let filters = [ EventFilter(type: ERC20Events.Transfer.self, allowedSenders: [EthereumAddress("0xdb0040451f373949a4be60dcd7b6b8d6e42658b6")]), EventFilter(type: TransferMatchingSignatureEvent.self, allowedSenders: [EthereumAddress("0xdb0040451f373949a4be60dcd7b6b8d6e42658b6")]) ] client?.getEvents(addresses: nil, topics: [try! ERC20Events.Transfer.signature(), nil, to.hexString, nil], fromBlock: .Earliest, toBlock: .Latest, matching: filters) { (error, events, logs) in XCTAssertNil(error) XCTAssertEqual(events.count, 2) XCTAssertEqual(logs.count, 2) expectation.fulfill() } wait(for: [expectation], timeout: timeout) } func test_GivenDynamicArrayResponse_ThenCallReceivesData() { let expect = expectation(description: "call") let function = GetGuardians(wallet: EthereumAddress("0x2A6295C34b4136F2C3c1445c6A0338D784fe0ddd")) function.call(withClient: self.client!, responseType: GetGuardians.Response.self) { (error, response) in XCTAssertNil(error) XCTAssertEqual(response?.guardians, [EthereumAddress("0x44fe11c90d2bcbc8267a0e56d55235ddc2b96c4f")]) expect.fulfill() } waitForExpectations(timeout: 10) } } struct GetGuardians: ABIFunction { static let name = "getGuardians" let contract = EthereumAddress("0x25BD64224b7534f7B9e3E16dd10b6dED1A412b90") let from: EthereumAddress? = EthereumAddress("0x25BD64224b7534f7B9e3E16dd10b6dED1A412b90") let gasPrice: BigUInt? = nil let gasLimit: BigUInt? = nil struct Response: ABIResponse { static var types: [ABIType.Type] = [ABIArray<EthereumAddress>.self] let guardians: [EthereumAddress] init?(values: [ABIDecoder.DecodedValue]) throws { self.guardians = try values[0].decodedArray() } } let wallet: EthereumAddress func encode(to encoder: ABIFunctionEncoder) throws { try encoder.encode(wallet) } }
43.029703
356
0.634319
5b83915eee01cd5bb9295670851bba0b527bc565
2,226
// // SunPlace.swift // SunriseSunset // // Created by Jake Runzer on 2016-07-25. // Copyright © 2016 Puddllee. All rights reserved. // import Foundation import UIKit import CoreLocation class SunPlace: Equatable { var location: CLLocationCoordinate2D? var placeID: String var timeZoneOffset: Int? var primary: String var secondary: String var isNotification: Bool = false class func sunPlaceFromString(_ string: String) -> SunPlace? { let split = string.split{$0 == "|"}.map(String.init) if split.count < 5 { return nil } let primary = split[0] let secondary = split[1] let latitude = Double(split[2])! let longitude = Double(split[3])! let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let placeID = split[4] let timeZoneOffset = split.count >= 6 ? Int(split[5]) : nil let isNotification = split.count >= 7 ? split[6] == "true" : false return SunPlace(primary: primary, secondary: secondary, location: location, placeID: placeID, timeZoneOffset: timeZoneOffset, isNotification: isNotification) } init(primary: String, secondary: String, placeID: String) { self.primary = primary self.secondary = secondary self.placeID = placeID } init(primary: String, secondary: String, location: CLLocationCoordinate2D, placeID: String, timeZoneOffset: Int?, isNotification: Bool) { self.primary = primary self.secondary = secondary self.location = location self.placeID = placeID self.timeZoneOffset = timeZoneOffset self.isNotification = isNotification } var toString: String? { guard let location = location else { return nil } let tzOffset = timeZoneOffset == nil ? "" : "\(timeZoneOffset!)" return "\(primary)|\(secondary)|\(location.latitude)|\(location.longitude)|\(placeID)|\(tzOffset)|\(isNotification)" } } func ==(lhs: SunPlace, rhs: SunPlace) -> Bool { return lhs.placeID == rhs.placeID }
29.289474
165
0.61186
edaa480a5d89ce71808b91e7333d6328afa96942
1,404
// // FilmeAPI.swift // MLIF // // Created by Rafael Teixeira Martins on 05/06/20. // Copyright © 2020 Rafael Teixeira Martins. All rights reserved. // import UIKit import Alamofire class TrendMediaAPI: NSObject { //MARK: - GET func recoveryTrendMovies(completion:@escaping() -> Void) { AF.request("https://api.themoviedb.org/3/trending/all/week?api_key=fce1620169267c457d7e75e3f6dcf6a0&language=pt-BR", method: .get).responseJSON { (response) in switch response.result { case .success: if let responseJSON = response.value as? Dictionary<String, Any> { guard let listMovies = responseJSON["results"] as? Array<Dictionary<String, Any>> else { return } for dictionaryMovie in listMovies { if (dictionaryMovie["media_type"] as? String == "movie"){ MovieDAO().saveMovie(dictionaryMovie: dictionaryMovie) } else if (dictionaryMovie["media_type"] as? String == "tv") { MovieDAO().saveTVShow(dictionaryTVShow: dictionaryMovie) } } completion() } break case .failure: print(response.error!) completion() break } } } }
34.243902
167
0.540598
67d1ee93cc2354e3be1cb7960749f9e1ff2c8eef
265
import Combine import CoreLocation import Foundation @objc public protocol DeprecatedLocationManager { var isAvailable: Bool { get } weak var delegate: DeprecatedLocationManagerDelegate? { get set } var distanceFilter: CLLocationDistance { get set } }
24.090909
69
0.777358
648743c5b83790fa8dbddd499869ca49633c3b3a
3,959
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import GRPC import GRPCSampleData import NIOCore import NIOPosix /// Tests unary throughput by sending requests on a single connection. /// /// Requests are sent in batches of (up-to) 100 requests. This is due to /// https://github.com/apple/swift-nio-http2/issues/87#issuecomment-483542401. class Unary: ServerProvidingBenchmark { private let useNIOTSIfAvailable: Bool private let useTLS: Bool private var group: EventLoopGroup! private(set) var client: Echo_EchoClient! let requestCount: Int let requestText: String init(requests: Int, text: String, useNIOTSIfAvailable: Bool, useTLS: Bool) { self.useNIOTSIfAvailable = useNIOTSIfAvailable self.useTLS = useTLS self.requestCount = requests self.requestText = text super.init( providers: [MinimalEchoProvider()], useNIOTSIfAvailable: useNIOTSIfAvailable, useTLS: useTLS ) } override func setUp() throws { try super.setUp() if self.useNIOTSIfAvailable { self.group = PlatformSupport.makeEventLoopGroup(loopCount: 1) } else { self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1) } let channel: ClientConnection if self.useTLS { #if canImport(NIOSSL) channel = ClientConnection.usingTLSBackedByNIOSSL(on: self.group) .withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate])) .withTLS(serverHostnameOverride: "localhost") .connect(host: "127.0.0.1", port: self.server.channel.localAddress!.port!) #else fatalError("NIOSSL must be imported to use TLS") #endif } else { channel = ClientConnection.insecure(group: self.group) .connect(host: "127.0.0.1", port: self.server.channel.localAddress!.port!) } self.client = .init(channel: channel) } override func run() throws -> Int { var messages = 0 let batchSize = 100 for lowerBound in stride(from: 0, to: self.requestCount, by: batchSize) { let upperBound = min(lowerBound + batchSize, self.requestCount) let requests = (lowerBound ..< upperBound).map { _ in client.get(Echo_EchoRequest.with { $0.text = self.requestText }).response } messages += requests.count try EventLoopFuture.andAllSucceed(requests, on: self.group.next()).wait() } return messages } override func tearDown() throws { try self.client.channel.close().wait() try self.group.syncShutdownGracefully() try super.tearDown() } } /// Tests bidirectional throughput by sending requests over a single stream. class Bidi: Unary { let batchSize: Int init(requests: Int, text: String, batchSize: Int, useNIOTSIfAvailable: Bool, useTLS: Bool) { self.batchSize = batchSize super.init( requests: requests, text: text, useNIOTSIfAvailable: useNIOTSIfAvailable, useTLS: useTLS ) } override func run() throws -> Int { var messages = 0 let update = self.client.update { _ in } for _ in stride(from: 0, to: self.requestCount, by: self.batchSize) { let batch = (0 ..< self.batchSize).map { _ in Echo_EchoRequest.with { $0.text = self.requestText } } messages += batch.count update.sendMessages(batch, promise: nil) } update.sendEnd(promise: nil) _ = try update.status.wait() return messages } }
30.453846
94
0.689821
22a16ba7635b2f42a2030a8615701edf42f72c59
7,261
// // LyricsView.swift // SpotlightLyrics // // Created by Lyt on 9/28/20. // open class LyricsView: NSView { private let cellIdentifier: NSUserInterfaceItemIdentifier = .init(rawValue: "LyricsCell") private var parser: LyricsParser? = nil private var lyricsViewModels: [LyricsCellViewModel] = [] private var lastIndex: Int? = nil private(set) public var timer: LyricsViewTimer = LyricsViewTimer() private var scrollViewHadScrolledByUser = false private let scrollView: NSScrollView = { let scrollView = NSScrollView() scrollView.drawsBackground = false scrollView.backgroundColor = .clear return scrollView }() private lazy var tableView: NSTableView = { let tableView = NSTableView() tableView.dataSource = self tableView.delegate = self tableView.selectionHighlightStyle = .none tableView.headerView = nil tableView.gridColor = .clear tableView.wantsLayer = true tableView.backgroundColor = .clear return tableView }() // MARK: Public properties public var currentLyric: String? { get { guard let lastIndex = lastIndex else { return nil } guard lastIndex < lyricsViewModels.count else { return nil } return lyricsViewModels[lastIndex].lyric } } public var lyrics: String? = nil { didSet { reloadViewModels() } } public var lyricFont: NSFont = .systemFont(ofSize: 14) { didSet { reloadViewModels() } } public var lyricHighlightedFont: NSFont = .systemFont(ofSize: 24) { didSet { reloadViewModels() } } public var lyricTextColor: NSColor = .labelColor { didSet { reloadViewModels() } } public var lyricHighlightedTextColor: NSColor = .selectedTextColor { didSet { reloadViewModels() } } public var lineSpacing: CGFloat = 16 { didSet { reloadViewModels() } } // MARK: Initializations override init(frame: CGRect) { super.init(frame: frame) setupLayout() setupBinding() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { NotificationCenter.default.removeObserver(self) } private func setupBinding() { scrollView.postsFrameChangedNotifications = true NotificationCenter.default.addObserver(self, selector: #selector(scrollViewDidEndLiveScroll(notification:)), name: NSScrollView.willStartLiveScrollNotification, object: scrollView) } private func setupLayout() { timer.lyricsView = self addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.documentView = tableView NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), scrollView.topAnchor.constraint(equalTo: topAnchor, constant: 8), scrollView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8), scrollView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), scrollView.widthAnchor.constraint(greaterThanOrEqualToConstant: 400) ]) let column = NSTableColumn(identifier: cellIdentifier) column.minWidth = 400 tableView.addTableColumn(column) } } extension LyricsView: NSTableViewDataSource { public func numberOfRows(in tableView: NSTableView) -> Int { lyricsViewModels.count } public func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { let cellViewModel = lyricsViewModels[row] return lineSpacing + cellViewModel.calcHeight(containerWidth: bounds.width) } public func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let view = tableView.makeView(withIdentifier: cellIdentifier, owner: self) as? LyricsCell ?? LyricsCell() view.update(with: lyricsViewModels[row]) return view } } extension LyricsView: NSTableViewDelegate { private func reloadViewModels() { scrollViewHadScrolledByUser = false lyricsViewModels.removeAll() guard let lyrics = lyrics?.emptyToNil() else { tableView.reloadData() return } parser = LyricsParser(lyrics: lyrics) for lyric in parser!.lyrics { let viewModel = LyricsCellViewModel.cellViewModel(lyric: lyric.text, font: lyricFont, highlightedFont: lyricHighlightedFont, textColor: lyricTextColor, highlightedTextColor: lyricHighlightedTextColor ) lyricsViewModels.append(viewModel) } tableView.reloadData() enclosingScrollView?.contentInsets = NSEdgeInsets(top: frame.height / 2, left: 0, bottom: frame.height / 2, right: 0) } internal func scroll(toTime time: TimeInterval, animated: Bool) { guard !scrollViewHadScrolledByUser, let lyrics = parser?.lyrics else { return } guard let index = lyrics.index(where: { $0.time >= time }) else { // when no lyric is before the time passed in means scrolling to the first if (lyricsViewModels.count > 0) { tableView.scrollToBeginningOfDocument(nil) } return } guard lastIndex == nil || index - 1 != lastIndex else { return } if let lastIndex = lastIndex, lyricsViewModels.count > lastIndex { lyricsViewModels[lastIndex].highlighted = false } if index > 0, lyricsViewModels.count >= index { lyricsViewModels[index - 1].highlighted = true tableView.centreRow(row: index - 1, animated: true) lastIndex = index - 1 } } } private extension LyricsView { @objc func scrollViewDidEndLiveScroll(notification: Notification) { scrollViewHadScrolledByUser = true } } private extension NSTableView { func centreRow(row: Int, animated: Bool) { guard numberOfRows > row else { return } selectRowIndexes(IndexSet.init(integer: row), byExtendingSelection: false) let rowRect = frameOfCell(atColumn: 0, row: row) if let scrollView = enclosingScrollView { let centredPoint = NSMakePoint(0.0, rowRect.origin.y + (rowRect.size.height / 2) - ((scrollView.frame.size.height) / 2)) if animated { scrollView.contentView.animator().setBoundsOrigin(centredPoint) } else { scroll(centredPoint) } } } }
31.569565
132
0.598402
d9bbbfd69bd19fe40e2674f0ba75511092765fb5
11,464
// // QULFavoritesTableViewController.swift // Kluegste Nacht // // Created by Tilo Westermann on 03/06/15. // Copyright (c) 2015 Quality and Usability Lab, Telekom Innovation Laboratories, TU Berlin. All rights reserved. // import UIKit import Alamofire class QULFavoritesTableViewController: UITableViewController { var stationInfo: NSDictionary! var data: Array<NSDictionary> = [] let deviceId = UIDevice.currentDevice().identifierForVendor.UUIDString var host: String! var viewName: String! override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 290.0 tableView.rowHeight = UITableViewAutomaticDimension if host == nil { host = "http://favorites.kluegste-nacht.de/listv2/?d=\(deviceId)" viewName = "Favorites" } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) Alamofire.request(.GET, host) .responseJSON { (_, _, JSON, _) in if !(JSON is NSNull) { self.data = JSON as! Array<NSDictionary> self.tableView.reloadData() } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showEventStationOnMap" { let cityMapController = segue.destinationViewController as! QULCityMapViewController cityMapController.selectedStationId = (sender as! UIButton).tag } } @IBAction func didSelectLocationButton(sender: UIButton) { let point: CGPoint = tableView!.convertPoint(sender.center, fromView: sender.superview) let indexPath: NSIndexPath = tableView!.indexPathForRowAtPoint(point)! performSegueWithIdentifier("showEventStationOnMap", sender: sender) } @IBAction func didSelectFavoriteButton(sender: UIButton) { let point: CGPoint = tableView!.convertPoint(sender.center, fromView: sender.superview) let indexPath: NSIndexPath = tableView!.indexPathForRowAtPoint(point)! var route: NSDictionary = data[indexPath.section] var events = route["events"] as! Array<NSDictionary> let event: NSDictionary = events[indexPath.row] let eventId = event["id"] as! String let favorite = event["favorite"] as! Bool let markUnmark = favorite ? "unmark" : "mark" let urlString = "http://favorites.kluegste-nacht.de/\(markUnmark)/?id=\(eventId)&d=\(UIDevice.currentDevice().identifierForVendor.UUIDString)" Alamofire.request(.GET, urlString) .responseString { (_, _, string, _) in if self.viewName == "Favorites" { self.tableView.beginUpdates() events.removeAtIndex(indexPath.row) if events.count == 0 { self.data.removeAtIndex(indexPath.section) self.tableView.deleteSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic) } else { var newRoute:NSDictionary = route.mutableCopy() as! NSDictionary newRoute.setValue(events, forKey: "events") self.data[indexPath.section] = newRoute self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } self.tableView.endUpdates() } else { sender.selected = !favorite } } } @IBAction func didSelectShareButton(sender: UIButton) { let point: CGPoint = tableView!.convertPoint(sender.center, fromView: sender.superview) let indexPath: NSIndexPath = tableView!.indexPathForRowAtPoint(point)! let route: NSDictionary = data[indexPath.section] let events = route["events"] as! Array<NSDictionary> let event: NSDictionary = events[indexPath.row] let eventName = event["titel"] as! String let text = "\(eventName) #lndw2015" let appURL: NSURL! = NSURL(string: "http://app.kluegste-nacht.de") let activityViewController = UIActivityViewController(activityItems: [text], applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList] self.presentViewController(activityViewController, animated: true) { () -> Void in let eventId = event["id"] as! String } } } extension QULFavoritesTableViewController : UITableViewDataSource { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return data.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let route: NSDictionary = data[section] if let events = route["events"] as? Array<NSDictionary> { return events.count } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let route: NSDictionary = data[indexPath.section] let events = route["events"] as! Array<NSDictionary> var cell:QULExhibitionCell = tableView.dequeueReusableCellWithIdentifier("exhibitionCell") as! QULExhibitionCell cell.backgroundColor = UIColor.clearColor() let event: NSDictionary = events[indexPath.row] var content = "" if let description = event["beschreibung"] as? String { content += description } if let additionalText = event["zusatztext"] as? String { content += content == "" ? "" : "\n\n" content += additionalText } var additionalInformation = "" if let location = event["ort"] as? String { additionalInformation += "Ort: \(location)" } if let time = event["zeit"] as? String { additionalInformation += additionalInformation == "" ? "" : "\n" additionalInformation += "Zeit: \(time)" } if let subinstitution = event["untereinrichtung"] as? String { additionalInformation += additionalInformation == "" ? "" : "\n" additionalInformation += "Untereinrichtung: \(subinstitution)" } if let type = event["veranstaltungstyp"] as? String { additionalInformation += additionalInformation == "" ? "" : "\n" additionalInformation += "Veranstaltungstyp: \(type)" } if let accessible = event["barrierefrei"] as? String { var accessibleString: String switch accessible { case "0": accessibleString = "Nein" case "1": accessibleString = "Ja" default: accessibleString = "k.A." } additionalInformation += additionalInformation == "" ? "" : "\n" additionalInformation += "Barrierefrei: \(accessibleString)" } if let programForChildren = event["kinderprogramm"] as? String { var programForChildrenString: String switch programForChildren { case "0": programForChildrenString = "Nein" case "1": programForChildrenString = "Ja" case "2": programForChildrenString = "für Kinder unter 10 Jahren" case "3": programForChildrenString = "für Kinder ab 10 Jahren" default: programForChildrenString = "k.A." } additionalInformation += additionalInformation == "" ? "" : "\n" additionalInformation += "Kinderprogramm: \(programForChildrenString)" } if additionalInformation != "" { content += "\n\n" + additionalInformation } cell.contentLabel.text = content cell.titleLabel.text = event["titel"] as? String cell.coverImageView?.image = nil cell.coverImageView?.contentMode = UIViewContentMode.ScaleAspectFill cell.coverImageView.layer.masksToBounds = true cell.coverImageView.layer.cornerRadius = 5.0 cell.favoriteButton.selected = event["favorite"] as! Bool cell.locationButton.tag = (event["stationId"] as! NSString).integerValue if let stationDict = QULDataSource.sharedInstance.station(cell.locationButton.tag)! as NSDictionary? { cell.locationButton.enabled = !(stationDict["geo1"] is NSNull) } if event["images"] != nil && !(event["images"] is NSNull) && event["images"]!.count > 0 { if let images = event["images"] as? Array<NSDictionary> { let imageDict = images[0] if let imageName = imageDict["datei"] as? String { let imageUrl = NSURL(string: "http://www.langenachtderwissenschaften.de/files/docs/resized/444x380/" + imageName) let request: NSURLRequest = NSURLRequest(URL: imageUrl!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in if error == nil { let image = UIImage(data: data) dispatch_async(dispatch_get_main_queue(), { cell.coverImageView.image = image }) } }) } } } else { cell.coverImageView.image = UIImage(named: "launchbg") } return cell } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let route: NSDictionary = data[section] if let headerTitle = route["name"] as? String { var header = QULExhibitionHeaderLabel() header.backgroundColor = UIColor.lightGrayColor() header.textColor = UIColor.darkGrayColor() header.numberOfLines = 0 header.font = UIFont.boldSystemFontOfSize(14.0) header.lineBreakMode = NSLineBreakMode.ByWordWrapping header.text = headerTitle header.sizeToFit() return header } return nil } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let route: NSDictionary = data[section] if let headerTitle = route["name"] as? String { let rect = NSString(string: headerTitle).boundingRectWithSize(CGSizeMake(CGRectGetWidth(tableView.frame)-20.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(14.0)], context: nil) return max(CGRectGetHeight(rect), 38.0) } return 0 } }
41.23741
193
0.586183
d7b98d2daad536d6607182ff7bcc3be9d8c216f7
1,637
// // AuthorizedSegue.swift // ukmdm // // Created by Yevhen Herasymenko on 12/9/17. // Copyright © 2017 UK MDM. All rights reserved. // import UIKit extension UIWindow { func set(rootViewController newRootViewController: UIViewController, withTransition transition: CATransition? = nil) { let previousViewController = rootViewController if let transition = transition { layer.add(transition, forKey: kCATransition) } rootViewController = newRootViewController if UIView.areAnimationsEnabled { UIView.animate(withDuration: CATransaction.animationDuration()) { newRootViewController.setNeedsStatusBarAppearanceUpdate() } } else { newRootViewController.setNeedsStatusBarAppearanceUpdate() } if let transitionViewClass = NSClassFromString("UITransitionView") { for subview in subviews where subview.isKind(of: transitionViewClass) { subview.removeFromSuperview() } } if let previousViewController = previousViewController { previousViewController.dismiss(animated: false) { previousViewController.view.removeFromSuperview() } } } } final class ChangeWindowRootSegue: UIStoryboardSegue { override func perform() { guard let window = source.view.window else { return } let transition = CATransition() transition.type = kCATransitionFade window.set(rootViewController: destination, withTransition: transition) } }
31.480769
83
0.649969
29b3721f9eb4f622c915d13c9b0636b381d0083b
13,291
// // Copyright (c) 2018. Uber Technologies // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import TSCUtility import MockoloFramework class Executor { let defaultTimeout = 20 // MARK: - Private private var loggingLevel: OptionArgument<Int>! private var outputFilePath: OptionArgument<String>! private var mockFileList: OptionArgument<String>! private var mockFilePaths: OptionArgument<[String]>! private var sourceDirs: OptionArgument<[String]>! private var sourceFiles: OptionArgument<[String]>! private var sourceFileList: OptionArgument<String>! private var exclusionSuffixes: OptionArgument<[String]>! private var header: OptionArgument<String>! private var macro: OptionArgument<String>! private var testableImports: OptionArgument<[String]>! private var customImports: OptionArgument<[String]>! private var excludeImports: OptionArgument<[String]>! private var annotation: OptionArgument<String>! private var useTemplateFunc: OptionArgument<Bool>! private var useMockObservable: OptionArgument<Bool>! private var mockAll: OptionArgument<Bool>! private var mockFinal: OptionArgument<Bool>! private var concurrencyLimit: OptionArgument<Int>! private var enableArgsHistory: OptionArgument<Bool>! /// Initializer. /// /// - parameter name: The name used to check if this command should /// be executed. /// - parameter overview: The overview description of this command. /// - parameter parser: The argument parser to use. init(parser: ArgumentParser) { setupArguments(with: parser) } /// Setup the arguments using the given parser. /// /// - parameter parser: The argument parser to use. private func setupArguments(with parser: ArgumentParser) { loggingLevel = parser.add(option: "--logging-level", shortName: "-l", kind: Int.self, usage: "The logging level to use. Default is set to 0 (info only). Set 1 for verbose, 2 for warning, and 3 for error.") sourceFiles = parser.add(option: "--sourcefiles", shortName: "-srcs", kind: [String].self, usage: "List of source files (separated by a comma or a space) to generate mocks for. If the --sourcedirs or --filelist value exists, this will be ignored. ", completion: .filename) sourceFileList = parser.add(option: "--filelist", shortName: "-f", kind: String.self, usage: "Path to a file containing a list of source file paths (delimited by a new line). If the --sourcedirs value exists, this will be ignored. ", completion: .filename) sourceDirs = parser.add(option: "--sourcedirs", shortName: "-s", kind: [String].self, usage: "Paths to the directories containing source files to generate mocks for. If the --filelist or --sourcefiles values exist, they will be ignored. ", completion: .filename) mockFileList = parser.add(option: "--mock-filelist", kind: String.self, usage: "Path to a file containing a list of dependent files (separated by a new line) of modules this target depends on.", completion: .filename) mockFilePaths = parser.add(option: "--mockfiles", shortName: "-mocks", kind: [String].self, usage: "List of mock files (separated by a comma or a space) from modules this target depends on. If the --mock-filelist value exists, this will be ignored.", completion: .filename) outputFilePath = parser.add(option: "--destination", shortName: "-d", kind: String.self, usage: "Output file path containing the generated Swift mock classes. If no value is given, the program will exit.", completion: .filename) exclusionSuffixes = parser.add(option: "--exclude-suffixes", shortName: "-x", kind: [String].self, usage: "List of filename suffix(es) without the file extensions to exclude from parsing (separated by a comma or a space).", completion: .filename) annotation = parser.add(option: "--annotation", shortName: "-a", kind: String.self, usage: "A custom annotation string used to indicate if a type should be mocked (default = @mockable).") macro = parser.add(option: "--macro", shortName: "-m", kind: String.self, usage: "If set, #if [macro] / #endif will be added to the generated mock file content to guard compilation.") testableImports = parser.add(option: "--testable-imports", shortName: "-i", kind: [String].self, usage: "If set, @testable import statments will be added for each module name in this list.") customImports = parser.add(option: "--custom-imports", shortName: "-c", kind: [String].self, usage: "If set, custom module imports will be added to the final import statement list.") excludeImports = parser.add(option: "--exclude-imports", kind: [String].self, usage: "If set, listed modules will be excluded from the import statements in the mock output.") header = parser.add(option: "--header", kind: String.self, usage: "A custom header documentation to be added to the beginning of a generated mock file.") useTemplateFunc = parser.add(option: "--use-template-func", kind: Bool.self, usage: "If set, a common template function will be called from all functions in mock classes (default is set to false).") useMockObservable = parser.add(option: "--use-mock-observable", kind: Bool.self, usage: "If set, a property wrapper will be used to mock RxSwift Observable variables (default is set to false).") mockAll = parser.add(option: "--mock-all", kind: Bool.self, usage: "If set, it will mock all types (protocols and classes) with a mock annotation (default is set to false and only mocks protocols with a mock annotation).") mockFinal = parser.add(option: "--mock-final", kind: Bool.self, usage: "If set, generated mock classes will have the 'final' attributes (default is set to false).") concurrencyLimit = parser.add(option: "--concurrency-limit", shortName: "-j", kind: Int.self, usage: "Maximum number of threads to execute concurrently (default = number of cores on the running machine).") enableArgsHistory = parser.add(option: "--enable-args-history", kind: Bool.self, usage: "Whether to enable args history for all functions (default = false). To enable history per function, use the 'history' keyword in the annotation argument. ") } private func fullPath(_ path: String) -> String { if path.hasPrefix("/") { return path } if path.hasPrefix("~") { let home = FileManager.default.homeDirectoryForCurrentUser.path return path.replacingOccurrences(of: "~", with: home, range: path.range(of: "~")) } return FileManager.default.currentDirectoryPath + "/" + path } /// Execute the command. /// /// - parameter arguments: The command line arguments to execute the command with. func execute(with arguments: ArgumentParser.Result) { guard let outputArg = arguments.get(outputFilePath) else { fatalError("Missing destination file path") } let outputFilePath = fullPath(outputArg) let srcDirs = arguments.get(sourceDirs)?.map(fullPath) var srcs: [String]? // If source file list exists, source files value will be overriden (see the usage in setupArguments above) if let srcList = arguments.get(sourceFileList) { let text = try? String(contentsOfFile: srcList, encoding: String.Encoding.utf8) srcs = text?.components(separatedBy: "\n").filter{!$0.isEmpty}.map(fullPath) } else { srcs = arguments.get(sourceFiles)?.map(fullPath) } if srcDirs == nil, srcs == nil { fatalError("Missing source files or directories") } var mockFilePaths: [String]? // First see if a list of mock files are stored in a file if let mockList = arguments.get(self.mockFileList) { let text = try? String(contentsOfFile: mockList, encoding: String.Encoding.utf8) mockFilePaths = text?.components(separatedBy: "\n").filter{!$0.isEmpty}.map(fullPath) } else { // If not, see if a list of mock files are directly passed in mockFilePaths = arguments.get(self.mockFilePaths)?.map(fullPath) } let concurrencyLimit = arguments.get(self.concurrencyLimit) let exclusionSuffixes = arguments.get(self.exclusionSuffixes) ?? [] let annotation = arguments.get(self.annotation) ?? String.mockAnnotation let header = arguments.get(self.header) let loggingLevel = arguments.get(self.loggingLevel) ?? 0 let macro = arguments.get(self.macro) let testableImports = arguments.get(self.testableImports) let customImports = arguments.get(self.customImports) let excludeImports = arguments.get(self.excludeImports) let shouldUseTemplateFunc = arguments.get(useTemplateFunc) ?? false let shouldUseMockObservable = arguments.get(useMockObservable) ?? false let shouldMockAll = arguments.get(mockAll) ?? false let shouldCaptureAllFuncArgsHistory = arguments.get(enableArgsHistory) ?? false let shouldMockFinal = arguments.get(mockFinal) ?? false do { try generate(sourceDirs: srcDirs, sourceFiles: srcs, parser: ParserViaSwiftSyntax(), exclusionSuffixes: exclusionSuffixes, mockFilePaths: mockFilePaths, annotation: annotation, header: header, macro: macro, declType: shouldMockAll ? .all : .protocolType, useTemplateFunc: shouldUseTemplateFunc, useMockObservable: shouldUseMockObservable, enableFuncArgsHistory: shouldCaptureAllFuncArgsHistory, mockFinal: shouldMockFinal, testableImports: testableImports, customImports: customImports, excludeImports: excludeImports, to: outputFilePath, loggingLevel: loggingLevel, concurrencyLimit: concurrencyLimit, onCompletion: { _ in log("Done. Exiting program.", level: .info) exit(0) }) } catch { fatalError("Generation error: \(error)") } } } public struct Version { /// The string value for this version. public let value: String /// The current Mockolo version. public static let current = Version(value: "1.3.0") }
56.080169
203
0.56369
1df050b8f85834d1a6430b7569e184841c5db5d6
1,151
// // YDOrmSQLAlterTableBuilder.swift // YDAppleKit // // Created by rowena on 2018/10/17. // Copyright © 2018年 wuyezhiguhun. All rights reserved. // import UIKit //为什么中间定义一个DM_SQLAlterTableBuilder? //原因:扩张 //ORM(有这样思想:映射) //案例一:xml文件->model->表(table):映射(ORM-XML方式) //案例二:json文件->model->表(table):映射(ORM-JSON方式) //案例三:model映射->model->表(table):映射(ORM-OBJ方式) //我们当前框架是基于ORM-xml配置文件的方式进行设计的 //假设有一天我改成ORM-OBj方式配置(说白了就是直接通过反射机制动态映射数据库表),但是同样又一些规范(例如:数据库的表字段和属性字段保持一致) //就如我们经常看到的FMDB原理实现 //然后这个时候你又要去写一个类吗?重复写基本SQL语句 //所以定义一个SQL语句基类 //总结:所以定义基类的目的就是为了解除耦合,解决基本的SQL语句构建和具体的ORM方案耦合问题 class YDOrmSQLAlterTableBuilder: YDSQLAlterTableBuilder { //orm:映射配置 //srcColumns:原始的字段 func alterTable(orm: YDOrm, srcColumns: [String: String]) -> YDSQLAlterTableBuilder { var columns = [String: String]() //过来已存在的字段,添加新的字段 for item in orm.items { let result = srcColumns[item.column] if (result == nil) { //注意:保存nil不行 columns[item.column] = item.columnType } } return self.alterTableAddColumnMulti(orm.tableName, columns: columns) } }
27.404762
89
0.67854
2f6749567c6e013e9c6a11456a03b7247a1a9cf1
21,962
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import Foundation import AWSSDKSwiftCore extension ConnectParticipant { //MARK: Enums public enum ChatItemType: String, CustomStringConvertible, Codable { case message = "MESSAGE" case event = "EVENT" case connectionAck = "CONNECTION_ACK" public var description: String { return self.rawValue } } public enum ConnectionType: String, CustomStringConvertible, Codable { case websocket = "WEBSOCKET" case connectionCredentials = "CONNECTION_CREDENTIALS" public var description: String { return self.rawValue } } public enum ParticipantRole: String, CustomStringConvertible, Codable { case agent = "AGENT" case customer = "CUSTOMER" case system = "SYSTEM" public var description: String { return self.rawValue } } public enum ScanDirection: String, CustomStringConvertible, Codable { case forward = "FORWARD" case backward = "BACKWARD" public var description: String { return self.rawValue } } public enum SortKey: String, CustomStringConvertible, Codable { case descending = "DESCENDING" case ascending = "ASCENDING" public var description: String { return self.rawValue } } //MARK: Shapes public struct ConnectionCredentials: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ConnectionToken", required: false, type: .string), AWSShapeMember(label: "Expiry", required: false, type: .string) ] /// The connection token. public let connectionToken: String? /// The expiration of the token. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z. public let expiry: String? public init(connectionToken: String? = nil, expiry: String? = nil) { self.connectionToken = connectionToken self.expiry = expiry } private enum CodingKeys: String, CodingKey { case connectionToken = "ConnectionToken" case expiry = "Expiry" } } public struct CreateParticipantConnectionRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ParticipantToken", location: .header(locationName: "X-Amz-Bearer"), required: true, type: .string), AWSShapeMember(label: "Type", required: true, type: .list) ] /// Participant Token as obtained from StartChatContact API response. public let participantToken: String /// Type of connection information required. public let `type`: [ConnectionType] public init(participantToken: String, type: [ConnectionType]) { self.participantToken = participantToken self.`type` = `type` } public func validate(name: String) throws { try validate(self.participantToken, name:"participantToken", parent: name, max: 1000) try validate(self.participantToken, name:"participantToken", parent: name, min: 1) try validate(self.`type`, name:"`type`", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case participantToken = "X-Amz-Bearer" case `type` = "Type" } } public struct CreateParticipantConnectionResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ConnectionCredentials", required: false, type: .structure), AWSShapeMember(label: "Websocket", required: false, type: .structure) ] /// Creates the participant's connection credentials. The authentication token associated with the participant's connection. public let connectionCredentials: ConnectionCredentials? /// Creates the participant's websocket connection. public let websocket: Websocket? public init(connectionCredentials: ConnectionCredentials? = nil, websocket: Websocket? = nil) { self.connectionCredentials = connectionCredentials self.websocket = websocket } private enum CodingKeys: String, CodingKey { case connectionCredentials = "ConnectionCredentials" case websocket = "Websocket" } } public struct DisconnectParticipantRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClientToken", required: false, type: .string), AWSShapeMember(label: "ConnectionToken", location: .header(locationName: "X-Amz-Bearer"), required: true, type: .string) ] /// A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. public let clientToken: String? /// The authentication token associated with the participant's connection. public let connectionToken: String public init(clientToken: String? = DisconnectParticipantRequest.idempotencyToken(), connectionToken: String) { self.clientToken = clientToken self.connectionToken = connectionToken } public func validate(name: String) throws { try validate(self.clientToken, name:"clientToken", parent: name, max: 500) try validate(self.connectionToken, name:"connectionToken", parent: name, max: 1000) try validate(self.connectionToken, name:"connectionToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case connectionToken = "X-Amz-Bearer" } } public struct DisconnectParticipantResponse: AWSShape { public init() { } } public struct GetTranscriptRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ConnectionToken", location: .header(locationName: "X-Amz-Bearer"), required: true, type: .string), AWSShapeMember(label: "ContactId", required: false, type: .string), AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "ScanDirection", required: false, type: .enum), AWSShapeMember(label: "SortOrder", required: false, type: .enum), AWSShapeMember(label: "StartPosition", required: false, type: .structure) ] /// The authentication token associated with the participant's connection. public let connectionToken: String /// The contactId from the current contact chain for which transcript is needed. public let contactId: String? /// The maximum number of results to return in the page. Default: 10. public let maxResults: Int? /// The pagination token. Use the value returned previously in the next subsequent request to retrieve the next set of results. public let nextToken: String? /// The direction from StartPosition from which to retrieve message. Default: BACKWARD when no StartPosition is provided, FORWARD with StartPosition. public let scanDirection: ScanDirection? /// The sort order for the records. Default: DESCENDING. public let sortOrder: SortKey? /// A filtering option for where to start. public let startPosition: StartPosition? public init(connectionToken: String, contactId: String? = nil, maxResults: Int? = nil, nextToken: String? = nil, scanDirection: ScanDirection? = nil, sortOrder: SortKey? = nil, startPosition: StartPosition? = nil) { self.connectionToken = connectionToken self.contactId = contactId self.maxResults = maxResults self.nextToken = nextToken self.scanDirection = scanDirection self.sortOrder = sortOrder self.startPosition = startPosition } public func validate(name: String) throws { try validate(self.connectionToken, name:"connectionToken", parent: name, max: 1000) try validate(self.connectionToken, name:"connectionToken", parent: name, min: 1) try validate(self.contactId, name:"contactId", parent: name, max: 256) try validate(self.contactId, name:"contactId", parent: name, min: 1) try validate(self.maxResults, name:"maxResults", parent: name, max: 100) try validate(self.maxResults, name:"maxResults", parent: name, min: 0) try validate(self.nextToken, name:"nextToken", parent: name, max: 1000) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) try self.startPosition?.validate(name: "\(name).startPosition") } private enum CodingKeys: String, CodingKey { case connectionToken = "X-Amz-Bearer" case contactId = "ContactId" case maxResults = "MaxResults" case nextToken = "NextToken" case scanDirection = "ScanDirection" case sortOrder = "SortOrder" case startPosition = "StartPosition" } } public struct GetTranscriptResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "InitialContactId", required: false, type: .string), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "Transcript", required: false, type: .list) ] /// The initial contact ID for the contact. public let initialContactId: String? /// The pagination token. Use the value returned previously in the next subsequent request to retrieve the next set of results. public let nextToken: String? /// The list of messages in the session. public let transcript: [Item]? public init(initialContactId: String? = nil, nextToken: String? = nil, transcript: [Item]? = nil) { self.initialContactId = initialContactId self.nextToken = nextToken self.transcript = transcript } private enum CodingKeys: String, CodingKey { case initialContactId = "InitialContactId" case nextToken = "NextToken" case transcript = "Transcript" } } public struct Item: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AbsoluteTime", required: false, type: .string), AWSShapeMember(label: "Content", required: false, type: .string), AWSShapeMember(label: "ContentType", required: false, type: .string), AWSShapeMember(label: "DisplayName", required: false, type: .string), AWSShapeMember(label: "Id", required: false, type: .string), AWSShapeMember(label: "ParticipantId", required: false, type: .string), AWSShapeMember(label: "ParticipantRole", required: false, type: .enum), AWSShapeMember(label: "Type", required: false, type: .enum) ] /// The time when the message or event was sent. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z. public let absoluteTime: String? /// The content of the message or event. public let content: String? /// The type of content of the item. public let contentType: String? /// The chat display name of the sender. public let displayName: String? /// The ID of the item. public let id: String? /// The ID of the sender in the session. public let participantId: String? /// The role of the sender. For example, is it a customer, agent, or system. public let participantRole: ParticipantRole? /// Type of the item: message or event. public let `type`: ChatItemType? public init(absoluteTime: String? = nil, content: String? = nil, contentType: String? = nil, displayName: String? = nil, id: String? = nil, participantId: String? = nil, participantRole: ParticipantRole? = nil, type: ChatItemType? = nil) { self.absoluteTime = absoluteTime self.content = content self.contentType = contentType self.displayName = displayName self.id = id self.participantId = participantId self.participantRole = participantRole self.`type` = `type` } private enum CodingKeys: String, CodingKey { case absoluteTime = "AbsoluteTime" case content = "Content" case contentType = "ContentType" case displayName = "DisplayName" case id = "Id" case participantId = "ParticipantId" case participantRole = "ParticipantRole" case `type` = "Type" } } public struct SendEventRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClientToken", required: false, type: .string), AWSShapeMember(label: "ConnectionToken", location: .header(locationName: "X-Amz-Bearer"), required: true, type: .string), AWSShapeMember(label: "Content", required: false, type: .string), AWSShapeMember(label: "ContentType", required: true, type: .string) ] /// A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. public let clientToken: String? /// The authentication token associated with the participant's connection. public let connectionToken: String /// The content of the event to be sent (for example, message text). This is not yet supported. public let content: String? /// The content type of the request. Supported types are: application/vnd.amazonaws.connect.event.typing application/vnd.amazonaws.connect.event.connection.acknowledged public let contentType: String public init(clientToken: String? = SendEventRequest.idempotencyToken(), connectionToken: String, content: String? = nil, contentType: String) { self.clientToken = clientToken self.connectionToken = connectionToken self.content = content self.contentType = contentType } public func validate(name: String) throws { try validate(self.clientToken, name:"clientToken", parent: name, max: 500) try validate(self.connectionToken, name:"connectionToken", parent: name, max: 1000) try validate(self.connectionToken, name:"connectionToken", parent: name, min: 1) try validate(self.content, name:"content", parent: name, max: 1024) try validate(self.content, name:"content", parent: name, min: 1) try validate(self.contentType, name:"contentType", parent: name, max: 100) try validate(self.contentType, name:"contentType", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case connectionToken = "X-Amz-Bearer" case content = "Content" case contentType = "ContentType" } } public struct SendEventResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AbsoluteTime", required: false, type: .string), AWSShapeMember(label: "Id", required: false, type: .string) ] /// The time when the event was sent. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z. public let absoluteTime: String? /// The ID of the response. public let id: String? public init(absoluteTime: String? = nil, id: String? = nil) { self.absoluteTime = absoluteTime self.id = id } private enum CodingKeys: String, CodingKey { case absoluteTime = "AbsoluteTime" case id = "Id" } } public struct SendMessageRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClientToken", required: false, type: .string), AWSShapeMember(label: "ConnectionToken", location: .header(locationName: "X-Amz-Bearer"), required: true, type: .string), AWSShapeMember(label: "Content", required: true, type: .string), AWSShapeMember(label: "ContentType", required: true, type: .string) ] /// A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. public let clientToken: String? /// The authentication token associated with the connection. public let connectionToken: String /// The content of the message. public let content: String /// The type of the content. Supported types are text/plain. public let contentType: String public init(clientToken: String? = SendMessageRequest.idempotencyToken(), connectionToken: String, content: String, contentType: String) { self.clientToken = clientToken self.connectionToken = connectionToken self.content = content self.contentType = contentType } public func validate(name: String) throws { try validate(self.clientToken, name:"clientToken", parent: name, max: 500) try validate(self.connectionToken, name:"connectionToken", parent: name, max: 1000) try validate(self.connectionToken, name:"connectionToken", parent: name, min: 1) try validate(self.content, name:"content", parent: name, max: 1024) try validate(self.content, name:"content", parent: name, min: 1) try validate(self.contentType, name:"contentType", parent: name, max: 100) try validate(self.contentType, name:"contentType", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case connectionToken = "X-Amz-Bearer" case content = "Content" case contentType = "ContentType" } } public struct SendMessageResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AbsoluteTime", required: false, type: .string), AWSShapeMember(label: "Id", required: false, type: .string) ] /// The time when the message was sent. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z. public let absoluteTime: String? /// The ID of the message. public let id: String? public init(absoluteTime: String? = nil, id: String? = nil) { self.absoluteTime = absoluteTime self.id = id } private enum CodingKeys: String, CodingKey { case absoluteTime = "AbsoluteTime" case id = "Id" } } public struct StartPosition: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AbsoluteTime", required: false, type: .string), AWSShapeMember(label: "Id", required: false, type: .string), AWSShapeMember(label: "MostRecent", required: false, type: .integer) ] /// The time in ISO format where to start. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z. public let absoluteTime: String? /// The ID of the message or event where to start. public let id: String? /// The start position of the most recent message where you want to start. public let mostRecent: Int? public init(absoluteTime: String? = nil, id: String? = nil, mostRecent: Int? = nil) { self.absoluteTime = absoluteTime self.id = id self.mostRecent = mostRecent } public func validate(name: String) throws { try validate(self.absoluteTime, name:"absoluteTime", parent: name, max: 100) try validate(self.absoluteTime, name:"absoluteTime", parent: name, min: 1) try validate(self.id, name:"id", parent: name, max: 256) try validate(self.id, name:"id", parent: name, min: 1) try validate(self.mostRecent, name:"mostRecent", parent: name, max: 100) try validate(self.mostRecent, name:"mostRecent", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case absoluteTime = "AbsoluteTime" case id = "Id" case mostRecent = "MostRecent" } } public struct Websocket: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ConnectionExpiry", required: false, type: .string), AWSShapeMember(label: "Url", required: false, type: .string) ] /// The URL expiration timestamp in ISO date format. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z. public let connectionExpiry: String? /// The URL of the websocket. public let url: String? public init(connectionExpiry: String? = nil, url: String? = nil) { self.connectionExpiry = connectionExpiry self.url = url } private enum CodingKeys: String, CodingKey { case connectionExpiry = "ConnectionExpiry" case url = "Url" } } }
46.235789
247
0.635416
11458771649b6b9454b50b6ad2fd9a1b8a0e3dca
9,956
// // Copyright © 2015 - 2022 Stephen F. Booth <[email protected]> // Part of https://github.com/sbooth/Pipeline // MIT license // import Foundation import CSQLite extension Database { /// A hook called when a database transaction is committed. /// /// - returns: `true` if the commit operation is allowed to proceed, `false` otherwise. /// /// - seealso: [Commit And Rollback Notification Callbacks](https://www.sqlite.org/c3ref/commit_hook.html) public typealias CommitHook = () -> Bool /// Sets the hook called when a database transaction is committed. /// /// - parameter commitHook: A closure called when a transaction is committed. public func setCommitHook(_ block: @escaping CommitHook) { let context = UnsafeMutablePointer<CommitHook>.allocate(capacity: 1) context.initialize(to: block) if let old = sqlite3_commit_hook(databaseConnection, { $0.unsafelyUnwrapped.assumingMemoryBound(to: CommitHook.self).pointee() ? 0 : 1 }, context) { let oldContext = old.assumingMemoryBound(to: CommitHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// Removes the commit hook. public func removeCommitHook() { if let old = sqlite3_commit_hook(databaseConnection, nil, nil) { let oldContext = old.assumingMemoryBound(to: CommitHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// A hook called when a database transaction is rolled back. /// /// - seealso: [Commit And Rollback Notification Callbacks](https://www.sqlite.org/c3ref/commit_hook.html) public typealias RollbackHook = () -> Void /// Sets the hook called when a database transaction is rolled back. /// /// - parameter rollbackHook: A closure called when a transaction is rolled back. public func setRollbackHook(_ block: @escaping RollbackHook) { let context = UnsafeMutablePointer<RollbackHook>.allocate(capacity: 1) context.initialize(to: block) if let old = sqlite3_rollback_hook(databaseConnection, { $0.unsafelyUnwrapped.assumingMemoryBound(to: RollbackHook.self).pointee() }, context) { let oldContext = old.assumingMemoryBound(to: RollbackHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// Removes the rollback hook. public func removeRollbackHook() { if let old = sqlite3_rollback_hook(databaseConnection, nil, nil) { let oldContext = old.assumingMemoryBound(to: RollbackHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } } extension Database { /// A hook called when a database transaction is committed in write-ahead log mode. /// /// - parameter databaseName: The name of the database that was written to. /// - parameter pageCount: The number of pages in the write-ahead log file. /// /// - returns: Normally `SQLITE_OK`. /// /// - seealso: [Write-Ahead Log Commit Hook](https://www.sqlite.org/c3ref/wal_hook.html) public typealias WALCommitHook = (_ databaseName: String, _ pageCount: Int) -> Int32 /// Sets the hook called when a database transaction is committed in write-ahead log mode. /// /// - parameter commitHook: A closure called when a transaction is committed. public func setWALCommitHook(_ block: @escaping WALCommitHook) { let context = UnsafeMutablePointer<WALCommitHook>.allocate(capacity: 1) context.initialize(to: block) if let old = sqlite3_wal_hook(databaseConnection, { context, database_connection, database_name, pageCount in // guard database_connection == self.databaseConnection else { // fatalError("Unexpected database connection handle from sqlite3_wal_hook") // } let database = String(utf8String: database_name.unsafelyUnwrapped).unsafelyUnwrapped return context.unsafelyUnwrapped.assumingMemoryBound(to: WALCommitHook.self).pointee(database, Int(pageCount)) }, context) { let oldContext = old.assumingMemoryBound(to: WALCommitHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// Removes the write-ahead log commit hook. public func removeWALCommitHook() { if let old = sqlite3_wal_hook(databaseConnection, nil, nil) { let oldContext = old.assumingMemoryBound(to: WALCommitHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } } extension Database { /// Possible types of row changes. public enum RowChangeType { /// A row was inserted. case insert /// A row was deleted. case delete /// A row was updated. case update } /// An insert, delete, or update event on a rowid table. public struct TableChangeEvent { /// The type of row change. public let changeType: RowChangeType /// The name of the database containing the table that changed. public let database: String /// The name of the table that changed. public let table: String /// The rowid of the row that changed. public let rowid: Int64 } /// A hook called when a row is inserted, deleted, or updated in a rowid table. /// /// - parameter changeEvent: The table change event triggering the hook. /// /// - seealso: [Commit And Rollback Notification Callbacks](https://www.sqlite.org/c3ref/commit_hook.html) /// - seealso: [Rowid Tables](https://www.sqlite.org/rowidtable.html) public typealias UpdateHook = (_ changeEvent: TableChangeEvent) -> Void /// Sets the hook called when a row is inserted, deleted, or updated in a rowid table. /// /// - parameter updateHook: A closure called when a row is inserted, deleted, or updated public func setUpdateHook(_ block: @escaping UpdateHook) { let context = UnsafeMutablePointer<UpdateHook>.allocate(capacity: 1) context.initialize(to: block) if let old = sqlite3_update_hook(databaseConnection, { context, op, database_name, table_name, rowid in let function_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: UpdateHook.self) let changeType = RowChangeType(op) let database = String(utf8String: database_name.unsafelyUnwrapped).unsafelyUnwrapped let table = String(utf8String: table_name.unsafelyUnwrapped).unsafelyUnwrapped let changeEvent = TableChangeEvent(changeType: changeType, database: database, table: table, rowid: rowid) function_ptr.pointee(changeEvent) }, context) { let oldContext = old.assumingMemoryBound(to: UpdateHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// Removes the update hook. public func removeUpdateHook() { if let old = sqlite3_update_hook(databaseConnection, nil, nil) { let oldContext = old.assumingMemoryBound(to: UpdateHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } } extension Database.RowChangeType { /// Convenience initializer for conversion of `SQLITE_` values. /// /// - parameter operation: The second argument to the callback function passed to `sqlite3_update_hook()`. init(_ operation: Int32) { switch operation { case SQLITE_INSERT: self = .insert case SQLITE_DELETE: self = .delete case SQLITE_UPDATE: self = .update default: fatalError("Unexpected SQLite row change type \(operation)") } } } #if canImport(Combine) import Combine extension Database { /// Returns a publisher for changes to rowid tables. /// /// - note: The publisher uses the database's update hook for event generation. If this /// publisher is used the update hook is unavailable. /// /// - returns: A publisher for changes to the database's rowid tables. public var tableChangeEventPublisher: AnyPublisher<TableChangeEvent, Never> { tableChangeEventSubject .eraseToAnyPublisher() } } #endif extension Database { /// A hook that may be called when an attempt is made to access a locked database table. /// /// - parameter attempts: The number of times the busy handler has been called for the same event. /// /// - returns: `true` if the attempts to access the database should stop, `false` to continue. /// /// - seealso: [Register A Callback To Handle SQLITE_BUSY Errors](https://www.sqlite.org/c3ref/busy_handler.html) public typealias BusyHandler = (_ attempts: Int) -> Bool /// Sets a callback that may be invoked when an attempt is made to access a locked database table. /// /// - parameter busyHandler: A closure called when an attempt is made to access a locked database table. /// /// - throws: An error if the busy handler couldn't be set. public func setBusyHandler(_ block: @escaping BusyHandler) throws { if busyHandler == nil { busyHandler = UnsafeMutablePointer<BusyHandler>.allocate(capacity: 1) } else { busyHandler?.deinitialize(count: 1) } busyHandler?.initialize(to: block) guard sqlite3_busy_handler(databaseConnection, { context, count in return context.unsafelyUnwrapped.assumingMemoryBound(to: BusyHandler.self).pointee(Int(count)) ? 0 : 1 }, busyHandler) == SQLITE_OK else { busyHandler?.deinitialize(count: 1) busyHandler?.deallocate() busyHandler = nil throw DatabaseError(message: "Error setting busy handler") } } /// Removes the busy handler. /// /// - throws: An error if the busy handler couldn't be removed. public func removeBusyHandler() throws { defer { busyHandler?.deinitialize(count: 1) busyHandler?.deallocate() busyHandler = nil } guard sqlite3_busy_handler(databaseConnection, nil, nil) == SQLITE_OK else { throw SQLiteError(fromDatabaseConnection: databaseConnection) } } /// Sets a busy handler that sleeps when an attempt is made to access a locked database table. /// /// - parameter ms: The minimum time in milliseconds to sleep. /// /// - throws: An error if the busy timeout couldn't be set. /// /// - seealso: [Set A Busy Timeout](https://www.sqlite.org/c3ref/busy_timeout.html) public func setBusyTimeout(_ ms: Int) throws { defer { busyHandler?.deinitialize(count: 1) busyHandler?.deallocate() busyHandler = nil } guard sqlite3_busy_timeout(databaseConnection, Int32(ms)) == SQLITE_OK else { throw DatabaseError(message: "Error setting busy timeout") } } }
36.335766
114
0.73413
5bc9aea0705881735ee1436d0b09605e1c961292
3,283
// // UIDeviceExtensions.swift // ModelForFawGen // // Created by Erick Olibo on 28/07/2019. // Copyright © 2019 DEFKUT Creations OU. All rights reserved. // import UIKit extension UIDevice { var modelName: DeviceModelName { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPhone6,1", "iPhone6,2": return .iPhone5s case "iPhone7,2": return .iPhone6 case "iPhone7,1": return .iPhone6Plus case "iPhone8,1": return .iPhone6s case "iPhone8,2": return .iPhone6sPlus case "iPhone8,4": return .iPhoneSE case "iPhone9,1", "iPhone9,3": return .iPhone7 case "iPhone9,2", "iPhone9,4": return .iPhone7Plus case "iPhone10,1", "iPhone10,4": return .iPhone8 case "iPhone10,2", "iPhone10,5": return .iPhone8Plus case "iPhone10,3", "iPhone10,6": return .iPhoneX case "iPhone11,2": return .iPhoneXs case "iPhone11,4", "iPhone11,6": return .iPhoneXsMax case "iPhone11,8": return .iPhoneXr default: return .other } } // Devices important to the App public enum DeviceModelName: String { case iPhone5s, iPhone6, iPhone6Plus // Low processing power case iPhone6s, iPhone6sPlus, iPhoneSE // midLow processing power case iPhone7, iPhone7Plus, iPhone8, iPhone8Plus // midHigh processing power case iPhoneX, iPhoneXs, iPhoneXsMax, iPhoneXr // high processing power case other // Not available } public var processingPower: ProcessingRank { switch modelName { case .iPhone5s, .iPhone6, .iPhone6Plus: return ProcessingRank.low case .iPhone6s, .iPhone6sPlus, .iPhoneSE: return ProcessingRank.midLow case .iPhone7, .iPhone7Plus, .iPhone8, .iPhone8Plus: return ProcessingRank.midHigh case .iPhoneX, .iPhoneXs, .iPhoneXsMax, .iPhoneXr: return ProcessingRank.high case .other: return .unRanked } } public enum ProcessingRank: String { case low, midLow, midHigh, high, unRanked } public var processingPowerKeywordsAndSynonymsLimit: Int { switch processingPower { case .low: return 30 case .midLow: return 50 case .midHigh: return 80 case .high, .unRanked: return 100 } } }
36.88764
91
0.521474
fcd82e05e26109e27c8953f7f35ab3b2d15e854e
974
import MapKit protocol DbHelper { func saveAll(_ denkmale: [Denkmal]) throws func save(_ event: Denkmal) throws func getAll() throws -> [Denkmal] func clean() throws func getDenkmale(success: @escaping ([Denkmal]) -> Void, failure: @escaping (Error) -> Void) func alreadyLoaded() -> Bool func setAlreadyLoaded() func getUserId() -> String func createUserId() func search(query: String, option: String, success: @escaping ([Denkmal]) -> Void, failure: @escaping (Error) -> Void) func bookmark(id: String, success: @escaping (() -> Void), failure: @escaping ((Error) -> Void)) func search(query: Bool, option: String, success: @escaping ([Denkmal]) -> Void, failure: @escaping (Error) -> Void) func getDenkmalById(id: String, success: @escaping ((Denkmal) -> Void), failure: @escaping ((Error) -> Void)) }
27.828571
122
0.585216
d75080fcfb6df6fac04386d01df75d699023197a
10,522
// // UIColorMetrics.swift // SFKit // // Created by David Moore on 3/10/18. // Copyright © 2018 Moore Development. All rights reserved. // import UIKit @objc open class UIColorMetrics: NSObject { // MARK: - Color Types /// Enumeration containing range of colors. @objc (UIColorMetricsHue) public enum Hue: Int, CaseIterable { case red case orange case yellow case green case tealBlue case blue case darkBlue case purple case pink case white case extraLightGray case lightGray case gray case darkGray case extraDarkGray case black case none } // MARK: - Properties /// Appearance style for the color metrics. private var appearanceStyle: SFAppearanceStyle // MARK: - Initialization /// The default color metrics object for content. Initialized with `SFAppearance.global`. @objc public class var `default`: UIColorMetrics { return UIColorMetrics(forAppearance: .global) } /// Creates a color metrics object for the provided appearance. @objc public convenience init(forAppearance appearance: SFAppearance) { self.init(forAppearanceStyle: appearance.style) } /// Creates a color metrics object for the specified appearance style. @objc public init(forAppearanceStyle appearanceStyle: SFAppearanceStyle) { self.appearanceStyle = appearanceStyle } // MARK: - Interface /// Returns a color adapted for the appearance style the receiver was initialized for. /// /// - Parameter hue: Color that is relative to the **light** appearance style. /// - Returns: Color that has been adapted for the initially specified appearance style. @objc(relativeColorForHue:) open func relativeColor(for hue: Hue) -> UIColor { switch hue { case .red: return red case .orange: return orange case .yellow: return yellow case .green: return green case .tealBlue: return tealBlue case .blue: return blue case .darkBlue: return darkBlue case .purple: return purple case .pink: return pink case .white: return white case .extraLightGray: return extraLightGray case .lightGray: return lightGray case .gray: return gray case .darkGray: return darkGray case .extraDarkGray: return extraDarkGray case .black: return black case .none: return .clear } } /// Returns the relative hue for the provided color. /// /// - Parameter color: Color that will be matched to a color metrics hue. /// - Returns: Color metrics hue that is associated with the provided color, relative to the appearance style with which the receiver was initialized. @objc(relativeHueForColor:) open func relativeHue(for color: UIColor) -> Hue { typealias Result = (hue: Hue, confidence: Float) // Reduce the cases to produce a result. let result = Hue.allCases.reduce((.none, 0.8)) { result, hue -> Result in guard result.confidence < 1.0 else { return result } switch relativeColor(for: hue).cgColor.compare(to: color.cgColor) { case .equal: return (hue, 1.0) case .approximatelyEqual(let confidence): return confidence > result.confidence ? (hue, confidence) : result case .notEqual: return result } } return result.hue } // MARK: - Colors private var red: UIColor { switch appearanceStyle { case .light: return #colorLiteral(red: 1, green: 0.231372549, blue: 0.1882352941, alpha: 1) case .dark: return #colorLiteral(red: 0.9952381253, green: 0.3384355307, blue: 0.1943919361, alpha: 1) } } private var orange: UIColor { switch appearanceStyle { case .light, .dark: return #colorLiteral(red: 1, green: 0.5583720207, blue: 0, alpha: 1) } } private var yellow: UIColor { switch appearanceStyle { case .light, .dark: return #colorLiteral(red: 1, green: 0.7921642661, blue: 0, alpha: 1) } } private var green: UIColor { switch appearanceStyle { case .light, .dark: return #colorLiteral(red: 0, green: 0.8660034537, blue: 0.3203170896, alpha: 1) } } private var tealBlue: UIColor { switch appearanceStyle { case .light: return #colorLiteral(red: 0.27843137255, green: 0.90588235294, blue: 1, alpha: 1) case .dark: return UIColorMetrics(forAppearanceStyle: .light).relativeColor(for: .blue) } } private var blue: UIColor { switch appearanceStyle { case .light: return #colorLiteral(red: 0.019607843137, green: 0.49803921569, blue: 1, alpha: 1) case .dark: return UIColorMetrics(forAppearanceStyle: .light).relativeColor(for: .tealBlue) } } private var darkBlue: UIColor { switch appearanceStyle { case .light: return #colorLiteral(red: 0.01693210378, green: 0.378747046, blue: 0.787571609, alpha: 1) case .dark: return #colorLiteral(red: 0.02031199378, green: 0.4543503714, blue: 0.9447821623, alpha: 1) } } private var purple: UIColor { switch appearanceStyle { case .light, .dark: return #colorLiteral(red: 0.3467972279, green: 0.3371668756, blue: 0.8699499965, alpha: 1) } } private var pink: UIColor { switch appearanceStyle { case .light, .dark: return #colorLiteral(red: 1, green: 0, blue: 0.3104304075, alpha: 1) } } // MARK: Grayscale /// An off-white color. private var white: UIColor { switch appearanceStyle { case .light: return .white case .dark: return #colorLiteral(red: 0.1992851496, green: 0.1992851496, blue: 0.1992851496, alpha: 1) } } private var extraLightGray: UIColor { switch appearanceStyle { case .light: return #colorLiteral(red: 0.9035493731, green: 0.9035493731, blue: 0.9035493731, alpha: 1) case .dark: return UIColorMetrics(forAppearanceStyle: .light).relativeColor(for: .extraDarkGray) } } /// A light gray. private var lightGray: UIColor { switch appearanceStyle { case .light: return #colorLiteral(red: 0.7952535152, green: 0.7952535152, blue: 0.7952535152, alpha: 1) case .dark: return UIColorMetrics(forAppearanceStyle: .light).relativeColor(for: .darkGray) } } /// A medium colored gray. private var gray: UIColor { switch appearanceStyle { case .light, .dark: return #colorLiteral(red: 0.5723067522, green: 0.5723067522, blue: 0.5723067522, alpha: 1) } } /// A darker than medium gray. private var darkGray: UIColor { switch appearanceStyle { case .light: return #colorLiteral(red: 0.45389539, green: 0.45389539, blue: 0.45389539, alpha: 1) case .dark: return UIColorMetrics(forAppearanceStyle: .light).relativeColor(for: .lightGray) } } private var extraDarkGray: UIColor { switch appearanceStyle { case .light: return #colorLiteral(red: 0.3179988265, green: 0.3179988265, blue: 0.3179988265, alpha: 1) case .dark: return UIColorMetrics(forAppearanceStyle: .light).relativeColor(for: .extraLightGray) } } /// Depp black color which is adaptive. private var black: UIColor { switch appearanceStyle { case .light: return .black case .dark: return UIColorMetrics(forAppearanceStyle: .light).relativeColor(for: .white) } } } // MARK: - Deprecations /// Enumeration containing range of colors. @available(*, deprecated, renamed: "UIColorMetrics.Hue") public typealias UIColorMetricsHue = UIColorMetrics.Hue extension UIColorMetrics { /// Returns the relative hue for the provided color. /// /// - Parameter color: Color that will be matched to a color metrics hue. /// - Returns: Color metrics hue that is associated with the provided color, relative to the appearance style with which the receiver was initialized. @available(*, deprecated, renamed: "relativeHue(for:)") open func relativeHue(forColor color: UIColor) -> UIColorMetricsHue? { return relativeHue(for:color) } /// Returns a color adapted for the appearance style the receiver was initialized for. /// /// - Parameter hue: Color that is relative to the **light** appearance style. /// - Returns: Color that has been adapted for the initially specified appearance style. @available(*, deprecated, renamed: "relativeColor(for:)") @objc(colorForRelativeHue:) open func color(forRelativeHue hue: Hue) -> UIColor { return relativeColor(for: hue) } /// Returns a color adapted for the appearance style the receiver was initialized for. /// /// - Parameters: /// - color: Color that is relative to a particular `UIColorMetrics` instance. /// - colorMetrics: `UIColorMetrics` instance for which `color` is relative to. This will be used to convert the color between appearance styles. /// /// - Returns: Color that has been adapted for the appearance style. @available(*, deprecated, message: "This method is no longer supported.") @objc open func color(forColor color: UIColor, relativeTo colorMetrics: UIColorMetrics) -> UIColor { // Determine the color's hue, but if it cannot be found then simply return the provided color. guard let hue = colorMetrics.relativeHue(forColor: color) else { return color } // Return the color adapted to the receiver. return self.color(forRelativeHue: hue) } }
33.403175
154
0.606919
20a9b366cc26f51fa9a87c067affe60385815a64
1,019
// // Constraints+Activation+Priority.swift // import UIKit extension Sequence where Element == NSLayoutConstraint { func activate() { if let constraints = self as? [NSLayoutConstraint] { NSLayoutConstraint.activate(constraints) } } func deActivate() { if let constraints = self as? [NSLayoutConstraint] { NSLayoutConstraint.deactivate(constraints) } } } extension NSLayoutConstraint { func with(_ p: UILayoutPriority) -> Self { priority = p return self } func set(active: Bool) -> Self { isActive = active return self } } extension UIView { func setHugging(_ priority: UILayoutPriority, for axis: NSLayoutConstraint.Axis) { setContentHuggingPriority(priority, for: axis) } func setCompressionResistance(_ priority: UILayoutPriority, for axis: NSLayoutConstraint.Axis) { setContentCompressionResistancePriority(priority, for: axis) } }
22.644444
100
0.641806
2fed646f5d60dcae414bc26cd61daeec62b70c32
2,314
// // Tweets.swift // Twift_SwiftUI // // Created by Daniel Eden on 15/01/2022. // import SwiftUI import Twift struct Tweets: View { @EnvironmentObject var twitterClient: Twift var body: some View { Form { Section("Manage Tweets") { NavigationLink(destination: PostTweet()) { MethodRow(label: "`postTweet(_ tweet)`", method: .POST) } } Section("Get Tweets") { NavigationLink(destination: GetTweet()) { MethodRow(label: "`getTweet(_ tweetId)`", method: .GET) } } Section("Timelines") { NavigationLink(destination: UserTimeline()) { MethodRow(label: "`userTimeline(_ userId)`", method: .GET) } NavigationLink(destination: UserMentions()) { MethodRow(label: "`userMentions(_ userId)`", method: .GET) } NavigationLink(destination: ReverseChronologicalTimeline()) { MethodRow(label: "`reverseChronologicalTimeline(_ userId)`", method: .GET) } } Section("Likes") { NavigationLink(destination: LikeTweet()) { MethodRow(label: "`likeTweet(_ tweetId, userId)`", method: .POST) } NavigationLink(destination: UserLikes()) { MethodRow(label: "`getUserLikes(for userId)`", method: .GET) } } Section("Bookmarks") { NavigationLink(destination: GetBookmarks()) { MethodRow(label: "`getBookmarks(for userId)`", method: .GET) } NavigationLink(destination: AddBookmark()) { MethodRow(label: "`addBookmark(_ tweetId, userId)`", method: .POST) } NavigationLink(destination: DeleteBookmark()) { MethodRow(label: "`deleteBookmark(_ tweetId, userId)`", method: .DELETE) } } Section { NavigationLink(destination: VolumeStream()) { MethodRow(label: "`volumeStream()`", method: .GET) } } header: { Text("Volume Stream") } footer: { Text("Volume Stream requires OAuth 2.0 App-Only authentication (bearer token)") }.disabled(!isEnabled) }.navigationTitle("Tweets") } var isEnabled: Bool { switch twitterClient.authenticationType { case .appOnly(_): return true default: return false } } } struct Tweets_Previews: PreviewProvider { static var previews: some View { Tweets() } }
35.6
148
0.617545
46e0c676bf4e5abf38eb20d86da28f4cc6217cb8
4,259
// // popup.swift // Bluetooth // // Created by Serhiy Mytrovtsiy on 22/06/2021. // Using Swift 5.0. // Running on macOS 10.15. // // Copyright © 2021 Serhiy Mytrovtsiy. All rights reserved. // import Cocoa import Kit internal class Popup: NSStackView, Popup_p { public var sizeCallback: ((NSSize) -> Void)? = nil private let emptyView: EmptyView = EmptyView(height: 30, isHidden: false) public init() { super.init(frame: NSRect(x: 0, y: 0, width: Constants.Popup.width, height: 30)) self.orientation = .vertical self.spacing = Constants.Popup.margins } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func batteryCallback(_ list: [BLEDevice]) { defer { if list.isEmpty && self.emptyView.superview == nil { self.addArrangedSubview(self.emptyView) } else if !list.isEmpty && self.emptyView.superview != nil { self.emptyView.removeFromSuperview() } let h = self.arrangedSubviews.map({ $0.bounds.height + self.spacing }).reduce(0, +) - self.spacing if h > 0 && self.frame.size.height != h { self.setFrameSize(NSSize(width: self.frame.width, height: h)) self.sizeCallback?(self.frame.size) } } var views = self.subviews.filter{ $0 is BLEView }.map{ $0 as! BLEView } if list.count < views.count && !views.isEmpty { views.forEach{ $0.removeFromSuperview() } views = [] } list.reversed().forEach { (ble: BLEDevice) in if let view = views.first(where: { $0.address == ble.address }) { view.update(ble.batteryLevel) } else { self.addArrangedSubview(BLEView( width: self.frame.width, address: ble.address, name: ble.name, batteryLevel: ble.batteryLevel )) } } } } internal class BLEView: NSStackView { public var address: String open override var intrinsicContentSize: CGSize { return CGSize(width: self.bounds.width, height: self.bounds.height) } public init(width: CGFloat, address: String, name: String, batteryLevel: [KeyValue_t]) { self.address = address super.init(frame: NSRect(x: 0, y: 0, width: width, height: 30)) self.orientation = .horizontal self.alignment = .centerY self.spacing = 0 self.wantsLayer = true self.layer?.cornerRadius = 2 let nameView: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 16)) nameView.font = NSFont.systemFont(ofSize: 13, weight: .light) nameView.stringValue = name nameView.toolTip = address self.addArrangedSubview(nameView) self.addArrangedSubview(NSView()) batteryLevel.forEach { (pair: KeyValue_t) in self.addLevel(pair) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateLayer() { self.layer?.backgroundColor = isDarkMode ? NSColor(hexString: "#111111", alpha: 0.25).cgColor : NSColor(hexString: "#f5f5f5", alpha: 1).cgColor } public func update(_ batteryLevel: [KeyValue_t]) { batteryLevel.forEach { (pair: KeyValue_t) in if let view = self.subviews.first(where: { $0.identifier?.rawValue == pair.key }) as? NSTextField { view.stringValue = "\(pair.value)%" } else { self.addLevel(pair) } } } private func addLevel(_ pair: KeyValue_t) { let valueView: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 13)) valueView.identifier = NSUserInterfaceItemIdentifier(rawValue: pair.key) valueView.font = NSFont.systemFont(ofSize: 12, weight: .regular) valueView.stringValue = "\(pair.value)%" valueView.toolTip = pair.key self.addArrangedSubview(valueView) } }
34.346774
151
0.576426
67b6d9516e6dbb58034dd1edc75956ce63a670de
19,013
import Foundation import TSCBasic import TuistCore import TuistCoreTesting import TuistSupport import XcodeProj import XCTest @testable import TuistGenerator @testable import TuistSupportTesting final class ConfigGeneratorTests: TuistUnitTestCase { var pbxproj: PBXProj! var graph: Graph! var subject: ConfigGenerator! var pbxTarget: PBXNativeTarget! override func setUp() { super.setUp() pbxproj = PBXProj() pbxTarget = PBXNativeTarget(name: "Test") system.swiftVersionStub = { "5.2" } pbxproj.add(object: pbxTarget) subject = ConfigGenerator() } override func tearDown() { pbxproj = nil pbxTarget = nil subject = nil super.tearDown() } func test_generateProjectConfig_whenDebug() throws { try generateProjectConfig(config: .debug) XCTAssertEqual(pbxproj.configurationLists.count, 1) let configurationList: XCConfigurationList = pbxproj.configurationLists.first! let debugConfig: XCBuildConfiguration = configurationList.buildConfigurations[2] XCTAssertEqual(debugConfig.name, "Debug") XCTAssertEqual(debugConfig.buildSettings["Debug"] as? String, "Debug") XCTAssertEqual(debugConfig.buildSettings["Base"] as? String, "Base") } func test_generateProjectConfig_whenRelease() throws { try generateProjectConfig(config: .release) XCTAssertEqual(pbxproj.configurationLists.count, 1) let configurationList: XCConfigurationList = pbxproj.configurationLists.first! let releaseConfig: XCBuildConfiguration = configurationList.buildConfigurations[3] XCTAssertEqual(releaseConfig.name, "Release") XCTAssertEqual(releaseConfig.buildSettings["Release"] as? String, "Release") XCTAssertEqual(releaseConfig.buildSettings["Base"] as? String, "Base") XCTAssertEqual(releaseConfig.buildSettings["MTL_ENABLE_DEBUG_INFO"] as? String, "NO") let customReleaseConfig: XCBuildConfiguration = configurationList.buildConfigurations[1] XCTAssertEqual(customReleaseConfig.name, "CustomRelease") XCTAssertEqual(customReleaseConfig.buildSettings["Base"] as? String, "Base") XCTAssertEqual(customReleaseConfig.buildSettings["MTL_ENABLE_DEBUG_INFO"] as? String, "NO") } func test_generateTargetConfig() throws { // Given let commonSettings = [ "Base": "Base", "INFOPLIST_FILE": "Info.plist", "PRODUCT_BUNDLE_IDENTIFIER": "com.test.bundle_id", "CODE_SIGN_ENTITLEMENTS": "$(SRCROOT)/Test.entitlements", "SWIFT_VERSION": "5.2", ] let debugSettings = [ "SWIFT_OPTIMIZATION_LEVEL": "-Onone", ] let releaseSettings = [ "SWIFT_OPTIMIZATION_LEVEL": "-Owholemodule", ] // When try generateTargetConfig() // Then let configurationList = pbxTarget.buildConfigurationList let debugConfig = configurationList?.configuration(name: "Debug") let customDebugConfig = configurationList?.configuration(name: "CustomDebug") let releaseConfig = configurationList?.configuration(name: "Release") let customReleaseConfig = configurationList?.configuration(name: "CustomRelease") assert(config: debugConfig, contains: commonSettings) assert(config: debugConfig, contains: debugSettings) assert(config: debugConfig, hasXcconfig: "debug.xcconfig") assert(config: customDebugConfig, contains: commonSettings) assert(config: customDebugConfig, contains: debugSettings) assert(config: releaseConfig, contains: commonSettings) assert(config: releaseConfig, contains: releaseSettings) assert(config: releaseConfig, hasXcconfig: "release.xcconfig") assert(config: customReleaseConfig, contains: commonSettings) assert(config: customReleaseConfig, contains: releaseSettings) } func test_generateTestTargetConfiguration() throws { // Given / When try generateTestTargetConfig() let configurationList = pbxTarget.buildConfigurationList let debugConfig = configurationList?.configuration(name: "Debug") let releaseConfig = configurationList?.configuration(name: "Release") let testHostSettings = [ "TEST_HOST": "$(BUILT_PRODUCTS_DIR)/App.app/App", "BUNDLE_LOADER": "$(TEST_HOST)", ] assert(config: debugConfig, contains: testHostSettings) assert(config: releaseConfig, contains: testHostSettings) } func test_generateUITestTargetConfiguration() throws { // Given / When try generateTestTargetConfig(uiTest: true) let configurationList = pbxTarget.buildConfigurationList let debugConfig = configurationList?.configuration(name: "Debug") let releaseConfig = configurationList?.configuration(name: "Release") let testHostSettings = [ "TEST_TARGET_NAME": "App", ] assert(config: debugConfig, contains: testHostSettings) assert(config: releaseConfig, contains: testHostSettings) } func test_generateTargetWithDeploymentTarget_whenIOS() throws { // Given let project = Project.test() let target = Target.test(deploymentTarget: .iOS("12.0", [.iphone, .ipad])) // When try subject.generateTargetConfig(target, project: project, pbxTarget: pbxTarget, pbxproj: pbxproj, projectSettings: .default, fileElements: ProjectFileElements(), graph: Graph.test(), sourceRootPath: AbsolutePath("/project")) // Then let configurationList = pbxTarget.buildConfigurationList let debugConfig = configurationList?.configuration(name: "Debug") let releaseConfig = configurationList?.configuration(name: "Release") let expectedSettings = [ "TARGETED_DEVICE_FAMILY": "1,2", "IPHONEOS_DEPLOYMENT_TARGET": "12.0", ] assert(config: debugConfig, contains: expectedSettings) assert(config: releaseConfig, contains: expectedSettings) } func test_generateTargetWithDeploymentTarget_whenMac() throws { // Given let project = Project.test() let target = Target.test(deploymentTarget: .macOS("10.14.1")) // When try subject.generateTargetConfig(target, project: project, pbxTarget: pbxTarget, pbxproj: pbxproj, projectSettings: .default, fileElements: ProjectFileElements(), graph: Graph.test(), sourceRootPath: AbsolutePath("/project")) // Then let configurationList = pbxTarget.buildConfigurationList let debugConfig = configurationList?.configuration(name: "Debug") let releaseConfig = configurationList?.configuration(name: "Release") let expectedSettings = [ "MACOSX_DEPLOYMENT_TARGET": "10.14.1", ] assert(config: debugConfig, contains: expectedSettings) assert(config: releaseConfig, contains: expectedSettings) } func test_generateTargetWithDeploymentTarget_whenCatalyst() throws { // Given let project = Project.test() let target = Target.test(deploymentTarget: .iOS("13.1", [.iphone, .ipad, .mac])) // When try subject.generateTargetConfig(target, project: project, pbxTarget: pbxTarget, pbxproj: pbxproj, projectSettings: .default, fileElements: ProjectFileElements(), graph: Graph.test(), sourceRootPath: AbsolutePath("/project")) // Then let configurationList = pbxTarget.buildConfigurationList let debugConfig = configurationList?.configuration(name: "Debug") let releaseConfig = configurationList?.configuration(name: "Release") let expectedSettings = [ "TARGETED_DEVICE_FAMILY": "1,2", "IPHONEOS_DEPLOYMENT_TARGET": "13.1", "SUPPORTS_MACCATALYST": "YES", "DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER": "YES", ] assert(config: debugConfig, contains: expectedSettings) assert(config: releaseConfig, contains: expectedSettings) } func test_generateProjectConfig_defaultConfigurationName() throws { // Given let settings = Settings(configurations: [ .debug("CustomDebug"): nil, .debug("AnotherDebug"): nil, .release("CustomRelease"): nil, ]) let project = Project.test(settings: settings) // When let result = try subject.generateProjectConfig(project: project, pbxproj: pbxproj, fileElements: ProjectFileElements()) // Then XCTAssertEqual(result.defaultConfigurationName, "CustomRelease") } func test_generateProjectConfig_defaultConfigurationName_whenNoReleaseConfiguration() throws { // Given let settings = Settings(configurations: [ .debug("CustomDebug"): nil, .debug("AnotherDebug"): nil, ]) let project = Project.test(settings: settings) // When let result = try subject.generateProjectConfig(project: project, pbxproj: pbxproj, fileElements: ProjectFileElements()) // Then XCTAssertEqual(result.defaultConfigurationName, "AnotherDebug") } func test_generateTargetConfig_defaultConfigurationName() throws { // Given let projectSettings = Settings(configurations: [ .debug("CustomDebug"): nil, .debug("AnotherDebug"): nil, .release("CustomRelease"): nil, ]) let project = Project.test() let target = Target.test() // When try subject.generateTargetConfig(target, project: project, pbxTarget: pbxTarget, pbxproj: pbxproj, projectSettings: projectSettings, fileElements: ProjectFileElements(), graph: Graph.test(), sourceRootPath: AbsolutePath("/project")) // Then let result = pbxTarget.buildConfigurationList XCTAssertEqual(result?.defaultConfigurationName, "CustomRelease") } func test_generateTargetConfig_defaultConfigurationName_whenNoReleaseConfiguration() throws { // Given let projectSettings = Settings(configurations: [ .debug("CustomDebug"): nil, .debug("AnotherDebug"): nil, ]) let project = Project.test() let target = Target.test() // When try subject.generateTargetConfig(target, project: project, pbxTarget: pbxTarget, pbxproj: pbxproj, projectSettings: projectSettings, fileElements: ProjectFileElements(), graph: Graph.test(), sourceRootPath: AbsolutePath("/project")) // Then let result = pbxTarget.buildConfigurationList XCTAssertEqual(result?.defaultConfigurationName, "AnotherDebug") } // MARK: - Helpers private func generateProjectConfig(config _: BuildConfiguration) throws { let dir = try temporaryPath() let xcconfigsDir = dir.appending(component: "xcconfigs") try FileHandler.shared.createFolder(xcconfigsDir) try "".write(to: xcconfigsDir.appending(component: "debug.xcconfig").url, atomically: true, encoding: .utf8) try "".write(to: xcconfigsDir.appending(component: "release.xcconfig").url, atomically: true, encoding: .utf8) // CustomDebug, CustomRelease, Debug, Release let configurations: [BuildConfiguration: Configuration?] = [ .debug: Configuration(settings: ["Debug": "Debug"], xcconfig: xcconfigsDir.appending(component: "debug.xcconfig")), .debug("CustomDebug"): Configuration(settings: ["CustomDebug": "CustomDebug"], xcconfig: nil), .release: Configuration(settings: ["Release": "Release"], xcconfig: xcconfigsDir.appending(component: "release.xcconfig")), .release("CustomRelease"): Configuration(settings: ["CustomRelease": "CustomRelease"], xcconfig: nil), ] let project = Project.test(path: dir, name: "Test", settings: Settings(base: ["Base": "Base"], configurations: configurations), targets: []) let fileElements = ProjectFileElements() _ = try subject.generateProjectConfig(project: project, pbxproj: pbxproj, fileElements: fileElements) } private func generateTargetConfig() throws { let dir = try temporaryPath() let xcconfigsDir = dir.appending(component: "xcconfigs") try FileHandler.shared.createFolder(xcconfigsDir) try "".write(to: xcconfigsDir.appending(component: "debug.xcconfig").url, atomically: true, encoding: .utf8) try "".write(to: xcconfigsDir.appending(component: "release.xcconfig").url, atomically: true, encoding: .utf8) let configurations: [BuildConfiguration: Configuration?] = [ .debug: Configuration(settings: ["Debug": "Debug"], xcconfig: xcconfigsDir.appending(component: "debug.xcconfig")), .debug("CustomDebug"): Configuration(settings: ["CustomDebug": "CustomDebug"], xcconfig: nil), .release: Configuration(settings: ["Release": "Release"], xcconfig: xcconfigsDir.appending(component: "release.xcconfig")), .release("CustomRelease"): Configuration(settings: ["CustomRelease": "CustomRelease"], xcconfig: nil), ] let target = Target.test(name: "Test", settings: Settings(base: ["Base": "Base"], configurations: configurations)) let project = Project.test(path: dir, name: "Test", settings: .default, targets: [target]) let fileElements = ProjectFileElements() let groups = ProjectGroups.generate(project: project, pbxproj: pbxproj, xcodeprojPath: project.path.appending(component: "\(project.fileName).xcodeproj"), sourceRootPath: dir) let graph = Graph.test() try fileElements.generateProjectFiles(project: project, graph: graph, groups: groups, pbxproj: pbxproj, sourceRootPath: project.path) _ = try subject.generateTargetConfig(target, project: project, pbxTarget: pbxTarget, pbxproj: pbxproj, projectSettings: project.settings, fileElements: fileElements, graph: graph, sourceRootPath: AbsolutePath("/")) } private func generateTestTargetConfig(uiTest: Bool = false) throws { let dir = try temporaryPath() let appTarget = Target.test(name: "App", platform: .iOS, product: .app) let target = Target.test(name: "Test", product: uiTest ? .uiTests : .unitTests) let project = Project.test(path: dir, name: "Project", targets: [target]) let appTargetNode = TargetNode(project: project, target: appTarget, dependencies: []) let testTargetNode = TargetNode(project: project, target: target, dependencies: [appTargetNode]) let graph = Graph.test(entryNodes: [appTargetNode, testTargetNode]) _ = try subject.generateTargetConfig(target, project: project, pbxTarget: pbxTarget, pbxproj: pbxproj, projectSettings: project.settings, fileElements: .init(), graph: graph, sourceRootPath: dir) } func assert(config: XCBuildConfiguration?, contains settings: [String: String], file: StaticString = #file, line: UInt = #line) { let matches = settings.filter { config?.buildSettings[$0.key] as? String == $0.value } XCTAssertEqual(matches.count, settings.count, "Settings \(String(describing: config?.buildSettings)) do not contain expected settings \(settings)", file: file, line: line) } func assert(config: XCBuildConfiguration?, hasXcconfig xconfigPath: String, file: StaticString = #file, line: UInt = #line) { let xcconfig: PBXFileReference? = config?.baseConfiguration XCTAssertEqual(xcconfig?.path, xconfigPath, file: file, line: line) } }
44.422897
126
0.563562
1468273d142aa94ebfaeb6e5c8243b0c45625ddc
700
import UIKit import XCTest public extension XCTestCase { @objc public func verify(view: UIView, function: String = #function, file: String = #file) { let testTarget = TestTarget( function: function, file: file ) return resolver.makeMatcher( with: view, isRecording: isRecording, tesTarget: testTarget ).toMatchSnapshot() } @objc public func verify(layer: CALayer, function: String = #function, file: String = #file) { let testTarget = TestTarget( function: function, file: file ) return resolver.makeMatcher( with: layer, isRecording: isRecording, tesTarget: testTarget ).toMatchSnapshot() } }
22.580645
90
0.65
50ebd672437dc9ca9c0092008c70f1cfd1ad4800
193
// Created by Geoff Pado on 6/17/19. // Copyright © 2019 Geoff Pado. All rights reserved. import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? }
21.444444
57
0.735751
e6dc6cebc62edaa1ae381e99534d19936786dba1
786
// // LocationsViewModelTests.swift // WeatherApp // // Created by Emilio Fernandez on 07/01/15. // Copyright (c) 2015 Emilio Fernandez. All rights reserved. // import UIKit import XCTest class LocationsViewModelTests: XCTestCase { var sut: LocationsViewModel! override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
23.117647
111
0.637405
ebfa021b865adc78da8eb440fabe05d6d43dc937
7,543
// // AppDelegate.swift // BasicFrameworkWithSwift // // Created by mr-tech on 16/9/23. // Copyright © 2016年 Rainy. All rights reserved. /* 找到Swift Compiler - Search Paths 下的 Use Legacy Swift Language Version:把后面的改成YES。 //:configuration = Debug SWIFT_VERSION = 2.3 //:configuration = Release SWIFT_VERSION = 2.3 //:completeSettings = some SWIFT_VERSION*/ /* 找到Swift Compiler - Search Paths 下的 Use Legacy Swift Language Version:把后面的改成NO。 //:configuration = Debug SWIFT_VERSION = 3.0 //:configuration = Release SWIFT_VERSION = 3.0 //:completeSettings = some SWIFT_VERSION*/ /* Xcode8,新建立工程,都会打印一堆莫名其妙看不懂的Log. 如这些 subsystem: com.apple.UIKit, category: HIDEventFiltered, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, 屏蔽的方法如下: Xcode8里边 Edit Scheme-> Run -> Arguments, 在Environment Variables里边添加 OS_ACTIVITY_MODE = Disable */ /* // 推送的代理 [<UNUserNotificationCenterDelegate>] iOS10收到通知不再是在 [application: didReceiveRemoteNotification:]方法去处理, iOS10推出新的代理方法,接收和处理各类通知(本地或者远程) - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { //应用在前台收到通知 NSLog(@"========%@", notification);}- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { //点击通知进入应用 NSLog(@"response:%@", response);} */ import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "hzmr-tech.com.BasicFrameworkWithSwift" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("BasicFrameworkWithSwift", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
50.624161
487
0.732202
38c0f9a8afffcc631aad873f0833f24bc8dbb7ec
35,678
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import Foundation import AWSSDKSwiftCore extension MarketplaceCatalog { //MARK: Enums public enum ChangeStatus: String, CustomStringConvertible, Codable { case preparing = "PREPARING" case applying = "APPLYING" case succeeded = "SUCCEEDED" case cancelled = "CANCELLED" case failed = "FAILED" public var description: String { return self.rawValue } } public enum SortOrder: String, CustomStringConvertible, Codable { case ascending = "ASCENDING" case descending = "DESCENDING" public var description: String { return self.rawValue } } //MARK: Shapes public struct CancelChangeSetRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Catalog", location: .querystring(locationName: "catalog"), required: true, type: .string), AWSShapeMember(label: "ChangeSetId", location: .querystring(locationName: "changeSetId"), required: true, type: .string) ] /// Required. The catalog related to the request. Fixed value: AWSMarketplace. public let catalog: String /// Required. The unique identifier of the StartChangeSet request that you want to cancel. public let changeSetId: String public init(catalog: String, changeSetId: String) { self.catalog = catalog self.changeSetId = changeSetId } public func validate(name: String) throws { try validate(self.catalog, name:"catalog", parent: name, max: 64) try validate(self.catalog, name:"catalog", parent: name, min: 1) try validate(self.catalog, name:"catalog", parent: name, pattern: "^[a-zA-Z]+$") try validate(self.changeSetId, name:"changeSetId", parent: name, max: 255) try validate(self.changeSetId, name:"changeSetId", parent: name, min: 1) try validate(self.changeSetId, name:"changeSetId", parent: name, pattern: "^[\\w\\-]+$") } private enum CodingKeys: String, CodingKey { case catalog = "catalog" case changeSetId = "changeSetId" } } public struct CancelChangeSetResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ChangeSetArn", required: false, type: .string), AWSShapeMember(label: "ChangeSetId", required: false, type: .string) ] /// The ARN associated with the change set referenced in this request. public let changeSetArn: String? /// The unique identifier for the change set referenced in this request. public let changeSetId: String? public init(changeSetArn: String? = nil, changeSetId: String? = nil) { self.changeSetArn = changeSetArn self.changeSetId = changeSetId } private enum CodingKeys: String, CodingKey { case changeSetArn = "ChangeSetArn" case changeSetId = "ChangeSetId" } } public struct Change: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ChangeType", required: true, type: .string), AWSShapeMember(label: "Details", required: true, type: .string), AWSShapeMember(label: "Entity", required: true, type: .structure) ] /// Change types are single string values that describe your intention for the change. Each change type is unique for each EntityType provided in the change's scope. public let changeType: String /// This object contains details specific to the change type of the requested change. public let details: String /// The entity to be changed. public let entity: Entity public init(changeType: String, details: String, entity: Entity) { self.changeType = changeType self.details = details self.entity = entity } public func validate(name: String) throws { try validate(self.changeType, name:"changeType", parent: name, max: 255) try validate(self.changeType, name:"changeType", parent: name, min: 1) try validate(self.changeType, name:"changeType", parent: name, pattern: "^[A-Z][\\w]*$") try validate(self.details, name:"details", parent: name, max: 16384) try validate(self.details, name:"details", parent: name, min: 2) try validate(self.details, name:"details", parent: name, pattern: "^[\\s]*\\{[\\s\\S]*\\}[\\s]*$") try self.entity.validate(name: "\(name).entity") } private enum CodingKeys: String, CodingKey { case changeType = "ChangeType" case details = "Details" case entity = "Entity" } } public struct ChangeSetSummaryListItem: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ChangeSetArn", required: false, type: .string), AWSShapeMember(label: "ChangeSetId", required: false, type: .string), AWSShapeMember(label: "ChangeSetName", required: false, type: .string), AWSShapeMember(label: "EndTime", required: false, type: .string), AWSShapeMember(label: "EntityIdList", required: false, type: .list), AWSShapeMember(label: "StartTime", required: false, type: .string), AWSShapeMember(label: "Status", required: false, type: .enum) ] /// The ARN associated with the unique identifier for the change set referenced in this request. public let changeSetArn: String? /// The unique identifier for a change set. public let changeSetId: String? /// The non-unique name for the change set. public let changeSetName: String? /// The time, in ISO 8601 format (2018-02-27T13:45:22Z), when the change set was finished. public let endTime: String? /// This object is a list of entity IDs (string) that are a part of a change set. The entity ID list is a maximum of 20 entities. It must contain at least one entity. public let entityIdList: [String]? /// The time, in ISO 8601 format (2018-02-27T13:45:22Z), when the change set was started. public let startTime: String? /// The current status of the change set. public let status: ChangeStatus? public init(changeSetArn: String? = nil, changeSetId: String? = nil, changeSetName: String? = nil, endTime: String? = nil, entityIdList: [String]? = nil, startTime: String? = nil, status: ChangeStatus? = nil) { self.changeSetArn = changeSetArn self.changeSetId = changeSetId self.changeSetName = changeSetName self.endTime = endTime self.entityIdList = entityIdList self.startTime = startTime self.status = status } private enum CodingKeys: String, CodingKey { case changeSetArn = "ChangeSetArn" case changeSetId = "ChangeSetId" case changeSetName = "ChangeSetName" case endTime = "EndTime" case entityIdList = "EntityIdList" case startTime = "StartTime" case status = "Status" } } public struct ChangeSummary: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ChangeType", required: false, type: .string), AWSShapeMember(label: "Entity", required: false, type: .structure), AWSShapeMember(label: "ErrorDetailList", required: false, type: .list) ] /// The type of the change. public let changeType: String? /// The entity to be changed. public let entity: Entity? /// An array of ErrorDetail objects associated with the change. public let errorDetailList: [ErrorDetail]? public init(changeType: String? = nil, entity: Entity? = nil, errorDetailList: [ErrorDetail]? = nil) { self.changeType = changeType self.entity = entity self.errorDetailList = errorDetailList } private enum CodingKeys: String, CodingKey { case changeType = "ChangeType" case entity = "Entity" case errorDetailList = "ErrorDetailList" } } public struct DescribeChangeSetRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Catalog", location: .querystring(locationName: "catalog"), required: true, type: .string), AWSShapeMember(label: "ChangeSetId", location: .querystring(locationName: "changeSetId"), required: true, type: .string) ] /// Required. The catalog related to the request. Fixed value: AWSMarketplace public let catalog: String /// Required. The unique identifier for the StartChangeSet request that you want to describe the details for. public let changeSetId: String public init(catalog: String, changeSetId: String) { self.catalog = catalog self.changeSetId = changeSetId } public func validate(name: String) throws { try validate(self.catalog, name:"catalog", parent: name, max: 64) try validate(self.catalog, name:"catalog", parent: name, min: 1) try validate(self.catalog, name:"catalog", parent: name, pattern: "^[a-zA-Z]+$") try validate(self.changeSetId, name:"changeSetId", parent: name, max: 255) try validate(self.changeSetId, name:"changeSetId", parent: name, min: 1) try validate(self.changeSetId, name:"changeSetId", parent: name, pattern: "^[\\w\\-]+$") } private enum CodingKeys: String, CodingKey { case catalog = "catalog" case changeSetId = "changeSetId" } } public struct DescribeChangeSetResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ChangeSet", required: false, type: .list), AWSShapeMember(label: "ChangeSetArn", required: false, type: .string), AWSShapeMember(label: "ChangeSetId", required: false, type: .string), AWSShapeMember(label: "ChangeSetName", required: false, type: .string), AWSShapeMember(label: "EndTime", required: false, type: .string), AWSShapeMember(label: "FailureDescription", required: false, type: .string), AWSShapeMember(label: "StartTime", required: false, type: .string), AWSShapeMember(label: "Status", required: false, type: .enum) ] /// An array of ChangeSummary objects. public let changeSet: [ChangeSummary]? /// The ARN associated with the unique identifier for the change set referenced in this request. public let changeSetArn: String? /// Required. The unique identifier for the change set referenced in this request. public let changeSetId: String? /// The optional name provided in the StartChangeSet request. If you do not provide a name, one is set by default. public let changeSetName: String? /// The date and time, in ISO 8601 format (2018-02-27T13:45:22Z), the request transitioned to a terminal state. The change cannot transition to a different state. Null if the request is not in a terminal state. public let endTime: String? /// Returned if there is a failure on the change set, but that failure is not related to any of the changes in the request. public let failureDescription: String? /// The date and time, in ISO 8601 format (2018-02-27T13:45:22Z), the request started. public let startTime: String? /// The status of the change request. public let status: ChangeStatus? public init(changeSet: [ChangeSummary]? = nil, changeSetArn: String? = nil, changeSetId: String? = nil, changeSetName: String? = nil, endTime: String? = nil, failureDescription: String? = nil, startTime: String? = nil, status: ChangeStatus? = nil) { self.changeSet = changeSet self.changeSetArn = changeSetArn self.changeSetId = changeSetId self.changeSetName = changeSetName self.endTime = endTime self.failureDescription = failureDescription self.startTime = startTime self.status = status } private enum CodingKeys: String, CodingKey { case changeSet = "ChangeSet" case changeSetArn = "ChangeSetArn" case changeSetId = "ChangeSetId" case changeSetName = "ChangeSetName" case endTime = "EndTime" case failureDescription = "FailureDescription" case startTime = "StartTime" case status = "Status" } } public struct DescribeEntityRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Catalog", location: .querystring(locationName: "catalog"), required: true, type: .string), AWSShapeMember(label: "EntityId", location: .querystring(locationName: "entityId"), required: true, type: .string) ] /// Required. The catalog related to the request. Fixed value: AWSMarketplace public let catalog: String /// Required. The unique ID of the entity to describe. public let entityId: String public init(catalog: String, entityId: String) { self.catalog = catalog self.entityId = entityId } public func validate(name: String) throws { try validate(self.catalog, name:"catalog", parent: name, max: 64) try validate(self.catalog, name:"catalog", parent: name, min: 1) try validate(self.catalog, name:"catalog", parent: name, pattern: "^[a-zA-Z]+$") try validate(self.entityId, name:"entityId", parent: name, max: 255) try validate(self.entityId, name:"entityId", parent: name, min: 1) try validate(self.entityId, name:"entityId", parent: name, pattern: "^[\\w\\-]+$") } private enum CodingKeys: String, CodingKey { case catalog = "catalog" case entityId = "entityId" } } public struct DescribeEntityResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Details", required: false, type: .string), AWSShapeMember(label: "EntityArn", required: false, type: .string), AWSShapeMember(label: "EntityIdentifier", required: false, type: .string), AWSShapeMember(label: "EntityType", required: false, type: .string), AWSShapeMember(label: "LastModifiedDate", required: false, type: .string) ] /// This stringified JSON object includes the details of the entity. public let details: String? /// The ARN associated to the unique identifier for the change set referenced in this request. public let entityArn: String? /// The identifier of the entity, in the format of EntityId@RevisionId. public let entityIdentifier: String? /// The named type of the entity, in the format of EntityType@Version. public let entityType: String? /// The last modified date of the entity, in ISO 8601 format (2018-02-27T13:45:22Z). public let lastModifiedDate: String? public init(details: String? = nil, entityArn: String? = nil, entityIdentifier: String? = nil, entityType: String? = nil, lastModifiedDate: String? = nil) { self.details = details self.entityArn = entityArn self.entityIdentifier = entityIdentifier self.entityType = entityType self.lastModifiedDate = lastModifiedDate } private enum CodingKeys: String, CodingKey { case details = "Details" case entityArn = "EntityArn" case entityIdentifier = "EntityIdentifier" case entityType = "EntityType" case lastModifiedDate = "LastModifiedDate" } } public struct Entity: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Identifier", required: false, type: .string), AWSShapeMember(label: "Type", required: true, type: .string) ] /// The identifier for the entity. public let identifier: String? /// The type of entity. public let `type`: String public init(identifier: String? = nil, type: String) { self.identifier = identifier self.`type` = `type` } public func validate(name: String) throws { try validate(self.identifier, name:"identifier", parent: name, max: 255) try validate(self.identifier, name:"identifier", parent: name, min: 1) try validate(self.identifier, name:"identifier", parent: name, pattern: "^[\\w\\-@]+$") try validate(self.`type`, name:"`type`", parent: name, max: 255) try validate(self.`type`, name:"`type`", parent: name, min: 1) try validate(self.`type`, name:"`type`", parent: name, pattern: "^[a-zA-Z]+$") } private enum CodingKeys: String, CodingKey { case identifier = "Identifier" case `type` = "Type" } } public struct EntitySummary: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "EntityArn", required: false, type: .string), AWSShapeMember(label: "EntityId", required: false, type: .string), AWSShapeMember(label: "EntityType", required: false, type: .string), AWSShapeMember(label: "LastModifiedDate", required: false, type: .string), AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "Visibility", required: false, type: .string) ] /// The ARN associated with the unique identifier for the entity. public let entityArn: String? /// The unique identifier for the entity. public let entityId: String? /// The type of the entity. public let entityType: String? /// The last time the entity was published, using ISO 8601 format (2018-02-27T13:45:22Z). public let lastModifiedDate: String? /// The name for the entity. This value is not unique. It is defined by the provider. public let name: String? /// The visibility status of the entity to subscribers. This value can be Public (everyone can view the entity), Limited (the entity is visible to limited accounts only), or Restricted (the entity was published and then unpublished and only existing subscribers can view it). public let visibility: String? public init(entityArn: String? = nil, entityId: String? = nil, entityType: String? = nil, lastModifiedDate: String? = nil, name: String? = nil, visibility: String? = nil) { self.entityArn = entityArn self.entityId = entityId self.entityType = entityType self.lastModifiedDate = lastModifiedDate self.name = name self.visibility = visibility } private enum CodingKeys: String, CodingKey { case entityArn = "EntityArn" case entityId = "EntityId" case entityType = "EntityType" case lastModifiedDate = "LastModifiedDate" case name = "Name" case visibility = "Visibility" } } public struct ErrorDetail: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ErrorCode", required: false, type: .string), AWSShapeMember(label: "ErrorMessage", required: false, type: .string) ] /// The error code that identifies the type of error. public let errorCode: String? /// The message for the error. public let errorMessage: String? public init(errorCode: String? = nil, errorMessage: String? = nil) { self.errorCode = errorCode self.errorMessage = errorMessage } private enum CodingKeys: String, CodingKey { case errorCode = "ErrorCode" case errorMessage = "ErrorMessage" } } public struct Filter: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "ValueList", required: false, type: .list) ] /// For ListEntities, the supported value for this is an EntityId. For ListChangeSets, the supported values are as follows: public let name: String? /// ListEntities - This is a list of unique EntityIds. ListChangeSets - The supported filter names and associated ValueLists is as follows: ChangeSetName - The supported ValueList is a list of non-unique ChangeSetNames. These are defined when you call the StartChangeSet action. Status - The supported ValueList is a list of statuses for all change set requests. EntityId - The supported ValueList is a list of unique EntityIds. BeforeStartTime - The supported ValueList is a list of all change sets that started before the filter value. AfterStartTime - The supported ValueList is a list of all change sets that started after the filter value. BeforeEndTime - The supported ValueList is a list of all change sets that ended before the filter value. AfterEndTime - The supported ValueList is a list of all change sets that ended after the filter value. public let valueList: [String]? public init(name: String? = nil, valueList: [String]? = nil) { self.name = name self.valueList = valueList } public func validate(name: String) throws { try validate(self.name, name:"name", parent: name, max: 255) try validate(self.name, name:"name", parent: name, min: 1) try validate(self.name, name:"name", parent: name, pattern: "^[a-zA-Z]+$") try validate(self.valueList, name:"valueList", parent: name, max: 10) try validate(self.valueList, name:"valueList", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case name = "Name" case valueList = "ValueList" } } public struct ListChangeSetsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Catalog", required: true, type: .string), AWSShapeMember(label: "FilterList", required: false, type: .list), AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "Sort", required: false, type: .structure) ] /// The catalog related to the request. Fixed value: AWSMarketplace public let catalog: String /// An array of filter objects. public let filterList: [Filter]? /// The maximum number of results returned by a single call. This value must be provided in the next call to retrieve the next set of results. By default, this value is 20. public let maxResults: Int? /// The token value retrieved from a previous call to access the next page of results. public let nextToken: String? /// An object that contains two attributes, sortBy and sortOrder. public let sort: Sort? public init(catalog: String, filterList: [Filter]? = nil, maxResults: Int? = nil, nextToken: String? = nil, sort: Sort? = nil) { self.catalog = catalog self.filterList = filterList self.maxResults = maxResults self.nextToken = nextToken self.sort = sort } public func validate(name: String) throws { try validate(self.catalog, name:"catalog", parent: name, max: 64) try validate(self.catalog, name:"catalog", parent: name, min: 1) try validate(self.catalog, name:"catalog", parent: name, pattern: "^[a-zA-Z]+$") try self.filterList?.forEach { try $0.validate(name: "\(name).filterList[]") } try validate(self.filterList, name:"filterList", parent: name, max: 8) try validate(self.filterList, name:"filterList", parent: name, min: 1) try validate(self.maxResults, name:"maxResults", parent: name, max: 20) try validate(self.maxResults, name:"maxResults", parent: name, min: 1) try validate(self.nextToken, name:"nextToken", parent: name, max: 2048) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) try validate(self.nextToken, name:"nextToken", parent: name, pattern: "^[\\w+=.:@\\-\\/]$") try self.sort?.validate(name: "\(name).sort") } private enum CodingKeys: String, CodingKey { case catalog = "Catalog" case filterList = "FilterList" case maxResults = "MaxResults" case nextToken = "NextToken" case sort = "Sort" } } public struct ListChangeSetsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ChangeSetSummaryList", required: false, type: .list), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// Array of ChangeSetSummaryListItem objects. public let changeSetSummaryList: [ChangeSetSummaryListItem]? /// The value of the next token, if it exists. Null if there are no more results. public let nextToken: String? public init(changeSetSummaryList: [ChangeSetSummaryListItem]? = nil, nextToken: String? = nil) { self.changeSetSummaryList = changeSetSummaryList self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case changeSetSummaryList = "ChangeSetSummaryList" case nextToken = "NextToken" } } public struct ListEntitiesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Catalog", required: true, type: .string), AWSShapeMember(label: "EntityType", required: true, type: .string), AWSShapeMember(label: "FilterList", required: false, type: .list), AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "Sort", required: false, type: .structure) ] /// The catalog related to the request. Fixed value: AWSMarketplace public let catalog: String /// The type of entities to retrieve. public let entityType: String /// An array of filter objects. Each filter object contains two attributes, filterName and filterValues. public let filterList: [Filter]? /// Specifies the upper limit of the elements on a single page. If a value isn't provided, the default value is 20. public let maxResults: Int? /// The value of the next token, if it exists. Null if there are no more results. public let nextToken: String? /// An object that contains two attributes, sortBy and sortOrder. public let sort: Sort? public init(catalog: String, entityType: String, filterList: [Filter]? = nil, maxResults: Int? = nil, nextToken: String? = nil, sort: Sort? = nil) { self.catalog = catalog self.entityType = entityType self.filterList = filterList self.maxResults = maxResults self.nextToken = nextToken self.sort = sort } public func validate(name: String) throws { try validate(self.catalog, name:"catalog", parent: name, max: 64) try validate(self.catalog, name:"catalog", parent: name, min: 1) try validate(self.catalog, name:"catalog", parent: name, pattern: "^[a-zA-Z]+$") try validate(self.entityType, name:"entityType", parent: name, max: 255) try validate(self.entityType, name:"entityType", parent: name, min: 1) try validate(self.entityType, name:"entityType", parent: name, pattern: "^[a-zA-Z]+$") try self.filterList?.forEach { try $0.validate(name: "\(name).filterList[]") } try validate(self.filterList, name:"filterList", parent: name, max: 8) try validate(self.filterList, name:"filterList", parent: name, min: 1) try validate(self.maxResults, name:"maxResults", parent: name, max: 20) try validate(self.maxResults, name:"maxResults", parent: name, min: 1) try validate(self.nextToken, name:"nextToken", parent: name, max: 2048) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) try validate(self.nextToken, name:"nextToken", parent: name, pattern: "^[\\w+=.:@\\-\\/]$") try self.sort?.validate(name: "\(name).sort") } private enum CodingKeys: String, CodingKey { case catalog = "Catalog" case entityType = "EntityType" case filterList = "FilterList" case maxResults = "MaxResults" case nextToken = "NextToken" case sort = "Sort" } } public struct ListEntitiesResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "EntitySummaryList", required: false, type: .list), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// Array of EntitySummary object. public let entitySummaryList: [EntitySummary]? /// The value of the next token if it exists. Null if there is no more result. public let nextToken: String? public init(entitySummaryList: [EntitySummary]? = nil, nextToken: String? = nil) { self.entitySummaryList = entitySummaryList self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case entitySummaryList = "EntitySummaryList" case nextToken = "NextToken" } } public struct Sort: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "SortBy", required: false, type: .string), AWSShapeMember(label: "SortOrder", required: false, type: .enum) ] /// For ListEntities, supported attributes include LastModifiedDate (default), Visibility, EntityId, and Name. For ListChangeSets, supported attributes include StartTime and EndTime. public let sortBy: String? /// The sorting order. Can be ASCENDING or DESCENDING. The default value is DESCENDING. public let sortOrder: SortOrder? public init(sortBy: String? = nil, sortOrder: SortOrder? = nil) { self.sortBy = sortBy self.sortOrder = sortOrder } public func validate(name: String) throws { try validate(self.sortBy, name:"sortBy", parent: name, max: 255) try validate(self.sortBy, name:"sortBy", parent: name, min: 1) try validate(self.sortBy, name:"sortBy", parent: name, pattern: "^[a-zA-Z]+$") } private enum CodingKeys: String, CodingKey { case sortBy = "SortBy" case sortOrder = "SortOrder" } } public struct StartChangeSetRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Catalog", required: true, type: .string), AWSShapeMember(label: "ChangeSet", required: true, type: .list), AWSShapeMember(label: "ChangeSetName", required: false, type: .string), AWSShapeMember(label: "ClientRequestToken", required: false, type: .string) ] /// The catalog related to the request. Fixed value: AWSMarketplace public let catalog: String /// Array of change object. public let changeSet: [Change] /// Optional case sensitive string of up to 100 ASCII characters. The change set name can be used to filter the list of change sets. public let changeSetName: String? /// A unique token to identify the request to ensure idempotency. public let clientRequestToken: String? public init(catalog: String, changeSet: [Change], changeSetName: String? = nil, clientRequestToken: String? = nil) { self.catalog = catalog self.changeSet = changeSet self.changeSetName = changeSetName self.clientRequestToken = clientRequestToken } public func validate(name: String) throws { try validate(self.catalog, name:"catalog", parent: name, max: 64) try validate(self.catalog, name:"catalog", parent: name, min: 1) try validate(self.catalog, name:"catalog", parent: name, pattern: "^[a-zA-Z]+$") try self.changeSet.forEach { try $0.validate(name: "\(name).changeSet[]") } try validate(self.changeSet, name:"changeSet", parent: name, max: 20) try validate(self.changeSet, name:"changeSet", parent: name, min: 1) try validate(self.changeSetName, name:"changeSetName", parent: name, max: 100) try validate(self.changeSetName, name:"changeSetName", parent: name, min: 1) try validate(self.changeSetName, name:"changeSetName", parent: name, pattern: "^[\\w\\s+=.:@-]+$") try validate(self.clientRequestToken, name:"clientRequestToken", parent: name, max: 36) try validate(self.clientRequestToken, name:"clientRequestToken", parent: name, min: 1) try validate(self.clientRequestToken, name:"clientRequestToken", parent: name, pattern: "^[\\w\\-]+$") } private enum CodingKeys: String, CodingKey { case catalog = "Catalog" case changeSet = "ChangeSet" case changeSetName = "ChangeSetName" case clientRequestToken = "ClientRequestToken" } } public struct StartChangeSetResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ChangeSetArn", required: false, type: .string), AWSShapeMember(label: "ChangeSetId", required: false, type: .string) ] /// The ARN associated to the unique identifier generated for the request. public let changeSetArn: String? /// Unique identifier generated for the request. public let changeSetId: String? public init(changeSetArn: String? = nil, changeSetId: String? = nil) { self.changeSetArn = changeSetArn self.changeSetId = changeSetId } private enum CodingKeys: String, CodingKey { case changeSetArn = "ChangeSetArn" case changeSetId = "ChangeSetId" } } }
49.211034
885
0.62568
213a8995db22dbc6b752977af25bb4578c372c25
4,956
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest import AmplifyPlugins import AWSPluginsCore @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStoreCategoryPlugin class DataStoreConfigurationTests: XCTestCase { override func setUp() { Amplify.reset() } override func tearDown() { Amplify.DataStore.clear(completion: { _ in }) } func testConfigureWithSameSchemaDoesNotDeleteDatabase() throws { let previousVersion = "previousVersion" let saveSuccess = expectation(description: "Save was successful") do { let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels(version: previousVersion)) try Amplify.add(plugin: dataStorePlugin) try Amplify.configure(AmplifyConfiguration(dataStore: nil)) } catch { XCTFail("Failed to initialize Amplify with \(error)") } let post = Post(title: "title", content: "content", createdAt: .now()) Amplify.DataStore.save(post, completion: { result in switch result { case .success: saveSuccess.fulfill() case .failure(let error): XCTFail("Error saving post \(error)") } }) wait(for: [saveSuccess], timeout: TestCommonConstants.networkTimeout) Amplify.reset() let querySuccess = expectation(description: "query was successful") do { let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels(version: previousVersion)) try Amplify.add(plugin: dataStorePlugin) try Amplify.configure(AmplifyConfiguration(dataStore: nil)) } catch { XCTFail("Failed to initialize Amplify with \(error)") } // Query for the previously saved post. Data should be retrieved successfully which indicates that // the database file was not deleted after re-configuring Amplify when using the same model registry version Amplify.DataStore.query(Post.self, byId: post.id) { result in switch result { case .success(let postResult): guard let queriedPost = postResult else { XCTFail("could not retrieve post across Amplify re-configure") return } XCTAssertEqual(queriedPost.title, "title") XCTAssertEqual(queriedPost.content, "content") XCTAssertEqual(queriedPost.createdAt, post.createdAt) querySuccess.fulfill() case .failure(let error): XCTFail("Failed to query post, error: \(error)") } } wait(for: [querySuccess], timeout: TestCommonConstants.networkTimeout) } func testConfigureWithDifferentSchemaClearsDatabase() throws { let prevoisVersion = "previousVersion" let saveSuccess = expectation(description: "Save was successful") do { let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels(version: prevoisVersion)) try Amplify.add(plugin: dataStorePlugin) try Amplify.configure(AmplifyConfiguration(dataStore: nil)) } catch { XCTFail("Failed to initialize Amplify with \(error)") } let post = Post(title: "title", content: "content", createdAt: .now()) Amplify.DataStore.save(post, completion: { result in switch result { case .success: saveSuccess.fulfill() case .failure(let error): XCTFail("Error saving post \(error)") } }) wait(for: [saveSuccess], timeout: TestCommonConstants.networkTimeout) Amplify.reset() let querySuccess = expectation(description: "query was successful") do { let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels(version: "1234")) try Amplify.add(plugin: dataStorePlugin) try Amplify.configure(AmplifyConfiguration(dataStore: nil)) } catch { XCTFail("Failed to initialize Amplify with \(error)") } // Query for the previously saved post. Data should not be retrieved successfully which indicates that // the database file was deleted after re-configuring Amplify when using a different model registry version Amplify.DataStore.query(Post.self) { result in switch result { case .success(let postResult): XCTAssertTrue(postResult.isEmpty) querySuccess.fulfill() case .failure(let error): XCTFail(error.errorDescription) } } wait(for: [querySuccess], timeout: TestCommonConstants.networkTimeout) } }
35.654676
116
0.628329
ed2beb83cac44a0322b27f74c4f11fe6302d782c
13,130
import XCTest @testable import NdArray // swiftlint:disable:next type_name class initTests: XCTestCase { func testInitShouldConstructContiguousArrayWhenInitializedFrom2dArrays() { do { let a = NdArray<Double>([[1, 2, 3], [4, 5, 6]], order: .C) XCTAssertEqual(a.dataArray, [1, 2, 3, 4, 5, 6]) XCTAssertEqual(a.strides, [3, 1]) XCTAssertTrue(a.isCContiguous) XCTAssertFalse(a.isFContiguous) } do { let a = NdArray<Double>([[1, 2, 3], [4, 5, 6]], order: .F) XCTAssertEqual(a.dataArray, [1, 4, 2, 5, 3, 6]) XCTAssertEqual(a.strides, [1, 2]) XCTAssertTrue(a.isFContiguous) XCTAssertFalse(a.isCContiguous) } } func testInit1dShouldCreateContiguousArray() { let a = NdArray<Double>([1, 2, 3]) XCTAssert(a.ownsData) XCTAssertEqual(a.dataArray, [1, 2, 3]) XCTAssertEqual(a.shape, [3]) XCTAssertEqual(a.strides, [1]) XCTAssert(a.isCContiguous) XCTAssert(a.isFContiguous) } func testInit1dShouldCreateEmptyArray() { let a = NdArray<Double>([]) XCTAssert(a.ownsData) XCTAssertEqual(a.dataArray, []) XCTAssertEqual(a.shape, [0]) XCTAssertEqual(a.strides, [1]) XCTAssert(a.isCContiguous) XCTAssert(a.isFContiguous) } func testInit2dShouldCreateContiguousArray() { let a = NdArray<Double>([[1, 2, 3], [4, 5, 6]]) XCTAssert(a.ownsData) XCTAssertEqual(a.dataArray, [1, 2, 3, 4, 5, 6]) XCTAssertEqual(a.shape, [2, 3]) XCTAssertEqual(a.strides, [3, 1]) XCTAssert(a.isCContiguous) XCTAssertFalse(a.isFContiguous) } func testInit2dShouldCreateEmptyArray() { let a = NdArray<Double>([[Double]]()) XCTAssert(a.ownsData) XCTAssertEqual(a.dataArray, []) XCTAssertEqual(a.shape, [1, 0]) XCTAssertEqual(a.strides, [1, 1]) XCTAssert(a.isCContiguous) XCTAssert(a.isFContiguous) } func testInit3dShouldCreateEmptyArray() { let a = NdArray<Double>([[[Double]]]()) XCTAssert(a.ownsData) XCTAssertEqual(a.dataArray, []) XCTAssertEqual(a.shape, [1, 1, 0]) XCTAssertEqual(a.strides, [1, 1, 1]) XCTAssert(a.isCContiguous) XCTAssert(a.isFContiguous) } func testInit3dShouldCreateCContiguousArray() { let a = NdArray<Double>( [[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 07, 08], [ 9, 10, 11]]]) XCTAssert(a.ownsData) XCTAssertEqual(a.dataArray, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) XCTAssertEqual(a.shape, [2, 2, 3]) XCTAssertEqual(a.strides, [6, 3, 1]) XCTAssert(a.isCContiguous) XCTAssertFalse(a.isFContiguous) } func testInit3dShouldCreateFContiguousArray() { let a = NdArray<Double>( [[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 07, 08], [ 9, 10, 11]]], order: .F) XCTAssert(a.ownsData) XCTAssertEqual(a.dataArray, [ 0, 6, 3, 9, 1, 7, 4, 10, 2, 8, 5, 11]) XCTAssertEqual(a.shape, [2, 2, 3]) XCTAssertEqual(a.strides, [1, 2, 4]) XCTAssertFalse(a.isCContiguous) XCTAssert(a.isFContiguous) } func testInitZeros1dShouldCreateZerosArray() { do { let a = NdArray<Double>.zeros(3) XCTAssertEqual(a.dataArray, [0, 0, 0]) XCTAssertEqual(a.shape, [3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Float>.zeros(3) XCTAssertEqual(a.dataArray, [0, 0, 0]) XCTAssertEqual(a.shape, [3]) XCTAssert(a.isCContiguous) } } func testInitOnes1dShouldCreateZerosArray() { do { let a = NdArray<Double>.ones(3) XCTAssertEqual(a.dataArray, [1, 1, 1]) XCTAssertEqual(a.shape, [3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Float>.ones(3) XCTAssertEqual(a.dataArray, [1, 1, 1]) XCTAssertEqual(a.shape, [3]) XCTAssert(a.isCContiguous) } } func testInitRepeating1dShouldCreateZerosArray() { do { let a = NdArray<Double>.repeating(3, count: 3) XCTAssertEqual(a.dataArray, [3, 3, 3]) XCTAssertEqual(a.shape, [3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Float>.repeating(3, count: 3) XCTAssertEqual(a.dataArray, [3, 3, 3]) XCTAssertEqual(a.shape, [3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Int>.repeating(3, count: 3) XCTAssertEqual(a.dataArray, [3, 3, 3]) XCTAssertEqual(a.shape, [3]) XCTAssert(a.isCContiguous) } } func testInitZeros2dShouldCreateZerosArray() { do { let a = NdArray<Double>.zeros([2, 3], order: .C) XCTAssertEqual(a.dataArray, [0, 0, 0, 0, 0, 0]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Double>.zeros([2, 3], order: .F) XCTAssertEqual(a.dataArray, [0, 0, 0, 0, 0, 0]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isFContiguous) } do { let a = NdArray<Float>.zeros([2, 3], order: .C) XCTAssertEqual(a.dataArray, [0, 0, 0, 0, 0, 0]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Float>.zeros([2, 3], order: .F) XCTAssertEqual(a.dataArray, [0, 0, 0, 0, 0, 0]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isFContiguous) } } func testInitOnes2dShouldCreateZerosArray() { do { let a = NdArray<Double>.ones([2, 3], order: .C) XCTAssertEqual(a.dataArray, [1, 1, 1, 1, 1, 1]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Double>.ones([2, 3], order: .F) XCTAssertEqual(a.dataArray, [1, 1, 1, 1, 1, 1]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isFContiguous) } do { let a = NdArray<Float>.ones([2, 3], order: .C) XCTAssertEqual(a.dataArray, [1, 1, 1, 1, 1, 1]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Float>.ones([2, 3], order: .F) XCTAssertEqual(a.dataArray, [1, 1, 1, 1, 1, 1]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isFContiguous) } } func testInitRepeating2dShouldCreateZerosArray() { do { let a = NdArray<Double>.repeating(3, shape: [2, 3], order: .C) XCTAssertEqual(a.dataArray, [3, 3, 3, 3, 3, 3]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Double>.repeating(3, shape: [2, 3], order: .F) XCTAssertEqual(a.dataArray, [3, 3, 3, 3, 3, 3]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isFContiguous) } do { let a = NdArray<Float>.repeating(3, shape: [2, 3], order: .C) XCTAssertEqual(a.dataArray, [3, 3, 3, 3, 3, 3]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Float>.repeating(3, shape: [2, 3], order: .F) XCTAssertEqual(a.dataArray, [3, 3, 3, 3, 3, 3]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isFContiguous) } do { let a = NdArray<Int>.repeating(3, shape: [2, 3], order: .C) XCTAssertEqual(a.dataArray, [3, 3, 3, 3, 3, 3]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isCContiguous) } do { let a = NdArray<Int>.repeating(3, shape: [2, 3], order: .F) XCTAssertEqual(a.dataArray, [3, 3, 3, 3, 3, 3]) XCTAssertEqual(a.shape, [2, 3]) XCTAssert(a.isFContiguous) } } func testInitShouldCreateCContiguousViewWhenSourceIsCContiguous() { let a = NdArray<Double>.range(to: 5) let b = NdArray<Double>(a, order: .C) XCTAssertEqual(a.dataArray, b.dataArray) XCTAssert(a.ownsData) XCTAssertFalse(b.ownsData) XCTAssert(a.isCContiguous) XCTAssert(b.isCContiguous) } func testInitShouldCreateCContiguousViewWhenSourceIsNotCContiguous() { let a = NdArray<Double>.range(to: 5)[..., 2] let b = NdArray<Double>(a, order: .C) XCTAssert(b.ownsData) XCTAssert(b.ownsData) XCTAssertFalse(a.isCContiguous) XCTAssert(b.isCContiguous) } func testInitShouldCreateFContiguousViewWhenSourceIsCContiguous() { let a = NdArray<Double>.range(to: 5) let b = NdArray<Double>(a, order: .F) XCTAssertEqual(a.dataArray, b.dataArray) XCTAssert(a.ownsData) XCTAssertFalse(b.ownsData) XCTAssert(a.isCContiguous) XCTAssert(b.isCContiguous) } func testInitShouldCreateFContiguousViewWhenSourceIsNotCContiguous() { let a = NdArray<Double>.range(to: 5)[..., 2] let b = NdArray<Double>(a, order: .F) XCTAssert(b.ownsData) XCTAssert(b.ownsData) XCTAssertFalse(a.isCContiguous) XCTAssert(b.isCContiguous) } func testInitShouldCreateCContiguousCopyWhenSourceIsCContiguous() { let a = NdArray<Double>.range(to: 5) let b = NdArray<Double>(copy: a, order: .C) XCTAssertEqual(a.dataArray, b.dataArray) XCTAssert(a.ownsData) XCTAssert(b.ownsData) XCTAssert(a.isCContiguous) XCTAssert(b.isCContiguous) } func testInitShouldCreateCContiguousCopyWhenSourceIsNotCContiguous() { let a = NdArray<Double>.range(to: 5)[..., 2] let b = NdArray<Double>(copy: a, order: .C) XCTAssert(b.ownsData) XCTAssert(b.ownsData) XCTAssertFalse(a.isCContiguous) XCTAssert(b.isCContiguous) } func testInitShouldCreateFContiguousCopyWhenSourceIsCContiguous() { let a = NdArray<Double>.range(to: 5) let b = NdArray<Double>(copy: a, order: .F) XCTAssertEqual(a.dataArray, b.dataArray) XCTAssert(a.ownsData) XCTAssert(b.ownsData) XCTAssert(a.isCContiguous) XCTAssert(b.isCContiguous) } func testInitShouldCreateFContiguousCopyWhenSourceIsNotCContiguous() { let a = NdArray<Double>.range(to: 5)[..., 2] let b = NdArray<Double>(copy: a, order: .F) XCTAssert(b.ownsData) XCTAssert(b.ownsData) XCTAssertFalse(a.isCContiguous) XCTAssert(b.isCContiguous) } func testRangeShouldCreateHalfOpenIntervalWhenTypeIsDouble() { XCTAssertEqual(NdArray<Double>.range(to: 3).dataArray, [0, 1, 2]) XCTAssertEqual(NdArray<Double>.range(from: 1, to: 3).dataArray, [1, 2]) XCTAssertEqual(NdArray<Double>.range(from: 1, to: 3, by: 2).dataArray, [1]) XCTAssertEqual(NdArray<Double>.range(to: 3, by: 0.7).dataArray, [0.0, 0.7, 1.4, 2.1, 2.8], accuracy: 1e-15) XCTAssertEqual(NdArray<Double>.range(to: 3, by: 1.1).dataArray, [0.0, 1.1, 2.2], accuracy: 1e-15) XCTAssertEqual(NdArray<Double>.range(to: 3, by: -1).dataArray, []) XCTAssertEqual(NdArray<Double>.range(from: 3, to: 0, by: 1).dataArray, []) XCTAssertEqual(NdArray<Double>.range(from: 3, to: 0, by: -1).dataArray, [3, 2, 1]) XCTAssertEqual(NdArray<Double>.range(from: 3, to: 0, by: -1.1).dataArray, [3.0, 1.9, 0.8], accuracy: 1e-15) XCTAssertEqual(NdArray<Double>.range(from: 3, to: 0, by: -0.7).dataArray, [3.0, 2.3, 1.6, 0.9, 0.2], accuracy: 1e-15) } func testRangeShouldCreateHalfOpenIntervalWhenTypeIsFloat() { XCTAssertEqual(NdArray<Float>.range(to: 3).dataArray, [0, 1, 2]) XCTAssertEqual(NdArray<Float>.range(from: 1, to: 3).dataArray, [1, 2]) XCTAssertEqual(NdArray<Float>.range(from: 1, to: 3, by: 2).dataArray, [1]) XCTAssertEqual(NdArray<Float>.range(to: 3, by: 0.7).dataArray, [0.0, 0.7, 1.4, 2.1, 2.8], accuracy: 1e-6) XCTAssertEqual(NdArray<Float>.range(to: 3, by: 1.1).dataArray, [0.0, 1.1, 2.2], accuracy: 1e-6) XCTAssertEqual(NdArray<Float>.range(to: 3, by: -1).dataArray, []) XCTAssertEqual(NdArray<Float>.range(from: 3, to: 0, by: 1).dataArray, []) XCTAssertEqual(NdArray<Float>.range(from: 3, to: 0, by: -1).dataArray, [3, 2, 1]) XCTAssertEqual(NdArray<Float>.range(from: 3, to: 0, by: -1.1).dataArray, [3.0, 1.9, 0.8], accuracy: 1e-6) XCTAssertEqual(NdArray<Float>.range(from: 3, to: 0, by: -0.7).dataArray, [3.0, 2.3, 1.6, 0.9, 0.2], accuracy: 1e-6) } }
36.778711
125
0.562224
4a7f273b88e4fe22d6db83ce8b9b8cda66e731c6
3,235
// // MapViewController.swift // Awesome // // Created by Nicholas on 2021/10/12. // import UIKit import MAMapKit import AMapFoundationKit class MapViewController: MainViewController { var mapView: MAMapView! var customUserLocationView: MAAnnotationView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white initMapView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) mapView.showsUserLocation = true mapView.customizeUserLocationAccuracyCircleRepresentation = true mapView.userTrackingMode = .follow } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initMapView() { mapView = MAMapView(frame: self.view.bounds) mapView.delegate = self mapView.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth] mapView.setZoomLevel(17.5, animated: true) self.view.addSubview(mapView) } } // MARK: - MAMapViewDelegate extension MapViewController: MAMapViewDelegate { func mapViewRequireLocationAuth(_ locationManager: CLLocationManager!) { locationManager.requestAlwaysAuthorization() } func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! { if annotation.isKind(of: MAUserLocation.self) { let pointReuseIndetifier = "userLocationStyleReuseIndetifier" var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier) if annotationView == nil { annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier) } annotationView!.image = UIImage(systemName: "location") self.customUserLocationView = annotationView return (annotationView!) } return nil } func mapView(_ mapView:MAMapView!, rendererFor overlay:MAOverlay) -> MAOverlayRenderer! { if(overlay.isEqual(mapView.userLocationAccuracyCircle)) { let circleRender = MACircleRenderer.init(circle:mapView.userLocationAccuracyCircle) circleRender?.lineWidth = 2.0 circleRender?.strokeColor = UIColor.lightGray circleRender?.fillColor = UIColor.red.withAlphaComponent(0.3) return circleRender } return nil } func mapView(_ mapView:MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation:Bool ) { if(!updatingLocation && self.customUserLocationView != nil) { UIView.animate(withDuration: 0.1, animations: { let degree = userLocation.heading.trueHeading - Double(self.mapView.rotationDegree) let radian = (degree * Double.pi) / 180.0 self.customUserLocationView.transform = CGAffineTransform.init(rotationAngle: CGFloat(radian)) }) } } }
33.697917
114
0.653168
212ae46d5e08ea2ebc99e8835cddc63365ce8ad2
1,349
// // AppDelegate.swift // Prework // // Created by Sophie Tompkins on 1/27/22. // 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.459459
179
0.745738
0e71144eb9e7290a158d9fc8935f63e3e92959ea
378
// // FileManager+stlr.swift // stlr // // Created by RED When Excited on 10/01/2018. // import Foundation public extension FileManager{ public func isDirectory(_ url:URL)->Bool{ var isDirectory : ObjCBool = false let _ = fileExists(atPath: url.path, isDirectory: &isDirectory) return isDirectory.description == "true" } }
19.894737
71
0.632275
f79e1c8267e5ec8ef5815b57b0e4c501953a237a
2,017
// // LEERuleDescView.swift // LEERandom // // Created by 李江波 on 2017/11/18. // Copyright © 2017年 lijiangbo. All rights reserved. // import UIKit class LEERuleDescView: UIView { @IBOutlet weak var ruleImageV: UIImageView! @IBOutlet weak var closeButton: HighlightButton! enum RuleType { case RuleTypeBall case RuleTypeCard case RuleTypeGroup } public var type: RuleType? { didSet { switch type { case .RuleTypeBall?: ruleImageV.image = #imageLiteral(resourceName: "chouqiuqiu-guize") closeButton.setImage(#imageLiteral(resourceName: "close"), for: .normal) closeButton.setImage(#imageLiteral(resourceName: "close"), for: .highlighted) break case .RuleTypeCard?: ruleImageV.image = #imageLiteral(resourceName: "fankapian-guize") closeButton.setImage(#imageLiteral(resourceName: "close"), for: .normal) closeButton.setImage(#imageLiteral(resourceName: "close"), for: .highlighted) break case .RuleTypeGroup?: ruleImageV.image = #imageLiteral(resourceName: "fenzu-guize") closeButton.setImage(#imageLiteral(resourceName: "tanchuang_close"), for: .normal) closeButton.setImage(#imageLiteral(resourceName: "tanchuang_close"), for: .highlighted) break case .none: ruleImageV.image = #imageLiteral(resourceName: "chouqiuqiu-guize") closeButton.setImage(#imageLiteral(resourceName: "close"), for: .normal) closeButton.setImage(#imageLiteral(resourceName: "close"), for: .highlighted) } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.removeFromSuperview() } @IBAction func closeAction(_ sender: Any) { self.removeFromSuperview() } }
33.616667
103
0.603867
db661d7d690f12c8b8e6997a94472020ddd19c6c
1,054
// // ErrorChatItem.swift // Barcelona // // Created by Eric Rabil on 10/28/21. // import Foundation import IMCore public struct ErrorChatItem: ChatItem, Hashable { public var type: ChatItemType { .error } public static let ingestionClasses: [NSObject.Type] = [IMErrorMessagePartChatItem.self] public init?(ingesting item: NSObject, context: IngestionContext) { self.init(item as! IMErrorMessagePartChatItem, chatID: context.chatID) } init(_ item: IMErrorMessagePartChatItem, chatID: String) { id = item.id self.chatID = chatID fromMe = item.isFromMe time = item.effectiveTime if #available(macOS 11.0, iOS 14.0, *) { threadIdentifier = item.threadIdentifier() threadOriginator = item.threadOriginatorID } } public var id: String public var chatID: String public var fromMe: Bool public var time: Double public var threadIdentifier: String? public var threadOriginator: String? }
25.707317
91
0.649905
c13bafbdc96dec1e7b1261f902dce25902e2bba4
603
// swiftlint:disable all // swift-format-ignore-file // swiftformat:disable all import Foundation // MARK: - Swift Bundle Accessor private class BundleFinder {} extension Foundation.Bundle { /// Since MOIZA is a application, the bundle containing the resources is copied into the final product. static var module: Bundle = { return Bundle(for: BundleFinder.self) }() } // MARK: - Objective-C Bundle Accessor @objc public class MOIZAResources: NSObject { @objc public class var bundle: Bundle { return .module } } // swiftlint:enable all // swiftformat:enable all
22.333333
107
0.709784
d6d66150dadfa92350c0e6b935c52cdfc57c28ee
3,614
// // RestTableViewController.swift // CancerInstituteDemo // // Created by Anna Benson on 11/9/15. // Copyright © 2015 KAG. All rights reserved. // import UIKit class RestTableViewController: UITableViewController { //data arrays var restTitles = ["Spiritual Self Care", "Open Meditation", "Write For You", "Tai Chi", "Pet Therapy"] var restDescriptions = [ "Spiritual Self Care is a chaplain-led group for spiritual self-care planning. Sessions include reflection on spiritual health and wellness, tools for spiritual-emotional resilience/coping and care planning. Sessions are also available in-clinic, inpatient or by phone. For inquiries, contact Annette Olsen, Chaplain, at 919.684.2843 or email at [email protected].", "Facilitated drop-in sessions are open to persons of diverse religious and philosophical beliefs. All experience levels are welcome. Sessions include an introduction to a technique, practice period and closing. For more information or inquires, call Annette Olsen, Chaplain, at 919.684.2843 or email at [email protected].", "Discover how journaling can help you express emotions and thoughts, reduce anxiety, promote healthy creativity and help organize your life. Hosted by Arts & Health at Duke, participants receive complimentary journals, poetry packets and more. Write For You is held in the Level 0 Conference Room. Drop-ins are welcome. For more information, call 919.613.6601 or email katja. [email protected].", "Tai Chi is a holistic health practice that brings the mind and body together with slow, graceful, flowing movements performed in a meditative manner. Tai Chi is held in the Quiet Room. Registration is not required. Drop-ins are welcome. For more information, email [email protected].", "The Pets At Duke Therapy Program is routinely available in our lobbies. To learn more about Pets At Duke or to schedule an appointment, email [email protected]."] var restImages = ["quietRoom.jpg", "quietRoom.jpg", "writeForYou.jpg", "quietRoom.jpg", "petTherapy.jpg"] override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(patternImage: UIImage(named: "blueGradient.jpg")!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restTitles.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //set up table view let cell = self.tableView.dequeueReusableCellWithIdentifier("RestTableViewCell", forIndexPath: indexPath) as! RestTableViewCell let row = indexPath.row cell.restLabel.text = restTitles[row] return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { //navigate to new pages via segues if segue.identifier == "ShowRestDetails" { let detailViewController = segue.destinationViewController as! RestDetailViewController let myIndexPath = self.tableView.indexPathForSelectedRow! let row = myIndexPath.row detailViewController.myTitle = restTitles[row] detailViewController.myDescription = restDescriptions[row] detailViewController.myImage = restImages[row] } } }
57.365079
400
0.724405
019adf0ae0f4b4b72b991c2c2ffd9d254298d03b
937
// // DailyKoreanTests.swift // DailyKoreanTests // // Created by MountainX on 2019/5/16. // Copyright © 2019 MTX Software Technology Co.,Ltd. All rights reserved. // import XCTest @testable import DailyKorean class DailyKoreanTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.771429
111
0.662753
cc37d52d9ba618b9f4e93a0acafe8daf892a7489
1,493
// // Created by Brian Coyner on 7/11/19. // Copyright © 2019 Brian Coyner. All rights reserved. // import SwiftUI /// A custom `ProgressViewStyle` that displays a progress ring centered on top of a ring. The user /// sees the current progress displayed as a percent in the center of the view. /// /// This style is useful when displaying progress "full screen" (e.g. long running task while onboarding a user). struct ProminentProgressViewStyle: ProgressViewStyle { func makeBody(configuration: Configuration) -> some View { let value = CGFloat(configuration.fractionCompleted ?? 0) return GeometryReader { context in ZStack { Circle() .stroke(Color.primary, lineWidth: 2) Circle() .trim(from: 0, to: value) .stroke(Color.accentColor, lineWidth: self.progressLineWidth(basedOn: context.size)) .rotationEffect(.degrees(-90)) } .overlay( Text(verbatim: "\(format: value, using: .percent)") .font(.system(size: max(context.size.width * 0.2, UIFont.smallSystemFontSize), design: Font.Design.monospaced)) ) } } private func progressLineWidth(basedOn size: CGSize) -> CGFloat { return floor(max(radius(baseOn: size) * 0.1, 2.0)) } private func radius(baseOn size: CGSize) -> CGFloat { return min(size.width, size.height) * 0.5 } }
37.325
131
0.61152
1de861b8e8f8c28b5324dee5d3c2a90b5bbb726c
9,242
/* * ColorDataView.swift * SensorTester * * Created by John Wong on 8/09/2015. * Copyright (c) 2015-2015, John Wong <john dot innovation dot au at gmail dot com> * * All rights reserved. * * http://www.bitranslator.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * 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. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Foundation import UIKit public class ColorDataView : UIView { private var m_dataController : ViewController? func setDataController( dataController : ViewController ) -> Void { m_dataController = dataController } private func redrawDataArea() -> Void { let frameSize: CGRect = self.frame frameSize.origin.x frameSize.origin.y frameSize.size.height frameSize.size.width let rawBuffer: DataBuffer<RawColor> = m_dataController!.getRawColorBuffer() let nColorCount: Int32 = rawBuffer.getBufferSize() } override public func drawRect(rect: CGRect) { let context: CGContext? = UIGraphicsGetCurrentContext() if( context != nil ) { //CGContextClearRect( context, rect ) let strokeWidth = 1.0 CGContextSetLineWidth(context, CGFloat(strokeWidth)) CGContextSetFillColorWithColor(context, UIColor.clearColor().CGColor) self.drawRectAround( context!, rect: rect ) CGContextStrokePath(context) if( m_dataController != nil) { let rawBuffer: DataBuffer<RawColor> = m_dataController!.getRawColorBuffer() self.drawRawColorPoint( context!, rect: rect, rawBuffer: rawBuffer ) CGContextStrokePath(context) let dashArray:[CGFloat] = [2,4] CGContextSetLineDash(context, 3, dashArray, 2) self.drawRectColumns( context!, rect: rect, rawBuffer: rawBuffer ) self.drawRectRows( context!, rect: rect, rawBuffer: rawBuffer ) CGContextStrokePath(context) } } } private func drawRectAround( context: CGContext, rect: CGRect ) -> Void { // Rectangle around the area CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor) var points: Array<CGPoint> = Array<CGPoint>() points.append( CGPoint(x: 0, y: 0) ) points.append( CGPoint(x: rect.width, y: 0) ) points.append( CGPoint(x: rect.width, y: rect.height) ) points.append( CGPoint(x: 0, y: rect.height) ) points.append( CGPoint(x: 0, y: 0) ) CGContextAddLines(context, points, points.count) } private func drawRectColumns( context: CGContext, rect: CGRect, rawBuffer: DataBuffer<RawColor> ) -> Void { let nBufferSize: Int32 = rawBuffer.getBufferSize() let nDrawColumes: Int32 = (nBufferSize >> 6) CGContextSetStrokeColorWithColor(context, UIColor.grayColor().CGColor) for( var i: Int32 = 1; i<nDrawColumes; i += 1 ) { var points: Array<CGPoint> = Array<CGPoint>() let nPositionX: Double = Double(rect.width)*Double(i)/Double(nDrawColumes) points.append( CGPoint(x: CGFloat(nPositionX), y: CGFloat(0)) ) points.append( CGPoint(x: CGFloat(nPositionX), y: CGFloat(rect.height)) ) CGContextAddLines(context, points, points.count) } } private func drawRectRows( context: CGContext, rect: CGRect, rawBuffer: DataBuffer<RawColor> ) -> Void { let MAX_ROW: Int32 = 10 CGContextSetStrokeColorWithColor(context, UIColor.grayColor().CGColor) for( var i: Int32 = 1; i<MAX_ROW; i += 1 ) { var points: Array<CGPoint> = Array<CGPoint>() let nPositionY: Double = Double(rect.height)*Double(i)/Double(MAX_ROW) points.append( CGPoint(x: CGFloat(0), y: CGFloat(nPositionY)) ) points.append( CGPoint(x: CGFloat(rect.width), y: CGFloat(nPositionY)) ) CGContextAddLines(context, points, points.count) } } private func drawRawColorPoint( context: CGContext, rect: CGRect, rawBuffer: DataBuffer<RawColor> ) -> Void { let nBufferSize: Int32 = rawBuffer.getBufferSize() let nDotRectSize: CGFloat = 2 CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor) for( var i: Int32 = 1; i<nBufferSize; i += 1 ) { let rawColor: RawColor? = rawBuffer.getData( i ) if( rawColor != nil ) { let nRawRed: Double = rawColor!.getRawRed() let nPositionX: Double = Double(rect.width) * Double(i) / Double(nBufferSize) let nPositionY: Double = Double(rect.height) - Double(nRawRed) * Double(rect.height) let origin: CGPoint = CGPoint(x: nPositionX, y: nPositionY) let size: CGSize = CGSize(width: nDotRectSize, height: nDotRectSize) let rectRed: CGRect = CGRect( origin: origin, size: size ) CGContextAddRect( context, rectRed ) } } CGContextStrokePath(context) CGContextSetStrokeColorWithColor(context, UIColor.greenColor().CGColor) //let nRawGreen: Double = rawColor.getRawGreen() for( var i: Int32 = 1; i<nBufferSize; i += 1 ) { let rawColor: RawColor? = rawBuffer.getData( i ) if( rawColor != nil ) { let nRawGreen: Double = rawColor!.getRawGreen() let nPositionX: Double = Double(rect.width) * Double(i) / Double(nBufferSize) let nPositionY: Double = Double(rect.height) - Double(nRawGreen) * Double(rect.height) let origin: CGPoint = CGPoint(x: nPositionX, y: nPositionY) let size: CGSize = CGSize(width: nDotRectSize, height: nDotRectSize) let rectRed: CGRect = CGRect( origin: origin, size: size ) CGContextAddRect( context, rectRed ) } } CGContextStrokePath(context) CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) //let nRawBlue: Double = rawColor.getRawBlue() for( var i: Int32 = 1; i<nBufferSize; i += 1 ) { let rawColor: RawColor? = rawBuffer.getData( i ) if( rawColor != nil ) { let nRawBlue: Double = rawColor!.getRawBlue() let nPositionX: Double = Double(rect.width) * Double(i) / Double(nBufferSize) let nPositionY: Double = Double(rect.height) - Double(nRawBlue) * Double(rect.height) let origin: CGPoint = CGPoint(x: nPositionX, y: nPositionY) let size: CGSize = CGSize(width: nDotRectSize, height: nDotRectSize) let rectRed: CGRect = CGRect( origin: origin, size: size ) CGContextAddRect( context, rectRed ) } } CGContextStrokePath(context) } }
41.819005
111
0.626488
5dd50afc3b344f7cbd425ef7bece8356891739c9
12,828
// // TransactionsViewController.swift // Lumenshine // // Created by Soneso GmbH on 12/12/2018. // Munich, Germany // web: https://soneso.com // email: [email protected] // Copyright © 2018 Soneso. All rights reserved. // import UIKit import Material class TransactionsViewController: UITableViewController { // MARK: - Parameters & Constants fileprivate static let CellIdentifier = "TransactionsCell" // MARK: - Properties fileprivate let walletLabel = UILabel() fileprivate let dateFromLabel = UILabel() fileprivate let dateToLabel = UILabel() fileprivate let filterButton = LSButton() fileprivate let sortButton = LSButton() fileprivate let verticalSpacing = 31.0 fileprivate let horizontalSpacing = 15.0 fileprivate let viewModel: TransactionsViewModelType fileprivate var showsOperationDetails = false init(viewModel: TransactionsViewModelType) { self.viewModel = viewModel super.init(style: .grouped) viewModel.reloadClosure = { DispatchQueue.main.async { self.tableView.reloadData() } } viewModel.showActivityClosure = { DispatchQueue.main.async { self.showActivity(message: R.string.localizable.loading(), animated: false) } } viewModel.hideActivityClosure = { DispatchQueue.main.async { self.hideActivity(animated: false) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() prepare() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !showsOperationDetails { updateHeader() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !showsOperationDetails { viewModel.applyFilters() } showsOperationDetails = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.itemCount } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = TransactionsViewController.CellIdentifier let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) if var tableCell = cell as? TransactionsCellProtocol { tableCell.setDate(viewModel.date(at: indexPath)) tableCell.setType(viewModel.type(at: indexPath)) tableCell.setAmount(viewModel.amount(at: indexPath)) tableCell.setCurrency(viewModel.currency(at: indexPath)) tableCell.setFee(viewModel.feePaid(at: indexPath)) tableCell.setOfferId(viewModel.offer(at: indexPath), transactionHash:viewModel.transactionHash(at: indexPath)) tableCell.setDetails(viewModel.details(at: indexPath)) tableCell.delegate = self } return cell } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let separator = UIView() separator.roundCorners([.layerMinXMinYCorner, .layerMaxXMinYCorner], radius: 12) separator.backgroundColor = .white let label = UILabel() label.text = R.string.localizable.transactions() label.textColor = Stylesheet.color(.blue) label.font = R.font.encodeSansSemiBold(size: 15) if viewModel.itemCount == 0 { label.text = R.string.localizable.no_transactions_found() label.textColor = Stylesheet.color(.darkGray) } separator.addSubview(label) label.snp.makeConstraints { make in make.top.equalTo(10) make.left.equalTo(horizontalSpacing) make.right.equalTo(-horizontalSpacing) make.bottom.equalTo(-10) } let header = UIView() header.addSubview(separator) separator.snp.makeConstraints { make in make.top.equalTo(5) make.left.equalTo(horizontalSpacing) make.right.equalTo(-horizontalSpacing) make.bottom.equalToSuperview() } return header } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 25 } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let separator = UIView() separator.roundCorners([.layerMinXMaxYCorner, .layerMaxXMaxYCorner], radius: 12) separator.backgroundColor = .white // separator.depthPreset = .depth3 let header = UIView() header.addSubview(separator) separator.snp.makeConstraints { make in make.top.equalToSuperview() make.left.equalTo(horizontalSpacing) make.right.equalTo(-horizontalSpacing) make.bottom.equalTo(-5) } return header } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { viewModel.itemSelected(at: indexPath) } } extension TransactionsViewController: TransactionsCellDelegate { func cellCopiedToPasteboard(_ cell: TransactionsCellProtocol) { let alert = UIAlertController(title: nil, message: R.string.localizable.copied_clipboard(), preferredStyle: .actionSheet) self.present(alert, animated: true) let when = DispatchTime.now() + 0.75 DispatchQueue.main.asyncAfter(deadline: when){ alert.dismiss(animated: true) } } func cell(_ cell: TransactionsCellProtocol, didInteractWith url: URL) { showsOperationDetails = true viewModel.showOperationDetails(operationId: url.lastPathComponent) } } extension TransactionsViewController { @objc func filterAction(sender: UIButton) { viewModel.filterClick() } @objc func sortAction(sender: UIButton) { viewModel.sortClick() } func updateHeader() { let name = viewModel.wallets.count > 0 ? viewModel.wallets[viewModel.walletIndex] : R.string.localizable.primary() walletLabel.text = "\(name) \(R.string.localizable.wallet())" let dateFrom = DateUtils.format(viewModel.dateFrom, in: .date) ?? viewModel.dateFrom.description dateFromLabel.text = "\(R.string.localizable.date_from()): \(dateFrom)" let dateTo = DateUtils.format(viewModel.dateTo, in: .date) ?? viewModel.dateTo.description dateToLabel.text = "\(R.string.localizable.date_to()): \(dateTo)" } } fileprivate extension TransactionsViewController { func prepare() { prepareTableView() prepareCopyright() prepareNavigationItem() } func prepareTableView() { tableView.register(TransactionsTableViewCell.self, forCellReuseIdentifier: TransactionsViewController.CellIdentifier) tableView.rowHeight = UITableView.automaticDimension tableView.separatorStyle = .singleLine tableView.separatorColor = Stylesheet.color(.lightGray) tableView.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 50) if #available(iOS 11.0, *) { tableView.separatorInsetReference = .fromAutomaticInsets } let headerView = prepareTableHeader() headerView.frame = CGRect(origin: .zero, size: CGSize(width: 30, height: 80)) tableView.tableHeaderView = headerView tableView.tableFooterView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 30, height: 30))) } func prepareNavigationItem() { snackbarController?.navigationItem.titleLabel.text = R.string.localizable.transactions() snackbarController?.navigationItem.titleLabel.textColor = Stylesheet.color(.blue) snackbarController?.navigationItem.titleLabel.font = R.font.encodeSansSemiBold(size: 15) navigationController?.navigationBar.setBackgroundImage(R.image.nav_background(), for: .default) } func prepareTableHeader() -> UIView { let headerView = UIView() walletLabel.textColor = Stylesheet.color(.black) walletLabel.font = R.font.encodeSansSemiBold(size: 13) walletLabel.adjustsFontSizeToFitWidth = true headerView.addSubview(walletLabel) walletLabel.snp.makeConstraints { (make) in make.top.equalTo(horizontalSpacing) make.left.equalTo(horizontalSpacing + 15) } dateFromLabel.textColor = Stylesheet.color(.darkGray) dateFromLabel.font = R.font.encodeSansRegular(size: 13) dateFromLabel.adjustsFontSizeToFitWidth = true headerView.addSubview(dateFromLabel) dateFromLabel.snp.makeConstraints { (make) in make.top.equalTo(walletLabel.snp.bottom) make.left.equalTo(walletLabel) } dateToLabel.text = R.string.localizable.unlock_app() dateToLabel.textColor = Stylesheet.color(.darkGray) dateToLabel.font = R.font.encodeSansRegular(size: 13) dateToLabel.adjustsFontSizeToFitWidth = true headerView.addSubview(dateToLabel) dateToLabel.snp.makeConstraints { (make) in make.top.equalTo(dateFromLabel.snp.bottom) make.left.equalTo(walletLabel) } sortButton.title = R.string.localizable.sort().uppercased() sortButton.titleColor = Stylesheet.color(.blue) sortButton.borderWidthPreset = .border1 sortButton.borderColor = Stylesheet.color(.blue) sortButton.cornerRadiusPreset = .cornerRadius5 sortButton.setGradientLayer(color: Stylesheet.color(.white)) sortButton.addTarget(self, action: #selector(sortAction(sender:)), for: .touchUpInside) headerView.addSubview(sortButton) sortButton.snp.makeConstraints { make in make.right.equalTo(-horizontalSpacing) make.centerY.equalTo(dateFromLabel) make.width.equalTo(80) make.height.equalTo(36) } filterButton.title = R.string.localizable.filter().uppercased() filterButton.titleColor = Stylesheet.color(.blue) filterButton.borderWidthPreset = .border1 filterButton.borderColor = Stylesheet.color(.blue) filterButton.cornerRadiusPreset = .cornerRadius5 filterButton.setGradientLayer(color: Stylesheet.color(.white)) filterButton.addTarget(self, action: #selector(filterAction(sender:)), for: .touchUpInside) headerView.addSubview(filterButton) filterButton.snp.makeConstraints { make in make.right.equalTo(sortButton.snp.left).offset(-10) make.centerY.equalTo(dateFromLabel) make.width.equalTo(80) make.height.equalTo(36) } return headerView } func prepareCopyright() { let backgroundView = UIView() backgroundView.backgroundColor = Stylesheet.color(.lightGray) let imageView = UIImageView(image: R.image.soneso()) imageView.backgroundColor = Stylesheet.color(.clear) backgroundView.addSubview(imageView) imageView.snp.makeConstraints { make in make.bottom.equalTo(-20) make.centerX.equalToSuperview() } let background = UIImageView(image: R.image.soneso_background()) background.contentMode = .scaleAspectFit backgroundView.addSubview(background) background.snp.makeConstraints { make in make.top.greaterThanOrEqualToSuperview() make.left.right.equalToSuperview() make.bottom.equalTo(imageView.snp.top) } tableView.backgroundView = backgroundView tableView.backgroundView?.isUserInteractionEnabled = true } }
36.651429
129
0.649751
fba8093677321066426ef44869a0da657b48d221
983
// // ButtonView.swift // RustAnywhere // import Cocoa @IBDesignable class ButtonView: NSView { private let simulator = Simulator.sharedInstance @IBInspectable var color: NSColor = .systemGray { didSet { layer?.backgroundColor = color.cgColor } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) wantsLayer = true } required init?(coder decoder: NSCoder) { super.init(coder: decoder) wantsLayer = true } override func prepareForInterfaceBuilder() { layer?.backgroundColor = color.cgColor } override func awakeFromNib() { layer?.backgroundColor = color.cgColor } override func mouseDown(with event: NSEvent) { simulator.onButtonPressed(pressed: true) color = .systemBlue } override func mouseUp(with event: NSEvent) { simulator.onButtonPressed(pressed: false) color = .systemGray } }
21.844444
53
0.633774
2155b12927f732785edfeddeff128682c6b3371c
5,815
// // GridViewController.swift // Pods // // Created by Tapani Saarinen on 04/09/15. // // import UIKit public class GridViewController: UICollectionViewController { weak var browser: PhotoBrowser? var selectionMode = false var initialContentOffset = CGPointMake(0.0, CGFloat.max) init() { super.init(collectionViewLayout: UICollectionViewFlowLayout()) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - View public override func viewDidLoad() { super.viewDidLoad() if let cv = collectionView { cv.registerClass(GridCell.self, forCellWithReuseIdentifier: "GridCell") cv.alwaysBounceVertical = true cv.backgroundColor = UIColor.whiteColor() } } public override func viewWillDisappear(animated: Bool) { // Cancel outstanding loading if let cv = collectionView { for cell in cv.visibleCells() { let c = cell as! GridCell if let p = c.photo { p.cancelAnyLoading() } } } super.viewWillDisappear(animated) } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } func adjustOffsetsAsRequired() { // Move to previous content offset if initialContentOffset.y != CGFloat.max { collectionView!.contentOffset = initialContentOffset collectionView!.layoutIfNeeded() // Layout after content offset change } // Check if current item is visible and if not, make it so! if let b = browser where b.numberOfPhotos > 0 { let currentPhotoIndexPath = NSIndexPath(forItem: b.currentIndex, inSection: 0) let visibleIndexPaths = collectionView!.indexPathsForVisibleItems() var currentVisible = false for indexPath in visibleIndexPaths { if indexPath == currentPhotoIndexPath { currentVisible = true break } } if !currentVisible { collectionView!.scrollToItemAtIndexPath(currentPhotoIndexPath, atScrollPosition: UICollectionViewScrollPosition.None, animated: false) } } } //MARK: - Layout private var columns: CGFloat { return floorcgf(view.bounds.width / 93.0) } private var margin = CGFloat(5.0) private var gutter = CGFloat(5.0) public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition(nil) { _ in if let cv = self.collectionView { cv.reloadData() } } super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) } //MARK: - Collection View public override func collectionView(view: UICollectionView, numberOfItemsInSection section: Int) -> NSInteger { if let b = browser { return b.numberOfPhotos } return 0 } public override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("GridCell", forIndexPath: indexPath) as! GridCell if let b = browser, photo = b.thumbPhotoAtIndex(indexPath.row) { cell.photo = photo cell.gridController = self cell.selectionMode = selectionMode cell.index = indexPath.row cell.selected = b.photoIsSelectedAtIndex(indexPath.row) if let _ = b.imageForPhoto(photo) { cell.displayImage() } else { photo.loadUnderlyingImageAndNotify() } } return cell } public override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let b = browser { b.currentPhotoIndex = indexPath.row b.hideGrid() } } public override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { if let gridCell = cell as? GridCell { if let gcp = gridCell.photo { gcp.cancelAnyLoading() } } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let value = CGFloat(floorf(Float((view.bounds.size.width - (columns - 1.0) * gutter - 2.0 * margin) / columns))) return CGSizeMake(value, value) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return gutter } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return gutter } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { let margin = self.margin return UIEdgeInsetsMake(margin, margin, margin, margin) } }
33.80814
178
0.631298
89e341a62de7a3b43153ce3390388ef9cb29f334
1,473
/* The MIT License (MIT) Copyright (c) 2018-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public protocol Item: ViewControllerProviding { var identifier: ItemIdentifier { get } var title: String { get } var subtitle: String? { get } var subitems: [Item] { get } var elementsProvider: ElementsProviding? { get } var image: UIImage? { get } var preferredPresentationStyle: PresentationStyle { get } }
40.916667
78
0.763747
87c5a2045ed44d2ae6160b301e21e6218235a124
9,500
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest @testable import Amplify import AWSCognitoAuthPlugin import AmplifyTestCommon class AuthUsernamePasswordSignInTests: AWSAuthBaseTest { override func setUp() { super.setUp() initializeAmplify() } override func tearDown() { super.tearDown() Amplify.reset() sleep(2) } /// Test successful signIn of a valid user /// /// - Given: A user registered in Cognito user pool /// - When: /// - I invoke Amplify.Auth.signIn with the username and password /// - Then: /// - I should get a completed signIn flow. /// func testSuccessfulSignIn() { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" let signUpExpectation = expectation(description: "SignUp operation should complete") AuthSignInHelper.signUpUser(username: username, password: password, email: email) { didSucceed, error in signUpExpectation.fulfill() XCTAssertTrue(didSucceed, "Signup operation failed - \(String(describing: error))") } wait(for: [signUpExpectation], timeout: networkTimeout) let operationExpectation = expectation(description: "Operation should complete") let operation = Amplify.Auth.signIn(username: username, password: password) { result in defer { operationExpectation.fulfill() } switch result { case .success(let signInResult): XCTAssertTrue(signInResult.isSignedIn, "SignIn should be complete") case .failure(let error): XCTFail("SignIn with a valid username/password should not fail \(error)") } } XCTAssertNotNil(operation, "SignIn operation should not be nil") wait(for: [operationExpectation], timeout: networkTimeout) } /// Test successful signIn of a valid user /// Internally, Two Cognito APIs will be called, Cognito's `InitiateAuth` and `RespondToAuthChallenge` API. /// /// `InitiateAuth` will trigger the Pre signup, Pre authentication, and User migration lambdas. Passed in metadata /// will be used as client metadata to Cognito's API, and passed to the the lambda as validationData. /// See https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html for more /// details. /// /// `RespondToAuthChallenge` will trigger the Post authentication, Pre token generation, Define auth challenge, /// Create auth challenge, and Verify auth challenge lambdas. Passed in metadata will be used as client metadata to /// Cognito's API, and passed to the lambda as clientMetadata. /// See https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html /// for more details /// /// - Given: A user registered in Cognito user pool /// - When: /// - I invoke Amplify.Auth.signIn with the username, password and AWSAuthSignInOptions /// - Then: /// - I should get a completed signIn flow. /// func testSignInWithSignInOptions() { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" let signUpExpectation = expectation(description: "SignUp operation should complete") AuthSignInHelper.signUpUser(username: username, password: password, email: email) { didSucceed, error in signUpExpectation.fulfill() XCTAssertTrue(didSucceed, "Signup operation failed - \(String(describing: error))") } wait(for: [signUpExpectation], timeout: networkTimeout) let operationExpectation = expectation(description: "Operation should complete") let awsAuthSignInOptions = AWSAuthSignInOptions(metadata: ["mySignInData": "myvalue"]) let options = AuthSignInOperation.Request.Options(pluginOptions: awsAuthSignInOptions) let operation = Amplify.Auth.signIn(username: username, password: password, options: options) { result in defer { operationExpectation.fulfill() } switch result { case .success(let signInResult): XCTAssertTrue(signInResult.isSignedIn, "SignIn should be complete") case .failure(let error): XCTFail("SignIn with a valid username/password should not fail \(error)") } } XCTAssertNotNil(operation, "SignIn operation should not be nil") wait(for: [operationExpectation], timeout: networkTimeout) } /// Test if user not found error is returned for signIn with unknown user /// /// - Given: Amplify Auth plugin in signedout state /// - When: /// - I try to signIn with an unknown user /// - Then: /// - I should get a user not found error /// func testSignInWithInvalidUser() { let operationExpectation = expectation(description: "Operation should complete") let operation = Amplify.Auth.signIn(username: "username-doesnot-exist", password: "password") { result in defer { operationExpectation.fulfill() } switch result { case .success: XCTFail("SignIn with unknown user should not succeed") case .failure(let error): guard let cognitoError = error.underlyingError as? AWSCognitoAuthError, case .userNotFound = cognitoError else { XCTFail("Should return userNotFound error") return } } } XCTAssertNotNil(operation, "SignIn operation should not be nil") wait(for: [operationExpectation], timeout: networkTimeout) } /// Test if signIn to an already signedIn session returns error /// /// - Given: Amplify Auth plugin in signedIn state /// - When: /// - I try to signIn again /// - Then: /// - I should get a invalid state error /// func testSignInWhenAlreadySignedIn() { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" let firstSignInExpectation = expectation(description: "SignIn operation should complete") AuthSignInHelper.registerAndSignInUser(username: username, password: password, email: email) { didSucceed, error in firstSignInExpectation.fulfill() XCTAssertTrue(didSucceed, "SignIn operation failed - \(String(describing: error))") } wait(for: [firstSignInExpectation], timeout: networkTimeout) let secondSignInExpectation = expectation(description: "SignIn operation should complete") AuthSignInHelper.signInUser(username: username, password: password) { didSucceed, error in defer { secondSignInExpectation.fulfill() } XCTAssertFalse(didSucceed, "Second signIn should fail") guard case .invalidState = error else { XCTFail("Should return invalid state \(String(describing: error))") return } } wait(for: [secondSignInExpectation], timeout: networkTimeout) } /// Test if signIn return validation error /// /// - Given: An invalid input to signIn like empty username /// - When: /// - I invoke signIn with empty username /// - Then: /// - I should get validation error. /// func testSignInValidation() { let operationExpectation = expectation(description: "Operation should complete") let operation = Amplify.Auth.signIn(username: "", password: "password") { result in defer { operationExpectation.fulfill() } switch result { case .success: XCTFail("SignIn with empty user should not succeed") case .failure(let error): guard case .validation = error else { XCTFail("Should return validation error") return } } } XCTAssertNotNil(operation, "SignIn operation should not be nil") wait(for: [operationExpectation], timeout: networkTimeout) } /// Calling cancel in signIn operation should cancel /// /// - Given: A valid username and password /// - When: /// - I invoke signIn with the username password and then call cancel /// - Then: /// - I should not get any result back /// func testCancelSignInOperation() { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" let operationExpectation = expectation(description: "Operation should not complete") operationExpectation.isInverted = true let operation = Amplify.Auth.signIn(username: username, password: password) { result in XCTFail("Received result \(result)") operationExpectation.fulfill() } XCTAssertNotNil(operation, "signIn operations should not be nil") operation.cancel() wait(for: [operationExpectation], timeout: networkTimeout) } }
41.484716
119
0.624211
160c260fffdfdf201bdd88cf2484e727f3d3d4ec
432
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest import Amplify @testable import AmplifyTestCommon class HubListenerTests: XCTestCase { /// Given: A configured hub, and a category API that takes a listener callback /// When: I invoke the API with a callback /// Then: I receive callbacks func testListen() { } }
20.571429
82
0.699074
9b065c2cec1fd1c34501014e62cd5b926e6739c6
1,471
// // HTMapViewModel.swift // Pods // // Created by Ravi Jain on 04/06/17. // // import UIKit import MapKit class HTMapViewModel: NSObject { var heroMarker : HTMapAnnotation? var destinationMarker : HTMapAnnotation? var sourceMarker : HTMapAnnotation? var acionSummaryStartMarker : HTMapAnnotation? var actionSummaryEndMarker : HTMapAnnotation? var actionSummaryPolylineLatLng : [CLLocationCoordinate2D]? var rotateHeroMarker = true var isHeroMarkerVisible = true var isDestinationMarkerVisible = true var isActionSummaryInfoVisible = true var isAddressInfoVisible = true var isUserInfoVisible = false var isOrderDetailsButtonVisible = false var isSourceMarkerVisible = true var isCallButtonVisible = true var disableEditDestination = false var showUserLocationMissingAlert = true var showEditDestinationFailureAlert = true var type = HTConstants.AnnotationType.ACTION override init(){ } init(heroMarker:HTMapAnnotation?,destinationMarker : HTMapAnnotation?,sourceMarker : HTMapAnnotation?,acionSummaryStartMarker : HTMapAnnotation?,actionSummaryEndMarker : HTMapAnnotation?){ self.heroMarker = heroMarker self.destinationMarker = destinationMarker self.sourceMarker = sourceMarker self.actionSummaryEndMarker = actionSummaryEndMarker self.acionSummaryStartMarker = acionSummaryStartMarker } }
30.020408
192
0.736914
9b636c60e9594b0ea2e5e03269dcff9d0783aed2
6,573
// // Date+Extension.swift // SGSwiftExtensionsWithUtilities // // Created by Sanjeev Gautam on 28/05/20. // Copyright © 2020 SG. All rights reserved. // import Foundation // MARK:- Instance Methods public extension Date { func toStringWithTimeZone(format:String = "EEE, dd-MMM-yy 'at' hh:mm aa", timezone:TimeZone = TimeZone.current) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format dateFormatter.timeZone = timezone let dateStr = dateFormatter.string(from: self) return dateStr } func newDate(hours: Int) -> Date? { return newDate(hour: hours) } func newDate(minutes: Int) -> Date? { return newDate(minute: minutes) } func newDate(seconds: Int) -> Date? { return newDate(second: seconds) } func newDate(days: Int) -> Date? { return newDate(day: days) } func newDate(months: Int) -> Date? { return newDate(month: months) } func newDate(years: Int) -> Date? { return newDate(year: years) } func newDate(hour:Int? = nil, minute:Int? = nil, second:Int? = nil, day:Int? = nil, month:Int? = nil, year:Int? = nil) -> Date? { var components: DateComponents = DateComponents() components.hour = hour components.minute = minute components.second = second components.day = day components.month = month components.year = year return Calendar.current.date(byAdding: components, to: self) } func years(fromDate: Date) -> Int? { return Calendar.current.dateComponents([.year], from: fromDate, to: self).year } func months(fromDate: Date) -> Int? { return Calendar.current.dateComponents([.month], from: fromDate, to: self).month } func weeks(fromDate: Date) -> Int? { return Calendar.current.dateComponents([.weekOfMonth], from: fromDate, to: self).weekOfMonth } func days(fromDate: Date) -> Int? { return Calendar.current.dateComponents([.day], from: fromDate, to: self).day } func hours(fromDate: Date) -> Int? { return Calendar.current.dateComponents([.hour], from: fromDate, to: self).hour } func minutes(fromDate: Date) -> Int? { return Calendar.current.dateComponents([.minute], from: fromDate, to: self).minute } func seconds(fromDate: Date) -> Int? { return Calendar.current.dateComponents([.second], from: fromDate, to: self).second } } // MARK:- Static Methods public extension Date { static func difference(startDate: Date, endDate: Date, differenceBy: Calendar.Component) -> DateComponents? { let calendar = NSCalendar.current let date1 = calendar.startOfDay(for: startDate) let date2 = calendar.startOfDay(for: endDate) let components = calendar.dateComponents([differenceBy], from: date1, to: date2) return components } static func eraDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .era)?.era } static func yearsDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .year)?.year } static func monthsDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .month)?.month } static func daysDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .day)?.day } static func hoursDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .hour)?.hour } static func minutesDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .minute)?.minute } static func secondsDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .second)?.second } static func weekdaysDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .weekday)?.weekday } static func weekdayOrdinalDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .weekdayOrdinal)?.weekdayOrdinal } static func quarterDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .quarter)?.quarter } static func weekOfMonthDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .weekOfMonth)?.weekOfMonth } static func weekOfYearDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .weekOfYear)?.weekOfYear } static func yearForWeekOfYearDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .yearForWeekOfYear)?.yearForWeekOfYear } static func nanosecondsDifference(startDate: Date, endDate: Date) -> Int? { return self.difference(startDate: startDate, endDate: endDate, differenceBy: .nanosecond)?.nanosecond } } // MARK:- Variables public extension Date { var yearsFromNow: Int? { return Calendar.current.dateComponents([.year], from: self, to: Date()).year } var monthsFromNow: Int? { return Calendar.current.dateComponents([.month], from: self, to: Date()).month } var weeksFromNow: Int? { return Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear } var daysFromNow: Int? { return Calendar.current.dateComponents([.day], from: self, to: Date()).day } var hoursFromNow: Int? { return Calendar.current.dateComponents([.hour], from: self, to: Date()).hour } var minutesFromNow: Int? { return Calendar.current.dateComponents([.minute], from: self, to: Date()).minute } var secondsFromNow: Int? { return Calendar.current.dateComponents([.second], from: self, to: Date()).second } }
39.596386
133
0.661494
e5f9e6eb65a72a0d11459bd8101826d0183351bf
221
enum Departments: CaseIterable { case mail case marketing case managing } var message = "" for department in Departments.allCases { message += "\(department) " } print(message) // "mail marketing managing "
18.416667
45
0.696833
9cf850500dd66b681ad4051003a17dd5986fe986
713
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing compose<d : B enum e { println("\(f<c> func p(" let a { func b struct S<T where h: B func f<I : Int -> U))"\(T) { p() -> { va d<T where h: T struct c> if true { } 1 class b<T where h: NSObject { let a { let a { let a { func c<T.b println(f<T where T) -> U)" import Foundation S<I : U : A.B == b<T where g.c<(T struct d<T where g: Any, A? { va d var f = compose<Q class A { func e<Q var f = { println(T: NSObject { } class n { enum e where g: B struct c<()"\(x: e, g: e where g: B let i: T: Int -> { println() -> { } func p(f<T where g: e where
17.390244
87
0.619916
b9521019fb2eba8edc3dd8e85b6bf96d04ecb6c0
317
// // Common.swift // DYZB // // Created by 訾玉洁 on 2016/10/31. // Copyright © 2016年 鼎商动力. All rights reserved. // import UIKit let kStatusBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabBarH : CGFloat = 49 let kScreenW = UIScreen.main.bounds.width let kScreenH = UIScreen.main.bounds.height
16.684211
48
0.700315
fe40d28f3c86d00bff5dfd89bbce444235475aec
2,098
// // Corona-Warn-App // // SAP SE and all other contributors // copyright owners license this file to you under the Apache // License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // import XCTest class ENAUITests_03_Settings: XCTestCase { var app: XCUIApplication! override func setUpWithError() throws { continueAfterFailure = false app = XCUIApplication() setupSnapshot(app) app.setDefaults() app.launchArguments.append(contentsOf: ["-isOnboarded", "YES"]) } func test_0030_SettingsFlow() throws { app.launch() app.swipeUp() XCTAssert(app.cells["AppStrings.Home.settingsCardTitle"].waitForExistence(timeout: 5.0)) app.cells["AppStrings.Home.settingsCardTitle"].tap() XCTAssert(app.cells["AppStrings.Settings.tracingLabel"].waitForExistence(timeout: 5.0)) XCTAssert(app.cells["AppStrings.Settings.notificationLabel"].waitForExistence(timeout: 5.0)) XCTAssert(app.cells["AppStrings.Settings.backgroundAppRefreshLabel"].waitForExistence(timeout: 5.0)) XCTAssert(app.cells["AppStrings.Settings.resetLabel"].waitForExistence(timeout: 5.0)) } func test_0031_SettingsFlow_BackgroundAppRefresh() throws { app.launch() app.swipeUp() XCTAssert(app.cells["AppStrings.Home.settingsCardTitle"].waitForExistence(timeout: 5.0)) app.cells["AppStrings.Home.settingsCardTitle"].tap() XCTAssert(app.cells["AppStrings.Settings.backgroundAppRefreshLabel"].waitForExistence(timeout: 5.0)) app.cells["AppStrings.Settings.backgroundAppRefreshLabel"].tap() XCTAssert(app.images["AppStrings.Settings.backgroundAppRefreshImageDescription"].waitForExistence(timeout: 5.0)) } }
33.83871
114
0.762631
3a3b06298eeafdcc6f2c4c9dd128c294577b1cab
21,927
import Foundation import UIKit import AsyncDisplayKit import Display import TelegramCore import SyncCore import SwiftSignalKit import Postbox import TelegramPresentationData import RadialStatusNode import PhotoResources import StickerResources final class VerticalListContextResultsChatInputPanelItem: ListViewItem { fileprivate let account: Account fileprivate let theme: PresentationTheme fileprivate let result: ChatContextResult fileprivate let resultSelected: (ChatContextResult, ASDisplayNode, CGRect) -> Bool let selectable: Bool = true public init(account: Account, theme: PresentationTheme, result: ChatContextResult, resultSelected: @escaping (ChatContextResult, ASDisplayNode, CGRect) -> Bool) { self.account = account self.theme = theme self.result = result self.resultSelected = resultSelected } public func nodeConfiguredForParams(async: @escaping (@escaping () -> Void) -> Void, params: ListViewItemLayoutParams, synchronousLoads: Bool, previousItem: ListViewItem?, nextItem: ListViewItem?, completion: @escaping (ListViewItemNode, @escaping () -> (Signal<Void, NoError>?, (ListViewItemApply) -> Void)) -> Void) { let configure = { () -> Void in let node = VerticalListContextResultsChatInputPanelItemNode() let nodeLayout = node.asyncLayout() let (top, bottom) = (previousItem != nil, nextItem != nil) let (layout, apply) = nodeLayout(self, params, top, bottom) node.contentSize = layout.contentSize node.insets = layout.insets Queue.mainQueue().async { completion(node, { return (nil, { _ in apply(.None) }) }) } } if Thread.isMainThread { async { configure() } } else { configure() } } public func updateNode(async: @escaping (@escaping () -> Void) -> Void, node: @escaping () -> ListViewItemNode, params: ListViewItemLayoutParams, previousItem: ListViewItem?, nextItem: ListViewItem?, animation: ListViewItemUpdateAnimation, completion: @escaping (ListViewItemNodeLayout, @escaping (ListViewItemApply) -> Void) -> Void) { Queue.mainQueue().async { if let nodeValue = node() as? VerticalListContextResultsChatInputPanelItemNode { let nodeLayout = nodeValue.asyncLayout() async { let (top, bottom) = (previousItem != nil, nextItem != nil) let (layout, apply) = nodeLayout(self, params, top, bottom) Queue.mainQueue().async { completion(layout, { _ in apply(animation) }) } } } else { assertionFailure() } } } } private let titleFont = Font.medium(16.0) private let textFont = Font.regular(15.0) private let iconFont = Font.medium(25.0) private let iconTextBackgroundImage = generateStretchableFilledCircleImage(radius: 2.0, color: UIColor(rgb: 0xdfdfdf)) final class VerticalListContextResultsChatInputPanelItemNode: ListViewItemNode { static let itemHeight: CGFloat = 75.0 private let iconTextBackgroundNode: ASImageNode private let iconTextNode: TextNode private let iconImageNode: TransformImageNode private let titleNode: TextNode private let textNode: TextNode private let topSeparatorNode: ASDisplayNode private let separatorNode: ASDisplayNode private let highlightedBackgroundNode: ASDisplayNode private var statusDisposable = MetaDisposable() private let statusNode: RadialStatusNode = RadialStatusNode(backgroundNodeColor: UIColor(white: 0.0, alpha: 0.5)) private var resourceStatus: MediaResourceStatus? private var currentIconImageResource: TelegramMediaResource? private var item: VerticalListContextResultsChatInputPanelItem? init() { self.titleNode = TextNode() self.textNode = TextNode() self.topSeparatorNode = ASDisplayNode() self.topSeparatorNode.isLayerBacked = true self.separatorNode = ASDisplayNode() self.separatorNode.isLayerBacked = true self.highlightedBackgroundNode = ASDisplayNode() self.highlightedBackgroundNode.isLayerBacked = true self.iconTextBackgroundNode = ASImageNode() self.iconTextBackgroundNode.isLayerBacked = true self.iconTextBackgroundNode.displaysAsynchronously = false self.iconTextBackgroundNode.displayWithoutProcessing = true self.iconTextNode = TextNode() self.iconTextNode.isUserInteractionEnabled = false self.iconImageNode = TransformImageNode() self.iconImageNode.contentAnimations = [.subsequentUpdates] self.iconImageNode.isLayerBacked = !smartInvertColorsEnabled() self.iconImageNode.displaysAsynchronously = false super.init(layerBacked: false, dynamicBounce: false) self.addSubnode(self.topSeparatorNode) self.addSubnode(self.separatorNode) self.addSubnode(self.iconImageNode) self.addSubnode(self.titleNode) self.addSubnode(self.textNode) self.addSubnode(self.statusNode) } deinit { statusDisposable.dispose() } override public func layoutForParams(_ params: ListViewItemLayoutParams, item: ListViewItem, previousItem: ListViewItem?, nextItem: ListViewItem?) { if let item = item as? VerticalListContextResultsChatInputPanelItem { let doLayout = self.asyncLayout() let merged = (top: previousItem != nil, bottom: nextItem != nil) let (layout, apply) = doLayout(item, params, merged.top, merged.bottom) self.contentSize = layout.contentSize self.insets = layout.insets apply(.None) } } func asyncLayout() -> (_ item: VerticalListContextResultsChatInputPanelItem, _ params: ListViewItemLayoutParams, _ mergedTop: Bool, _ mergedBottom: Bool) -> (ListViewItemNodeLayout, (ListViewItemUpdateAnimation) -> Void) { let makeTitleLayout = TextNode.asyncLayout(self.titleNode) let makeTextLayout = TextNode.asyncLayout(self.textNode) let iconTextMakeLayout = TextNode.asyncLayout(self.iconTextNode) let iconImageLayout = self.iconImageNode.asyncLayout() let currentIconImageResource = self.currentIconImageResource return { [weak self] item, params, mergedTop, mergedBottom in let leftInset: CGFloat = 80.0 + params.leftInset let rightInset: CGFloat = 10.0 + params.rightInset let applyIconTextBackgroundImage = iconTextBackgroundImage var titleString: NSAttributedString? var textString: NSAttributedString? var iconText: NSAttributedString? var updateIconImageSignal: Signal<(TransformImageArguments) -> DrawingContext?, NoError>? var updatedStatusSignal: Signal<MediaResourceStatus, NoError>? if let title = item.result.title { titleString = NSAttributedString(string: title, font: titleFont, textColor: item.theme.list.itemPrimaryTextColor) } if let text = item.result.description { textString = NSAttributedString(string: text, font: textFont, textColor: item.theme.list.itemSecondaryTextColor) } var imageResource: TelegramMediaResource? var stickerFile: TelegramMediaFile? switch item.result { case let .externalReference(externalReference): if let thumbnail = externalReference.thumbnail { imageResource = thumbnail.resource } var selectedUrl: String? if let url = externalReference.url { selectedUrl = url } else if let content = externalReference.content { if let resource = content.resource as? HttpReferenceMediaResource { selectedUrl = resource.url } else if let resource = content.resource as? WebFileReferenceMediaResource { selectedUrl = resource.url } } if let selectedUrl = selectedUrl, let parsedUrl = URL(string: selectedUrl) { if let host = parsedUrl.host, !host.isEmpty { iconText = NSAttributedString(string: host.substring(to: host.index(after: host.startIndex)).uppercased(), font: iconFont, textColor: UIColor.white) } } case let .internalReference(internalReference): if let image = internalReference.image { imageResource = imageRepresentationLargerThan(image.representations, size: PixelDimensions(width: 200, height: 200))?.resource } else if let file = internalReference.file { if file.isSticker { stickerFile = file imageResource = file.resource } else { imageResource = smallestImageRepresentation(file.previewRepresentations)?.resource } } } if iconText == nil { if let title = item.result.title, !title.isEmpty { let titleText = title.substring(to: title.index(after: title.startIndex)).uppercased() iconText = NSAttributedString(string: titleText, font: iconFont, textColor: UIColor.white) } } var iconImageApply: (() -> Void)? if let imageResource = imageResource { let boundingSize = CGSize(width: 55.0, height: 55.0) let iconSize: CGSize if let stickerFile = stickerFile, let dimensions = stickerFile.dimensions { iconSize = dimensions.cgSize.fitted(boundingSize) } else { iconSize = boundingSize } let imageCorners = ImageCorners(topLeft: .Corner(2.0), topRight: .Corner(2.0), bottomLeft: .Corner(2.0), bottomRight: .Corner(2.0)) let arguments = TransformImageArguments(corners: imageCorners, imageSize: iconSize, boundingSize: boundingSize, intrinsicInsets: UIEdgeInsets()) iconImageApply = iconImageLayout(arguments) updatedStatusSignal = item.account.postbox.mediaBox.resourceStatus(imageResource) } var updatedIconImageResource = false if let currentIconImageResource = currentIconImageResource, let imageResource = imageResource { if !currentIconImageResource.isEqual(to: imageResource) { updatedIconImageResource = true } } else if (currentIconImageResource != nil) != (imageResource != nil) { updatedIconImageResource = true } if updatedIconImageResource { if let imageResource = imageResource { if let stickerFile = stickerFile { updateIconImageSignal = chatMessageSticker(account: item.account, file: stickerFile, small: false, fetched: true) } else { let tmpRepresentation = TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: 55, height: 55), resource: imageResource, progressiveSizes: []) let tmpImage = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: [tmpRepresentation], immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: []) updateIconImageSignal = chatWebpageSnippetPhoto(account: item.account, photoReference: .standalone(media: tmpImage)) } } else { updateIconImageSignal = .complete() } } let (titleLayout, titleApply) = makeTitleLayout(TextNodeLayoutArguments(attributedString: titleString, backgroundColor: nil, maximumNumberOfLines: 1, truncationType: .end, constrainedSize: CGSize(width: params.width - leftInset - rightInset, height: 100.0), alignment: .natural, cutout: nil, insets: UIEdgeInsets())) let (textLayout, textApply) = makeTextLayout(TextNodeLayoutArguments(attributedString: textString, backgroundColor: nil, maximumNumberOfLines: 2, truncationType: .end, constrainedSize: CGSize(width: params.width - leftInset - rightInset, height: 100.0), alignment: .natural, cutout: nil, insets: UIEdgeInsets())) let (iconTextLayout, iconTextApply) = iconTextMakeLayout(TextNodeLayoutArguments(attributedString: iconText, backgroundColor: nil, maximumNumberOfLines: 1, truncationType: .end, constrainedSize: CGSize(width: 38.0, height: CGFloat.infinity), alignment: .natural, cutout: nil, insets: UIEdgeInsets())) var titleFrame: CGRect? if let _ = titleString { titleFrame = CGRect(origin: CGPoint(x: leftInset, y: 9.0), size: titleLayout.size) } var textFrame: CGRect? if let _ = textString { var topOffset: CGFloat = 9.0 if let titleFrame = titleFrame { topOffset = titleFrame.maxY + 1.0 } textFrame = CGRect(origin: CGPoint(x: leftInset, y: topOffset), size: textLayout.size) } let nodeLayout = ListViewItemNodeLayout(contentSize: CGSize(width: params.width, height: VerticalListContextResultsChatInputPanelItemNode.itemHeight), insets: UIEdgeInsets()) return (nodeLayout, { _ in if let strongSelf = self { strongSelf.item = item strongSelf.separatorNode.backgroundColor = item.theme.list.itemPlainSeparatorColor strongSelf.topSeparatorNode.backgroundColor = item.theme.list.itemPlainSeparatorColor strongSelf.backgroundColor = item.theme.list.plainBackgroundColor strongSelf.highlightedBackgroundNode.backgroundColor = item.theme.list.itemHighlightedBackgroundColor let _ = titleApply() let _ = textApply() if let titleFrame = titleFrame { strongSelf.titleNode.frame = titleFrame } if let textFrame = textFrame { strongSelf.textNode.frame = textFrame } let iconFrame = CGRect(origin: CGPoint(x: params.leftInset + 12.0, y: 11.0), size: CGSize(width: 55.0, height: 55.0)) strongSelf.iconTextNode.frame = CGRect(origin: CGPoint(x: iconFrame.minX + floor((55.0 - iconTextLayout.size.width) / 2.0), y: iconFrame.minY + floor((55.0 - iconTextLayout.size.height) / 2.0) + 2.0), size: iconTextLayout.size) let _ = iconTextApply() strongSelf.currentIconImageResource = imageResource if let iconImageApply = iconImageApply { if let updateImageSignal = updateIconImageSignal { strongSelf.iconImageNode.setSignal(updateImageSignal) } if strongSelf.iconImageNode.supernode == nil { strongSelf.addSubnode(strongSelf.iconImageNode) } strongSelf.iconImageNode.frame = iconFrame iconImageApply() if strongSelf.iconTextBackgroundNode.supernode != nil { strongSelf.iconTextBackgroundNode.removeFromSupernode() } if strongSelf.iconTextNode.supernode != nil { strongSelf.iconTextNode.removeFromSupernode() } } else if strongSelf.iconImageNode.supernode != nil { strongSelf.iconImageNode.removeFromSupernode() if strongSelf.iconTextBackgroundNode.supernode == nil { strongSelf.iconTextBackgroundNode.image = applyIconTextBackgroundImage strongSelf.addSubnode(strongSelf.iconTextBackgroundNode) } strongSelf.iconTextBackgroundNode.frame = iconFrame if strongSelf.iconTextNode.supernode == nil { strongSelf.addSubnode(strongSelf.iconTextNode) } } strongSelf.topSeparatorNode.isHidden = mergedTop strongSelf.separatorNode.isHidden = !mergedBottom strongSelf.topSeparatorNode.frame = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: params.width, height: UIScreenPixel)) strongSelf.separatorNode.frame = CGRect(origin: CGPoint(x: leftInset, y: nodeLayout.contentSize.height - UIScreenPixel), size: CGSize(width: params.width - leftInset, height: UIScreenPixel)) strongSelf.highlightedBackgroundNode.frame = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: params.width, height: nodeLayout.size.height + UIScreenPixel)) let progressSize = CGSize(width: 24.0, height: 24.0) let progressFrame = CGRect(origin: CGPoint(x: iconFrame.minX + floorToScreenPixels((iconFrame.width - progressSize.width) / 2.0), y: iconFrame.minY + floorToScreenPixels((iconFrame.height - progressSize.height) / 2.0)), size: progressSize) if let updatedStatusSignal = updatedStatusSignal { strongSelf.statusDisposable.set((updatedStatusSignal |> deliverOnMainQueue).start(next: { [weak strongSelf] status in displayLinkDispatcher.dispatch { if let strongSelf = strongSelf { strongSelf.resourceStatus = status strongSelf.statusNode.frame = progressFrame let state: RadialStatusNodeState let statusForegroundColor: UIColor = .white switch status { case let .Fetching(_, progress): state = RadialStatusNodeState.progress(color: statusForegroundColor, lineWidth: nil, value: CGFloat(max(progress, 0.2)), cancelEnabled: false, animateRotation: true) case .Remote: state = .download(statusForegroundColor) case .Local: state = .none } strongSelf.statusNode.transitionToState(state, completion: { }) } } })) } else { strongSelf.statusNode.transitionToState(.none, completion: { }) } } }) } } override func setHighlighted(_ highlighted: Bool, at point: CGPoint, animated: Bool) { super.setHighlighted(highlighted, at: point, animated: animated) if highlighted { self.highlightedBackgroundNode.alpha = 1.0 if self.highlightedBackgroundNode.supernode == nil { self.insertSubnode(self.highlightedBackgroundNode, aboveSubnode: self.separatorNode) } } else { if self.highlightedBackgroundNode.supernode != nil { if animated { self.highlightedBackgroundNode.layer.animateAlpha(from: self.highlightedBackgroundNode.alpha, to: 0.0, duration: 0.4, completion: { [weak self] completed in if let strongSelf = self { if completed { strongSelf.highlightedBackgroundNode.removeFromSupernode() } } }) self.highlightedBackgroundNode.alpha = 0.0 } else { self.highlightedBackgroundNode.removeFromSupernode() } } } } override func selected() { guard let item = self.item else { return } let _ = item.resultSelected(item.result, self, self.bounds) } }
52.083135
340
0.573631
ffea7108595fe5f803e6e169c8ea59ca6c8bb29b
4,712
// // ZKPhotoBrowserAnimator.swift // PhotoBrowser // // Created by 闫振奎 on 15/3/15. // Copyright © 2015年 only. All rights reserved. // import UIKit // 1.定义弹出协议 protocol PresentedProtocol : class { func getImageView(IndexPath : NSIndexPath) -> UIImageView func getStartRect(indexPath : NSIndexPath) -> CGRect func getEndRect(indexPath : NSIndexPath) -> CGRect } // 2.定义消失协议 protocol DismissProtocol : class { func getImageView() -> UIImageView func getIndexPath() -> NSIndexPath } class ZKPhotoBrowserAnimator: NSObject { // MARK:- 定义属性 var isPresented : Bool = false var indexPath : NSIndexPath? // 设置代理属性 weak var presentedDelegate : PresentedProtocol? weak var dismissDelegate : DismissProtocol? } // MARK:- 实现photoBrowser的转场代理方法 extension ZKPhotoBrowserAnimator : UIViewControllerTransitioningDelegate { // 告诉弹出的动画交给谁去处理 func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = true return self } // 告诉消失的动画交给谁去处理 func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = false return self } } // MARK:- 实现photoBrowser的转场动画 extension ZKPhotoBrowserAnimator : UIViewControllerAnimatedTransitioning { // 1.决定动画执行时间 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 2.0 } // 2.决定动画如何实现 func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if isPresented { // 0.nil值校验 guard let indexPath = indexPath, presentedDelegate = presentedDelegate else { return } // 1.获取弹出的View let presenttedView = transitionContext.viewForKey(UITransitionContextToViewKey)! // 2.1 获取执行动画的imageView let imageView = presentedDelegate.getImageView(indexPath) transitionContext.containerView()?.addSubview(imageView) // 2.2.设置动画的起始位置 imageView.frame = presentedDelegate.getStartRect(indexPath) // 2.3. 执行动画 // 获取动画时间 let duration = transitionDuration(transitionContext) // 设置containerView的背景色 transitionContext.containerView()?.backgroundColor = UIColor.blackColor() UIView.animateWithDuration(duration, animations: { () -> Void in imageView.frame = presentedDelegate.getEndRect(indexPath) }, completion: { (_) -> Void in // 将弹出的View添加到containerView中 transitionContext.containerView()?.addSubview(presenttedView) imageView.removeFromSuperview() transitionContext.containerView()?.backgroundColor = UIColor.clearColor() transitionContext.completeTransition(true) }) }else { // 1.控制校验 guard let dismissDelegate = dismissDelegate, presentedDelegate = presentedDelegate else { return } // 2.取出消失的View let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey) // 3.执行动画 // 3.1 获取执行动画的imageView let imageView = dismissDelegate.getImageView() transitionContext.containerView()?.addSubview(imageView) // 3.2 取出indexPath let indexPath = dismissDelegate.getIndexPath() // 3.3 获取结束的位置 let endRect = presentedDelegate.getStartRect(indexPath) dismissView?.alpha = endRect == CGRectZero ? 1.0 : 0.0 // 3.4 执行动画 let duration = transitionDuration(transitionContext) UIView.animateWithDuration(duration, animations: { () -> Void in if endRect == CGRectZero { imageView.removeFromSuperview() dismissView?.alpha = 0.0 } else { imageView.frame = endRect } }, completion: { (_) -> Void in // 告诉系统动画执行结束,可以移除执行动画的View transitionContext.completeTransition(true) // 移除model出来的view dismissView?.removeFromSuperview() }) } } }
33.899281
217
0.602292
6258e7cac035ff5032a4dc4fb89f6ad9410679a1
1,386
// // Created by Jesse Squires // https://www.jessesquires.com // // Documentation // https://hexedbits.github.io/AboutThisApp // // GitHub // https://github.com/hexedbits/AboutThisApp // // Copyright © 2020-present Jesse Squires, Hexed Bits // https://www.hexedbits.com // import XCTest final class ExampleAppUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false } override func tearDown() { super.tearDown() } func testDisplayAboutThisAppPanel() { let app = XCUIApplication() app.launch() app.windows["AboutThisApp"].buttons["Display About This App"].click() XCTAssertTrue(app.dialogs.firstMatch.exists) app.dialogs.firstMatch.click() XCTAssertTrue(app.images["application icon"].exists) XCTAssertTrue(app.staticTexts["ExampleApp"].exists) XCTAssertTrue(app.buttons["hexedbits.com"].exists) XCTAssertTrue(app.staticTexts["Copyright © 2020 Hexed Bits. All rights reserved."].exists) XCTAssertTrue(app.buttons["Version 1.2.3 (666)"].exists) app.buttons["Version 1.2.3 (666)"].click() XCTAssertTrue(app.buttons["🎉 optional \"easter egg\" text 🎉"].exists) app.buttons["🎉 optional \"easter egg\" text 🎉"].click() XCTAssertTrue(app.buttons["Version 1.2.3 (666)"].exists) } }
27.176471
98
0.651515
fec103cf18c7986cd24e6d383332e11f98e7ce75
4,428
// // PhotosTableViewController.swift // JSONSerialization // // Created by Brendan Krekeler on 2/20/19. // Copyright © 2019 Brendan Krekeler. All rights reserved. // import UIKit class PhotosTableViewController: UITableViewController { var model = [Photo]() let dateFormatterGet = DateFormatter() let dateFormatterPrint = DateFormatter() override func viewDidLoad() { super.viewDidLoad() dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm" dateFormatterPrint.dateStyle = .medium dateFormatterPrint.timeStyle = .short //Get JSON do { try getResponse() } catch let error { print(error.localizedDescription) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return model.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "photoCell", for: indexPath) as! PhotosTableViewCell let photo = model[indexPath.row] cell.titleLabel.text = photo.title cell.photoName.text = photo.image cell.descriptionLabel.text = photo.description cell.latLabel.text = "Lat:\(photo.latitude)" cell.longLabel.text = "Long:\(photo.longitude)" cell.dateLabel.text = dateFormatterPrint.string(from: dateFormatterGet.date(from: photo.date) ?? Date.distantPast) return cell } func getResponse() throws { guard let url = URL(string: "https://dalemusser.com/code/examples/data/nocaltrip/photos.json") else { throw MyError.runtimeError("Bad Status") } let task = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let dataResponse = data, error == nil else { print(error?.localizedDescription ?? "Response Error") return } do { //here dataResponse received from a network request guard let json = try? JSONSerialization.jsonObject(with: dataResponse, options: []), let rootNode = json as? [String: Any] else { //THROW ERROR //return (nil, "unable to parse response from server") throw MyError.runtimeError("Parsing Error") } if let status = rootNode["status"] { if let status = status as? Response<Photo>.Status { if status == Response<Photo>.Status.error { //THROW ERROR throw MyError.runtimeError("Bad Status") } } } var tempPhotos = [Photo]() if let photos = rootNode["photos"] as? [[String: Any]] { for photo in photos { if let image = photo["image"] as? String, let title = photo["title"] as? String, let latitude = photo["latitude"] as? Double, let longitude = photo["longitude"] as? Double, let description = photo["description"] as? String, let date = photo["date"] as? String { tempPhotos.append(Photo(image: image, title: title, description: description, latitude:latitude, longitude: longitude, date: date)) } } } self.model = tempPhotos DispatchQueue.main.async { self.tableView.reloadData() } } catch let parsingError { print("Error", parsingError) } } task.resume() } } enum MyError: Error { case runtimeError(String) }
38.172414
159
0.535456
4aee8697d002051e50c6eee42d093dc0b4e20076
8,258
// YatCacheManagerTests.swift /* Package UnitTests Created by Adrian Truszczynski on 15/11/2021 Using Swift 5.0 Running on macOS 12.0 Copyright 2019 The Tari Project 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 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 HOLDER 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. */ @testable import Tari_Aurora import XCTest final class YatCacheManagerTests: XCTestCase { private var cacheManager: YatCacheManager! private var cacheFolder: URL { FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! } override func setUp() { super.setUp() print(cacheFolder) try? FileManager.default.removeItem(at: cacheFolder) cacheManager = YatCacheManager() } func testAddFile() { let filename = "test_file-HASH.txt" let data = "Test data".data(using: .utf8)! let fileData = cacheManager.save(data: data, name: filename) let storedData = try! Data(contentsOf: fileData!.url) XCTAssert(fileData!.url.lastPathComponent.hasPrefix(filename)) XCTAssertEqual(data, storedData) } func testReplaceFile() { let filename1 = "test_file-HASH1.txt" let filename2 = "test_file-HASH2.txt" let data1 = "Test data 1".data(using: .utf8)! let data2 = "Test data 2".data(using: .utf8)! let fileData1 = cacheManager.save(data: data1, name: filename1) let fileData2 = cacheManager.save(data: data2, name: filename2) let storedData1 = try? Data(contentsOf: fileData1!.url) let storedData2 = try! Data(contentsOf: fileData2!.url) XCTAssertNil(storedData1) XCTAssert(fileData2!.url.lastPathComponent.hasPrefix(filename2)) XCTAssertEqual(data2, storedData2) } func testFetchFile() { let filename = "test_file-HASH.txt" let data = "Test data".data(using: .utf8)! let savedFileData = cacheManager.save(data: data, name: filename)! let fetchedFileData = cacheManager.fetchFileData(name: filename)! XCTAssertEqual(savedFileData.url, fetchedFileData.url) } func testFetchSquareVideoWithNoCachedVideo() { let inputTestData = testData(hash: "HASH", isVertical: false) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNil(fileData) } func testFetchSquareVideoWithCachedSquareVideo() { let inputTestData = testData(hash: "HASH", isVertical: false) _ = cacheManager.save(data: inputTestData.data, name: inputTestData.filename) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNotNil(fileData) XCTAssertEqual(fileData!.url.lastPathComponent, inputTestData.filename) XCTAssertEqual(fileData!.identifier, .normalVideo) } func testFetchSquareVideoWithCachedVerticalVideo() { let inputTestData = testData(hash: "HASH", isVertical: false) let verticalVideoData = testData(hash: "HASH", isVertical: true) _ = cacheManager.save(data: verticalVideoData.data, name: verticalVideoData.filename) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNotNil(fileData) XCTAssertEqual(fileData!.url.lastPathComponent, verticalVideoData.filename) XCTAssertEqual(fileData!.identifier, .verticalVideo) } func testFetchVerticalVideoWithNoCachedVideo() { let inputTestData = testData(hash: "HASH", isVertical: true) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNil(fileData) } func testFetchVerticalVideoWithCachedSquareVideo() { let inputTestData = testData(hash: "HASH", isVertical: true) let squareVideoData = testData(hash: "HASH", isVertical: false) _ = cacheManager.save(data: squareVideoData.data, name: squareVideoData.filename) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNil(fileData) } func testFetchVerticalVideoWithCachedVerticalVideo() { let inputTestData = testData(hash: "HASH", isVertical: true) _ = cacheManager.save(data: inputTestData.data, name: inputTestData.filename) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNotNil(fileData) XCTAssertEqual(fileData!.url.lastPathComponent, inputTestData.filename) XCTAssertEqual(fileData!.identifier, .verticalVideo) } func testFetchNewSquareVideoWithCachedSquareVideo() { let inputTestData = testData(hash: "NEWHASH", isVertical: false) let cachedVideoData = testData(hash: "HASH", isVertical: false) _ = cacheManager.save(data: cachedVideoData.data, name: cachedVideoData.filename) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNil(fileData) } func testFetchNewSquareVideoWithCachedVerticalVideo() { let inputTestData = testData(hash: "NEWHASH", isVertical: false) let cachedVideoData = testData(hash: "HASH", isVertical: true) _ = cacheManager.save(data: cachedVideoData.data, name: cachedVideoData.filename) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNil(fileData) } func testFetchNewVerticalVideoWithCachedSquareVideo() { let inputTestData = testData(hash: "NEWHASH", isVertical: true) let cachedVideoData = testData(hash: "HASH", isVertical: false) _ = cacheManager.save(data: cachedVideoData.data, name: cachedVideoData.filename) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNil(fileData) } func testFetchNewVerticalVideoWithCachedVerticalVideo() { let inputTestData = testData(hash: "NEWHASH", isVertical: true) let cachedVideoData = testData(hash: "HASH", isVertical: true) _ = cacheManager.save(data: cachedVideoData.data, name: cachedVideoData.filename) let fileData = cacheManager.fetchFileData(name: inputTestData.filename) XCTAssertNil(fileData) } // MARK: - Helpers private func testData(hash: String, isVertical: Bool) -> (filename: String, data: Data) { let identifier = isVertical ? ".vert" : "" let filename = "test_file-\(hash)\(identifier).mp4" let data = "test_data_\(hash)_\(identifier)".data(using: .utf8)! return (filename: filename, data: data) } }
38.231481
112
0.684185
6a1d260d9482b0f383eafc99a688cd1092745dcb
11,559
// // Created by RevenueCat. // Copyright (c) 2019 RevenueCat. All rights reserved. // import Nimble import XCTest @testable import RevenueCat class IdentityManagerTests: XCTestCase { private var mockDeviceCache: MockDeviceCache! private let mockBackend = MockBackend() private var mockCustomerInfoManager: MockCustomerInfoManager! private let mockCustomerInfo = CustomerInfo(testData: [ "request_date": "2019-08-16T10:30:42Z", "subscriber": [ "first_seen": "2019-07-17T00:05:54Z", "original_app_user_id": "", "subscriptions": [:], "other_purchases": [:] ]])! private func create(appUserID: String?) -> IdentityManager { return IdentityManager(deviceCache: mockDeviceCache, backend: mockBackend, customerInfoManager: mockCustomerInfoManager, appUserID: appUserID) } override func setUp() { super.setUp() let systemInfo = MockSystemInfo(finishTransactions: false) self.mockDeviceCache = MockDeviceCache(systemInfo: systemInfo) self.mockCustomerInfoManager = MockCustomerInfoManager(operationDispatcher: MockOperationDispatcher(), deviceCache: self.mockDeviceCache, backend: MockBackend(), systemInfo: systemInfo) } func testConfigureWithAnonymousUserIDGeneratesAnAppUserID() { let manager = create(appUserID: nil) assertCorrectlyIdentifiedWithAnonymous(manager) } func testConfigureSavesTheIDInTheCache() { let manager = create(appUserID: "cesar") assertCorrectlyIdentified(manager, expectedAppUserID: "cesar") } func testAppUserIDDoesNotTrimTrailingOrLeadingSpaces() { let name = " user with spaces " let manager = create(appUserID: name) assertCorrectlyIdentified(manager, expectedAppUserID: name) } func testConfigureCleansUpSubscriberAttributes() { _ = create(appUserID: "andy") expect(self.mockDeviceCache.invokedCleanupSubscriberAttributesCount) == 1 } func testIdentifyingCorrectlyIdentifies() { _ = create(appUserID: "appUserToBeReplaced") let newAppUserID = "cesar" let newManager = create(appUserID: newAppUserID) assertCorrectlyIdentified(newManager, expectedAppUserID: newAppUserID) } func testNilAppUserIDBecomesAnonimous() { assertCorrectlyIdentifiedWithAnonymous(create(appUserID: nil)) } func testEmptyAppUserIDBecomesAnonymous() { assertCorrectlyIdentifiedWithAnonymous(create(appUserID: "")) } func testEmptyAppUserWithSpacesIDBecomesAnonymous() { assertCorrectlyIdentifiedWithAnonymous(create(appUserID: " ")) } func testMigrationFromRandomIDConfiguringAnonymously() { self.mockDeviceCache.stubbedLegacyAppUserID = "an_old_random" let manager = create(appUserID: nil) assertCorrectlyIdentifiedWithAnonymous(manager, usingOldID: true) expect(manager.currentAppUserID).to(equal("an_old_random")) } func testMigrationFromRandomIDConfiguringWithUser() { self.mockDeviceCache.stubbedLegacyAppUserID = "an_old_random" let manager = create(appUserID: "cesar") assertCorrectlyIdentified(manager, expectedAppUserID: "cesar") } func testLogInFailsIfEmptyAppUserID() throws { var receivedResult: Result<(info: CustomerInfo, created: Bool), Error>? let manager = create(appUserID: nil) manager.logIn(appUserID: "") { result in receivedResult = result } expect(receivedResult).toEventuallyNot(beNil()) let receivedNSError = try XCTUnwrap(receivedResult?.error as NSError?) expect(receivedNSError.code) == ErrorCode.invalidAppUserIdError.rawValue } func testLogInWithSameAppUserIDFetchesCustomerInfo() { let appUserID = "myUser" var receivedResult: Result<(info: CustomerInfo, created: Bool), Error>? let manager = create(appUserID: nil) mockDeviceCache.stubbedAppUserID = appUserID manager.logIn(appUserID: appUserID) { result in receivedResult = result } expect(receivedResult).toEventuallyNot(beNil()) expect(self.mockBackend.invokedLogInCount) == 0 expect(self.mockCustomerInfoManager.invokedCustomerInfoCount) == 1 } func testLogInWithSameAppUserIDPassesBackendCustomerInfoErrors() { let appUserID = "myUser" let manager = create(appUserID: nil) mockDeviceCache.stubbedAppUserID = appUserID var receivedResult: Result<(info: CustomerInfo, created: Bool), Error>? let stubbedError = NSError(domain: RCPurchasesErrorCodeDomain, code: ErrorCode.invalidAppUserIdError.rawValue, userInfo: [:]) self.mockCustomerInfoManager.stubbedCustomerInfoResult = .failure(stubbedError) manager.logIn(appUserID: appUserID) { result in receivedResult = result } expect(receivedResult).toEventuallyNot(beNil()) expect(receivedResult?.error as NSError?) == stubbedError expect(self.mockBackend.invokedLogInCount) == 0 expect(self.mockCustomerInfoManager.invokedCustomerInfoCount) == 1 } func testLogInCallsBackendLogin() { let oldAppUserID = "anonymous" let newAppUserID = "myUser" let manager = create(appUserID: nil) mockDeviceCache.stubbedAppUserID = oldAppUserID var receivedResult: Result<(info: CustomerInfo, created: Bool), Error>? self.mockBackend.stubbedLogInCompletionResult = .success((mockCustomerInfo, true)) manager.logIn(appUserID: newAppUserID) { result in receivedResult = result } expect(receivedResult).toEventuallyNot(beNil()) expect(receivedResult?.value?.created) == true expect(receivedResult?.value?.info) == mockCustomerInfo expect(self.mockBackend.invokedLogInCount) == 1 expect(self.mockCustomerInfoManager.invokedCustomerInfoCount) == 0 } func testLogInPassesBackendLoginErrors() { let oldAppUserID = "anonymous" let newAppUserID = "myUser" mockDeviceCache.stubbedAppUserID = oldAppUserID var receivedResult: Result<(info: CustomerInfo, created: Bool), Error>? let manager = create(appUserID: nil) let stubbedError = NSError(domain: RCPurchasesErrorCodeDomain, code: ErrorCode.invalidAppUserIdError.rawValue, userInfo: [:]) self.mockBackend.stubbedLogInCompletionResult = .failure(stubbedError) self.mockCustomerInfoManager.stubbedCustomerInfoResult = .failure(stubbedError) manager.logIn(appUserID: newAppUserID) { result in receivedResult = result } expect(receivedResult).toEventuallyNot(beNil()) expect(receivedResult?.error as NSError?) == stubbedError expect(self.mockBackend.invokedLogInCount) == 1 expect(self.mockCustomerInfoManager.invokedCustomerInfoCount) == 0 expect(self.mockDeviceCache.invokedClearCachesForAppUserID) == false expect(self.mockCustomerInfoManager.invokedCachedCustomerInfo) == false } func testLogInClearsCachesIfSuccessful() { var completionCalled: Bool = false let oldAppUserID = "anonymous" let newAppUserID = "myUser" mockDeviceCache.stubbedAppUserID = oldAppUserID let manager = create(appUserID: nil) self.mockBackend.stubbedLogInCompletionResult = .success((mockCustomerInfo, true)) manager.logIn(appUserID: newAppUserID) { _ in completionCalled = true } expect(completionCalled).toEventually(beTrue()) expect(self.mockDeviceCache.invokedClearCachesForAppUserID) == true } func testLogInCachesNewCustomerInfoIfSuccessful() { var completionCalled: Bool = false let oldAppUserID = "anonymous" let newAppUserID = "myUser" let manager = create(appUserID: nil) mockDeviceCache.stubbedAppUserID = oldAppUserID self.mockBackend.stubbedLogInCompletionResult = .success((mockCustomerInfo, true)) manager.logIn(appUserID: newAppUserID) { _ in completionCalled = true } expect(completionCalled).toEventually(beTrue()) expect(self.mockCustomerInfoManager.invokedCacheCustomerInfo) == true expect(self.mockCustomerInfoManager.invokedCacheCustomerInfoParameters?.info) == mockCustomerInfo expect(self.mockCustomerInfoManager.invokedCacheCustomerInfoParameters?.appUserID) == newAppUserID } func testLogOutCallsCompletionWithErrorIfUserAnonymous() { let manager = create(appUserID: nil) mockDeviceCache.stubbedAppUserID = IdentityManager.generateRandomID() var completionCalled = false var receivedError: Error? manager.logOut { error in completionCalled = true receivedError = error } expect(completionCalled).toEventually(beTrue()) expect(receivedError).toNot(beNil()) expect((receivedError as NSError?)?.code) == ErrorCode.logOutAnonymousUserError.rawValue } func testLogOutCallsCompletionWithNoErrorIfSuccessful() { let manager = create(appUserID: nil) mockDeviceCache.stubbedAppUserID = "myUser" var completionCalled = false var receivedError: Error? manager.logOut { error in completionCalled = true receivedError = error } expect(completionCalled).toEventually(beTrue()) expect(receivedError).to(beNil()) } func testLogOutClearsCachesAndAttributionData() { let manager = create(appUserID: nil) mockDeviceCache.stubbedAppUserID = "myUser" var completionCalled = false manager.logOut { _ in completionCalled = true } expect(completionCalled).toEventually(beTrue()) expect(self.mockDeviceCache.invokedClearCachesForAppUserID) == true expect(self.mockDeviceCache.invokedClearLatestNetworkAndAdvertisingIdsSent) == true } } private extension IdentityManagerTests { func assertCorrectlyIdentified(_ manager: IdentityManager, expectedAppUserID: String) { expect(manager.currentAppUserID).to(equal(expectedAppUserID)) expect(self.mockDeviceCache.userIDStoredInCache!).to(equal(expectedAppUserID)) expect(manager.currentUserIsAnonymous).to(beFalse()) } func assertCorrectlyIdentifiedWithAnonymous(_ manager: IdentityManager, usingOldID: Bool = false) { if !usingOldID { var obtainedRange = manager.currentAppUserID.range( of: IdentityManager.anonymousRegex, options: .regularExpression ) expect(obtainedRange).toNot(beNil()) obtainedRange = self.mockDeviceCache.userIDStoredInCache!.range( of: IdentityManager.anonymousRegex, options: .regularExpression ) expect(obtainedRange).toNot(beNil()) } expect(manager.currentUserIsAnonymous).to(beTrue()) } }
35.675926
110
0.668743
48673b1d14a116e1b778daa82a8fcc18c49c3dce
4,299
import XCTest import Mapbox class MGLMapViewDelegateIntegrationTests: XCTestCase { func testCoverage() { MGLSDKTestHelpers.checkTestsContainAllMethods(testClass: MGLMapViewDelegateIntegrationTests.self, in: MGLMapViewDelegate.self) } } extension MGLMapViewDelegateIntegrationTests: MGLMapViewDelegate { func mapViewRegionIsChanging(_ mapView: MGLMapView) {} func mapViewRegionIsChanging(_ mapView: MGLMapView, reason: MGLCameraChangeReason) {} func mapView(_ mapView: MGLMapView, regionIsChangingWith reason: MGLCameraChangeReason) {} func mapView(_ mapView: MGLMapView, didChange mode: MGLUserTrackingMode, animated: Bool) {} func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {} func mapViewDidStopLocatingUser(_ mapView: MGLMapView) {} func mapViewWillStartLoadingMap(_ mapView: MGLMapView) {} func mapViewWillStartLocatingUser(_ mapView: MGLMapView) {} func mapViewWillStartRenderingMap(_ mapView: MGLMapView) {} func mapViewWillStartRenderingFrame(_ mapView: MGLMapView) {} func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {} func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {} func mapView(_ mapView: MGLMapView, didDeselect annotation: MGLAnnotation) {} func mapView(_ mapView: MGLMapView, didSingleTapAt coordinate: CLLocationCoordinate2D) {} func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool) {} func mapView(_ mapView: MGLMapView, regionDidChangeWith reason: MGLCameraChangeReason, animated: Bool) {} func mapView(_ mapView: MGLMapView, regionWillChangeAnimated animated: Bool) {} func mapView(_ mapView: MGLMapView, regionWillChangeWith reason: MGLCameraChangeReason, animated: Bool) {} func mapViewDidFailLoadingMap(_ mapView: MGLMapView, withError error: Error) {} func mapView(_ mapView: MGLMapView, didUpdate userLocation: MGLUserLocation?) {} func mapViewDidFinishRenderingMap(_ mapView: MGLMapView, fullyRendered: Bool) {} func mapView(_ mapView: MGLMapView, didFailToLocateUserWithError error: Error) {} func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {} func mapViewDidFinishRenderingFrame(_ mapView: MGLMapView, fullyRendered: Bool) {} func mapView(_ mapView: MGLMapView, shapeAnnotationIsEnabled annotation: MGLShape) -> Bool { return false } func mapView(_ mapView: MGLMapView, didAdd annotationViews: [MGLAnnotationView]) {} func mapView(_ mapView: MGLMapView, didSelect annotationView: MGLAnnotationView) {} func mapView(_ mapView: MGLMapView, didDeselect annotationView: MGLAnnotationView) {} func mapView(_ mapView: MGLMapView, alphaForShapeAnnotation annotation: MGLShape) -> CGFloat { return 0 } func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? { return nil } func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? { return nil } func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool { return false } func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView? { return nil } func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor { return .black } func mapView(_ mapView: MGLMapView, fillColorForPolygonAnnotation annotation: MGLPolygon) -> UIColor { return .black } func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? { return nil } func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat { return 0 } func mapView(_ mapView: MGLMapView, rightCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? { return nil } func mapView(_ mapView: MGLMapView, annotation: MGLAnnotation, calloutAccessoryControlTapped control: UIControl) {} func mapView(_ mapView: MGLMapView, shouldChangeFrom oldCamera: MGLMapCamera, to newCamera: MGLMapCamera) -> Bool { return false } func mapView(_ mapView: MGLMapView, shouldChangeFrom oldCamera: MGLMapCamera, to newCamera: MGLMapCamera, reason: MGLCameraChangeReason) -> Bool { return false } }
44.78125
165
0.772738
69275c6a3985dbf46ea2b78b33f4fba222e8eaad
4,050
// // DUXBetaBindings.swift // DJIUXSDKCore // // Copyright © 2018-2020 DJI // // 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. // /** DUXBetaSwiftBindings - This is an extension that allows the developer to bind the the SDK keys observe changes. It allows writting widgets and models in Swift. These are the same functionality as the binding macros written in Objective-C (see NSObject+DUXBetaRKVOExtension.h) with one small change. When using bindRKVOModel to bind paths, all paths are put into a comma separated list inside a string. This list will then be decomposed in the binding extension. This is due to the inability to create a vardic list with multiple KeyPath elements. In general, where the Objective-C macros do inline replacement of property names, those property names need to be put into strings to pass as arguments in Swift. Any property to be observed or modified in Swift needs to be marked as dynamic. Also, any property to be observed from Swift which may be nil, MUST have a strong/weak designation if it is in Objective-C code to allow for proper treatment as an optional if needed. */ import Foundation protocol DUXBetaSwiftBindings { func bindRKVOModel(_ target: NSObject, _ selector: Selector, _ observedKeyPaths: String...) func bindRKVOModel(_ target: NSObject, _ selector: Selector, _ observedKeyPaths: String) func bindRKVOModel(_ target: NSObject, _ selector: Selector, _ observedKeyPaths: [String]) func unbindRKVOModel(_ target: NSObject) func bindSDKKey(_ key: DJIKey, _ property: String ) func checkSDKBindPropertyIsValid(_ propertyName: String) func unbindSDK(_ target: NSObject) } extension NSObject: DUXBetaSwiftBindings { open func bindRKVOModel(_ target: NSObject, _ selector: Selector, _ observedKeyPaths: String...) { bindRKVOModel(target, selector, observedKeyPaths) } open func bindRKVOModel(_ target: NSObject, _ selector: Selector, _ observedKeyPaths: String) { let keysArray = observedKeyPaths.components(separatedBy: ",").map({ $0.trimmingCharacters(in: .whitespaces) }) bindRKVOModel(target, selector, keysArray) } open func bindRKVOModel(_ target: NSObject, _ selector: Selector, _ keyPaths: [String]) { for keyPath in keyPaths { duxbeta_bindRKVO(withTarget: target, selector: selector, property: keyPath) } } open func unbindRKVOModel(_ target: NSObject) { target.duxbeta_unBindRKVO() } open func bindSDKKey(_ key: DJIKey, _ property: String ) { self.duxbeta_bindSDKKey(key, propertyName: property) } open func checkSDKBindPropertyIsValid(_ propertyName: String) { self.duxbeta_checkSDKBindPropertyIsValid(propertyName) } open func unbindSDK(_ target: NSObject) { target.duxbeta_unBindSDK() } } extension KeyPath where Root: NSObject { public var toString: String { return NSExpression(forKeyPath: self).keyPath } }
43.548387
139
0.737037
877addb403bba7e6f33324368ce3e58485841f3b
1,595
import HaishinKit import Logboard import ReplayKit import VideoToolbox @available(iOS 10.0, *) open class SampleHandler: RPBroadcastSampleHandler { private var broadcaster = RTMPBroadcaster() override open func broadcastStarted(withSetupInfo setupInfo: [String: NSObject]?) { /* let logger = Logboard.with(HaishinKitIdentifier) let socket = SocketAppender() socket.connect("192.168.11.15", port: 22222) logger.level = .debug logger.appender = socket */ broadcaster.streamName = Preference.defaultInstance.streamName broadcaster.connect(Preference.defaultInstance.uri!, arguments: nil) } override open func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) { switch sampleBufferType { case .video: if let description: CMVideoFormatDescription = CMSampleBufferGetFormatDescription(sampleBuffer) { let dimensions: CMVideoDimensions = CMVideoFormatDescriptionGetDimensions(description) broadcaster.stream.videoSettings = [ .width: dimensions.width, .height: dimensions.height , .profileLevel: kVTProfileLevel_H264_Baseline_AutoLevel ] } broadcaster.appendSampleBuffer(sampleBuffer, withType: .video) case .audioApp: break case .audioMic: broadcaster.appendSampleBuffer(sampleBuffer, withType: .audio) @unknown default: break } } }
37.093023
119
0.657053
6920bf3470a231cf366429ca25ed3573ec3eff8a
1,683
// // The MIT License (MIT) // // Copyright (c) 2016 Tony Arnold (@tonyarnold) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(macOS) import AppKit extension NSResponder: BindingExecutionContextProvider { public var bindingExecutionContext: ExecutionContext { return .immediateOnMain } } public extension ReactiveExtensions where Base: NSView { public var alphaValue: Bond<CGFloat> { return bond { $0.alphaValue = $1 } } public var isHidden: Bond<Bool> { return bond { $0.isHidden = $1 } } public var toolTip: Bond<String?> { return bond { $0.toolTip = $1 } } } #endif
34.346939
84
0.720143
5dc4479d1bc4a5f71cc61c82a4ca9257d8f11695
858
// // CalenderDelegate.swift // CalenderView // // Created by 小川 卓也 on 2017/10/31. // Copyright © 2017年 小川 卓也. All rights reserved. // import UIKit /// CollectionViewからViewに返すDelegate protocol CalendarDelegate: class { /// 日付選択した際に返す /// /// - Parameter date: 選択された日付 func didSelectStartDate(date : Date) /// 2つの日付を選択された際に返す /// /// - Parameters: /// - startDate: 開始日 /// - endDate: 終了日 func didSelectDoubleDate(startDate : Date, endDate : Date) } /// ViewController側に返すDelegate @objc protocol CalrendarViewDelegate { /// 日付を選択した際に返す /// /// - Parameter date: 選択された日付 func didSelectStartDate(date : Date) /// 2つの日付を選択された際に返す /// /// - Parameters: /// - startDate: 開始日 /// - endDate: 終了日 func didSelectDoubleDate(startDate : Date, endDate : Date) }
20.926829
62
0.617716
79bc8422482a467a17ccbd709db3b058ad5032c9
358
import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
25.571429
71
0.743017
62e4a7feaa3e79a82994b4f10004ea122c64b9f7
3,874
// // TSBaseResponse.swift // TSNetWork // // Created by 小铭 on 2018/6/6. // Copyright © 2018年 caiqr. All rights reserved. // 接口返回统一Response import UIKit import HandyJSON public protocol TSMoyaAddable : HandyJSON { //自定义API func objectToModelFinish () } public class TSBaseResponse{ public var code: Int { if let temp = jsonObject["code"] { if let codeInt = temp as? Int { return codeInt } else { debugPrint("json Code 不是Int类型") } if let codeString = temp as? String { return Int(codeString) ?? -1 } else { debugPrint("json Code 不是String类型") } } else { debugPrint("json Code 为空") } return -1 } public var errorMessage: String? { guard let temp = jsonObject["msg"] as? String else { debugPrint("json Msg 为空") return "" } return temp } public var jsonObject: [String : Any] required public init() { jsonObject = ["":""] } init?(data: Any) { guard let temp = data as? [String : Any] else { debugPrint("json 格式错误") return nil } self.jsonObject = temp // let resp = self.jsonData["resp"] // if let arrFistDic = (resp as? Array<Any>)?.first as? NSDictionary { // self.responeObject = JSONDeserializer<T>.deserializeFrom(dict: arrFistDic) // } // if let dic = resp as? Dictionary<String, Any> { // self.responeObject = JSONDeserializer<T>.deserializeFrom(dict: dic) // } // if let dicString = resp as? String { // self.responeObject = JSONDeserializer<T>.deserializeFrom(json: dicString) // } // self.responeObject.objectToModelFinish() } // public var responeObject: T! = T() } public extension TSBaseResponse { //通过dict转Model public class func ts_deserializeModelFrom<T : TSMoyaAddable> (dict : [String : Any]) -> T{ var model = T() if let modelT = JSONDeserializer<T>.deserializeFrom(dict: dict) { model = modelT model.objectToModelFinish() } return model } public class func ts_deserializeModelFrom<T : TSMoyaAddable> (dict : NSDictionary) -> T{ var model = T() if let modelT = JSONDeserializer<T>.deserializeFrom(dict: dict) { model = modelT model.objectToModelFinish() } return model } //通过jsonString转Model public class func ts_deserializeModelFrom<T : TSMoyaAddable> (json : String) -> T{ var model = T() if let modelT = JSONDeserializer<T>.deserializeFrom(json: json) { model = modelT model.objectToModelFinish() } return model } //通过数组转模型数组 public class func ts_deserializeModelArrFrom<T : TSMoyaAddable> (arr : [Any]) -> [T]{ var modelArr : [T] = [] if let modelTArr = JSONDeserializer<T>.deserializeModelArrayFrom(array: arr) { modelArr = modelTArr as! [T] } return modelArr } public class func ts_deserializeModelArrFrom<T : TSMoyaAddable> (arr : NSArray) -> [T]{ var modelArr : [T] = [] if let modelTArr = JSONDeserializer<T>.deserializeModelArrayFrom(array: arr) { modelArr = modelTArr as! [T] } return modelArr } public class func ts_deserializeModelArrFrom<T : TSMoyaAddable> (jsonString : String) -> [T]{ var modelArr : [T] = [] if let modelTArr = JSONDeserializer<T>.deserializeModelArrayFrom(json: jsonString) { modelArr = modelTArr as! [T] } return modelArr } } public extension TSMoyaAddable { func objectToModelFinish () { } }
30.031008
97
0.570212
f42ebfb86f5cee290221cf90f14aa1ac13df4645
23,972
//RUN: %target-prepare-obfuscation-for-file "TypeCasting" %target-run-full-obfuscation import AppKit class SomeGenericClass<Param> {} enum RandomEnum { case Foo } func someRandomFunc() -> RandomEnum { return RandomEnum.Foo } final class TestController2: NSViewController { override func viewDidLoad() { super.viewDidLoad() } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if case .Foo = someRandomFunc() , sender is SomeGenericClass<String> { let casted = sender as! SomeGenericClass<String> } } } class SampleClass { } enum SampleEnum { case case1 } let enumCase = SampleEnum.case1 class GenericClass<T> { } let castedNonOptional = SampleClass() let castedOptional: SampleClass? = nil let genericNonOptional = GenericClass<SampleClass>() let genericOptional: GenericClass<SampleClass>? = nil let genericParameterOptional: GenericClass<SampleClass>? = nil // binary-expression with type-casting-operator let _ = castedNonOptional is SampleClass let _ = castedNonOptional is SampleClass? let _ = castedNonOptional is GenericClass<SampleClass> //let _ = castedNonOptional is GenericClass<SampleClass>? //compiler error let _ = castedNonOptional is GenericClass<SampleClass?> let _ = castedNonOptional is GenericClass<Int> //let _ = castedNonOptional is GenericClass<Int>? //compiler error let _ = castedNonOptional is GenericClass<Int?> let _ = castedNonOptional as SampleClass let _ = castedNonOptional as SampleClass? //let _ = castedNonOptional as GenericClass<SampleClass> //compiler error //let _ = castedNonOptional as GenericClass<SampleClass>? //compiler error //let _ = castedNonOptional as GenericClass<SampleClass?> //compiler error //let _ = castedNonOptional as GenericClass<Int> //compiler error //let _ = castedNonOptional as GenericClass<Int>? //compiler error //let _ = castedNonOptional as GenericClass<Int?> //compiler error let _ = castedNonOptional as? SampleClass let _ = castedNonOptional as? SampleClass? let _ = castedNonOptional as? GenericClass<SampleClass> //let _ = castedNonOptional as? GenericClass<SampleClass>? //compiler error let _ = castedNonOptional as? GenericClass<SampleClass?> let _ = castedNonOptional as? GenericClass<Int> //let _ = castedNonOptional as? GenericClass<Int>? //compiler error let _ = castedNonOptional as? GenericClass<Int?> let _ = castedNonOptional as! SampleClass let _ = castedNonOptional as! SampleClass? let _ = castedNonOptional as! GenericClass<SampleClass> //let _ = castedNonOptional as! GenericClass<SampleClass>? //compiler error let _ = castedNonOptional as! GenericClass<SampleClass?> let _ = castedNonOptional as! GenericClass<Int> //let _ = castedNonOptional as! GenericClass<Int>? //compiler error let _ = castedNonOptional as! GenericClass<Int?> let _ = castedOptional is SampleClass let _ = castedOptional is SampleClass? let _ = castedOptional is GenericClass<SampleClass> let _ = castedOptional is GenericClass<SampleClass>? let _ = castedOptional is GenericClass<SampleClass?> let _ = castedOptional is GenericClass<Int> let _ = castedOptional is GenericClass<Int>? let _ = castedOptional is GenericClass<Int?> //let _ = castedOptional as SampleClass //compiler error let _ = castedOptional as SampleClass? //let _ = castedOptional as GenericClass<SampleClass> //compiler error //let _ = castedOptional as GenericClass<SampleClass>? //compiler error //let _ = castedOptional as GenericClass<SampleClass?> //compiler error //let _ = castedOptional as GenericClass<Int> //compiler error //let _ = castedOptional as GenericClass<Int>? //compiler error //let _ = castedOptional as GenericClass<Int?> //compiler error let _ = castedOptional as? SampleClass let _ = castedOptional as? SampleClass? let _ = castedOptional as? GenericClass<SampleClass> let _ = castedOptional as? GenericClass<SampleClass>? let _ = castedOptional as? GenericClass<SampleClass?> let _ = castedOptional as? GenericClass<Int> let _ = castedOptional as? GenericClass<Int>? let _ = castedOptional as? GenericClass<Int?> let _ = castedOptional as! SampleClass let _ = castedOptional as! SampleClass? let _ = castedOptional as! GenericClass<SampleClass> let _ = castedOptional as! GenericClass<SampleClass>? let _ = castedOptional as! GenericClass<SampleClass?> let _ = castedOptional as! GenericClass<Int> let _ = castedOptional as! GenericClass<Int>? let _ = castedOptional as! GenericClass<Int?> let _ = genericNonOptional is SampleClass //let _ = genericNonOptional is SampleClass? //compiler error let _ = genericNonOptional is GenericClass<SampleClass> let _ = genericNonOptional is GenericClass<SampleClass>? let _ = genericNonOptional is GenericClass<SampleClass?> let _ = genericNonOptional is GenericClass<Int> //let _ = genericNonOptional is GenericClass<Int>? //compiler error let _ = genericNonOptional is GenericClass<Int?> //let _ = genericNonOptional as SampleClass //compiler error //let _ = genericNonOptional as SampleClass? //compiler error let _ = genericNonOptional as GenericClass<SampleClass> let _ = genericNonOptional as GenericClass<SampleClass>? //let _ = genericNonOptional as GenericClass<SampleClass?> //compiler error //let _ = genericNonOptional as GenericClass<Int> //compiler error //let _ = genericNonOptional as GenericClass<Int>? //compiler error //let _ = genericNonOptional as GenericClass<Int?> //compiler error let _ = genericNonOptional as? SampleClass //let _ = genericNonOptional as? SampleClass? //compiler error let _ = genericNonOptional as? GenericClass<SampleClass> let _ = genericNonOptional as? GenericClass<SampleClass>? let _ = genericNonOptional as? GenericClass<SampleClass?> let _ = genericNonOptional as? GenericClass<Int> //let _ = genericNonOptional as? GenericClass<Int>? //compiler error let _ = genericNonOptional as? GenericClass<Int?> let _ = genericNonOptional as! SampleClass //let _ = genericNonOptional as! SampleClass? //compiler error let _ = genericNonOptional as! GenericClass<SampleClass> let _ = genericNonOptional as! GenericClass<SampleClass>? let _ = genericNonOptional as! GenericClass<SampleClass?> let _ = genericNonOptional as! GenericClass<Int> //let _ = genericNonOptional as! GenericClass<Int>? //compiler error let _ = genericNonOptional as! GenericClass<Int?> let _ = genericOptional is SampleClass let _ = genericOptional is SampleClass? let _ = genericOptional is GenericClass<SampleClass> let _ = genericOptional is GenericClass<SampleClass>? let _ = genericOptional is GenericClass<SampleClass?> let _ = genericOptional is GenericClass<Int> let _ = genericOptional is GenericClass<Int>? let _ = genericOptional is GenericClass<Int?> //let _ = genericOptional as SampleClass //compiler error //let _ = genericOptional as SampleClass? //compiler error //let _ = genericOptional as GenericClass<SampleClass> //compiler error let _ = genericOptional as GenericClass<SampleClass>? //let _ = genericOptional as GenericClass<SampleClass?> //compiler error //let _ = genericOptional as GenericClass<Int> //compiler error //let _ = genericOptional as GenericClass<Int>? //compiler error //let _ = genericOptional as GenericClass<Int?> //compiler error let _ = genericOptional as? SampleClass let _ = genericOptional as? SampleClass? let _ = genericOptional as? GenericClass<SampleClass> let _ = genericOptional as? GenericClass<SampleClass>? let _ = genericOptional as? GenericClass<SampleClass?> let _ = genericOptional as? GenericClass<Int> let _ = genericOptional as? GenericClass<Int>? let _ = genericOptional as? GenericClass<Int?> let _ = genericOptional as! SampleClass let _ = genericOptional as! SampleClass? let _ = genericOptional as! GenericClass<SampleClass> let _ = genericOptional as! GenericClass<SampleClass>? let _ = genericOptional as! GenericClass<SampleClass?> let _ = genericOptional as! GenericClass<Int> let _ = genericOptional as! GenericClass<Int>? let _ = genericOptional as! GenericClass<Int?> let _ = genericParameterOptional is SampleClass let _ = genericParameterOptional is SampleClass? let _ = genericParameterOptional is GenericClass<SampleClass> let _ = genericParameterOptional is GenericClass<SampleClass>? let _ = genericParameterOptional is GenericClass<SampleClass?> let _ = genericParameterOptional is GenericClass<Int> let _ = genericParameterOptional is GenericClass<Int>? let _ = genericParameterOptional is GenericClass<Int?> //let _ = genericParameterOptional as SampleClass //compiler error //let _ = genericParameterOptional as SampleClass? //compiler error //let _ = genericParameterOptional as GenericClass<SampleClass> //compiler error let _ = genericParameterOptional as GenericClass<SampleClass>? //let _ = genericParameterOptional as GenericClass<SampleClass?> //compiler error //let _ = genericParameterOptional as GenericClass<Int> //compiler error //let _ = genericParameterOptional as GenericClass<Int>? //compiler error //let _ = genericParameterOptional as GenericClass<Int?> //compiler error let _ = genericParameterOptional as? SampleClass let _ = genericParameterOptional as? SampleClass? let _ = genericParameterOptional as? GenericClass<SampleClass> let _ = genericParameterOptional as? GenericClass<SampleClass>? let _ = genericParameterOptional as? GenericClass<SampleClass?> let _ = genericParameterOptional as? GenericClass<Int> let _ = genericParameterOptional as? GenericClass<Int>? let _ = genericParameterOptional as? GenericClass<Int?> let _ = genericParameterOptional as! SampleClass let _ = genericParameterOptional as! SampleClass? let _ = genericParameterOptional as! GenericClass<SampleClass> let _ = genericParameterOptional as! GenericClass<SampleClass>? let _ = genericParameterOptional as! GenericClass<SampleClass?> let _ = genericParameterOptional as! GenericClass<Int> let _ = genericParameterOptional as! GenericClass<Int>? let _ = genericParameterOptional as! GenericClass<Int?> // type-casting-pattern in case-condition if case .case1 = enumCase, castedNonOptional is SampleClass { } if case .case1 = enumCase, castedNonOptional is SampleClass? { } if case .case1 = enumCase, castedNonOptional is GenericClass<SampleClass> { } //if case .case1 = enumCase, castedNonOptional is GenericClass<SampleClass>? { } //compiler error if case .case1 = enumCase, castedNonOptional is GenericClass<SampleClass?> { } if case .case1 = enumCase, castedNonOptional is GenericClass<Int> { } //if case .case1 = enumCase, castedNonOptional is GenericClass<Int>? { } //compiler error if case .case1 = enumCase, castedNonOptional is GenericClass<Int?> { } //if case .case1 = enumCase, let _ = castedNonOptional as SampleClass { } //compiler error if case .case1 = enumCase, let _ = castedNonOptional as SampleClass? { } //if case .case1 = enumCase, let _ = castedNonOptional as GenericClass<SampleClass> { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as GenericClass<SampleClass>? { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as GenericClass<Int> { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as GenericClass<Int>? { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as GenericClass<Int?> { } //compiler error if case .case1 = enumCase, let _ = castedNonOptional as? SampleClass { } if case .case1 = enumCase, let _ = castedNonOptional as? SampleClass? { } if case .case1 = enumCase, let _ = castedNonOptional as? GenericClass<SampleClass> { } //if case .case1 = enumCase, let _ = castedNonOptional as? GenericClass<SampleClass>? { } //compiler error if case .case1 = enumCase, let _ = castedNonOptional as? GenericClass<SampleClass?> { } if case .case1 = enumCase, let _ = castedNonOptional as? GenericClass<Int> { } //if case .case1 = enumCase, let _ = castedNonOptional as? GenericClass<Int>? { } //compiler error if case .case1 = enumCase, let _ = castedNonOptional as? GenericClass<Int?> { } //if case .case1 = enumCase, let _ = castedNonOptional as! SampleClass { } //compiler error if case .case1 = enumCase, let _ = castedNonOptional as! SampleClass? { } //if case .case1 = enumCase, let _ = castedNonOptional as! GenericClass<SampleClass> { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as! GenericClass<SampleClass>? { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as! GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as! GenericClass<Int> { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as! GenericClass<Int>? { } //compiler error //if case .case1 = enumCase, let _ = castedNonOptional as! GenericClass<Int?> { } //compiler error if case .case1 = enumCase, castedOptional is SampleClass { } if case .case1 = enumCase, castedOptional is SampleClass? { } if case .case1 = enumCase, castedOptional is GenericClass<SampleClass> { } if case .case1 = enumCase, castedOptional is GenericClass<SampleClass>? { } if case .case1 = enumCase, castedOptional is GenericClass<SampleClass?> { } if case .case1 = enumCase, castedOptional is GenericClass<Int> { } if case .case1 = enumCase, castedOptional is GenericClass<Int>? { } if case .case1 = enumCase, castedOptional is GenericClass<Int?> { } //if case .case1 = enumCase, let _ = castedOptional as SampleClass { } //compiler error if case .case1 = enumCase, let _ = castedOptional as SampleClass? { } //if case .case1 = enumCase, let _ = castedOptional as GenericClass<SampleClass> { } //compiler error //if case .case1 = enumCase, let _ = castedOptional as GenericClass<SampleClass>? { } //compiler error //if case .case1 = enumCase, let _ = castedOptional as GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = castedOptional as GenericClass<Int> { } //compiler error //if case .case1 = enumCase, let _ = castedOptional as GenericClass<Int>? { } //compiler error //if case .case1 = enumCase, let _ = castedOptional as GenericClass<Int?> { } //compiler error if case .case1 = enumCase, let _ = castedOptional as? SampleClass { } if case .case1 = enumCase, let _ = castedOptional as? SampleClass? { } if case .case1 = enumCase, let _ = castedOptional as? GenericClass<SampleClass> { } if case .case1 = enumCase, let _ = castedOptional as? GenericClass<SampleClass>? { } if case .case1 = enumCase, let _ = castedOptional as? GenericClass<SampleClass?> { } if case .case1 = enumCase, let _ = castedOptional as? GenericClass<Int> { } if case .case1 = enumCase, let _ = castedOptional as? GenericClass<Int>? { } if case .case1 = enumCase, let _ = castedOptional as? GenericClass<Int?> { } //if case .case1 = enumCase, let _ = castedOptional as! SampleClass { } //compiler error if case .case1 = enumCase, let _ = castedOptional as! SampleClass? { } //if case .case1 = enumCase, let _ = castedOptional as! GenericClass<SampleClass> { } //compiler error if case .case1 = enumCase, let _ = castedOptional as! GenericClass<SampleClass>? { } //if case .case1 = enumCase, let _ = castedOptional as! GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = castedOptional as! GenericClass<Int> { } //compiler error if case .case1 = enumCase, let _ = castedOptional as! GenericClass<Int>? { } //if case .case1 = enumCase, let _ = castedOptional as! GenericClass<Int?> { } //compiler error if case .case1 = enumCase, genericNonOptional is SampleClass { } //if case .case1 = enumCase, genericNonOptional is SampleClass? { } //compiler error if case .case1 = enumCase, genericNonOptional is GenericClass<SampleClass> { } if case .case1 = enumCase, genericNonOptional is GenericClass<SampleClass>? { } if case .case1 = enumCase, genericNonOptional is GenericClass<SampleClass?> { } if case .case1 = enumCase, genericNonOptional is GenericClass<Int> { } //if case .case1 = enumCase, genericNonOptional is GenericClass<Int>? { } //compiler error if case .case1 = enumCase, genericNonOptional is GenericClass<Int?> { } //if case .case1 = enumCase, let _ = genericNonOptional as SampleClass { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as SampleClass? { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as GenericClass<SampleClass> { } //compiler error if case .case1 = enumCase, let _ = genericNonOptional as GenericClass<SampleClass>? { } //if case .case1 = enumCase, let _ = genericNonOptional as GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as GenericClass<Int> { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as GenericClass<Int>? { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as GenericClass<Int?> { } //compiler error if case .case1 = enumCase, let _ = genericNonOptional as? SampleClass { } //if case .case1 = enumCase, let _ = genericNonOptional as? SampleClass? { } //compiler error if case .case1 = enumCase, let _ = genericNonOptional as? GenericClass<SampleClass> { } if case .case1 = enumCase, let _ = genericNonOptional as? GenericClass<SampleClass>? { } if case .case1 = enumCase, let _ = genericNonOptional as? GenericClass<SampleClass?> { } if case .case1 = enumCase, let _ = genericNonOptional as? GenericClass<Int> { } //if case .case1 = enumCase, let _ = genericNonOptional as? GenericClass<Int>? { } //compiler error if case .case1 = enumCase, let _ = genericNonOptional as? GenericClass<Int?> { } //if case .case1 = enumCase, let _ = genericNonOptional as! SampleClass { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as! SampleClass? { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as! GenericClass<SampleClass> { } //compiler error if case .case1 = enumCase, let _ = genericNonOptional as! GenericClass<SampleClass>? { } //if case .case1 = enumCase, let _ = genericNonOptional as! GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as! GenericClass<Int> { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as! GenericClass<Int>? { } //compiler error //if case .case1 = enumCase, let _ = genericNonOptional as! GenericClass<Int?> { } //compiler error if case .case1 = enumCase, genericOptional is SampleClass { } if case .case1 = enumCase, genericOptional is SampleClass? { } if case .case1 = enumCase, genericOptional is GenericClass<SampleClass> { } if case .case1 = enumCase, genericOptional is GenericClass<SampleClass>? { } if case .case1 = enumCase, genericOptional is GenericClass<SampleClass?> { } if case .case1 = enumCase, genericOptional is GenericClass<Int> { } if case .case1 = enumCase, genericOptional is GenericClass<Int>? { } if case .case1 = enumCase, genericOptional is GenericClass<Int?> { } //if case .case1 = enumCase, let _ = genericOptional as SampleClass { } //compiler error //if case .case1 = enumCase, let _ = genericOptional as SampleClass? { } //compiler error //if case .case1 = enumCase, let _ = genericOptional as GenericClass<SampleClass> { } //compiler error if case .case1 = enumCase, let _ = genericOptional as GenericClass<SampleClass>? { } //if case .case1 = enumCase, let _ = genericOptional as GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = genericOptional as GenericClass<Int> { } //compiler error //if case .case1 = enumCase, let _ = genericOptional as GenericClass<Int>? { } //compiler error //if case .case1 = enumCase, let _ = genericOptional as GenericClass<Int?> { } //compiler error if case .case1 = enumCase, let _ = genericOptional as? SampleClass { } if case .case1 = enumCase, let _ = genericOptional as? SampleClass? { } if case .case1 = enumCase, let _ = genericOptional as? GenericClass<SampleClass> { } if case .case1 = enumCase, let _ = genericOptional as? GenericClass<SampleClass>? { } if case .case1 = enumCase, let _ = genericOptional as? GenericClass<SampleClass?> { } if case .case1 = enumCase, let _ = genericOptional as? GenericClass<Int> { } if case .case1 = enumCase, let _ = genericOptional as? GenericClass<Int>? { } if case .case1 = enumCase, let _ = genericOptional as? GenericClass<Int?> { } //if case .case1 = enumCase, let _ = genericOptional as! SampleClass { } //compiler error if case .case1 = enumCase, let _ = genericOptional as! SampleClass? { } //if case .case1 = enumCase, let _ = genericOptional as! GenericClass<SampleClass> { } //compiler error if case .case1 = enumCase, let _ = genericOptional as! GenericClass<SampleClass>? { } //if case .case1 = enumCase, let _ = genericOptional as! GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = genericOptional as! GenericClass<Int> { } //compiler error if case .case1 = enumCase, let _ = genericOptional as! GenericClass<Int>? { } //if case .case1 = enumCase, let _ = genericOptional as! GenericClass<Int?> { } //compiler error if case .case1 = enumCase, genericParameterOptional is SampleClass { } if case .case1 = enumCase, genericParameterOptional is SampleClass? { } if case .case1 = enumCase, genericParameterOptional is GenericClass<SampleClass> { } if case .case1 = enumCase, genericParameterOptional is GenericClass<SampleClass>? { } if case .case1 = enumCase, genericParameterOptional is GenericClass<SampleClass?> { } if case .case1 = enumCase, genericParameterOptional is GenericClass<Int> { } if case .case1 = enumCase, genericParameterOptional is GenericClass<Int>? { } if case .case1 = enumCase, genericParameterOptional is GenericClass<Int?> { } //if case .case1 = enumCase, let _ = genericParameterOptional as SampleClass { } //compiler error //if case .case1 = enumCase, let _ = genericParameterOptional as SampleClass? { } //compiler error //if case .case1 = enumCase, let _ = genericParameterOptional as GenericClass<SampleClass> { } //compiler error //if case .case1 = enumCase, let _ = genericParameterOptional as GenericClass<SampleClass>? { } //compiler error //if case .case1 = enumCase, let _ = genericParameterOptional as GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = genericParameterOptional as GenericClass<Int> { } //compiler error //if case .case1 = enumCase, let _ = genericParameterOptional as GenericClass<Int>? { } //compiler error //if case .case1 = enumCase, let _ = genericParameterOptional as GenericClass<Int?> { } //compiler error if case .case1 = enumCase, let _ = genericParameterOptional as? SampleClass { } if case .case1 = enumCase, let _ = genericParameterOptional as? SampleClass? { } if case .case1 = enumCase, let _ = genericParameterOptional as? GenericClass<SampleClass> { } if case .case1 = enumCase, let _ = genericParameterOptional as? GenericClass<SampleClass>? { } if case .case1 = enumCase, let _ = genericParameterOptional as? GenericClass<SampleClass?> { } if case .case1 = enumCase, let _ = genericParameterOptional as? GenericClass<Int> { } if case .case1 = enumCase, let _ = genericParameterOptional as? GenericClass<Int>? { } if case .case1 = enumCase, let _ = genericParameterOptional as? GenericClass<Int?> { } //if case .case1 = enumCase, let _ = genericParameterOptional as! SampleClass { } //compiler error if case .case1 = enumCase, let _ = genericParameterOptional as! SampleClass? { } //if case .case1 = enumCase, let _ = genericParameterOptional as! GenericClass<SampleClass> { } //compiler error if case .case1 = enumCase, let _ = genericParameterOptional as! GenericClass<SampleClass>? { } //if case .case1 = enumCase, let _ = genericParameterOptional as! GenericClass<SampleClass?> { } //compiler error //if case .case1 = enumCase, let _ = genericParameterOptional as! GenericClass<Int> { } //compiler error if case .case1 = enumCase, let _ = genericParameterOptional as! GenericClass<Int>? { } //if case .case1 = enumCase, let _ = genericParameterOptional as! GenericClass<Int?> { } //compiler error
65.141304
113
0.757717
50bbd3ff60ff82d3f38e0f0c2e29bc5f031defe6
1,953
// // Solution208.swift // leetcode // // Created by youzhuo wang on 2020/4/15. // Copyright © 2020 youzhuo wang. All rights reserved. // import Foundation // 单词查找树 class Trie { private let root: TrieNode? private var size:Int = 0 /** Initialize your data structure here. */ init() { root = TrieNode() } /** Inserts a word into the trie. */ func insert(_ word: String) { var cursor = root let chars = Array(word) for item in chars { if cursor!.next[item] == nil { cursor!.next[item] = TrieNode() } cursor = cursor!.next[item] } if !cursor!.isWord { cursor!.isWord = true size = size + 1 } } /** Returns if the word is in the trie. */ func search(_ word: String) -> Bool { var cursor = root let chars = Array(word) for item in chars { if cursor!.next[item] == nil { return false } cursor = cursor!.next[item] } return cursor?.isWord ?? false } /** Returns if there is any word in the trie that starts with the given prefix. */ func startsWith(_ prefix: String) -> Bool { var cursor = root let chars = Array(prefix) for item in chars { if cursor!.next[item] == nil { return false } cursor = cursor!.next[item] } return true } func test() { // self.insert("apple") print(self.search("apple")) print(self.search("app")) print(self.startsWith("app")) print(self.insert("app")) print(self.search("app")) } } class TrieNode { var isWord:Bool = false var next:[Character: TrieNode] = [Character: TrieNode]() init(){ //next = [Character: TrieNode]() } }
23.25
86
0.502304
ab4945dcd58dec90eaceb2acbf1f31d7e88c1531
14,563
// // SensorFusion.swift // GAEN Explorer // // Created by Bill on 6/7/20. // Copyright © 2020 NinjaMonkeyCoders. All rights reserved. // import CoreMotion import Foundation func getTimeFormatter() -> DateFormatter { let timeFormatter = DateFormatter() timeFormatter.timeStyle = .long return timeFormatter } enum Activity: String { case off case faceup case facedown case stationary case walking case moving case unknown static func get(_ cmActivity: CMMotionActivity?, _ hMode: HorizontalMode, _ scanningOn: Bool) -> Activity { if !scanningOn { return .off } switch hMode { case .faceup: return .faceup case .facedown: return .facedown default: guard let cmA = cmActivity else { return .unknown } if cmA.stationary { return .stationary } if cmA.running || cmA.cycling || cmA.automotive { return .moving } return .unknown } } } enum SensorReading { case scanning(Bool) case motion(CMMotionActivity) case horizontal(HorizontalMode) } struct AccumulatingAngle { var count: Int = 0 var x: Double = 0.0 var y: Double = 0.0 var lastAngle: Double init(_ count: Int = 0, _ x: Double = 0.0, _ y: Double = 0.0, last: Double = .nan) { self.count = count self.x = x self.y = y self.lastAngle = last } func add(_ radians: Double) -> AccumulatingAngle { AccumulatingAngle(count + 1, x + cos(radians), y + sin(radians), last: radians) } func add(degrees: Double) -> AccumulatingAngle { add(Double.pi * degrees / 180.0) } var average: Double { if count == 0 { return .nan } if x == 0, y == 0 { return .nan } return atan2(y, x) } var degrees: Int { let v = average if v.isNaN { return 0 } return Int(180 * v / Double.pi) } var lastDegrees: Int { let v = lastAngle if v.isNaN { return 0 } return Int(180 * v / Double.pi) } var confidence: Double { sqrt(x * x + y * y) / Double(count) } } struct SensorData { let at: Date var time: String { getTimeFormatter().string(from: at) } let sensor: SensorReading } struct FusedData: Hashable { let at: Date var time: String { getTimeFormatter().string(from: at) } let activity: Activity } struct SignificantActivity: Hashable { init(_ data: FusedData, seconds: Int) { self.at = data.at self.activity = data.activity self.duration = seconds } let at: Date var time: String { getTimeFormatter().string(from: at) } let activity: Activity let duration: Int } extension CMSensorDataList: Sequence { public typealias Iterator = NSFastEnumerationIterator public func makeIterator() -> NSFastEnumerationIterator { NSFastEnumerationIterator(self) } } enum HorizontalMode { static func get(_ a: CMAcceleration) -> HorizontalMode { let az = abs(a.z) guard a.x * a.x + a.y * a.y < 0.1, az < 1.05, az > 0.9 else { return .unknown } if a.z > 0 { return .facedown } return .faceup } case unknown case faceup case facedown case invalid } enum PhoneOrientation { case faceup case facedown case landscapeRight case landscapeLeft case portrait case portraintUpsidedown case unknown } struct HoritzontalState { let at: Date let status: HorizontalMode } struct MotionAnalysis { let activities: [SignificantActivity] let activityDurations: [Activity: Int] let roll: AccumulatingAngle let pitch: AccumulatingAngle let yaw: AccumulatingAngle } class SensorFusion { static let shared = SensorFusion() private let analyzeMotionQueue = DispatchQueue(label: "com.ninjamonkeycoders.gaen.analyzeMotion", attributes: .concurrent) let motionActivityManager = CMMotionActivityManager() let motionManager = CMMotionManager() let pedometer = CMPedometer() var sensorRecorder: CMSensorRecorder? lazy var motionQueue: OperationQueue = { var queue = OperationQueue() queue.name = "Motion queue" queue.maxConcurrentOperationCount = 1 return queue }() func requestMotionPermission(block: @escaping () -> Void) { motionActivityManager.queryActivityStarting(from: Date(timeIntervalSinceNow: -500), to: Date(), to: motionQueue) { activities, _ in guard let activities = activities else { return } print("Got \(activities.count) activities") block() } } var motionPermission: CMAuthorizationStatus { CMMotionActivityManager.authorizationStatus() } func startMotionCapture() { motionManager.deviceMotionUpdateInterval = 1.0 motionManager.startDeviceMotionUpdates(using: .xMagneticNorthZVertical, to: motionQueue) { data, _ in // Make sure the data is valid before accessing it. if let validData = data { // Get the attitude relative to the magnetic north reference frame. self.roll = self.roll.add(validData.attitude.roll) self.pitch = self.pitch.add(validData.attitude.pitch) self.yaw = self.yaw.add(validData.attitude.yaw) } } startAccel() } func stopMotionCapture() { motionManager.stopDeviceMotionUpdates() } func startAccel() { if CMSensorRecorder.isAccelerometerRecordingAvailable() { print("accelerometerRecordingAvailable") sensorRecorder = CMSensorRecorder() print("startAccel") analyzeMotionQueue.async { self.sensorRecorder!.recordAccelerometer(forDuration: 2 * 60 * 60) // Record for 20 minutes print("started record accelerometer") } } else { print("accelerometerRecording not available") } } static let minimumNumberOfSecondsToRecord: TimeInterval = 5 var roll = AccumulatingAngle() var pitch = AccumulatingAngle() var yaw = AccumulatingAngle() private func fuseMotionData(from: Date, to: Date, _ sensorData: [SensorData], _ motions: [CMMotionActivity], _ results: (MotionAnalysis?) -> Void) { var motionData: [SensorData] = motions.map { motion in SensorData(at: motion.startDate, sensor: SensorReading.motion(motion)) } print("Have \(motionData.count) motion readings") motionData.append(contentsOf: sensorData) var accel: CMMotionActivity? var scanning = true var horizontalMode: HorizontalMode = .unknown var fusedData: [FusedData] = [] var activityDurations: [Activity: Int] = [:] motionData.sorted { $0.at < $1.at }.forEach { sensorData in switch sensorData.sensor { case let .scanning(isOn): scanning = isOn case let .motion(cmmActivity): accel = cmmActivity case let .horizontal(hMode): horizontalMode = hMode } let newActivity = Activity.get(accel, horizontalMode, scanning) let fused = FusedData(at: sensorData.at, activity: newActivity) if fusedData.count == 0 { fusedData.append(fused) } else if newActivity != fusedData.last!.activity { if fusedData.last!.at.addingTimeInterval(SensorFusion.minimumNumberOfSecondsToRecord) > sensorData.at { if fusedData.count - 2 >= 0, fusedData[fusedData.count - 2].activity == fused.activity { fusedData.remove(at: fusedData.count - 1) } else { fusedData[fusedData.count - 1] = fused } } else { fusedData.append(fused) } } } print("Got \(fusedData.count) fused data items") let maxDuration = Int(to.timeIntervalSince(from) + 200) var prevData: FusedData? var significantActivities: [SignificantActivity] = [] fusedData.forEach { fd in print("\(fd.time) \(fd.activity)") if let prev = prevData { let oldDuration: Int = activityDurations[prev.activity] ?? 0 let thisDuration = Int(fd.at.timeIntervalSince(prev.at >= from ? prev.at : from)) if thisDuration > 90 { significantActivities.append(SignificantActivity(prev, seconds: thisDuration)) } let newDuration = oldDuration + thisDuration if thisDuration > maxDuration { let msg = "Got duration of \(thisDuration) for \(prev.activity), started \(prev.time), ended \(fd.time))" print(msg) LocalStore.shared.addDiaryEntry(.debugging, msg) } else { activityDurations[prev.activity] = newDuration print("set time doing \(prev.activity) to \(newDuration)") } } prevData = fd } if let prev = prevData { let oldDuration: Int = activityDurations[prev.activity] ?? 0 let thisDuration = Int(to.timeIntervalSince(prev.at >= from ? prev.at : from)) if thisDuration > 90 { significantActivities.append(SignificantActivity(prev, seconds: thisDuration)) } let newDuration = oldDuration + thisDuration if thisDuration > maxDuration { let msg = "Got duration of \(thisDuration) for \(prev.activity), started \(prev.time), ended at experiment end at \(timeFormatter.string(from: to)))" print(msg) LocalStore.shared.addDiaryEntry(.debugging, msg) } else { activityDurations[prev.activity] = newDuration print("set time doing \(prev.activity) to \(newDuration)") } } print("Got \(fusedData.count) fused data items") print("activity durations") for (key, value) in activityDurations { print(" \(key) \(Int(value))") } results(MotionAnalysis(activities: significantActivities, activityDurations: activityDurations, roll: roll, pitch: pitch, yaw: yaw)) } static let secondsNeededToRecognizeHorizontal: TimeInterval = 20 func getSensorData(from: Date, to: Date, results: @escaping (MotionAnalysis?) -> Void) { analyzeMotionQueue.async { if self.sensorRecorder != nil { print("sensor recorded present") } if let sensor = self.sensorRecorder, let data = sensor.accelerometerData(from: from, to: to) { print("Got accel") var horiztonalData: [SensorData] = [] var oldHorizontal: HorizontalMode = .invalid var startedHorizontal: Date? for datum in data { if let accdatum = datum as? CMRecordedAccelerometerData { let horizontal = HorizontalMode.get(accdatum.acceleration) if oldHorizontal != horizontal { if horizontal == .unknown { if let sh = startedHorizontal { if sh.addingTimeInterval(SensorFusion.secondsNeededToRecognizeHorizontal) < accdatum.startDate { horiztonalData.append(SensorData(at: sh, sensor: SensorReading.horizontal(oldHorizontal))) startedHorizontal = nil horiztonalData.append(SensorData(at: accdatum.startDate, sensor: SensorReading.horizontal(horizontal))) } } else if horiztonalData.isEmpty { horiztonalData.append(SensorData(at: accdatum.startDate, sensor: SensorReading.horizontal(horizontal))) } } else { // faceup or facedown startedHorizontal = accdatum.startDate } } oldHorizontal = horizontal } } if let sh = startedHorizontal { if sh.addingTimeInterval(SensorFusion.secondsNeededToRecognizeHorizontal) < Date() { horiztonalData.append(SensorData(at: sh, sensor: SensorReading.horizontal(oldHorizontal))) startedHorizontal = nil } } print("Got \(horiztonalData.count) sensor data in horizontal history") self.motionActivityManager.queryActivityStarting(from: from, to: to, to: self.motionQueue) { activities, _ in guard let a = activities else { results(nil) return } self.fuseMotionData(from: from, to: to, horiztonalData, a, results) } } else { print("No accelerometerData available") self.motionActivityManager.queryActivityStarting(from: from, to: to, to: self.motionQueue) { activities, _ in guard let a = activities else { results(nil) return } let horiztonalData: [SensorData] = [SensorData(at: from, sensor: SensorReading.horizontal(.unknown))] self.fuseMotionData(from: from, to: to, horiztonalData, a, results) } } } } }
35.007212
165
0.551397
5b2b06135c0dfdcd8fbecd14d4a203a5d7408cc0
8,906
// // SwiftDate, an handy tool to manage date and timezones in swift // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // 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 //MARK: - Extension of Int To Manage Operations - public extension NSDateComponents { /** Create a new date from a specific date by adding self components - parameter refDate: reference date - parameter region: optional region to define the timezone and calendar. By default is UTC Region - returns: a new NSDate instance in UTC format */ public func fromDate(refDate :NSDate!, inRegion region: Region = Region()) -> NSDate { let date = region.calendar.dateByAddingComponents(self, toDate: refDate, options: NSCalendarOptions(rawValue: 0)) return date! } /** Create a new date from a specific date by subtracting self components - parameter refDate: reference date - parameter region: optional region to define the timezone and calendar. By default is UTC Region - returns: a new NSDate instance in UTC format */ public func agoFromDate(refDate :NSDate!, inRegion region: Region = Region()) -> NSDate { for unit in DateInRegion.componentFlagSet { let value = self.valueForComponent(unit) if value != NSDateComponentUndefined { self.setValue((value * -1), forComponent: unit) } } return region.calendar.dateByAddingComponents(self, toDate: refDate, options: NSCalendarOptions(rawValue: 0))! } /** Create a new date from current date and add self components. So you can make something like: let date = 4.days.fromNow() - parameter region: optional region to define the timezone and calendar. By default is UTC Region - returns: a new NSDate instance in UTC format */ public func fromNow(inRegion region: Region = Region()) -> NSDate { return fromDate(NSDate(), inRegion: region) } /** Create a new date from current date and substract self components So you can make something like: let date = 5.hours.ago() - parameter region: optional region to define the timezone and calendar. By default is UTC Region - returns: a new NSDate instance in UTC format */ public func ago(inRegion region: Region = Region()) -> NSDate { return agoFromDate(NSDate()) } /// The same of calling fromNow() with default UTC region public var fromNow : NSDate { get { return fromDate(NSDate()) } } /// The same of calling ago() with default UTC region public var ago : NSDate { get { return agoFromDate(NSDate()) } } /// The dateInRegion for the current components public var dateInRegion: DateInRegion? { return DateInRegion(self) } } //MARK: - Combine NSDateComponents - public func | (lhs: NSDateComponents, rhs :NSDateComponents) -> NSDateComponents { let dc = NSDateComponents() for unit in DateInRegion.componentFlagSet { let lhs_value = lhs.valueForComponent(unit) let rhs_value = rhs.valueForComponent(unit) if lhs_value != NSDateComponentUndefined { dc.setValue(lhs_value, forComponent: unit) } if rhs_value != NSDateComponentUndefined { dc.setValue(rhs_value, forComponent: unit) } } return dc } /// Add date components to one another /// public func + (lhs: NSDateComponents, rhs: NSDateComponents) -> NSDateComponents { return sumDateComponents(lhs, rhs: rhs) } /// subtract date components from one another /// public func - (lhs: NSDateComponents, rhs: NSDateComponents) -> NSDateComponents { return sumDateComponents(lhs, rhs: rhs, sum: false) } /// Helper function for date component sum * subtract /// internal func sumDateComponents(lhs :NSDateComponents, rhs :NSDateComponents, sum :Bool = true) -> NSDateComponents { let newComponents = NSDateComponents() let components = DateInRegion.componentFlagSet for unit in components { let leftValue = lhs.valueForComponent(unit) let rightValue = rhs.valueForComponent(unit) guard leftValue != NSDateComponentUndefined || rightValue != NSDateComponentUndefined else { continue // both are undefined, don't touch } let checkedLeftValue = leftValue == NSDateComponentUndefined ? 0 : leftValue let checkedRightValue = rightValue == NSDateComponentUndefined ? 0 : rightValue let finalValue = checkedLeftValue + (sum ? checkedRightValue : -checkedRightValue) newComponents.setValue(finalValue, forComponent: unit) } return newComponents } // MARK: - Helpers to enable expressions e.g. date + 1.days - 20.seconds public extension NSTimeZone { /// Returns a new NSDateComponents object containing the time zone as specified by the receiver /// public var timeZone: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.timeZone = self return dateComponents } } public extension NSCalendar { /// Returns a new NSDateComponents object containing the calendar as specified by the receiver /// public var calendar: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.calendar = self return dateComponents } } public extension Int { /// Returns a new NSDateComponents object containing the number of nanoseconds as specified by the receiver /// public var nanoseconds: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.nanosecond = self return dateComponents } /// Returns a new NSDateComponents object containing the number of seconds as specified by the receiver /// public var seconds: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.second = self return dateComponents } /// Returns a new NSDateComponents object containing the number of minutes as specified by the receiver /// public var minutes: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.minute = self return dateComponents } /// Returns a new NSDateComponents object containing the number of hours as specified by the receiver /// public var hours: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.hour = self return dateComponents } /// Returns a new NSDateComponents object containing the number of days as specified by the receiver /// public var days: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.day = self return dateComponents } /// Returns a new NSDateComponents object containing the number of weeks as specified by the receiver /// public var weeks: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.weekOfYear = self return dateComponents } /// Returns a new NSDateComponents object containing the number of months as specified by the receiver /// public var months: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.month = self return dateComponents } /// Returns a new NSDateComponents object containing the number of years as specified by the receiver /// public var years: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.year = self return dateComponents } }
34.51938
121
0.67898
e27488c84b61142988372f21f07a05630dbf4eb8
2,999
import Foundation class RequestDispatcher: Dispatcher { weak var delegate: TokenDelegate? weak var loggingDelegate: Logging? let session: URLSessionProtocol let requestBuilder: URLRequestBuilding required init(server: Server) { let session = URLSession(configuration: .default) let requestBuilder = URLRequestBuilder(server: server) self.session = session self.requestBuilder = requestBuilder } init( session: URLSessionProtocol, requestBuilder: URLRequestBuilding ) { self.session = session self.requestBuilder = requestBuilder } func execute(request: Request, handler: @escaping (_ response: Response) -> Void) throws { if let headers = request.headers { loggingDelegate?.logRequestHeader(header: headers) } loggingDelegate?.logRequestParameters(body: request.parameters.parameterString) let urlRequest = try requestBuilder.urlRequest(withRequest: request) execute(request: urlRequest, handler: handler) } func execute( batch: [Request], handler: @escaping (_ response: Response) -> Void, completion: (() -> Void)? ) throws { guard let requests = try? batch.map({ (request) -> URLRequest in if let headers = request.headers { loggingDelegate?.logRequestHeader(header: headers) } self.loggingDelegate?.logRequestParameters(body: request.parameters.parameterString) let urlRequest = try self.requestBuilder.urlRequest(withRequest: request) return urlRequest } ) else { return } execute(batch: requests, handler: handler, completion: completion) } func execute(request: URLRequest, handler: @escaping (_ response: Response) -> Void) { let dataTask = session.dataTask(with: request) { (data, urlResponse, error) in if let response = urlResponse { self.loggingDelegate?.logURLResponse(response: response) } if let bodyData = data, let bodyString = String(data: bodyData, encoding: .utf8) { self.loggingDelegate?.logResponsebody(body: bodyString) } return handler( Response( response: (urlResponse as? HTTPURLResponse), data: data, error: error ) ) } dataTask.resume() } func execute( batch: [URLRequest], handler: @escaping (_ response: Response) -> Void, completion: (() -> Void)? ) { let group = DispatchGroup() for request in batch { group.enter() execute(request: request) { (response) in handler(response) group.leave() } } group.notify(queue: DispatchQueue.main) { completion?() } } }
32.247312
100
0.59053
fc5a16e5ede260717cc8947b30583e58ac0f6847
1,004
// // Tips_CalculatorTests.swift // Tips CalculatorTests // // Created by Tam Nguyen on 12/28/15. // Copyright © 2015 Tam Nguyen. All rights reserved. // import XCTest @testable import Tips_Calculator class Tips_CalculatorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
27.135135
111
0.643426
4621464d879b3cf37ae5ef4117db0f84d1eca4f4
2,182
// // AppDelegate.swift // Tip Calculator // // Created by Shaurya Sinha on 05/11/17. // Copyright © 2017 Shaurya Sinha. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.425532
285
0.755729
7a88598d4aed48fde22de4f79e369b6563545425
1,237
// // AnyStorageKey.swift // // // Created by Yehor Popovych on 10.08.2021. // import Foundation import ScaleCodec public protocol AnyStorageKey: ScaleDynamicEncodable { var module: String { get } var field: String { get } var path: [Any?] { get } var hashes: [Data]? { get } // TODO: Refactor dynamic types (DYNAMIC) func decode(valueFrom decoder: ScaleDecoder, registry: TypeRegistryProtocol) throws -> Any static func prefix(from decoder: ScaleDecoder) throws -> Data static func prefix(module: String, field: String) -> Data static var prefixHasher: NormalHasher { get } static var prefixSize: UInt { get } } extension AnyStorageKey { public static func prefix(from decoder: ScaleDecoder) throws -> Data { try decoder.decode(Data.self, .fixed(Self.prefixSize)) } public static func prefix(module: String, field: String) -> Data { Self.prefixHasher.hash(data: Data(module.utf8)) + Self.prefixHasher.hash(data: Data(field.utf8)) } public static var prefixSize: UInt { UInt(2 * Self.prefixHasher.hashPartByteLength) } public static var prefixHasher: NormalHasher { HXX128.hasher as! NormalHasher } }
29.452381
94
0.671787
e2539347c3ed9d33efbbf1e621177a019c393c0a
13,989
// // CourseOutlineViewController.swift // edX // // Created by Akiva Leffert on 4/30/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit public enum CourseOutlineMode { case full case video } public class CourseOutlineViewController : OfflineSupportViewController, CourseBlockViewController, CourseOutlineTableControllerDelegate, CourseContentPageViewControllerDelegate, CourseLastAccessedControllerDelegate, PullRefreshControllerDelegate, LoadStateViewReloadSupport, InterfaceOrientationOverriding { public typealias Environment = OEXAnalyticsProvider & DataManagerProvider & OEXInterfaceProvider & NetworkManagerProvider & ReachabilityProvider & OEXRouterProvider & OEXConfigProvider & OEXStylesProvider private var rootID : CourseBlockID? private var environment : Environment private let courseQuerier : CourseOutlineQuerier fileprivate let tableController : CourseOutlineTableController private let blockIDStream = BackedStream<CourseBlockID?>() private let headersLoader = BackedStream<CourseOutlineQuerier.BlockGroup>() fileprivate let rowsLoader = BackedStream<[CourseOutlineQuerier.BlockGroup]>() private let loadController : LoadStateViewController private let insetsController : ContentInsetsController private var lastAccessedController : CourseLastAccessedController private(set) var courseOutlineMode: CourseOutlineMode /// Strictly a test variable used as a trigger flag. Not to be used out of the test scope fileprivate var t_hasTriggeredSetLastAccessed = false public var blockID : CourseBlockID? { return blockIDStream.value ?? nil } public var courseID : String { return courseQuerier.courseID } public init(environment: Environment, courseID : String, rootID : CourseBlockID?, forMode mode: CourseOutlineMode?) { self.rootID = rootID self.environment = environment courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID: courseID, environment: environment) loadController = LoadStateViewController() insetsController = ContentInsetsController() courseOutlineMode = mode ?? .full tableController = CourseOutlineTableController(environment: environment, courseID: courseID, forMode: courseOutlineMode, courseBlockID: rootID) lastAccessedController = CourseLastAccessedController(blockID: rootID , dataManager: environment.dataManager, networkManager: environment.networkManager, courseQuerier: courseQuerier, forMode: courseOutlineMode) super.init(env: environment, shouldShowOfflineSnackBar: false) lastAccessedController.delegate = self addChild(tableController) tableController.didMove(toParent: self) tableController.delegate = self } public required init?(coder aDecoder: NSCoder) { // required by the compiler because UIViewController implements NSCoding, // but we don't actually want to serialize these things fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) view.backgroundColor = OEXStyles.shared().standardBackgroundColor() view.addSubview(tableController.view) loadController.setupInController(controller: self, contentView:tableController.view) tableController.refreshController.setupInScrollView(scrollView: tableController.tableView) tableController.refreshController.delegate = self insetsController.setupInController(owner: self, scrollView : self.tableController.tableView) view.setNeedsUpdateConstraints() addListeners() } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) lastAccessedController.loadLastAccessed(forMode: courseOutlineMode) lastAccessedController.saveLastAccessed() loadStreams() if courseOutlineMode == .video { // We are doing calculations to show downloading progress on video tab, For this purpose we are observing notifications. tableController.courseVideosHeaderView?.addObservers() } } public override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if courseOutlineMode == .video { // As calculations are made to show progress on view. So when any other view apear we stop observing and making calculations for better performance. tableController.courseVideosHeaderView?.removeObservers() } } override public var shouldAutorotate: Bool { return true } override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .allButUpsideDown } override public func updateViewConstraints() { loadController.insets = UIEdgeInsets(top: self.topLayoutGuide.length, left: 0, bottom: self.bottomLayoutGuide.length, right : 0) tableController.view.snp.remakeConstraints { make in make.edges.equalTo(safeEdges) } super.updateViewConstraints() } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.insetsController.updateInsets() } override func reloadViewData() { reload() } private func setupNavigationItem(block : CourseBlock) { navigationItem.title = (courseOutlineMode == .video && rootID == nil) ? Strings.Dashboard.courseVideos : block.displayName } private func loadStreams() { loadController.state = .Initial let stream = joinStreams(courseQuerier.rootID, courseQuerier.blockWithID(id: blockID)) stream.extendLifetimeUntilFirstResult (success : { [weak self] (rootID, block) in if self?.blockID == rootID || self?.blockID == nil { if self?.courseOutlineMode == .full { self?.environment.analytics.trackScreen(withName: OEXAnalyticsScreenCourseOutline, courseID: self?.courseID, value: nil) } else { self?.environment.analytics.trackScreen(withName: AnalyticsScreenName.CourseVideos.rawValue, courseID: self?.courseID, value: nil) } } else { self?.environment.analytics.trackScreen(withName: OEXAnalyticsScreenSectionOutline, courseID: self?.courseID, value: block.internalName) self?.tableController.hideTableHeaderView() } }, failure: { Logger.logError("ANALYTICS", "Unable to load block: \($0)") } ) reload() } private func reload() { self.blockIDStream.backWithStream(OEXStream(value : self.blockID)) } private func emptyState() -> LoadState { return LoadState.empty(icon: .UnknownError, message : (courseOutlineMode == .video) ? Strings.courseVideoUnavailable : Strings.coursewareUnavailable) } private func showErrorIfNecessary(error : NSError) { if self.loadController.state.isInitial { self.loadController.state = LoadState.failed(error: error) } } private func addListeners() { headersLoader.backWithStream(blockIDStream.transform {[weak self] blockID in if let owner = self { return owner.courseQuerier.childrenOfBlockWithID(blockID: blockID, forMode: owner.courseOutlineMode) } else { return OEXStream<CourseOutlineQuerier.BlockGroup>(error: NSError.oex_courseContentLoadError()) }} ) rowsLoader.backWithStream(headersLoader.transform {[weak self] headers in if let owner = self { let children = headers.children.map {header in return owner.courseQuerier.childrenOfBlockWithID(blockID: header.blockID, forMode: owner.courseOutlineMode) } return joinStreams(children) } else { return OEXStream(error: NSError.oex_courseContentLoadError()) }} ) self.blockIDStream.backWithStream(OEXStream(value: rootID)) headersLoader.listen(self, success: {[weak self] headers in self?.setupNavigationItem(block: headers.block) }, failure: {[weak self] error in self?.showErrorIfNecessary(error: error) } ) rowsLoader.listen(self, success : {[weak self] groups in if let owner = self { owner.tableController.groups = groups owner.tableController.tableView.reloadData() owner.loadController.state = groups.count == 0 ? owner.emptyState() : .Loaded } }, failure : {[weak self] error in self?.showErrorIfNecessary(error: error) }, finally: {[weak self] in if let active = self?.rowsLoader.active, !active { self?.tableController.refreshController.endRefreshing() } } ) } private func canDownload() -> Bool { return environment.dataManager.interface?.canDownload() ?? false } // MARK: Outline Table Delegate func outlineTableControllerChoseShowDownloads(controller: CourseOutlineTableController) { environment.router?.showDownloads(from: self) } func outlineTableController(controller: CourseOutlineTableController, choseDownloadVideos videos: [OEXHelperVideoDownload], rootedAtBlock block:CourseBlock) { if canDownload() { environment.dataManager.interface?.downloadVideos(videos) let courseID = self.courseID let analytics = environment.analytics courseQuerier.parentOfBlockWithID(blockID: block.blockID).listenOnce(self, success: { parentID in analytics.trackSubSectionBulkVideoDownload(parentID, subsection: block.blockID, courseID: courseID, videoCount: videos.count) }, failure: {error in Logger.logError("ANALYTICS", "Unable to find parent of block: \(block). Error: \(error.localizedDescription)") }) } else { showOverlay(withMessage: environment.interface?.networkErrorMessage() ?? Strings.noWifiMessage) } } func outlineTableController(controller: CourseOutlineTableController, choseDownloadVideoForBlock block: CourseBlock) { if canDownload() { environment.dataManager.interface?.downloadVideos(withIDs: [block.blockID], courseID: courseID) environment.analytics.trackSingleVideoDownload(block.blockID, courseID: courseID, unitURL: block.webURL?.absoluteString) } else { showOverlay(withMessage: environment.interface?.networkErrorMessage() ?? Strings.noWifiMessage) } } func outlineTableController(controller: CourseOutlineTableController, choseBlock block: CourseBlock, withParentID parent : CourseBlockID) { self.environment.router?.showContainerForBlockWithID(blockID: block.blockID, type:block.displayType, parentID: parent, courseID: courseQuerier.courseID, fromController:self, forMode: courseOutlineMode) } func outlineTableControllerReload(controller: CourseOutlineTableController) { courseQuerier.needsRefresh = true reload() } //MARK: PullRefreshControllerDelegate public func refreshControllerActivated(controller: PullRefreshController) { courseQuerier.needsRefresh = true reload() } //MARK: CourseContentPageViewControllerDelegate public func courseContentPageViewController(controller: CourseContentPageViewController, enteredBlockWithID blockID: CourseBlockID, parentID: CourseBlockID) { self.blockIDStream.backWithStream(courseQuerier.parentOfBlockWithID(blockID: parentID)) self.tableController.highlightedBlockID = blockID } //MARK: LastAccessedControllerDeleagte public func courseLastAccessedControllerDidFetchLastAccessedItem(item: CourseLastAccessed?) { if let lastAccessedItem = item { self.tableController.showLastAccessedWithItem(item: lastAccessedItem) } else { self.tableController.hideLastAccessed() } } //MARK:- LoadStateViewReloadSupport method func loadStateViewReload() { reload() } } extension CourseOutlineViewController { public func t_setup() -> OEXStream<Void> { return rowsLoader.map { _ in } } public func t_currentChildCount() -> Int { return tableController.groups.count } public func t_populateLastAccessedItem(item : CourseLastAccessed) -> Bool { self.tableController.showLastAccessedWithItem(item: item) return self.tableController.tableView.tableHeaderView != nil } public func t_didTriggerSetLastAccessed() -> Bool { return t_hasTriggeredSetLastAccessed } public func t_tableView() -> UITableView { return self.tableController.tableView } }
40.903509
219
0.65766
091576de415754477adcdf00db8f24bf0e85f130
1,221
// Copyright Keefer Taylor, 2019. import Base58Swift import Foundation /// Helper functions on Base58Swift for TezosCrypto extension Base58 { /// Encode a Base58Check string from the given message and prefix. /// /// The returned address is a Base58 encoded String with the following format: [prefix][key][4 byte checksum] public static func encode(message: [UInt8], prefix: [UInt8]) -> String { let prefixedMessage = prefix + message return Base58.base58CheckEncode(prefixedMessage) } /// Decode a Base58Check string to bytes and verify that the bytes begin with the given prefix. /// /// - Parameters: /// - string: The Base58Check string to decode. /// - prefix: The expected prefix bytes after decoding. /// - Returns: The raw bytes without the given prefix if the string was valid Base58Check and had the expected prefix, /// otherwise, nil. public static func base58CheckDecodeWithPrefix(string: String, prefix: [UInt8]) -> [UInt8]? { guard let bytes = Base58.base58CheckDecode(string), bytes.prefix(Prefix.Keys.secret.count).elementsEqual(prefix) else { return nil } return Array(bytes.suffix(from: Prefix.Keys.secret.count)) } }
39.387097
120
0.708436
e628fc373db1cba3f99b77d768e4dfb344f1dfad
3,925
// Copyright © 2017 Schibsted. All rights reserved. import QuartzCore extension CALayer: LayoutConfigurable { /// Expression names and types @objc class var expressionTypes: [String: RuntimeType] { var types = allPropertyTypes() types["contents"] = .cgImage for key in [ "borderWidth", "contentsScale", "cornerRadius", "shadowRadius", "rasterizationScale", "zPosition", ] { types[key] = .cgFloat } types["contentsGravity"] = .caLayerContentsGravity types["edgeAntialiasingMask"] = .caEdgeAntialiasingMask types["fillMode"] = .caMediaTimingFillMode types["minificationFilter"] = .caLayerContentsFilter types["magnificationFilter"] = .caLayerContentsFilter types["maskedCorners"] = .caCornerMask // Explicitly disabled properties for name in [ "bounds", "frame", ] { types[name] = .unavailable("Use top/left/width/height instead") let name = "\(name)." for key in types.keys where key.hasPrefix(name) { types[key] = .unavailable("Use top/left/width/height instead") } } for name in [ "needsDisplayInRect", ] { types[name] = .unavailable() for key in types.keys where key.hasPrefix(name) { types[key] = .unavailable() } } for name in [ "position", ] { types[name] = .unavailable("Use center.x or center.y instead") for key in types.keys where key.hasPrefix(name) { types[key] = .unavailable("Use center.x or center.y instead") } } #if arch(i386) || arch(x86_64) // Private properties for name in [ "acceleratesDrawing", "allowsContentsRectCornerMasking", "allowsDisplayCompositing", "allowsGroupBlending", "allowsHitTesting", "backgroundColorPhase", "behaviors", "canDrawConcurrently", "clearsContext", "coefficientOfRestitution", "contentsContainsSubtitles", "contentsDither", "contentsMultiplyByColor", "contentsOpaque", "contentsScaling", "contentsSwizzle", "continuousCorners", "cornerContentsCenter", "cornerContentsMasksEdges", "definesDisplayRegionOfInterest", "disableUpdateMask", "doubleBounds", "doublePosition", "flipsHorizontalAxis", "hitTestsAsOpaque", "hitTestsContentsAlphaChannel", "inheritsTiming", "invertsShadow", "isFlipped", "isFrozen", "literalContentsCenter", "mass", "meshTransform", "momentOfInertia", "motionBlurAmount", "needsLayoutOnGeometryChange", "perspectiveDistance", "preloadsCache", "presentationModifiers", "rasterizationPrefersDisplayCompositing", "sizeRequisition", "sortsSublayers", "stateTransitions", "states", "unsafeUnretainedDelegate", "velocityStretch", "wantsExtendedDynamicRangeContent", ] { types[name] = nil for key in types.keys where key.hasPrefix(name) { types[key] = nil } } #endif return types } }
34.429825
78
0.497834
1ee6e63e2ce8585c5b39e514360762340be39af0
15,268
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/main/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. @_exported import AWSSDKSwiftCore /* Client object for interacting with AWS Schemas service. Amazon EventBridge Schema Registry */ public struct Schemas: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the Schemas client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: AWSSDKSwiftCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, service: "schemas", serviceProtocol: .restjson, apiVersion: "2019-12-02", endpoint: endpoint, possibleErrorTypes: [SchemasErrorType.self], timeout: timeout ) } // MARK: API Calls /// Creates a discoverer. public func createDiscoverer(_ input: CreateDiscovererRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CreateDiscovererResponse> { return self.client.execute(operation: "CreateDiscoverer", path: "/v1/discoverers", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Creates a registry. public func createRegistry(_ input: CreateRegistryRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CreateRegistryResponse> { return self.client.execute(operation: "CreateRegistry", path: "/v1/registries/name/{registryName}", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Creates a schema definition. Inactive schemas will be deleted after two years. public func createSchema(_ input: CreateSchemaRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CreateSchemaResponse> { return self.client.execute(operation: "CreateSchema", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Deletes a discoverer. @discardableResult public func deleteDiscoverer(_ input: DeleteDiscovererRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteDiscoverer", path: "/v1/discoverers/id/{discovererId}", httpMethod: .DELETE, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Deletes a Registry. @discardableResult public func deleteRegistry(_ input: DeleteRegistryRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteRegistry", path: "/v1/registries/name/{registryName}", httpMethod: .DELETE, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Delete the resource-based policy attached to the specified registry. @discardableResult public func deleteResourcePolicy(_ input: DeleteResourcePolicyRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteResourcePolicy", path: "/v1/policy", httpMethod: .DELETE, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Delete a schema definition. @discardableResult public func deleteSchema(_ input: DeleteSchemaRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteSchema", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}", httpMethod: .DELETE, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Delete the schema version definition @discardableResult public func deleteSchemaVersion(_ input: DeleteSchemaVersionRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteSchemaVersion", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}/version/{schemaVersion}", httpMethod: .DELETE, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Describe the code binding URI. public func describeCodeBinding(_ input: DescribeCodeBindingRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeCodeBindingResponse> { return self.client.execute(operation: "DescribeCodeBinding", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}/language/{language}", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Describes the discoverer. public func describeDiscoverer(_ input: DescribeDiscovererRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeDiscovererResponse> { return self.client.execute(operation: "DescribeDiscoverer", path: "/v1/discoverers/id/{discovererId}", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Describes the registry. public func describeRegistry(_ input: DescribeRegistryRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeRegistryResponse> { return self.client.execute(operation: "DescribeRegistry", path: "/v1/registries/name/{registryName}", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Retrieve the schema definition. public func describeSchema(_ input: DescribeSchemaRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeSchemaResponse> { return self.client.execute(operation: "DescribeSchema", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Get the code binding source URI. public func getCodeBindingSource(_ input: GetCodeBindingSourceRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetCodeBindingSourceResponse> { return self.client.execute(operation: "GetCodeBindingSource", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}/language/{language}/source", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Get the discovered schema that was generated based on sampled events. public func getDiscoveredSchema(_ input: GetDiscoveredSchemaRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetDiscoveredSchemaResponse> { return self.client.execute(operation: "GetDiscoveredSchema", path: "/v1/discover", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Retrieves the resource-based policy attached to a given registry. public func getResourcePolicy(_ input: GetResourcePolicyRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetResourcePolicyResponse> { return self.client.execute(operation: "GetResourcePolicy", path: "/v1/policy", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// List the discoverers. public func listDiscoverers(_ input: ListDiscoverersRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListDiscoverersResponse> { return self.client.execute(operation: "ListDiscoverers", path: "/v1/discoverers", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// List the registries. public func listRegistries(_ input: ListRegistriesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListRegistriesResponse> { return self.client.execute(operation: "ListRegistries", path: "/v1/registries", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Provides a list of the schema versions and related information. public func listSchemaVersions(_ input: ListSchemaVersionsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListSchemaVersionsResponse> { return self.client.execute(operation: "ListSchemaVersions", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}/versions", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// List the schemas. public func listSchemas(_ input: ListSchemasRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListSchemasResponse> { return self.client.execute(operation: "ListSchemas", path: "/v1/registries/name/{registryName}/schemas", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Get tags for resource. public func listTagsForResource(_ input: ListTagsForResourceRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListTagsForResourceResponse> { return self.client.execute(operation: "ListTagsForResource", path: "/tags/{resource-arn}", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Put code binding URI public func putCodeBinding(_ input: PutCodeBindingRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<PutCodeBindingResponse> { return self.client.execute(operation: "PutCodeBinding", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}/language/{language}", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// The name of the policy. public func putResourcePolicy(_ input: PutResourcePolicyRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<PutResourcePolicyResponse> { return self.client.execute(operation: "PutResourcePolicy", path: "/v1/policy", httpMethod: .PUT, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Search the schemas public func searchSchemas(_ input: SearchSchemasRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<SearchSchemasResponse> { return self.client.execute(operation: "SearchSchemas", path: "/v1/registries/name/{registryName}/schemas/search", httpMethod: .GET, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Starts the discoverer public func startDiscoverer(_ input: StartDiscovererRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<StartDiscovererResponse> { return self.client.execute(operation: "StartDiscoverer", path: "/v1/discoverers/id/{discovererId}/start", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Stops the discoverer public func stopDiscoverer(_ input: StopDiscovererRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<StopDiscovererResponse> { return self.client.execute(operation: "StopDiscoverer", path: "/v1/discoverers/id/{discovererId}/stop", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Add tags to a resource. @discardableResult public func tagResource(_ input: TagResourceRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<Void> { return self.client.execute(operation: "TagResource", path: "/tags/{resource-arn}", httpMethod: .POST, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Removes tags from a resource. @discardableResult public func untagResource(_ input: UntagResourceRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<Void> { return self.client.execute(operation: "UntagResource", path: "/tags/{resource-arn}", httpMethod: .DELETE, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Updates the discoverer public func updateDiscoverer(_ input: UpdateDiscovererRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<UpdateDiscovererResponse> { return self.client.execute(operation: "UpdateDiscoverer", path: "/v1/discoverers/id/{discovererId}", httpMethod: .PUT, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Updates a registry. public func updateRegistry(_ input: UpdateRegistryRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<UpdateRegistryResponse> { return self.client.execute(operation: "UpdateRegistry", path: "/v1/registries/name/{registryName}", httpMethod: .PUT, serviceConfig: config, input: input, on: eventLoop, logger: logger) } /// Updates the schema definition Inactive schemas will be deleted after two years. public func updateSchema(_ input: UpdateSchemaRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<UpdateSchemaResponse> { return self.client.execute(operation: "UpdateSchema", path: "/v1/registries/name/{registryName}/schemas/name/{schemaName}", httpMethod: .PUT, serviceConfig: config, input: input, on: eventLoop, logger: logger) } }
72.018868
252
0.727404
e692122fda8e7b6712cc873e3df4ea39d6b1f7a8
859
// // File.swift // // // Created by Dmitry Lernatovich // import Foundation #if os(iOS) import UIKit // MARK: - Animation functional @objc public extension UIView { /// Method which provide the animate functional. /// - Parameters: /// - time: value /// - action: callback @objc func afAnimate(time: TimeInterval, action: @escaping () -> Void) { AFAnimationHelper.animate(view: self, time: time, action: action, complete: nil) } /// Method which provide the animate functional. /// - Parameters: /// - time: value /// - action: callback /// - complete: callback @objc func afAnimate(time: TimeInterval, action: @escaping () -> Void, complete: (() -> Void)?) { AFAnimationHelper.animate(view: self, time: time, action: action, complete: complete) } } #endif
24.542857
101
0.611176
23c39300c1bfeeab7300d5427ea7b4804fed0d51
1,285
// // Int.swift // csv2 // // Created by Michael Salmon on 2021-05-02. // import Foundation infix operator &== : LogicalDisjunctionPrecedence extension Int { /// Format an Int /// - Parameter width: string width /// - Returns: formatted string func d(_ width: Int = 1) -> String { return String(format: "%*d", width, self) } /// Format an Int with zero fill /// - Parameter width: string width /// - Returns: formatted string func d0(_ width: Int = 1) -> String { return String(format: "%0*d", width, self) } /// Format an Int in hex /// - Parameters width: string width /// - Returns: formatted string func x(_ width: Int = 1) -> String { return String(format: "%*x", width, self) } /// Format an Int in hex with zero fill /// - Parameter width: string width /// - Returns: formatted string func x0(_ width: Int = 1) -> String { return String(format: "%0*x", width, self) } /// Test for inclusion in a bitset /// - Parameters: /// - left: value to test /// - right: mask to test with /// - Returns: true if the mask is included static func &== (left: Int, right: Int) -> Bool { return (left & right) == right } }
23.363636
53
0.566537
f9841a76d029e8da2a40faf433c0e44d636279bd
1,696
// // TogetherTests.swift // TogetherTests // // Created by archerzz on 17/1/16. // Copyright © 2017年 archerzz. All rights reserved. // import XCTest @testable import Together class Person { var firstName: String? var lastName: String? } class Coder: Person { var language: String? } extension Person: TogetherCompatible {} class TogetherTests: XCTestCase { func testTogetherCustomAnyObject() { let person1 = Person() let person2 = Person() let person3 = Person() let coder = Coder() let lastName = "Zhang" person1.together(values: person2, person3, coder).do { $0.lastName = lastName } XCTAssertEqual(person1.lastName, lastName) XCTAssertEqual(person2.lastName, lastName) XCTAssertEqual(person3.lastName, lastName) XCTAssertEqual(coder.lastName, lastName) } func testTogetherSystemAnyObject() { #if os(macOS) typealias View = NSView typealias TextField = NSTextField typealias ImageView = NSImageView #else typealias View = UIView typealias TextField = UITextField typealias ImageView = UIImageView #endif let view1 = View() let view2 = TextField() let view3 = ImageView() let originX: CGFloat = 10 view1.together(values: view2, view3).do { $0.frame.origin.x = originX } XCTAssertEqual(view1.frame.origin.x, originX) XCTAssertEqual(view2.frame.origin.x, originX) XCTAssertEqual(view3.frame.origin.x, originX) } }
24.57971
62
0.597877
ab523a9eab950469c0f9708e4b01ae52ea80fb2e
2,132
// // User.swift responsible for capturing data type on my server // Twitter // // Created by Estella Lai on 10/29/16. // Copyright © 2016 Estella Lai. All rights reserved. // import UIKit class User: NSObject { // stored property var name : NSString? var screenName: NSString? var profileUrl: NSURL? var tagline: NSString? var dictionary: NSDictionary? // deserialization code init(dictionary: NSDictionary) { self.dictionary = dictionary name = dictionary["name"] as? String as NSString? screenName = dictionary["screen_name"] as? String as NSString? tagline = dictionary["description"] as? String as NSString? let profileUrlString = dictionary["profile_image_url_https"] as? String if let profileUrlString = profileUrlString { profileUrl = NSURL(string: profileUrlString) } } static var _currentUser: User? // computed property - not stored associated with the variable class var currentUser: User? { // NSUserDefault persisted key value store, cookies for iOS get { if _currentUser == nil { let defaults = UserDefaults.standard let userData = defaults.object(forKey: "currentUserData") as? Data if let userData = userData { let dictionary = try! JSONSerialization.jsonObject(with: userData, options: []) as! NSDictionary _currentUser = User(dictionary: dictionary) } } return _currentUser } set (user) { _currentUser = user // save the user any time i use user.currentUser = let defaults = UserDefaults.standard if let user = user { let data = try! JSONSerialization.data(withJSONObject: user.dictionary!, options: []) defaults.set(data, forKey: "currentUserData") } else { defaults.removeObject(forKey: "currentUserData") } defaults.synchronize() } } }
32.8
116
0.594278
c179f3026dd78ec4e4eabb5674e4269ba58a54d6
12,589
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import CoreFoundation import _SwiftCoreFoundationOverlayShims /** `Date` represents a single point in time. A `Date` is independent of a particular calendar or time zone. To represent a `Date` to a user, you must interpret it in the context of a `Calendar`. */ public struct Date : ReferenceConvertible, Comparable, Equatable { public typealias ReferenceType = NSDate fileprivate var _time : TimeInterval /// The number of seconds from 1 January 1970 to the reference date, 1 January 2001. public static let timeIntervalBetween1970AndReferenceDate : TimeInterval = 978307200.0 /// The interval between 00:00:00 UTC on 1 January 2001 and the current date and time. public static var timeIntervalSinceReferenceDate : TimeInterval { return CFAbsoluteTimeGetCurrent() } /// Returns a `Date` initialized to the current date and time. public init() { _time = CFAbsoluteTimeGetCurrent() } /// Returns a `Date` initialized relative to the current date and time by a given number of seconds. public init(timeIntervalSinceNow: TimeInterval) { self.init(timeIntervalSinceReferenceDate: timeIntervalSinceNow + CFAbsoluteTimeGetCurrent()) } /// Returns a `Date` initialized relative to 00:00:00 UTC on 1 January 1970 by a given number of seconds. public init(timeIntervalSince1970: TimeInterval) { self.init(timeIntervalSinceReferenceDate: timeIntervalSince1970 - Date.timeIntervalBetween1970AndReferenceDate) } /** Returns a `Date` initialized relative to another given date by a given number of seconds. - Parameter timeInterval: The number of seconds to add to `date`. A negative value means the receiver will be earlier than `date`. - Parameter date: The reference date. */ public init(timeInterval: TimeInterval, since date: Date) { self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate + timeInterval) } /// Returns a `Date` initialized relative to 00:00:00 UTC on 1 January 2001 by a given number of seconds. public init(timeIntervalSinceReferenceDate ti: TimeInterval) { _time = ti } /** Returns the interval between the date object and 00:00:00 UTC on 1 January 2001. This property's value is negative if the date object is earlier than the system's absolute reference date (00:00:00 UTC on 1 January 2001). */ public var timeIntervalSinceReferenceDate: TimeInterval { return _time } /** Returns the interval between the receiver and another given date. - Parameter another: The date with which to compare the receiver. - Returns: The interval between the receiver and the `another` parameter. If the receiver is earlier than `anotherDate`, the return value is negative. If `anotherDate` is `nil`, the results are undefined. - SeeAlso: `timeIntervalSince1970` - SeeAlso: `timeIntervalSinceNow` - SeeAlso: `timeIntervalSinceReferenceDate` */ public func timeIntervalSince(_ date: Date) -> TimeInterval { return self.timeIntervalSinceReferenceDate - date.timeIntervalSinceReferenceDate } /** The time interval between the date and the current date and time. If the date is earlier than the current date and time, this property's value is negative. - SeeAlso: `timeIntervalSince(_:)` - SeeAlso: `timeIntervalSince1970` - SeeAlso: `timeIntervalSinceReferenceDate` */ public var timeIntervalSinceNow: TimeInterval { return self.timeIntervalSinceReferenceDate - CFAbsoluteTimeGetCurrent() } /** The interval between the date object and 00:00:00 UTC on 1 January 1970. This property's value is negative if the date object is earlier than 00:00:00 UTC on 1 January 1970. - SeeAlso: `timeIntervalSince(_:)` - SeeAlso: `timeIntervalSinceNow` - SeeAlso: `timeIntervalSinceReferenceDate` */ public var timeIntervalSince1970: TimeInterval { return self.timeIntervalSinceReferenceDate + Date.timeIntervalBetween1970AndReferenceDate } /// Return a new `Date` by adding a `TimeInterval` to this `Date`. /// /// - parameter timeInterval: The value to add, in seconds. /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. public func addingTimeInterval(_ timeInterval: TimeInterval) -> Date { return self + timeInterval } /// Add a `TimeInterval` to this `Date`. /// /// - parameter timeInterval: The value to add, in seconds. /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. public mutating func addTimeInterval(_ timeInterval: TimeInterval) { self += timeInterval } /** Creates and returns a Date value representing a date in the distant future. The distant future is in terms of centuries. */ public static let distantFuture = Date(timeIntervalSinceReferenceDate: 63113904000.0) /** Creates and returns a Date value representing a date in the distant past. The distant past is in terms of centuries. */ public static let distantPast = Date(timeIntervalSinceReferenceDate: -63114076800.0) public var hashValue: Int { if #available(OSX 10.12, iOS 10.0, *) { return Int(bitPattern: __CFHashDouble(_time)) } else { // 10.11 and previous behavior fallback; this must allocate a date to reference the hash value and then throw away the reference return NSDate(timeIntervalSinceReferenceDate: _time).hash } } /// Compare two `Date` values. public func compare(_ other: Date) -> ComparisonResult { if _time < other.timeIntervalSinceReferenceDate { return .orderedAscending } else if _time > other.timeIntervalSinceReferenceDate { return .orderedDescending } else { return .orderedSame } } /// Returns true if the two `Date` values represent the same point in time. public static func ==(lhs: Date, rhs: Date) -> Bool { return lhs.timeIntervalSinceReferenceDate == rhs.timeIntervalSinceReferenceDate } /// Returns true if the left hand `Date` is earlier in time than the right hand `Date`. public static func <(lhs: Date, rhs: Date) -> Bool { return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate } /// Returns true if the left hand `Date` is later in time than the right hand `Date`. public static func >(lhs: Date, rhs: Date) -> Bool { return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate } /// Returns a `Date` with a specified amount of time added to it. public static func +(lhs: Date, rhs: TimeInterval) -> Date { return Date(timeIntervalSinceReferenceDate: lhs.timeIntervalSinceReferenceDate + rhs) } /// Returns a `Date` with a specified amount of time subtracted from it. public static func -(lhs: Date, rhs: TimeInterval) -> Date { return Date(timeIntervalSinceReferenceDate: lhs.timeIntervalSinceReferenceDate - rhs) } /// Add a `TimeInterval` to a `Date`. /// /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. public static func +=(lhs: inout Date, rhs: TimeInterval) { lhs = lhs + rhs } /// Subtract a `TimeInterval` from a `Date`. /// /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. public static func -=(lhs: inout Date, rhs: TimeInterval) { lhs = lhs - rhs } } extension Date : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable { /** A string representation of the date object (read-only). The representation is useful for debugging only. There are a number of options to acquire a formatted string for a date including: date formatters (see [NSDateFormatter](//apple_ref/occ/cl/NSDateFormatter) and [Data Formatting Guide](//apple_ref/doc/uid/10000029i)), and the `Date` function `description(locale:)`. */ public var description: String { // Defer to NSDate for description return NSDate(timeIntervalSinceReferenceDate: _time).description } /** Returns a string representation of the receiver using the given locale. - Parameter locale: A `Locale`. If you pass `nil`, `Date` formats the date in the same way as the `description` property. - Returns: A string representation of the `Date`, using the given locale, or if the locale argument is `nil`, in the international format `YYYY-MM-DD HH:MM:SS ±HHMM`, where `±HHMM` represents the time zone offset in hours and minutes from UTC (for example, "`2001-03-24 10:45:32 +0600`"). */ public func description(with locale: Locale?) -> String { return NSDate(timeIntervalSinceReferenceDate: _time).description(with: locale) } public var debugDescription: String { return description } public var customMirror: Mirror { let c: [(label: String?, value: Any)] = [ ("timeIntervalSinceReferenceDate", timeIntervalSinceReferenceDate) ] return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } } extension Date : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDate { return NSDate(timeIntervalSinceReferenceDate: _time) } public static func _forceBridgeFromObjectiveC(_ x: NSDate, result: inout Date?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ x: NSDate, result: inout Date?) -> Bool { result = Date(timeIntervalSinceReferenceDate: x.timeIntervalSinceReferenceDate) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDate?) -> Date { var result: Date? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension NSDate : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as Date) } } extension Date : CustomPlaygroundQuickLookable { var summary: String { let df = DateFormatter() df.dateStyle = .medium df.timeStyle = .short return df.string(from: self) } public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(summary) } } extension Date : Codable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let timestamp = try container.decode(Double.self) self.init(timeIntervalSinceReferenceDate: timestamp) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.timeIntervalSinceReferenceDate) } }
41.963333
293
0.689729
1e7fa0a6dca1c21bf98c00dd2c3a223c81e281af
512
// // ViewController.swift // TimeTable // // Created by Maxim Biriukov on 4/21/18. // Copyright © 2018 Maksym Biriukov. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.692308
80
0.671875
643fe50fb06e14270bb0df9b5dc25f4c66badeaa
761
// // AAMediaTests.swift // AwesomeAudio_Tests // // Created by Evandro Harrison on 12/04/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import XCTest @testable import AwesomeAudio class AAMediaTests: XCTestCase { func testUrl() { let media: AAMedia = AAMedia(media: "https://google.com") XCTAssertEqual(media.url, "https://google.com".url()?.offlineURLIfAvailable()) } func testBackgroundUrl() { let media: AAMedia = AAMedia(media: "https://google.com", background: "https://google.com/background") XCTAssertEqual(media.url, "https://google.com".url()?.offlineURLIfAvailable()) XCTAssertEqual(media.backgroundUrl, "https://google.com/background".url()?.offlineURLIfAvailable()) } }
30.44
110
0.684625
506767ee67b3b628e9a543235b5b16b2a86115f5
2,596
// // ViewController.swift // AJ_UIKit // // Created by aboojan on 16/4/10. // Copyright © 2016年 aboojan. All rights reserved. // import UIKit class ViewController: UIViewController, AJCheckboxDelegate{ @IBOutlet weak var checkboxBtn: AJCheckBox!; @IBOutlet weak var testTV: AJTextView! override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.endEdit)); tapGesture.numberOfTapsRequired = 1; tapGesture.numberOfTouchesRequired = 1; self.view.addGestureRecognizer(tapGesture); // CommonButton let testBtn = CommonButton(type: .Custom); testBtn.frame = CGRectMake(20.0, 90.0, 100.0, 40.0); testBtn.backgroundColor = UIColor.orangeColor(); testBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal); testBtn.setTitle("测试", forState: .Normal); testBtn.addTarget(self, action: #selector(ViewController.testBtnClick(_:)), forControlEvents: .TouchUpInside); self.view.addSubview(testBtn); // checkbox // self.checkboxBtn.checkboxImageAlignment = .Right; // self.checkboxBtn.checkedImage = UIImage(named: "ic_check_1"); // self.checkboxBtn.uncheckedImage = UIImage(named: "ic_check_0"); // self.checkboxBtn.isCheck = true; // self.checkboxBtn.canCheck = false; // self.checkboxBtn.title = "checkbox标题"; // self.checkboxBtn.titleFont = UIFont.systemFontOfSize(15.0); self.checkboxBtn.privateDelegate = self; // Label let testLabel = AJLabel(frame: CGRectMake(20.0, 200.0, 100.0, 40.0)); testLabel.backgroundColor = UIColor.lightGrayColor(); testLabel.verticalTextAlignment = .Top; testLabel.textEdgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 0.0); testLabel.text = "测试Label"; self.view.addSubview(testLabel); // TextView testTV.maxLetterCount = 20; testTV.isShowLetterCount = true; // testTV.limitContentLength = true; testTV.placeholder = "请输入内容"; print("是否超出字数:\(testTV.isOverMaxLength)"); } func endEdit() { self.view.endEditing(true); } // MARK: 事件监听 @IBAction func loginBtnClick(sender: AnyObject){ print("登录"); } func testBtnClick(sender: UIButton){ print("测试按钮:\(sender)"); } // MARK: 代理 func checkbox(checkbox: AJCheckBox, isCheck: Bool) { print("忘记密码:\(isCheck)"); } }
32.049383
118
0.62943
acfe82d5f72c247b289b648a97905ddcc0849004
17,333
// RUN: %target-swift-frontend -parse -verify %s // REQUIRES: objc_interop import Foundation public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> Any { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a non-whitelisted type from another module. extension LazyFilterIterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'LazyFilterIterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterIterator { let result: LazyFilterIterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { var hashValue: Int { return 0 } func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?) -> BridgedStruct { var result: BridgedStruct? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { var hashValue: Int { return 0 } } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { var hashValue: Int { return 0 } } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}} return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s // expected-error{{return expression of type 'BridgedStruct' does not conform to 'AnyObject'}} return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}} nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}} nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}} nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}} nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{use 'as!' to force downcast}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{use 'as!' to force downcast}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}} nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}} nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}} nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt] bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // FIXME: Another awful diagnostic. return d == d // expected-error{{binary operator '==' cannot be applied to two 'Dictionary<Int, NotEquatable>' operands}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 var inferDouble2 = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: Use truncatingRemainder instead}} let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error {{binary operator '*' cannot be applied to two 'Double' operands}} expected-note {{expected an argument list of type '(Int, Int)'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T: Hashable>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K: Hashable, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error{{generic parameter 'K' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}} // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} // expected-note@-1{{overloads for '+'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[Any]'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v75 = true + "str" // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'String'}} expected-note {{expected an argument list of type '(String, String)'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} // FIXME: there should be a fixit appending "as String?" to the line; for now // it's sufficient that it doesn't suggest appending "as String" // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{cannot convert value of type 'NSString?' to expected argument type 'String?'}} var s2 = ns ?? "str" as String as String // expected-error {{binary operator '??' cannot be applied to operands of type 'NSString?' and 'String'}} expected-note{{}} let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}} var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{20-20=(}}{{31-31=) as String}} var s5: String = (ns ?? "str") as String // fixed version } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array<_>'}} // FIXME: The following diagnostic is misleading and should not happen: expected-warning@-1{{cast from 'NSMutableArray' to unrelated type 'Array<_>' always fails}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString!' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{11-11= as String}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass!' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}{{13-13= as BridgedStruct}} } struct KnownUnbridged {} class KnownClass {} protocol KnownClassProtocol: class {} func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) { var z: AnyObject z = a as AnyObject z = b as AnyObject z = c as AnyObject z = d as AnyObject z = e as AnyObject z = f as AnyObject z = g as AnyObject z = h as AnyObject z = a // expected-error{{does not conform to 'AnyObject'}} z = b z = c // expected-error{{does not conform to 'AnyObject'}} z = d // expected-error{{does not conform to 'AnyObject'}} z = e z = f z = g z = h // expected-error{{does not conform to 'AnyObject'}} _ = z } func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) { var z: AnyObject z = x as AnyObject z = y as AnyObject _ = z } func bridgeTupleToAnyObject() { let x = (1, "two") let y = x as AnyObject _ = y }
47.881215
305
0.698898
50eb855c4e4fc0005d99bc05cf88a68227066ce8
1,443
// // Albums.swift // // Created by Anderson Carvalho on 12/09/18 // Copyright (c) . All rights reserved. // import Foundation import ObjectMapper public class Albums: Mappable { // MARK: Declaration for string constants to be used to decode and also serialize. private let kAlbumsUriKey: String = "uri" private let kAlbumsOptionsKey: String = "options" private let kAlbumsTotalKey: String = "total" // MARK: Properties public var uri: String? public var options: [String]? public var total: Int? // MARK: ObjectMapper Initalizers /** Map a JSON object to this class using ObjectMapper - parameter map: A mapping from ObjectMapper */ required public init?(map: Map){ } /** Map a JSON object to this class using ObjectMapper - parameter map: A mapping from ObjectMapper */ public func mapping(map: Map) { uri <- map[kAlbumsUriKey] options <- map[kAlbumsOptionsKey] total <- map[kAlbumsTotalKey] } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ public func dictionaryRepresentation() -> [String: Any] { var dictionary: [String: Any] = [:] if let value = uri { dictionary[kAlbumsUriKey] = value } if let value = options { dictionary[kAlbumsOptionsKey] = value } if let value = total { dictionary[kAlbumsTotalKey] = value } return dictionary } }
26.236364
84
0.692308
5b0bab14155207ff5369e6fbc75912241c0681b2
9,183
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * 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 Motion open class Button: UIButton, Pulseable, PulseableLayer, Themeable { /** A CAShapeLayer used to manage elements that would be affected by the clipToBounds property of the backing layer. For example, this allows the dropshadow effect on the backing layer, while clipping the image to a desired shape within the visualLayer. */ public let visualLayer = CAShapeLayer() /// A Pulse reference. internal var pulse: Pulse! /// A reference to the pulse layer. internal var pulseLayer: CALayer? { return pulse.pulseLayer } /// PulseAnimation value. open var pulseAnimation: PulseAnimation { get { return pulse.animation } set(value) { pulse.animation = value } } /// PulseAnimation color. @IBInspectable open var pulseColor: UIColor { get { return pulse.color } set(value) { pulse.color = value } } /// Pulse opacity. @IBInspectable open var pulseOpacity: CGFloat { get { return pulse.opacity } set(value) { pulse.opacity = value } } /// A property that accesses the backing layer's background @IBInspectable open override var backgroundColor: UIColor? { didSet { layer.backgroundColor = backgroundColor?.cgColor } } /// A preset property for updated contentEdgeInsets. open var contentEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset) } } /// Sets the normal and highlighted image for the button. @IBInspectable open var image: UIImage? { didSet { setImage(image, for: .normal) setImage(image, for: .selected) setImage(image, for: .highlighted) setImage(image, for: .disabled) if #available(iOS 9, *) { setImage(image, for: .application) setImage(image, for: .focused) setImage(image, for: .reserved) } } } /// Sets the normal and highlighted title for the button. @IBInspectable open var title: String? { didSet { setTitle(title, for: .normal) setTitle(title, for: .selected) setTitle(title, for: .highlighted) setTitle(title, for: .disabled) if #available(iOS 9, *) { setTitle(title, for: .application) setTitle(title, for: .focused) setTitle(title, for: .reserved) } guard nil != title else { return } guard nil == titleColor else { return } titleColor = MDColor.blue.base } } /// Sets the normal and highlighted titleColor for the button. @IBInspectable open var titleColor: UIColor? { didSet { setTitleColor(titleColor, for: .normal) setTitleColor(titleColor, for: .highlighted) setTitleColor(titleColor, for: .disabled) if nil == selectedTitleColor { setTitleColor(titleColor, for: .selected) } if #available(iOS 9, *) { setTitleColor(titleColor, for: .application) setTitleColor(titleColor, for: .focused) setTitleColor(titleColor, for: .reserved) } } } /// Sets the selected titleColor for the button. @IBInspectable open var selectedTitleColor: UIColor? { didSet { setTitleColor(selectedTitleColor, for: .selected) } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) /// Set these here to avoid overriding storyboard values tintColor = MDColor.blue.base titleLabel?.font = Theme.font.regular(with: fontSize) prepare() } /** A convenience initializer that acceps an image and tint - Parameter image: A UIImage. - Parameter tintColor: A UIColor. */ public init(image: UIImage?, tintColor: UIColor? = nil) { super.init(frame: .zero) prepare() prepare(with: image, tintColor: tintColor) } /** A convenience initializer that acceps a title and title - Parameter title: A String. - Parameter titleColor: A UIColor. */ public init(title: String?, titleColor: UIColor? = nil) { super.init(frame: .zero) prepare() prepare(with: title, titleColor: titleColor) } open override func layoutSubviews() { super.layoutSubviews() layoutShape() layoutVisualLayer() layoutShadowPath() } /** Triggers the pulse animation. - Parameter point: A Optional point to pulse from, otherwise pulses from the center. */ open func pulse(point: CGPoint? = nil) { pulse.expand(point: point ?? center) Motion.delay(0.35) { [weak self] in self?.pulse.contract() } } /** A delegation method that is executed when the view has began a touch event. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) pulse.expand(point: layer.convert(touches.first!.location(in: self), from: layer)) } /** A delegation method that is executed when the view touch event has ended. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) pulse.contract() } /** A delegation method that is executed when the view touch event has been cancelled. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) pulse.contract() } open func bringImageViewToFront() { guard let v = imageView else { return } bringSubviewToFront(v) } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { contentScaleFactor = Screen.scale prepareVisualLayer() preparePulse() applyCurrentTheme() } /** Applies the given theme. - Parameter theme: A Theme. */ open func apply(theme: Theme) { } } extension Button { /// Prepares the visualLayer property. fileprivate func prepareVisualLayer() { visualLayer.zPosition = 0 visualLayer.masksToBounds = true layer.addSublayer(visualLayer) } /// Prepares the pulse motion. fileprivate func preparePulse() { pulse = Pulse(pulseView: self, pulseLayer: visualLayer) } /** Prepares the Button with an image and tint - Parameter image: A UIImage. - Parameter tintColor: A UI */ fileprivate func prepare(with image: UIImage?, tintColor: UIColor?) { self.image = image self.tintColor = tintColor ?? self.tintColor } /** Prepares the Button with a title and title - Parameter title: A String. - Parameter titleColor: A UI */ fileprivate func prepare(with title: String?, titleColor: UIColor?) { self.title = title self.titleColor = titleColor ?? self.titleColor } } extension Button { /// Manages the layout for the visualLayer property. fileprivate func layoutVisualLayer() { visualLayer.frame = bounds visualLayer.cornerRadius = layer.cornerRadius } }
27.659639
86
0.671567
61481cf305ca90cb79666981497f3a95a773ed30
1,352
// // Reachability.swift // TableViewAsyncImages // // Created by Dhanuka, Tejas | ECMPD on 2020/07/30. // Copyright © 2020 Dhanuka, Tejas | ECMPD. All rights reserved. // import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } // Working for Cellular and WIFI let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 let ret = (isReachable && !needsConnection) return ret } }
34.666667
143
0.676775
87e58aab2353d9a86828c59719b71291831898a0
4,361
// // ReactorListView.swift // Rocket.Chat // // Created by Matheus Cardoso on 2/5/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation // MARK: Reactor Cell protocol ReactorPresenter { var reactor: String { get set } } typealias ReactorCell = UITableViewCell & ReactorPresenter class DefaultReactorCell: UITableViewCell, ReactorPresenter { var reactor: String = "" { didSet { textLabel?.text = reactor } } convenience init() { self.init(style: .default, reuseIdentifier: nil) } override func awakeFromNib() { textLabel?.font = UIFont.systemFont(ofSize: 11.0) } } // MARK: Reactor List struct ReactorListViewModel: RCEmojiKitLocalizable { let reactionViewModels: [ReactionViewModel] static var emptyState: ReactorListViewModel { return ReactorListViewModel(reactionViewModels: []) } } class ReactorListView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var reactorTableView: UITableView! { didSet { reactorTableView.bounces = false reactorTableView.tableFooterView = UIView() reactorTableView.dataSource = self reactorTableView.delegate = self } } var closePressed: () -> Void = { } var selectedReactor: (String) -> Void = { _ in } var configureCell: (ReactorCell) -> Void = { _ in } var model: ReactorListViewModel = .emptyState { didSet { map(model) } } func map(_ model: ReactorListViewModel) { } func registerReactorNib(_ nib: UINib) { reactorTableView.register(nib, forCellReuseIdentifier: "ReactorCell") } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } @IBAction func closePressed(_ sender: UIBarButtonItem) { closePressed() } } // MARK: Initialization extension ReactorListView { private func commonInit() { Bundle.main.loadNibNamed("ReactorListView", owner: self, options: nil) addSubview(contentView) contentView.frame = bounds contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] } } // MARK: UITableViewDataSource extension ReactorListView: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let dequeuedCell = tableView.dequeueReusableCell(withIdentifier: "ReactorCell") var cell = dequeuedCell as? ReactorCell ?? DefaultReactorCell() configureCell(cell) cell.reactor = model.reactionViewModels[indexPath.section].reactors[indexPath.row] return cell } func numberOfSections(in tableView: UITableView) -> Int { return model.reactionViewModels.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return model.reactionViewModels[section].reactors.count } } // MARK: UITableViewDelegate extension ReactorListView: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40)) view.backgroundColor = UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1) let stackView = UIStackView(frame: CGRect(x: 16, y: 8, width: tableView.frame.size.width - 16, height: 24)) stackView.spacing = 8 let reactionView = ReactionView() reactionView.model = model.reactionViewModels[section] let label = UILabel() label.textAlignment = .left label.text = reactionView.model.emoji stackView.addArrangedSubview(reactionView) stackView.addArrangedSubview(label) view.addSubview(stackView) return view } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) selectedReactor(model.reactionViewModels[indexPath.section].reactors[indexPath.row]) } }
27.25625
115
0.670947
f7d0f797271d87ad47cb68a2ec3a03332917ecaf
218
// // UIView+Binding.swift // // Created by Volodymyr Chernyshov on 06.04.2020. // Copyright © 2020 Garage Development. All rights reserved. // import UIKit import MultiPlatformLibrary public extension UIView { }
16.769231
61
0.738532
d7da2b6779b21d49d5875b4b5ecfe6d51af7e418
20,456
// // LDConfig.swift // LaunchDarkly // // Copyright © 2017 Catamorphic Co. All rights reserved. // import Foundation /// Defines the connection modes available to set into LDClient. public enum LDStreamingMode { /// In streaming mode, the LDClient opens a long-running connection to LaunchDarkly's streaming server (called *clientstream*). When a flag value changes on the server, the clientstream notifies the SDK to update the value. Streaming mode is not available on watchOS. On iOS and tvOS, the client app must be running in the foreground to connect to clientstream. On macOS the client app may run in either foreground or background to connect to clientstream. If streaming mode is not available, the SDK reverts to polling mode. case streaming /// In polling mode, the LDClient requests feature flags from LaunchDarkly's app server at regular intervals defined in the LDConfig. When a flag value changes on the server, the LDClient will learn of the change the next time the SDK requests feature flags. case polling } typealias MobileKey = String /** Use LDConfig to configure the LDClient. When initialized, a LDConfig contains the default values which can be changed as needed. The client app can change the LDConfig by getting the `config` from `LDClient`, adjusting the values, and setting it back into the `LDClient`. */ public struct LDConfig { /// The default values set when a LDConfig is initialized struct Defaults { /// The default url for making feature flag requests static let baseUrl = URL(string: "https://app.launchdarkly.com")! /// The default url for making event reports static let eventsUrl = URL(string: "https://mobile.launchdarkly.com")! /// The default url for connecting to the *clientstream* static let streamUrl = URL(string: "https://clientstream.launchdarkly.com")! /// The default maximum number of events the LDClient can store static let eventCapacity = 100 /// The default timeout interval for flag requests and event reports. (10 seconds) static let connectionTimeout: TimeInterval = 10.0 /// The default time interval between event reports. (30 seconds) static let eventFlushInterval: TimeInterval = 30.0 /// The default time interval between feature flag requests. Used only for polling mode. (5 minutes) static let flagPollingInterval: TimeInterval = 300.0 /// The default interval between feature flag requests while running in the background. Used only for polling mode. (60 minutes) static let backgroundFlagPollingInterval: TimeInterval = 3600.0 /// The default streaming mode (.streaming) static let streamingMode = LDStreamingMode.streaming /// The default mode for enabling background flag requests. (false) static let enableBackgroundUpdates = false /// The default mode to set LDClient online on a start call. (true) static let startOnline = true /// The default setting for private user attributes. (false) static let allUserAttributesPrivate = false /// The default private user attribute list (nil) static let privateUserAttributes: [String]? = nil /// The default HTTP request method for `clientstream` connection and feature flag requests. When true, these requests will use the non-standard verb `REPORT`. When false, these requests will use the standard verb `GET`. (false) static let useReport = false /// The default setting controlling the amount of user data sent in events. When true the SDK will generate events using the full LDUser, excluding private attributes. When false the SDK will generate events using only the LDUser.key. (false) static let inlineUserInEvents = false /// The default setting controlling information logged to the console, and modifying some setting ranges to facilitate debugging. (false) static let debugMode = false /// The default setting for whether we request evaluation reasons for all flags. (false) static let evaluationReasons = false /// The default setting for the maximum number of locally cached users. (5) static let maxCachedUsers = 5 /// The default setting for whether sending diagnostic data is disabled. (false) static let diagnosticOptOut = false /// The default time interval between sending periodic diagnostic data. (15 minutes) static let diagnosticRecordingInterval: TimeInterval = 900.0 /// The default wrapper name. (nil) static let wrapperName: String? = nil /// The default wrapper version. (nil) static let wrapperVersion: String? = nil /// The default secondary mobile keys. ([:]) static let secondaryMobileKeys: [String: String] = [:] } public struct Constants { /// The dafault environment name that must be present in a single or multiple environment configuration public static let primaryEnvironmentName = "default" } /// The minimum values allowed to be set into LDConfig. public struct Minima { //swiftlint:disable:next nesting struct Production { static let flagPollingInterval: TimeInterval = 300.0 static let backgroundFlagPollingInterval: TimeInterval = 900.0 static let diagnosticRecordingInterval: TimeInterval = 300.0 } //swiftlint:disable:next nesting struct Debug { static let flagPollingInterval: TimeInterval = 30.0 static let backgroundFlagPollingInterval: TimeInterval = 60.0 static let diagnosticRecordingInterval: TimeInterval = 60.0 } /// The minimum time interval between feature flag requests. Used only for polling mode. (5 minutes) public let flagPollingInterval: TimeInterval /// The minimum time interval between feature flag requests while running in the background. Used only for polling mode. (15 minutes) public let backgroundFlagPollingInterval: TimeInterval /// The minimum time interval between sending periodic diagnostic data. (5 minutes) public let diagnosticRecordingInterval: TimeInterval init(environmentReporter: EnvironmentReporting = EnvironmentReporter()) { let isDebug = environmentReporter.isDebugBuild self.flagPollingInterval = isDebug ? Debug.flagPollingInterval : Production.flagPollingInterval self.backgroundFlagPollingInterval = isDebug ? Debug.backgroundFlagPollingInterval : Production.backgroundFlagPollingInterval self.diagnosticRecordingInterval = isDebug ? Debug.diagnosticRecordingInterval : Production.diagnosticRecordingInterval } } /// The Mobile key from your [LaunchDarkly Account](app.launchdarkly.com) settings (on the left at the bottom). If you have multiple projects be sure to choose the correct Mobile key. public var mobileKey: String /// The url for making feature flag requests. Do not change unless instructed by LaunchDarkly. public var baseUrl: URL = Defaults.baseUrl /// The url for making event reports. Do not change unless instructed by LaunchDarkly. public var eventsUrl: URL = Defaults.eventsUrl /// The url for connecting to the *clientstream*. Do not change unless instructed by LaunchDarkly. public var streamUrl: URL = Defaults.streamUrl /// The maximum number of analytics events the LDClient can store. When the LDClient event store reaches the eventCapacity, the SDK discards events until it successfully reports them to LaunchDarkly. (Default: 100) public var eventCapacity: Int = Defaults.eventCapacity // MARK: Time configuration /// The timeout interval for flag requests and event reports. (Default: 10 seconds) public var connectionTimeout: TimeInterval = Defaults.connectionTimeout /// The time interval between event reports (Default: 30 seconds) public var eventFlushInterval: TimeInterval = Defaults.eventFlushInterval /// The time interval between feature flag requests. Used only for polling mode. (Default: 5 minutes) public var flagPollingInterval: TimeInterval = Defaults.flagPollingInterval /// The time interval between feature flag requests while running in the background. Used only for polling mode. (Default: 60 minutes) public var backgroundFlagPollingInterval: TimeInterval = Defaults.backgroundFlagPollingInterval /// Controls the method the SDK uses to keep feature flags updated. When set to .streaming, connects to `clientstream` which notifies the SDK of feature flag changes. When set to .polling, an efficient polling mechanism is used to periodically request feature flag values. Ignored for watchOS, which always uses .polling. See `LDStreamingMode` for more details. (Default: .streaming) public var streamingMode: LDStreamingMode = Defaults.streamingMode /// Indicates whether streaming mode is allowed for the operating system private(set) var allowStreamingMode: Bool private var enableBgUpdates: Bool = Defaults.enableBackgroundUpdates /// Enables feature flag updates when your app is in the background. Allowed on macOS only. (Default: false) public var enableBackgroundUpdates: Bool { set { enableBgUpdates = newValue && allowBackgroundUpdates } get { enableBgUpdates } } private var allowBackgroundUpdates: Bool /// Controls LDClient start behavior. When true, calling start causes LDClient to go online. When false, calling start causes LDClient to remain offline. If offline at start, set the client online to receive flag updates. (Default: true) public var startOnline: Bool = Defaults.startOnline //Private Attributes /** Treat all user attributes as private for event reporting for all users. The SDK will not include private attribute values in analytics events, but private attribute names will be sent. When true, ignores values in either LDConfig.privateUserAttributes or LDUser.privateAttributes. (Default: false) See Also: `privateUserAttributes` and `LDUser.privateAttributes` */ public var allUserAttributesPrivate: Bool = Defaults.allUserAttributesPrivate /** User attributes and top level custom dictionary keys to treat as private for event reporting for all users. The SDK will not include private attribute values in analytics events, but private attribute names will be sent. See `LDUser.privatizableAttributes` for the attribute names that can be declared private. To set private user attributes for a specific user, see `LDUser.privateAttributes`. (Default: nil) See Also: `allUserAttributesPrivate`, `LDUser.privatizableAttributes`, and `LDUser.privateAttributes`. */ public var privateUserAttributes: [String]? = Defaults.privateUserAttributes /** Directs the SDK to use REPORT for HTTP requests to connect to `clientstream` and make feature flag requests. When false the SDK uses GET for these requests. Do not use unless advised by LaunchDarkly. (Default: false) */ public var useReport: Bool = Defaults.useReport private static let flagRetryStatusCodes = [HTTPURLResponse.StatusCodes.methodNotAllowed, HTTPURLResponse.StatusCodes.badRequest, HTTPURLResponse.StatusCodes.notImplemented] /** Controls how the SDK reports the user in analytics event reports. When set to true, event reports will contain the user attributes, except attributes marked as private. When set to false, event reports will contain the user's key only, reducing the size of event reports. (Default: false) */ public var inlineUserInEvents: Bool = Defaults.inlineUserInEvents /// Enables logging for debugging. (Default: false) public var isDebugMode: Bool = Defaults.debugMode /// Enables requesting evaluation reasons for all flags. (Default: false) public var evaluationReasons: Bool = Defaults.evaluationReasons /// An Integer that tells UserEnvironmentFlagCache the maximum number of users to locally cache. Can be set to -1 for unlimited cached users. public var maxCachedUsers: Int = Defaults.maxCachedUsers /** Set to true to opt out of sending diagnostic data. (Default: false) Unless the diagnosticOptOut field is set to true, the client will send some diagnostics data to the LaunchDarkly servers in order to assist in the development of future SDK improvements. These diagnostics consist of an initial payload containing some details of the SDK in use, the SDK's configuration, and the platform the SDK is being run on; as well as payloads sent periodically with information on irregular occurrences such as dropped events. */ public var diagnosticOptOut: Bool = Defaults.diagnosticOptOut private var _diagnosticRecordingInterval: TimeInterval = Defaults.diagnosticRecordingInterval /// The interval between sending periodic diagnostic data. (Default: 15 minutes) public var diagnosticRecordingInterval: TimeInterval { get { _diagnosticRecordingInterval } set { _diagnosticRecordingInterval = max(minima.diagnosticRecordingInterval, newValue) } } /// For use by wrapper libraries to set an identifying name for the wrapper being used. This will be sent in the "X-LaunchDarkly-Wrapper" header on requests to the LaunchDarkly servers to allow recording metrics on the usage of wrapper libraries. (Default: nil) public var wrapperName: String? = Defaults.wrapperName /// For use by wrapper libraries to report the version of the library in use. If the `wrapperName` has not been set this field will be ignored. Otherwise the version string will be included with the `wrapperName` in the "X-LaunchDarkly-Wrapper" header on requests to the LaunchDarkly servers. (Default: nil) public var wrapperVersion: String? = Defaults.wrapperVersion /// LaunchDarkly defined minima for selected configurable items public let minima: Minima /// An NSObject wrapper for the Swift LDConfig struct. Intended for use in mixed apps when Swift code needs to pass a config into an Objective-C method. public var objcLdConfig: ObjcLDConfig { ObjcLDConfig(self) } let environmentReporter: EnvironmentReporting /// A Dictionary of identifying names to unique mobile keys for all environments private var mobileKeys: [String: String] { var internalMobileKeys = getSecondaryMobileKeys() internalMobileKeys[LDConfig.Constants.primaryEnvironmentName] = mobileKey return internalMobileKeys } /** Sets a Dictionary of identifying names to unique mobile keys to access secondary environments in the LDConfig. Throws `LDInvalidArgumentError` if you try to add duplicate keys or put the primary key or name in secondaryMobileKeys. - parameter newSecondaryMobileKeys: A Dictionary of String to String. */ public mutating func setSecondaryMobileKeys(_ newSecondaryMobileKeys: [String: String]) throws { let mobileKeyPresentInSecondaryMobileKeys = newSecondaryMobileKeys.values.contains(mobileKey) let primaryEnvironmentNamePresentInSecondaryMobileKeys = newSecondaryMobileKeys.keys.contains(LDConfig.Constants.primaryEnvironmentName) let mobileKeysUsedOnlyOnce = Set(newSecondaryMobileKeys.values) if mobileKeyPresentInSecondaryMobileKeys { throw(LDInvalidArgumentError("The primary environment key cannot be in the secondary mobile keys.")) } if primaryEnvironmentNamePresentInSecondaryMobileKeys { throw(LDInvalidArgumentError("The primary environment name is not a valid key.")) } if mobileKeysUsedOnlyOnce.count != newSecondaryMobileKeys.count { throw(LDInvalidArgumentError("A key can only be used once.")) } _secondaryMobileKeys = newSecondaryMobileKeys } /** Returns a Dictionary of identifying names to unique mobile keys to access secondary environments. - returns: A Dictionary of String to String. */ public func getSecondaryMobileKeys() -> [String: String] { return _secondaryMobileKeys } /// Internal variable for secondaryMobileKeys computed property private var _secondaryMobileKeys: [String: String] //Internal constructor to enable automated testing init(mobileKey: String, environmentReporter: EnvironmentReporting) { self.mobileKey = mobileKey self.environmentReporter = environmentReporter minima = Minima(environmentReporter: environmentReporter) allowStreamingMode = environmentReporter.operatingSystem.isStreamingEnabled allowBackgroundUpdates = environmentReporter.operatingSystem.isBackgroundEnabled _secondaryMobileKeys = Defaults.secondaryMobileKeys if mobileKey.isEmpty { Log.debug(typeName(and: #function, appending: ": ") + "mobileKey is empty. The SDK will not operate correctly without a valid mobile key.") } } ///LDConfig constructor. Configurable values are all set to their default values. The client app can modify these values as desired. Note that client app developers may prefer to get the LDConfig from `LDClient.config` in order to retain previously set values. public init(mobileKey: String) { self.init(mobileKey: mobileKey, environmentReporter: EnvironmentReporter()) } //Determine the effective flag polling interval based on runMode, configured foreground & background polling interval, and minimum foreground & background polling interval. func flagPollingInterval(runMode: LDClientRunMode) -> TimeInterval { let pollingInterval = runMode == .foreground ? max(flagPollingInterval, minima.flagPollingInterval) : max(backgroundFlagPollingInterval, minima.backgroundFlagPollingInterval) Log.debug(typeName(and: #function, appending: ": ") + "\(pollingInterval)") return pollingInterval } //Determines if the status code is a code that should cause the SDK to retry a failed HTTP Request that used the REPORT method. Retried requests will use the GET method. static func isReportRetryStatusCode(_ statusCode: Int) -> Bool { let isRetryStatusCode = LDConfig.flagRetryStatusCodes.contains(statusCode) Log.debug(LDConfig.typeName(and: #function, appending: ": ") + "\(isRetryStatusCode)") return isRetryStatusCode } } extension LDConfig: Equatable { ///Compares the settable properties in 2 LDConfig structs public static func == (lhs: LDConfig, rhs: LDConfig) -> Bool { return lhs.mobileKey == rhs.mobileKey && lhs.baseUrl == rhs.baseUrl && lhs.eventsUrl == rhs.eventsUrl && lhs.streamUrl == rhs.streamUrl && lhs.eventCapacity == rhs.eventCapacity //added && lhs.connectionTimeout == rhs.connectionTimeout && lhs.eventFlushInterval == rhs.eventFlushInterval && lhs.flagPollingInterval == rhs.flagPollingInterval && lhs.backgroundFlagPollingInterval == rhs.backgroundFlagPollingInterval && lhs.streamingMode == rhs.streamingMode && lhs.enableBackgroundUpdates == rhs.enableBackgroundUpdates && lhs.startOnline == rhs.startOnline && lhs.allUserAttributesPrivate == rhs.allUserAttributesPrivate && (lhs.privateUserAttributes == nil && rhs.privateUserAttributes == nil || (lhs.privateUserAttributes != nil && rhs.privateUserAttributes != nil && lhs.privateUserAttributes! == rhs.privateUserAttributes!)) && lhs.useReport == rhs.useReport && lhs.inlineUserInEvents == rhs.inlineUserInEvents && lhs.isDebugMode == rhs.isDebugMode && lhs.evaluationReasons == rhs.evaluationReasons && lhs.maxCachedUsers == rhs.maxCachedUsers && lhs.diagnosticOptOut == rhs.diagnosticOptOut && lhs.diagnosticRecordingInterval == rhs.diagnosticRecordingInterval && lhs.wrapperName == rhs.wrapperName && lhs.wrapperVersion == rhs.wrapperVersion } } extension LDConfig: TypeIdentifying { } #if DEBUG extension LDConfig { static let reportRetryStatusCodes = LDConfig.flagRetryStatusCodes } #endif
57.622535
529
0.73069
01aceded89eb80b5687bc51c9e7fbde1dc2c90f7
3,872
// Copyright SIX DAY LLC. All rights reserved. import Foundation import RealmSwift struct CoinTicker: Codable, Hashable { private enum CodingKeys: String, CodingKey { case price_usd = "current_price" case percent_change_24h = "price_change_percentage_24h" case id = "id" case symbol = "symbol" case image = "image" case market_cap case market_cap_rank case total_volume case high_24h case low_24h case market_cap_change_24h case market_cap_change_percentage_24h case circulating_supply case total_supply case max_supply case ath case ath_change_percentage } let id: String private let symbol: String private let image: String = "" let price_usd: Double let percent_change_24h: Double let market_cap: Double? let market_cap_rank: Double? let total_volume: Double? let high_24h: Double? let low_24h: Double? let market_cap_change_24h: Double? let market_cap_change_percentage_24h: Double? let circulating_supply: Double? let total_supply: Double? let max_supply: Double? let ath: Double? let ath_change_percentage: Double? lazy var rate: CurrencyRate = { CurrencyRate( currency: symbol, rates: [ Rate(code: symbol, price: price_usd), ] ) }() init(from decoder: Decoder) throws { enum AnyError: Error { case invalid } let container = try decoder.container(keyedBy: CodingKeys.self) self.price_usd = container.decode(Double.self, forKey: .price_usd, defaultValue: 0.0) self.percent_change_24h = container.decode(Double.self, forKey: .percent_change_24h, defaultValue: 0.0) self.market_cap = container.decode(Double.self, forKey: .market_cap, defaultValue: 0.0) self.market_cap_rank = container.decode(Double.self, forKey: .market_cap_rank, defaultValue: 0.0) self.total_volume = container.decode(Double.self, forKey: .total_volume, defaultValue: 0.0) self.high_24h = container.decode(Double.self, forKey: .high_24h, defaultValue: 0.0) self.low_24h = container.decode(Double.self, forKey: .low_24h, defaultValue: 0.0) self.market_cap_change_24h = container.decode(Double.self, forKey: .market_cap_change_24h, defaultValue: 0.0) self.market_cap_change_percentage_24h = container.decode(Double.self, forKey: .market_cap_change_percentage_24h, defaultValue: 0.0) self.circulating_supply = container.decode(Double.self, forKey: .circulating_supply, defaultValue: 0.0) self.total_supply = container.decode(Double.self, forKey: .total_supply, defaultValue: 0.0) self.max_supply = container.decode(Double.self, forKey: .max_supply, defaultValue: 0.0) self.ath = container.decode(Double.self, forKey: .ath, defaultValue: 0.0) self.ath_change_percentage = container.decode(Double.self, forKey: .ath_change_percentage, defaultValue: 0.0) if let value = try? container.decode(String.self, forKey: .id) { self.id = value } else { throw AnyError.invalid } if let value = try? container.decode(String.self, forKey: .symbol) { self.symbol = value } else { throw AnyError.invalid } } } extension CoinTicker { var imageURL: URL? { return URL(string: image) } } extension KeyedDecodingContainer where Key: Hashable { func decode<T>(_ type: T.Type, forKey key: Key, defaultValue: T) -> T where T: Decodable { if let typedValueOptional = try? decodeIfPresent(T.self, forKey: key), let typedValue = typedValueOptional { return typedValue } else { return defaultValue } } }
36.186916
139
0.66219
5652676df504a18ee43c5e2f36580e7935621a82
235
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let start = i [ { class A { extension g { func a { { class case ,
19.583333
87
0.723404
f51ab960ca08934ab8faeeeec713a6ad3b4bc2bf
9,084
// // SwipePageController.swift // projectDemo // // Created by Hai Vo L. on 12/19/18. // Copyright © 2018 Hai Vo L. All rights reserved. // import UIKit final class SwipePageCell: BaseCollectionCell<Page> { // top view private let topContainerView: UIView = { let v = UIView() v.backgroundColor = .white return v }() private let bearImageView: UIImageView = { let iv = UIImageView(image: #imageLiteral(resourceName: "bear")) iv.translatesAutoresizingMaskIntoConstraints = false iv.contentMode = .scaleAspectFit return iv }() // midle view private let textView: UITextView = { let tv = UITextView() let mutableAttributedString = NSMutableAttributedString(string: "More ways to shop", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]) mutableAttributedString.append(NSAttributedString(string: "\n\nAre you ready for loads and loads of fun? Don't wait any longer! We hope to see you in out stores soon.", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13),NSAttributedString.Key.foregroundColor: UIColor.gray])) tv.attributedText = mutableAttributedString tv.textAlignment = .center tv.isEditable = true tv.isScrollEnabled = true return tv }() override var item: Page! { didSet { bearImageView.image = item.imageName let mutableAttributedString = NSMutableAttributedString(string: item.headerText, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]) mutableAttributedString.append(NSAttributedString(string: "\n\n\(item.bodyText)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13),NSAttributedString.Key.foregroundColor: UIColor.gray])) textView.attributedText = mutableAttributedString textView.textAlignment = .center } } override func layoutSubviews() { super.layoutSubviews() setupViews() } } extension SwipePageCell { private func setupViews() { // add top view addSubview(topContainerView) topContainerView.anchor(top: safeAreaLayoutGuide.topAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor, size: CGSize(width: 0, height: frame.width / 2)) topContainerView.addSubview(bearImageView) bearImageView.centerXAnchor.constraint(equalTo: topContainerView.centerXAnchor).isActive = true bearImageView.centerYAnchor.constraint(equalTo: topContainerView.centerYAnchor).isActive = true bearImageView.heightAnchor.constraint(equalTo: topContainerView.heightAnchor, multiplier: 0.5).isActive = true // add midle view addSubview(textView) textView.anchor(top: topContainerView.bottomAnchor, leading: safeAreaLayoutGuide.leadingAnchor, bottom: safeAreaLayoutGuide.bottomAnchor, trailing: trailingAnchor) } } final class SwipePageController: BaseCollecitonView<SwipePageCell, Page>, UICollectionViewDelegateFlowLayout { // previousButton private let previousButton: UIButton = { let b = UIButton(type: .system) b.setTitle("PREVIOUS", for: .normal) b.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) b.setTitleColor(.gray, for: .normal) b.addTarget(self, action: #selector(handlePrev), for: .touchUpInside) return b }() @objc private func handlePrev() { let prevIndex = max(pageControl.currentPage - 1, 0) pageControl.currentPage = prevIndex let indexPath = IndexPath(item: prevIndex, section: 0) collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) } // nextButton private let nextButton: UIButton = { let b = UIButton(type: .system) b.setTitle("NEXT", for: .normal) b.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) let pinkColor = UIColor(red: 232/255, green: 68/255, blue: 133/255, alpha: 1) b.setTitleColor(pinkColor, for: .normal) b.addTarget(self, action: #selector(handleNext), for: .touchUpInside) return b }() @objc private func handleNext() { let nextIndex = min(pageControl.currentPage + 1, items.count - 1) pageControl.currentPage = nextIndex let indexPath = IndexPath(item: nextIndex, section: 0) collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) } // pageControl lazy private var pageControl: UIPageControl = { let pc = UIPageControl() pc.currentPage = 0 pc.numberOfPages = items.count let pinkColor = UIColor(red: 232/255, green: 68/255, blue: 133/255, alpha: 1) pc.currentPageIndicatorTintColor = pinkColor pc.pageIndicatorTintColor = .gray return pc }() private lazy var stackView: UIStackView = { let sv = UIStackView(arrangedSubviews: [previousButton, pageControl, nextButton]) sv.distribution = .fillEqually return sv }() override func viewDidLoad() { super.viewDidLoad() title = "Swipe Pages" collectionView.backgroundColor = .white items = [Page(imageName: #imageLiteral(resourceName: "bear"), headerText: "About the Teachers on Real English Conversations", bodyText: "Now, we live in Mexico. Even after moving to this country, I realized that living here and breathing in the Mexican air was not helping my Spanish skills."), Page(imageName: #imageLiteral(resourceName: "heart_second"), headerText: "Understand more of what you hear", bodyText: "After taking vacations in several countries in Central and South America, we decided to follow our dreams and move to another country."), Page(imageName: #imageLiteral(resourceName: "leaf_third"), headerText: "Practice speaking to use the new words you learned", bodyText: "Each lesson and activity in our courses follow one simple concept… To teach you the most important skills that make the biggest difference with your speaking and listening abilities."), Page(imageName: #imageLiteral(resourceName: "bear"), headerText: "About the Teachers on Real English Conversations", bodyText: "Now, we live in Mexico. Even after moving to this country, I realized that living here and breathing in the Mexican air was not helping my Spanish skills."), Page(imageName: #imageLiteral(resourceName: "heart_second"), headerText: "Understand more of what you hear", bodyText: "After taking vacations in several countries in Central and South America, we decided to follow our dreams and move to another country."), Page(imageName: #imageLiteral(resourceName: "leaf_third"), headerText: "Practice speaking to use the new words you learned", bodyText: "Each lesson and activity in our courses follow one simple concept… To teach you the most important skills that make the biggest difference with your speaking and listening abilities.")] setupViews() } override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let item = targetContentOffset.pointee.x / view.frame.width pageControl.currentPage = Int(item) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: view.frame.height) } // Support AutoLayout Landscape override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { [weak self] (_) in guard let this = self else { return } this.collectionViewLayout.invalidateLayout() if this.pageControl.currentPage == 0 { this.collectionView.contentInset = .zero } else { let indexPath = IndexPath(item: this.pageControl.currentPage, section: 0) this.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) } }) { (_) in } } } extension SwipePageController { private func setupViews() { if let layout = collectionViewLayout as? UICollectionViewFlowLayout { layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal } collectionView.isPagingEnabled = true setupBottomControler() } private func setupBottomControler() { view.addSubview(stackView) stackView.anchor(top: nil, leading: view.safeAreaLayoutGuide.leadingAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, trailing: view.safeAreaLayoutGuide.trailingAnchor, size: CGSize(width: 0, height: 50)) } }
47.810526
338
0.690665
50c031e033b7c8bcbdc1993d6bd962b5ec158b47
109
extension RawRepresentable { init?(_ rawValue: RawValue) { self.init(rawValue: rawValue) } }
18.166667
37
0.642202
14fbc326176fffef72902662c10259a24547fe68
465
/*  * users.swift  * officectl  *  * Created by François Lamboley on 20/08/2018.  */ import Foundation import ArgumentParser struct UserCommand : ParsableCommand { static var configuration = CommandConfiguration( commandName: "users", abstract: "Interact with the users", subcommands: [ UserCreateCommand.self, UserListCommand.self, UserChangePasswordCommand.self ] ) @OptionGroup() var globalOptions: OfficectlRootCommand.Options }
15.5
49
0.735484
7125313147c51853c9a81cacb8bc7ae1bb84c27e
22,497
import Flutter import UIKit import AVFoundation import MediaPlayer struct AudioMetas : Equatable { var title: String? var artist: String? var album: String? var image: String? var imageType: String? init(title: String?, artist: String?, album: String?, image: String?, imageType: String?) { self.title = title self.artist = artist self.album = album self.image = image self.imageType = imageType } static func ==(lhs: AudioMetas, rhs: AudioMetas) -> Bool { return lhs.title == rhs.title && lhs.artist == rhs.artist && lhs.album == rhs.album && lhs.image == rhs.image && lhs.imageType == rhs.imageType } } public class Player : NSObject, AVAudioPlayerDelegate { let channel: FlutterMethodChannel let registrar: FlutterPluginRegistrar var player: AVPlayer? var observerStatus: NSKeyValueObservation? var displayMediaPlayerNotification = false var audioMetas : AudioMetas? init(channel: FlutterMethodChannel, registrar: FlutterPluginRegistrar) { self.channel = channel self.registrar = registrar } func log(_ message: String){ channel.invokeMethod("log", arguments: message) } func getUrlByType(path: String, audioType: String) -> URL? { var url : URL if(audioType == "network"){ let urlStr : String = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! if let u = URL(string: urlStr) { return u } else { print("Couldn't parse myURL = \(urlStr)") return nil } } else if(audioType == "file"){ let urlStr : String = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! if let u = URL(string: urlStr) { return u } else { print("Couldn't parse myURL = \(urlStr)") return nil } } else { //asset let assetKey = self.registrar.lookupKey(forAsset: path) guard let path = Bundle.main.path(forResource: assetKey, ofType: nil) else { return nil } url = URL(fileURLWithPath: path) return url } } func getAudioCategory(respectSilentMode: Bool) -> AVAudioSession.Category { if(respectSilentMode) { return AVAudioSession.Category.soloAmbient } else { return AVAudioSession.Category.playback } } var targets: [String:Any] = [:] func setupMediaPlayerNotificationView(currentSongDuration: Any) { UIApplication.shared.beginReceivingRemoteControlEvents() let commandCenter = MPRemoteCommandCenter.shared() //commandCenter.playCommand.isEnabled = self.playing self.setupNotificationView(currentSongDuration: currentSongDuration) self.deinitMediaPlayerNotifEvent() // Add handler for Play Command self.targets["play"] = commandCenter.playCommand.addTarget { [unowned self] event in self.play(); return .success } // Add handler for Pause Command self.targets["pause"] = commandCenter.pauseCommand.addTarget { [unowned self] event in self.pause(); return .success } // Add handler for Pause Command self.targets["prev"] = commandCenter.previousTrackCommand.addTarget { [unowned self] event in self.channel.invokeMethod(Music.METHOD_PREV, arguments: []) return .success } // Add handler for Pause Command self.targets["next"] = commandCenter.nextTrackCommand.addTarget { [unowned self] event in self.channel.invokeMethod(Music.METHOD_NEXT, arguments: []) return .success } } func deinitMediaPlayerNotifEvent() { let commandCenter = MPRemoteCommandCenter.shared() if let t = self.targets["play"] { commandCenter.playCommand.removeTarget(t ); } if let t = self.targets["pause"] { commandCenter.pauseCommand.removeTarget(t); } if let t = self.targets["prev"] { commandCenter.previousTrackCommand.removeTarget(t); } if let t = self.targets["next"] { commandCenter.nextTrackCommand.removeTarget(t); } self.targets.removeAll() } var nowPlayingInfo = [String: Any]() func setupNotificationView(currentSongDuration: Any) { if(!self.displayMediaPlayerNotification){ return } let audioMetas : AudioMetas? = self.audioMetas if let t = audioMetas?.title { nowPlayingInfo[MPMediaItemPropertyTitle] = t } else { nowPlayingInfo[MPMediaItemPropertyTitle] = "" } if let art = audioMetas?.artist { nowPlayingInfo[MPMediaItemPropertyArtist] = art } else { nowPlayingInfo[MPMediaItemPropertyArtist] = "" } if let alb = audioMetas?.album { nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = alb } else { nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = "" } nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = currentSongDuration nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = _currentTime nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = 0 MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo //load image async if let imageMetasType = self.audioMetas?.imageType { if let imageMetas = self.audioMetas?.image { if #available(iOS 10.0, *) { if(imageMetasType == "asset") { DispatchQueue.global().async { let imageKey = self.registrar.lookupKey(forAsset: imageMetas) if(!imageKey.isEmpty){ if let imagePath = Bundle.main.path(forResource: imageKey, ofType: nil) { if(!imagePath.isEmpty){ let image: UIImage = UIImage(contentsOfFile: imagePath)! DispatchQueue.main.async { if(self.audioMetas == audioMetas){ //always the sam song ? self.nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (size) -> UIImage in return image }) MPNowPlayingInfoCenter.default().nowPlayingInfo = self.nowPlayingInfo } } } } } } } else { //network or else (file, but not on ios...) DispatchQueue.global().async { if let url = URL(string: imageMetas) { if let data = try? Data.init(contentsOf: url), let image = UIImage(data: data) { let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (_ size : CGSize) -> UIImage in return image }) DispatchQueue.main.async { if(self.audioMetas == audioMetas){ //always the sam song ? self.nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork MPNowPlayingInfoCenter.default().nowPlayingInfo = self.nowPlayingInfo } } } } } } } else { // Fallback on earlier versions } } } } class SlowMoPlayerItem: AVPlayerItem { override var canPlaySlowForward: Bool { return true } override var canPlayReverse: Bool { return true } override var canPlayFastForward: Bool { return true } override var canPlayFastReverse: Bool { return true } override var canPlaySlowReverse: Bool { return true } } func open(assetPath: String, audioType: String, autoStart: Bool, volume: Double, seek: Int?, respectSilentMode: Bool, audioMetas: AudioMetas, displayNotification: Bool, playSpeed: Double, result: FlutterResult ){ self.stop(); guard let url = self.getUrlByType(path: assetPath, audioType: audioType) else { log("resource not found \(assetPath)") result(""); return } do { // log("url: "+url.absoluteString) /* set session category and mode with options */ if #available(iOS 10.0, *) { try AVAudioSession.sharedInstance().setCategory(getAudioCategory(respectSilentMode: respectSilentMode), mode: AVAudioSession.Mode.default, options: [.mixWithOthers]) try AVAudioSession.sharedInstance().setActive(true) } else { try AVAudioSession.sharedInstance().setCategory(getAudioCategory(respectSilentMode: respectSilentMode), options: .mixWithOthers) try AVAudioSession.sharedInstance().setActive(true) } let item = SlowMoPlayerItem(url: url) self.player = AVPlayer(playerItem: item) self.displayMediaPlayerNotification = displayNotification self.audioMetas = audioMetas NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) observerStatus = item.observe(\.status, changeHandler: { [weak self] (item, value) in switch item.status { case .unknown: debugPrint("status: unknown") case .readyToPlay: debugPrint("status: ready to play") let audioDurationSeconds = CMTimeGetSeconds(item.duration) //CMTimeGetSeconds(asset.duration) self?.channel.invokeMethod(Music.METHOD_CURRENT, arguments: ["totalDuration": audioDurationSeconds]) self?.setupMediaPlayerNotificationView(currentSongDuration: audioDurationSeconds) if(autoStart == true){ self?.play() } self?.setVolume(volume: volume) self?.setPlaySpeed(playSpeed: playSpeed) if(seek != nil){ self?.seek(to: seek!) } case .failed: debugPrint("playback failed") @unknown default: fatalError() } }) if(self.player == nil){ //log("player is null"); return } self.currentTime = 0 self.playing = false result(true); } catch let error { result(error); log(error.localizedDescription) print(error.localizedDescription) } } func seek(to: Int){ let targetTime = CMTimeMakeWithSeconds(Double(to), preferredTimescale: 1) self.player?.seek(to: targetTime, toleranceBefore: .zero, toleranceAfter: .zero) } func setVolume(volume: Double){ self.player?.volume = Float(volume) self.channel.invokeMethod(Music.METHOD_VOLUME, arguments: volume) } var _rate : Float = 1.0 var rate : Float { get { return _rate } set(newValue) { if(_rate != newValue){ _rate = newValue self.channel.invokeMethod(Music.METHOD_PLAY_SPEED, arguments: _rate) } } }; func setPlaySpeed(playSpeed: Double){ self.rate = Float(playSpeed) self.player?.rate = self.rate } func forwardRewind(speed: Double){ //on ios we can have nevative speed self.player?.rate = Float(speed) //it does not changes self.rate here self.channel.invokeMethod(Music.METHOD_FORWARD_REWIND, arguments: speed) } func stop(){ self.player?.pause() self.player?.seek(to: CMTime.zero) self.player?.rate = 0.0 self.player = nil self.playing = false self.currentTimeTimer?.invalidate() self.deinitMediaPlayerNotifEvent() NotificationCenter.default.removeObserver(self) self.observerStatus?.invalidate() self.nowPlayingInfo.removeAll() } func play(){ self.player?.play() self.player?.rate = self.rate self.currentTimeTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) self.currentTimeTimer?.fire() self.playing = true } var _currentTime : TimeInterval = 0 private var currentTime : TimeInterval { get { return _currentTime } set(newValue) { if(_currentTime != newValue){ _currentTime = newValue self.channel.invokeMethod(Music.METHOD_POSITION, arguments: self._currentTime) if(self.displayMediaPlayerNotification){ self.nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = _currentTime self.nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = self.player!.rate MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } } } }; var _playing : Bool = false var playing : Bool { get { return _playing } set(newValue) { _playing = newValue self.channel.invokeMethod(Music.METHOD_IS_PLAYING, arguments: self._playing) } }; var currentTimeTimer: Timer? @objc public func playerDidFinishPlaying(note: NSNotification){ self.channel.invokeMethod(Music.METHOD_FINISHED, arguments: true) } deinit { observerStatus?.invalidate() self.deinitMediaPlayerNotifEvent() NotificationCenter.default.removeObserver(self) } func pause(){ self.player?.pause() if(self.displayMediaPlayerNotification){ self.nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = 0 MPNowPlayingInfoCenter.default().nowPlayingInfo = self.nowPlayingInfo } self.playing = false self.currentTimeTimer?.invalidate() } @objc func updateTimer(){ //log("updateTimer"); if let p = self.player { if let currentItem = p.currentItem { self.currentTime = CMTimeGetSeconds(currentItem.currentTime()) } } } } class Music : NSObject, FlutterPlugin { static let METHOD_POSITION = "player.position" static let METHOD_FINISHED = "player.finished" static let METHOD_IS_PLAYING = "player.isPlaying" static let METHOD_FORWARD_REWIND = "player.forwardRewind" static let METHOD_CURRENT = "player.current" static let METHOD_VOLUME = "player.volume" static let METHOD_PLAY_SPEED = "player.playSpeed" static let METHOD_NEXT = "player.next" static let METHOD_PREV = "player.prev" var players = Dictionary<String, Player>() func getOrCreatePlayer(id: String) -> Player { if let player = players[id] { return player } else { let newPlayer = Player( channel: FlutterMethodChannel(name: "assets_audio_player/"+id, binaryMessenger: registrar.messenger()), registrar: self.registrar ) players[id] = newPlayer return newPlayer } } static func register(with registrar: FlutterPluginRegistrar) { } //public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [AnyHashable : Any] = [:]) -> Bool { // application.beginReceivingRemoteControlEvents() // return true; //} let channel: FlutterMethodChannel let registrar: FlutterPluginRegistrar init(messenger: FlutterBinaryMessenger, registrar: FlutterPluginRegistrar) { self.channel = FlutterMethodChannel(name: "assets_audio_player", binaryMessenger: messenger); self.registrar = registrar } func start(){ self.registrar.addApplicationDelegate(self) channel.setMethodCallHandler({(call: FlutterMethodCall, result: FlutterResult) -> Void in //self.log(call.method + call.arguments.debugDescription) switch(call.method){ case "isPlaying" : let args = call.arguments as! NSDictionary let id = args["id"] as! String result(self.getOrCreatePlayer(id: id).playing); break; case "play" : let args = call.arguments as! NSDictionary let id = args["id"] as! String self.getOrCreatePlayer(id: id) .play(); result(true); break; case "pause" : let args = call.arguments as! NSDictionary let id = args["id"] as! String self.getOrCreatePlayer(id: id) .pause(); result(true); break; case "stop" : let args = call.arguments as! NSDictionary let id = args["id"] as! String self.getOrCreatePlayer(id: id) .stop(); result(true); break; case "seek" : let args = call.arguments as! NSDictionary let id = args["id"] as! String let pos = args["to"] as! Int; self.getOrCreatePlayer(id: id) .seek(to: pos); result(true); break; case "volume" : let args = call.arguments as! NSDictionary let id = args["id"] as! String let volume = args["volume"] as! Double; self.getOrCreatePlayer(id: id) .setVolume(volume: volume); result(true); break; case "playSpeed" : let args = call.arguments as! NSDictionary let id = args["id"] as! String let playSpeed = args["playSpeed"] as! Double; self.getOrCreatePlayer(id: id) .setPlaySpeed(playSpeed: playSpeed); result(true); break; case "forwardRewind" : let args = call.arguments as! NSDictionary let id = args["id"] as! String let speed = args["speed"] as! Double; self.getOrCreatePlayer(id: id) .forwardRewind(speed: speed); result(true); break; case "open" : let args = call.arguments as! NSDictionary let id = args["id"] as! String let assetPath = args["path"] as! String let audioType = args["audioType"] as! String let volume = args["volume"] as! Double let seek = args["seek"] as? Int let playSpeed = args["playSpeed"] as! Double let autoStart = args["autoStart"] as! Bool //metas let songTitle = args["song.title"] as? String let songArtist = args["song.artist"] as? String let songAlbum = args["song.album"] as? String let songImage = args["song.image"] as? String let songImageType = args["song.imageType"] as? String //end-metas let respectSilentMode = args["respectSilentMode"] as? Bool ?? false let displayNotification = args["displayNotification"] as? Bool ?? false let audioMetas = AudioMetas(title: songTitle, artist: songArtist, album: songAlbum, image: songImage, imageType: songImageType) self.getOrCreatePlayer(id: id) .open( assetPath: assetPath, audioType: audioType, autoStart: autoStart, volume:volume, seek: seek, respectSilentMode: respectSilentMode, audioMetas: audioMetas, displayNotification: displayNotification, playSpeed: playSpeed, result: result ); break; default: result(FlutterMethodNotImplemented); break; } }) } }
36.461912
183
0.526604
721eb4a300860954ea021cc2d3b430db0fae6ed0
4,491
// // XMCTD01YL+Defines.swift // OrzBLE // // Created by joker on 2019/1/1. // import CoreBluetooth import RxBluetoothKit public extension XMCTD01YL { enum Names: String { case Bedside = "XMCTD_" } enum Services: String, ServiceIdentifier{ case deviceInformation = "180A" case mcu = "8E2F0CBD-1A66-4B53-ACE6-B494E25F87BD" public var uuid: CBUUID { return CBUUID(string: self.rawValue) } } enum Characteristc: String, CharacteristicIdentifier { case manufactureName = "2A29" case modelNumber = "2A24" case control = "AA7D3F34-2D4F-41E0-807F-52FBF8CF7443" case status = "8F65073D-9F57-4AAA-AFEA-397D19D5BBEB" public var uuid: CBUUID { return CBUUID(string: self.rawValue) } public var service: ServiceIdentifier { switch self { case .manufactureName: fallthrough case .modelNumber: return Services.deviceInformation case .control: fallthrough case .status: return Services.mcu } } } enum Commands { case status case powerOn,powerOff case authAccess case bright(UInt8) case color((R: UInt8,G: UInt8,B: UInt8, brightness: UInt8)) case daylight case transition case movieNight case ambilight case disconnect case another var data: Data { var cmdData = Data(count:18) switch self { case .status: cmdData[0] = 0x43 cmdData[1] = 0x44 case .powerOn: cmdData[0] = 0x43 cmdData[1] = 0x40 cmdData[2] = 0x01 case .powerOff: cmdData[0] = 0x43 cmdData[1] = 0x40 cmdData[2] = 0x02 case .authAccess: cmdData[0] = 0x43 cmdData[1] = 0x67 cmdData[2] = 0x68 cmdData[3] = 0x3E cmdData[4] = 0x34 cmdData[5] = 0x08 cmdData[6] = 0xB2 cmdData[7] = 0xCD case .bright(let brightness): cmdData[0] = 0x43 cmdData[1] = 0x42 cmdData[2] = brightness case .color(let color): cmdData[0] = 0x43 cmdData[1] = 0x41 cmdData[2] = color.R cmdData[3] = color.G cmdData[4] = color.B cmdData[6] = color.brightness case .daylight: cmdData[0] = 0x43 cmdData[1] = 0x4A cmdData[2] = 0x01 cmdData[3] = 0x01 cmdData[4] = 0x01 case .transition: cmdData[0] = 0x43 cmdData[1] = 0x7F cmdData[2] = 0x03 case .another: cmdData[0] = 0x43 cmdData[1] = 0x43 cmdData[2] = 0x0C cmdData[3] = 0x80 cmdData[4] = 0x50 case .movieNight: cmdData[0] = 0x43 cmdData[1] = 0x41 cmdData[2] = 0x14 cmdData[3] = 0x14 cmdData[4] = 0x32 cmdData[6] = 0x32 // >=74 白光会亮 case .ambilight: cmdData[0] = 0x43 cmdData[1] = 0x4A cmdData[2] = 0x02 cmdData[3] = 0x01 cmdData[4] = 0x01 case .disconnect: cmdData[0] = 0x43 cmdData[1] = 0x52 } return cmdData } } enum MessageTip: String { case disconnected = "device disconnected!" case authTip = "Need auth! You should press the mode change Button of Yeelight Bedside light to allow you phone control it!" case authSuccess = "Auth successfully!" case authFailed = "Auth timeout Failed!" case connecting = "Connecting ..." case connected = "device connected!" } enum LightMode: UInt8, Identifiable, CaseIterable { case unknown = 0 case color = 1 case day = 2 case ambient = 3 public var id: UInt8 { self.rawValue } } }
29.352941
132
0.470274
de4558959867d0f5873973ef568fe891c7a7992a
6,426
// // Enums.swift // Baker Street // // Created by Ian Hocking on 20/06/2020. // Copyright © 2020 Ian Hocking. MIT Licence. // import Foundation /// A logical operator associativity type, e.g. left associative. public enum OperatorAssociativity { case leftAssociative case rightAssociative } /// The syntactic turnstile public enum MetaType: CustomStringConvertible { case turnStile case justificationSeparator /// Returns the string public var description: String { switch self { case .turnStile: return "|-" case .justificationSeparator: return ":" } } /// Returns the HTML string public var htmlEntity: String { switch self { case .turnStile: return " &#8870; " case .justificationSeparator: return ":" } } /// Returns the Latex string public var latexEntity: String { switch self { case .turnStile: return " \\vdash " case .justificationSeparator: return ":" } } /// Returns the glyph public var glyph: String { switch self { case .turnStile: return "⊦" case .justificationSeparator: return ":" } } } /// A logical operator type (e.g. `and`) /// /// Currently, we have `and`, `or`, `not`, `if` and `iff` (bi-directional if) public enum OperatorType: CustomStringConvertible, CaseIterable { case lAnd case lOr case lNot case lIff case lIf /// Returns the string of the operator type. public var description: String { switch self { case .lAnd: return "AND" case .lOr: return "OR" case .lNot: return "~" case .lIff: return "<->" case .lIf: return "->" } } /// Returns the glyph of the operator type. public var glyph: String { switch self { case .lAnd: return "∧" case .lOr: return "∨" case .lNot: return "¬" case .lIff: return "↔" case .lIf: return "→" } } /// Returns the HTML string of the operator type. public var htmlEntity: String { switch self { case .lAnd: return "&and;" case .lOr: return "&or;" case .lNot: return "&not;" case .lIff: return "&harr;" case .lIf: return "&rarr;" } } /// Returns the Latex string of the operator type. public var latexEntity: String { switch self { case .lAnd: return "\\land" case .lOr: return "\\lor" case .lNot: return "\\lnot" case .lIff: return "\\Leftrightarrow" case .lIf: return "\\Rightarrow" } } } /** The main Token type (e.g. `operator`). We have four types of token: - `bracket` - `operator` - `operand` - `poorly formed` - `empty` ## Poorly Formed Poorly formed is used *only* during evaluation, not string tokenising. For example, when evaluation fails (e.g. `AND `is given only one argument) we drop a `poorly formed` token into the returned array of Tokens. A formula with any one of these means the whole formula must be poorly formed. ## Empty This is useful when we want to initialise a Token type without filling it with something meaningful. */ public enum TokenType: CustomStringConvertible, Hashable { public static func == (lhs: TokenType, rhs: TokenType) -> Bool { lhs.description == rhs.description } case openBracket case closeBracket case Operator(OperatorToken) case operand(String) case poorlyFormed case empty /// Returns the string of the operator type. public var description: String { switch self { case .openBracket: return "(" case .closeBracket: return ")" case .Operator(let operatorToken): return operatorToken.description case .operand(let value): return "\(value)" case .poorlyFormed: return "PF" case .empty: return "" } } } public enum CompletionMode: String { case justification case logic case all public var completions: [String] { switch self { case .justification: let completion = [": " + Justification.assumption.description + " ", ": " + Justification.andIntroduction.description + " ", ": " + Justification.orIntroduction.description + " ", ": " + Justification.notIntroduction.description + " ", ": " + Justification.ifIntroduction.description + " ", ": " + Justification.iffIntroduction.description + " ", ": " + Justification.andElimination.description + " ", ": " + Justification.orElimination.description + " ", ": " + Justification.notElimination.description + " ", ": " + Justification.ifElimination.description + " ", ": " + Justification.iffElimination.description + " ", ": " + Justification.trueIntroduction.description + " ", ": " + Justification.falseElimination.description + " "] return completion case .logic: let completion = [OperatorType.lAnd.description + " ", OperatorType.lOr.description + " ", OperatorType.lNot.description + " ", OperatorType.lIf.description + " ", OperatorType.lIff.description + " ", MetaType.turnStile.description + " "] return completion case .all: var completion = CompletionMode.justification.completions let logi = CompletionMode.logic.completions completion.append(contentsOf: logi) return completion } } }
27
77
0.523965
cc270f6f6040dd93ca65cc1899502b57443c711a
681
// // MyClassSubclass.swift // Example // // Created by Valeriy Bezuglyy on 01/09/2019. // Copyright © 2019 Valeriy Bezuglyy. All rights reserved. // import Foundation //sourcery: mirageMock class MyProtocolledSubclass: MyProtocolledClass { override var value2: Int { get{ return 5 } } var value3: Int init(value3: Int) { self.value3 = value3 super.init(value1: 0) } deinit { value3 = 0 } func changeValueBetter() { value1 += value2 + value3 } override func resetValue() { value3 = value2 * value1 super.resetValue() } }
17.025
59
0.555066
e8700b8c5fc8ae8aa497d5a7758b5e4c893970ea
6,329
//===----------------------------------------------------------------------===// // // This source file is part of the Hummingbird server framework project // // Copyright (c) 2021-2021 the Hummingbird authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Hummingbird import HummingbirdJobs import HummingbirdRedis import NIOCore import RediStack /// Redis implementation of job queues public class HBRedisJobQueue: HBJobQueue { public enum RedisQueueError: Error, CustomStringConvertible { case unexpectedRedisKeyType case jobMissing(JobIdentifier) public var description: String { switch self { case .unexpectedRedisKeyType: return "Unexpected redis key type" case .jobMissing(let value): return "Job associated with \(value) is missing" } } } let application: HBApplication let configuration: Configuration public var pollTime: TimeAmount { self.configuration.pollTime } /// Initialize redis job queue /// - Parameters: /// - application: Application /// - configuration: Configuration public init(_ application: HBApplication, configuration: Configuration) { self.application = application self.configuration = configuration } /// This is run at initialization time. /// /// Will push all the jobs in the processing queue back onto to the main queue so they can /// be rerun /// - Parameter eventLoop: eventLoop to run process on public func onInit(on eventLoop: EventLoop) -> EventLoopFuture<Void> { if self.configuration.rerunProcessing { return self.rerunProcessing(on: eventLoop) } else { return eventLoop.makeSucceededVoidFuture() } } /// Push Job onto queue /// - Parameters: /// - job: Job descriptor /// - eventLoop: eventLoop to do work on /// - Returns: Queued job public func push(_ job: HBJob, on eventLoop: EventLoop) -> EventLoopFuture<HBQueuedJob> { let pool = self.application.redis.pool(for: eventLoop) let queuedJob = HBQueuedJob(job) return self.set(jobId: queuedJob.id, job: queuedJob.job, pool: pool) .flatMap { pool.lpush(queuedJob.id.redisKey, into: self.configuration.queueKey) } .map { _ in return queuedJob } } /// Pop Job off queue /// - Parameter eventLoop: eventLoop to do work on /// - Returns: queued job public func pop(on eventLoop: EventLoop) -> EventLoopFuture<HBQueuedJob?> { let pool = self.application.redis.pool(for: eventLoop) return pool.rpoplpush(from: self.configuration.queueKey, to: self.configuration.processingQueueKey) .flatMap { key -> EventLoopFuture<HBQueuedJob?> in if key.isNull { return eventLoop.makeSucceededFuture(nil) } guard let key = String(fromRESP: key) else { return eventLoop.makeFailedFuture(RedisQueueError.unexpectedRedisKeyType) } let identifier = JobIdentifier(fromKey: key) return self.get(jobId: identifier, pool: pool) .unwrap(orError: RedisQueueError.jobMissing(identifier)) .map { job in return .init(id: identifier, job: job) } } } /// Flag job is done /// /// Removes job id from processing queue /// - Parameters: /// - jobId: Job id /// - eventLoop: eventLoop to do work on public func finished(jobId: JobIdentifier, on eventLoop: EventLoop) -> EventLoopFuture<Void> { let pool = self.application.redis.pool(for: eventLoop) return pool.lrem(jobId.description, from: self.configuration.processingQueueKey, count: 0) .flatMap { _ in return self.delete(jobId: jobId, pool: pool) } } /// Push all the entries on the processing list back onto the main list. /// /// This is run at initialization. If a job is in the processing queue at initialization it never was completed the /// last time queues were processed so needs to be re run public func rerunProcessing(on eventLoop: EventLoop) -> EventLoopFuture<Void> { let promise = eventLoop.makePromise(of: Void.self) let pool = self.application.redis.pool(for: eventLoop) func _moveOneEntry() { pool.rpoplpush(from: self.configuration.processingQueueKey, to: self.configuration.queueKey) .whenComplete { result in switch result { case .success(let key): if key.isNull { promise.succeed(()) } else { _moveOneEntry() } case .failure(let error): promise.fail(error) } } } _moveOneEntry() return promise.futureResult } func get(jobId: JobIdentifier, pool: RedisConnectionPool) -> EventLoopFuture<HBJobContainer?> { return pool.get(jobId.redisKey, asJSON: HBJobContainer.self) } func set(jobId: JobIdentifier, job: HBJobContainer, pool: RedisConnectionPool) -> EventLoopFuture<Void> { return pool.set(jobId.redisKey, toJSON: job) } func delete(jobId: JobIdentifier, pool: RedisConnectionPool) -> EventLoopFuture<Void> { return pool.delete(jobId.redisKey).map { _ in } } } extension HBJobQueueFactory { /// In memory driver for persist system public static func redis(configuration: HBRedisJobQueue.Configuration = .init()) -> HBJobQueueFactory { .init(create: { app in HBRedisJobQueue(app, configuration: configuration) }) } } extension JobIdentifier { var redisKey: RedisKey { .init(self.description) } init(fromKey key: String) { self.init(key) } }
37.449704
119
0.600095
4a48b44dfd3bedd6accde16b095a74cca10da5d3
1,906
// // PlaySoundsViewController.swift // PitchPerfect // // Created by José Naves on 06/09/18. // Copyright © 2018 José Naves. All rights reserved. // import UIKit import AVFoundation class PlaySoundsViewController: UIViewController { @IBOutlet weak var snailButton: UIButton! @IBOutlet weak var chipmunkButton: UIButton! @IBOutlet weak var rabbitButton: UIButton! @IBOutlet weak var vaderButton: UIButton! @IBOutlet weak var echoButton: UIButton! @IBOutlet weak var reverbButton: UIButton! @IBOutlet weak var stopButton: UIButton! var recordedAudioURL: URL! var audioFile: AVAudioFile! var audioEngine: AVAudioEngine! var audioPlayerNode: AVAudioPlayerNode! var stopTimer: Timer! enum ButtonType: Int { case slow = 0, fast, chipmunk, vader, echo, reverb } @IBAction func playSoundForButton(_ sender: UIButton) { switch (ButtonType(rawValue: sender.tag)!) { case .slow: playSound(rate: 0.5) case .fast: playSound(rate: 1.5) case .chipmunk: playSound(pitch: 1000) case .vader: playSound(pitch: -1000) case .echo: playSound(echo: true) case .reverb: playSound(reverb: true) } configureUI(.playing) } @IBAction func stopButtonPressed(_ sender: UIButton) { stopAudio() } override func viewDidLoad() { super.viewDidLoad() setupAudio() print("PlaySoundsViewController: \(recordedAudioURL)") // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureUI(.notPlaying) } override func viewWillDisappear(_ animated: Bool) { stopAudio() } }
27.228571
62
0.616474
18a65a810dfc456488bf7cca0637668067adcc88
469
//___FILEHEADER___ import Foundation import ComposableArchitecture public struct ___VARIABLE_productName___State: Equatable { public init() {} } public enum ___VARIABLE_productName___Action: Equatable {} public struct ___VARIABLE_productName___Environment {} public let reducer___VARIABLE_productName___ = Reducer<___VARIABLE_productName___State, ___VARIABLE_productName___Action, ___VARIABLE_productName___Environment> { state, action, _ in return .none }
29.3125
182
0.842217