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
0a97e8c055781f31aaa7e508477e46867a166f22
1,150
// https://github.com/Quick/Quick import Quick import Nimble import Aladin class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
22.54902
60
0.355652
7664b41f2314bd4a25c441a32c74f591d88c8723
8,876
// // ViewController.swift // telling_bot // // Created by Đại Nguyễn on 9/13/21. // import UIKit import AlanSDK import FBSDKShareKit class TellingViewController: UIViewController { private var button: AlanButton! private var text: AlanText! private var greetingIsPlayed = false let gfID = "100028331418733" @IBOutlet weak var mess: UIButton! override func viewDidLoad() { super.viewDidLoad() self.setupAlan() self.setupAlanEventHandler() self.setupAlanStateHandler() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.setVisualState(state: ["screen": "home"]) } @IBAction func callMess(_ sender: Any) { guard let url = URL(string: "https://newsroom.fb.com/") else { preconditionFailure("URL is invalid") } let content = ShareLinkContent() content.contentURL = url let dialog = MessageDialog() dialog.shareContent = content dialog.delegate = self do { try dialog.validate() } catch { print(error) } dialog.show() } private func setupAlan() { // Define the project key let config = AlanConfig(key: "6562e1fcf53c9a2d10187a219ed379242e956eca572e1d8b807a3e2338fdd0dc/stage") // Init button, text self.button = AlanButton(config: config) self.text = AlanText(frame: CGRect.zero) // add subview self.view.addSubview(self.button) self.button.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.text) self.text.translatesAutoresizingMaskIntoConstraints = false // Layout let views = ["button" : self.button!, "text" : self.text!] let verticalButton = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=0@299)-[button(64)]-40-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: views) let verticalText = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=0@299)-[text(64)]-40-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: views) let horizontalButton = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=0@299)-[button(64)]-20-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: views) let horizontalText = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[text]-20-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: views) self.view.addConstraints(verticalButton + verticalText + horizontalButton + horizontalText) } private func goForward() { let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "NextViewController") as! UIViewController vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.title = "Next" navigationController?.pushViewController(vc, animated: true) } private func goBack() { navigationController?.popViewController(animated: true) } @IBAction func next(_ sender: Any) { let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "NextViewController") as! UIViewController vc.modalPresentationStyle = .overCurrentContext vc.modalTransitionStyle = .crossDissolve vc.title = "Next" navigationController?.pushViewController(vc, animated: true) } func setVisualState(state: [AnyHashable: Any]) { self.button.setVisualState(state) } private func setupAlanEventHandler() { // Add an observer to get events NotificationCenter.default.addObserver(self, selector: #selector(self.handleEvent(_:)), name:NSNotification.Name(rawValue: "kAlanSDKEventNotification"), object:nil) } @objc func handleEvent(_ notification: Notification) { // Get the user info object with JSON guard let userInfo = notification.userInfo, let jsonString = userInfo["jsonString"] as? String, let jsonData = jsonString.data(using: .utf8), let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any], let commandObject = jsonObject["data"] as? [String: Any], // Get the command name string let commandString = commandObject["command"] as? String else { return } // navigate if commandString == "navigation" { // Get the route name string guard let routeString = commandObject["route"] as? String else { return } if routeString == "next" { DispatchQueue.main.async { self.goForward() } } else if routeString == "back" { DispatchQueue.main.async { self.goBack() } } } // highlight else if commandString == "highlight" { guard let itemString = commandObject["item"] as? String else { return } DispatchQueue.main.async { self.highlightItem(item: itemString) } } else if commandString == "mess" { DispatchQueue.main.async { self.openMess() } } } private func openMess() { let id = "fb-messenger://user-thread/\(gfID)" let url = URL(string: id)! if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } else { //redirect to home because the user doesn't have messenger UIApplication.shared.open(URL(string: "fb-messenger://user-thread/dainguyen.175")!) } } private func highlightItem(item: String) { if let secondVC = self.navigationController?.viewControllers.last as? NextViewController { secondVC.highlightItem(item: item) } } func selectItem(item: String) { if !self.button.isActive() { self.button.activate() } // send data to server self.button.callProjectApi("selectItem", withData: ["item": item]) { (_, _) in print("callProjectApi was called") DispatchQueue.main.asyncAfter(deadline: .now() + 4) { self.button.deactivate() } } } private func setupAlanStateHandler() { NotificationCenter.default.addObserver(self, selector: #selector(self.handleState(_:)), name:NSNotification.Name(rawValue: "kAlanSDKAlanButtonStateNotification"), object:nil) } @objc func handleState(_ notification: Notification) { guard let userInfo = notification.userInfo, /// Get the number value for the Alan button state let stateValue = userInfo["onButtonState"] as? NSNumber, /// Get the Alan button state let buttonState = AlanSDKButtonState.init(rawValue: stateValue.intValue) else { return } switch buttonState { case .online: if !self.greetingIsPlayed { self.greetingIsPlayed = true DispatchQueue.main.async { self.greeting() } } break case .offline: break case .noPermission: break case .connecting: break case .listen: break case .process: break case .reply: break default: break } } private func greeting() { // Check if the Alan button is active if !self.button.isActive() { self.button.activate() } // Play the greeting text self.button.playText("Welcome to the my Swift bot") DispatchQueue.main.asyncAfter(deadline: .now() + 4) { self.button.deactivate() } } } extension TellingViewController: SharingDelegate { func sharer(_ sharer: Sharing, didCompleteWithResults results: [String : Any]) { print(results) } func sharer(_ sharer: Sharing, didFailWithError error: Error) { } func sharerDidCancel(_ sharer: Sharing) { } }
31.928058
187
0.574245
11c0339cf77bbf4c03d70921472c9ee740ea4e0c
5,056
// The MIT License (MIT) // // Copyright (c) 2015-2019 Alexander Grebenyuk (github.com/kean). import XCTest @testable import Nuke class ImageViewPerformanceTests: XCTestCase { // This is the primary use case that we are optimizing for - loading images // into target, the API that majoriy of the apps are going to use. func testImageViewMainThreadPerformance() { let view = _ImageView() let urls = (0..<25_000).map { _ in return URL(string: "http://test.com/\(rnd(5000))")! } measure { for url in urls { Nuke.loadImage(with: url, into: view) } } } } class ImagePipelinePerfomanceTests: XCTestCase { /// A very broad test that establishes how long in general it takes to load /// data, decode, and decomperss 50+ images. It's very useful to get a /// broad picture about how loader options affect perofmance. func testLoaderOverallPerformance() { let dataLoader = MockDataLoader() let loader = ImagePipeline { $0.dataLoader = dataLoader // This must be off for this test, because rate limiter is optimized for // the actual loading in the apps and not the syntetic tests like this. $0.isRateLimiterEnabled = false $0.isDeduplicationEnabled = false // Disables processing which takes a bulk of time. $0.imageProcessor = { (_, _) in nil } } let urls = (0...3_000).map { _ in return URL(string: "http://test.com/\(rnd(500))")! } measure { let expectation = self.expectation(description: "Image loaded") var finished: Int = 0 for url in urls { loader.loadImage(with: url) { _, _ in finished += 1 if finished == urls.count { expectation.fulfill() } } } wait(10) } } } class ImageCachePerformanceTests: XCTestCase { func testCacheWrite() { let cache = ImageCache() let response = ImageResponse(image: Image(), urlResponse: nil) let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(500))")! } let requests = urls.map { ImageRequest(url: $0) } measure { for request in requests { cache.storeResponse(response, for: request) } } } func testCacheHit() { let cache = ImageCache() let response = ImageResponse(image: Image(), urlResponse: nil) for index in 0..<200 { cache.storeResponse(response, for: ImageRequest(url: URL(string: "http://test.com/\(index)")!)) } var hits = 0 let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(200))")! } let requests = urls.map { ImageRequest(url: $0) } measure { for request in requests { if cache.cachedResponse(for: request) != nil { hits += 1 } } } print("hits: \(hits)") } func testCacheMiss() { let cache = ImageCache() var misses = 0 let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(200))")! } let requests = urls.map { ImageRequest(url: $0) } measure { for request in requests { if cache.cachedResponse(for: request) == nil { misses += 1 } } } print("misses: \(misses)") } } class RequestPerformanceTests: XCTestCase { func testStoringRequestInCollections() { let urls = (0..<200_000).map { _ in return URL(string: "http://test.com/\(rnd(200))")! } let requests = urls.map { ImageRequest(url: $0) } measure { var array = [ImageRequest]() for request in requests { array.append(request) } } } } class DataCachePeformanceTests: XCTestCase { var cache: DataCache! override func setUp() { cache = try! DataCache(name: UUID().uuidString, filenameGenerator: { guard let data = $0.cString(using: .utf8) else { return "" } return _nuke_sha1(data, UInt32(data.count)) }) _ = cache["key"] // Wait till index is loaded. } override func tearDown() { try? FileManager.default.removeItem(at: cache.path) } func testReadFlushedPerformance() { for idx in 0..<1000 { cache["\(idx)"] = Data(repeating: 1, count: 256 * 1024) } cache.flush() let queue = OperationQueue() queue.maxConcurrentOperationCount = 2 measure { for idx in 0..<1000 { queue.addOperation { _ = self.cache["\(idx)"] } } queue.waitUntilAllOperationsAreFinished() } } }
30.275449
107
0.53659
aca26cbfb00361cbfdd265690b1ea547c52f6c79
1,547
// // ColorTest.swift // D2Layers // // Created by Michael Seemann on 23.11.15. // Copyright © 2015 CocoaPods. All rights reserved. // import XCTest import Quick import Nimble @testable import D2Layers class ColorSpec: QuickSpec { override func spec() { describe("color extensions") { it("is should make color brighter") { let blueColor = UIColor.blueColor() let rgbBlue = blueColor.rgb() expect(rgbBlue.red) == 0 expect(rgbBlue.green) == 0 expect(rgbBlue.blue) == 1.0 let lightBlueColor = blueColor.brighter().rgb() expect(rgbBlue.red) < lightBlueColor.red expect(rgbBlue.green) < lightBlueColor.green expect(rgbBlue.blue) == lightBlueColor.blue } it("should make color darker") { let blueColor = UIColor.blueColor() let rgbBlue = blueColor.rgb() expect(rgbBlue.red) == 0 expect(rgbBlue.green) == 0 expect(rgbBlue.blue) == 1.0 let darkerBlueColor = blueColor.darker().rgb() expect(rgbBlue.red) == darkerBlueColor.red expect(rgbBlue.green) == darkerBlueColor.green expect(rgbBlue.blue) > darkerBlueColor.blue } } } }
27.140351
63
0.489334
6aa7e83b50265d8e132acb083438849c60214e0b
3,411
import SwiftUI struct ChartView: View { private let data: [Double] private let maxY: Double private let minY: Double private let lineColor: Color private let startingDate: Date private let endingDate: Date @State private var percentage: CGFloat = 0 init(coin: CoinModel) { data = coin.sparklineIn7D?.price ?? [] maxY = data.max() ?? 0 minY = data.min() ?? 0 let priceChange = (data.last ?? 0) - (data.first ?? 0) lineColor = priceChange > 0 ? Color.theme.green : Color.theme.red endingDate = Date(coinGeckoString: coin.lastUpdated ?? "") startingDate = endingDate.addingTimeInterval(-7*24*60*60) } var body: some View { VStack { chartView .frame(height: 200) .background(chartBackground) .overlay(chartYAxis.padding(.horizontal, 4), alignment: .leading) chartDateLabels .padding(.horizontal, 4) } .font(.caption) .foregroundColor(Color.theme.SecondaryText) .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { withAnimation(.linear(duration: 2.0)) { percentage = 1.0 } } } } } struct ChartView_Previews: PreviewProvider { static var previews: some View { ChartView(coin: dev.coin) } } extension ChartView { private var chartView: some View { GeometryReader { geometry in Path { path in for index in data.indices { let xPosition = geometry.size.width / CGFloat(data.count) * CGFloat(index + 1) let yAxis = maxY - minY let yPosition = (1 - CGFloat((data[index] - minY) / yAxis)) * geometry.size.height if index == 0 { path.move(to: CGPoint(x: xPosition, y: yPosition)) } path.addLine(to: CGPoint(x: xPosition, y: yPosition)) } } .trim(from: 0, to: percentage) .stroke(lineColor , style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round)) .shadow(color: lineColor, radius: 10, x: 0.0, y: 10) .shadow(color: lineColor.opacity(0.5), radius: 10, x: 0.0, y: 20) .shadow(color: lineColor.opacity(0.2), radius: 10, x: 0.0, y: 30) .shadow(color: lineColor.opacity(0.1), radius: 10, x: 0.0, y: 40) } } private var chartBackground: some View { VStack { Divider() Spacer() Divider() Spacer() Divider() } } private var chartYAxis: some View { VStack { Text(maxY.formattedWithAbbreviations()) Spacer() Text(((maxY + minY) / 2).formattedWithAbbreviations()) Spacer() Text(minY.formattedWithAbbreviations()) } } private var chartDateLabels: some View { HStack { Text(startingDate.asShortDateString()) Spacer() Text(endingDate.asShortDateString()) } } }
30.185841
102
0.502199
dd634b4c2a7c011d42f92428d2f85724f9153de5
413
// // User.swift // CallMeMaybe // // Created by Ebubekir Ogden on 1/16/17. // Copyright © 2017 Ebubekir. All rights reserved. // import Foundation class User{ static var sharedInstance = User() private init(){} var name: String! var surname: String! var departmentName: String! var fullName: String!{ return "\(name!) \(surname!)" } }
14.75
51
0.571429
692ca16f5793f62835b51b008afacb0c37e866ea
948
// // Color.swift // BasicKit // // Created by Harvey on 2020/1/6. // Copyright © 2020 姚作潘/Harvey. All rights reserved. // #if os(macOS) import Cocoa #else import UIKit #endif public extension Color { convenience init(red: UInt, green: UInt, blue: UInt, alpha: Float = 1.0) { self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha)) } } public extension BasicKit where Base == Color { /// 灰色 level in [0, 255] static func gray(_ level: UInt, alpha: Float = 1.0) -> Base { return Base(red: level, green: level, blue: level, alpha: alpha) } /// 十六进制颜色 e.g. 0xFFFF99 static func hex(_ value: UInt) -> Base { let red = (value & 0xFF0000) >> 16 let green = (value & 0x00FF00) >> 8 let blue = value & 0x0000FF return Base(red: red, green: green, blue: blue) } }
23.7
127
0.580169
14fd23878980821b7bc1b6a3c5e41ab7f1e52ec3
6,360
// // Copyright (c) 2016-2017 Anton Mironov // // 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 Dispatch // swiftlint:disable line_length /// Protocol for concurrency-aware active objects. /// Conforming to this protocol helps to avoid boilerplate code related to dispatching and memory management. /// See ["Moving to nice asynchronous Swift code"](https://github.com/AsyncNinja/article-moving-to-nice-asynchronous-swift-code/blob/master/ARTICLE.md) for complete explanation. /// /// Best way to conform for model-related classes looks like: /// /// ```swift /// public class MyService: ExecutionContext, ReleasePoolOwner { /// private let _internalQueue = DispatchQueue(label: "my-service-queue", target: .global()) /// public var executor: Executor { return .queue(_internalQueue) } /// public let releasePool = ReleasePool() /// /// /* class implementation */ /// } /// ``` /// /// Best way to conform for classes related to main queue looks like: /// /// ```swift /// public class MyMainQueueService: ExecutionContext, ReleasePoolOwner { /// public var executor: Executor { return .main } /// public let releasePool = ReleasePool() /// /// /* class implementation */ /// } /// ``` /// /// Best way to conform for classes related to UI manipulations looks like: /// /// ```swift /// public class MyPresenter: NSObject, ObjCUIInjectedExecutionContext { /// /* class implementation */ /// } /// ``` /// Classes that conform to NSResponder/UIResponder are automatically conformed to exection context. public protocol ExecutionContext: Retainer { /// Executor to perform internal state-changing operations on. /// It is highly recommended to use serial executor var executor: Executor { get } } // swiftlint:enable line_length public extension ExecutionContext { /// Schedules execution of the block /// /// - Parameters: /// - cancellationToken: `CancellationToken` that can cancel execution /// - block: to schedule after timeout /// - strongSelf: is `ExecutionContext` restored from weak reference of self func async(cancellationToken: CancellationToken? = nil, block: @escaping (_ strongContext: Self) -> Void) { self.executor.execute(from: nil) { [weak self] (_) in guard let strongSelf = self else { return } block(strongSelf) } } /// Schedules execution of the block after specified timeout /// /// - Parameters: /// - timeout: (in seconds) to execute the block after /// - cancellationToken: `CancellationToken` that can cancel execution /// - block: to schedule after timeout /// - strongSelf: is `ExecutionContext` restored from weak reference of self func after(_ timeout: Double, cancellationToken: CancellationToken? = nil, block: @escaping (_ strongContext: Self) -> Void) { self.executor.execute(after: timeout) { [weak self] (_) in if cancellationToken?.isCancelled ?? false { return } guard let strongSelf = self else { return } block(strongSelf) } } /// Adds dependent `Cancellable`. `Cancellable` will be weakly referenced /// and cancelled on deinit func addDependent(cancellable: Cancellable) { self.notifyDeinit { [weak cancellable] in cancellable?.cancel() } } /// Adds dependent `Completable`. `Completable` will be weakly /// referenced and cancelled because of deallocated context on deinit func addDependent<T: Completable>(completable: T) { self.notifyDeinit { [weak completable] in completable?.cancelBecauseOfDeallocatedContext() } } /// Makes a dynamic property bound to the execution context /// /// - Parameters: /// - initialValue: initial value to set /// - bufferSize: `DerivedChannelBufferSize` of derived channel. /// Keep default value of the argument unless you need /// an extended buffering options of returned channel /// - Returns: `DynamicProperty` bound to the context func makeDynamicProperty<T>( _ initialValue: T, bufferSize: Int = AsyncNinjaConstants.defaultChannelBufferSize ) -> DynamicProperty<T> { return DynamicProperty( initialValue: initialValue, updateExecutor: executor, bufferSize: bufferSize) } } /// Protocol for any instance that has `ReleasePool`. /// Made to proxy calls of `func releaseOnDeinit(_ object: AnyObject)` /// and `func notifyDeinit(_ block: @escaping () -> Void)` to `ReleasePool` public protocol ReleasePoolOwner: Retainer { /// `ReleasePool` to proxy calls to. Perfect implementation looks like: /// ```swift /// public class MyService: ExecutionContext, ReleasePoolOwner { /// let releasePool = ReleasePool() /// /* other implementation */ /// } /// ``` var releasePool: ReleasePool { get } } public extension ExecutionContext where Self: ReleasePoolOwner { func releaseOnDeinit(_ object: AnyObject) { self.releasePool.insert(object) } func notifyDeinit(_ block: @escaping () -> Void) { self.releasePool.notifyDrain(block) } } /// An object that can extend lifetime of another objects up to deinit or notify deinit public protocol Retainer: class { /// Extends lifetime of specified object func releaseOnDeinit(_ object: AnyObject) /// calls specified block on deinit func notifyDeinit(_ block: @escaping () -> Void) }
37.192982
177
0.707862
87b5c52cece4219445298b172174f8fb62a4b90f
243
// // NetworkerJsonResponse.swift // Pods // // Created by Igor on 10/16/17. // // public struct NetworkerJSONResponse { /// HTTP status code public let statusCode: Int /// JSON dictionary public let json: JSON }
14.294118
37
0.621399
71c52bc7e8352d40e433e54fb53c94ad85c7685e
2,935
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 StructuralCore /// A duplicate, simplified version of the `Equatable` protocol. /// - Note: a duplicate protocol is used to avoid triggering existing `Equatable` derived /// conformances. public protocol MyEquatable { func myEqual(_ other: Self) -> Bool } // Inductive cases. extension StructuralCons: MyEquatable where Value: MyEquatable, Next: MyEquatable { public func myEqual(_ other: Self) -> Bool { return value.myEqual(other.value) && next.myEqual(other.next) } } extension StructuralEither: MyEquatable where Left: MyEquatable, Right: MyEquatable { public func myEqual(_ other: Self) -> Bool { switch (self, other) { case (.left(let lhs), .left(let rhs)): return lhs.myEqual(rhs) case (.right(let lhs), .right(let rhs)): return lhs.myEqual(rhs) default: return false } } } extension StructuralCase: MyEquatable where AssociatedValues: MyEquatable { public func myEqual(_ other: Self) -> Bool { associatedValues.myEqual(other.associatedValues) } } extension StructuralProperty: MyEquatable where Value: MyEquatable { public func myEqual(_ other: Self) -> Bool { return value.myEqual(other.value) } } extension StructuralEnum: MyEquatable where Cases: MyEquatable { public func myEqual(_ other: Self) -> Bool { cases.myEqual(other.cases) } } extension StructuralStruct: MyEquatable where Properties: MyEquatable { public func myEqual(_ other: Self) -> Bool { properties.myEqual(other.properties) } } // Base cases. extension StructuralEmpty: MyEquatable { public func myEqual(_ other: StructuralEmpty) -> Bool { return true } } extension Int: MyEquatable { public func myEqual(_ other: Int) -> Bool { return self == other } } extension Float: MyEquatable { public func myEqual(_ other: Float) -> Bool { return self == other } } extension Double: MyEquatable { public func myEqual(_ other: Double) -> Bool { return self == other } } // Syntactic Sugar extension MyEquatable where Self: Structural, Self.StructuralRepresentation: MyEquatable { public func myEqual(_ other: Self) -> Bool { return self.structuralRepresentation.myEqual(other.structuralRepresentation) } }
27.175926
90
0.688245
b9408a1e435a85e2808517bf69d84b47f7cb72b7
843
// // emptyTableView.swift // ChowTown // // Created by Jordain Gijsbertha on 09/01/2020. // Copyright © 2020 Jordain Gijsbertha. All rights reserved. // import UIKit class emptyTableView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subTitleLabel: UILabel! override init(frame: CGRect) { super.init(frame : frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder : aDecoder) commonInit() } private func commonInit(){ Bundle.main.loadNibNamed("emptyTableView", owner: self, options: nil) addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] } }
22.184211
77
0.633452
5dfbab52bf01859f499bd8baec67b47eb581e1ea
2,730
import UIKit import SwiftUI import shared class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? let log = KmLog(tag: "SceneDelegate") func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). log.info { "scene" } // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } TestIOS().logOnThread() } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
47.068966
147
0.704029
e4e9466d3d1f1f93e21987e1c23a4cf68d90ae72
7,794
// // TimeUnit+Int.swift // // Created by Chris Scalcucci on 4/20/20. // import Foundation public extension Int64 { func nanoseconds(_ from: TimeUnit) -> Int64 { switch from { case .nanoseconds: return self case .microseconds: return Int64(us2ns(Double(self))) case .milliseconds: return Int64(ms2ns(Double(self))) case .seconds: return Int64(s2ns(Double(self))) case .minutes: return Int64(min2ns(Double(self))) case .hours: return Int64(hr2ns(Double(self))) case .days: return Int64(d2ns(Double(self))) } } func microseconds(_ from: TimeUnit) -> Int64 { switch from { case .nanoseconds: return Int64(ns2us(Double(self))) case .microseconds: return self case .milliseconds: return Int64(ms2us(Double(self))) case .seconds: return Int64(s2us(Double(self))) case .minutes: return Int64(min2us(Double(self))) case .hours: return Int64(hr2us(Double(self))) case .days: return Int64(d2us(Double(self))) } } func milliseconds(from: TimeUnit) -> Int64 { switch from { case .nanoseconds: return Int64(ns2ms(Double(self))) case .microseconds: return Int64(us2ms(Double(self))) case .milliseconds: return self case .seconds: return Int64(s2ms(Double(self))) case .minutes: return Int64(min2ms(Double(self))) case .hours: return Int64(hr2ms(Double(self))) case .days: return Int64(d2ms(Double(self))) } } func seconds(from: TimeUnit) -> Int64 { switch from { case .nanoseconds: return Int64(ns2s(Double(self))) case .microseconds: return Int64(us2s(Double(self))) case .milliseconds: return Int64(ms2s(Double(self))) case .seconds: return self case .minutes: return Int64(min2s(Double(self))) case .hours: return Int64(hr2s(Double(self))) case .days: return Int64(d2s(Double(self))) } } func minutes(from: TimeUnit) -> Int64 { switch from { case .nanoseconds: return Int64(ns2min(Double(self))) case .microseconds: return Int64(us2min(Double(self))) case .milliseconds: return Int64(ms2min(Double(self))) case .seconds: return Int64(s2min(Double(self))) case .minutes: return self case .hours: return Int64(hr2min(Double(self))) case .days: return Int64(d2min(Double(self))) } } func hours(from: TimeUnit) -> Int64 { switch from { case .nanoseconds: return Int64(ns2hr(Double(self))) case .microseconds: return Int64(us2hr(Double(self))) case .milliseconds: return Int64(ms2hr(Double(self))) case .seconds: return Int64(s2hr(Double(self))) case .minutes: return Int64(min2hr(Double(self))) case .hours: return self case .days: return Int64(d2hr(Double(self))) } } func days(from: TimeUnit) -> Int64 { switch from { case .nanoseconds: return Int64(ns2d(Double(self))) case .microseconds: return Int64(us2d(Double(self))) case .milliseconds: return Int64(ms2d(Double(self))) case .seconds: return Int64(s2d(Double(self))) case .minutes: return Int64(min2d(Double(self))) case .hours: return Int64(hr2d(Double(self))) case .days: return self } } } public extension Int { func nanoseconds(_ from: TimeUnit) -> Int { switch from { case .nanoseconds: return self case .microseconds: return Int(us2ns(Double(self))) case .milliseconds: return Int(ms2ns(Double(self))) case .seconds: return Int(s2ns(Double(self))) case .minutes: return Int(min2ns(Double(self))) case .hours: return Int(hr2ns(Double(self))) case .days: return Int(d2ns(Double(self))) } } func microseconds(_ from: TimeUnit) -> Int { switch from { case .nanoseconds: return Int(ns2us(Double(self))) case .microseconds: return self case .milliseconds: return Int(ms2us(Double(self))) case .seconds: return Int(s2us(Double(self))) case .minutes: return Int(min2us(Double(self))) case .hours: return Int(hr2us(Double(self))) case .days: return Int(d2us(Double(self))) } } func milliseconds(from: TimeUnit) -> Int { switch from { case .nanoseconds: return Int(ns2ms(Double(self))) case .microseconds: return Int(us2ms(Double(self))) case .milliseconds: return self case .seconds: return Int(s2ms(Double(self))) case .minutes: return Int(min2ms(Double(self))) case .hours: return Int(hr2ms(Double(self))) case .days: return Int(d2ms(Double(self))) } } func seconds(from: TimeUnit) -> Int { switch from { case .nanoseconds: return Int(ns2s(Double(self))) case .microseconds: return Int(us2s(Double(self))) case .milliseconds: return Int(ms2s(Double(self))) case .seconds: return self case .minutes: return Int(min2s(Double(self))) case .hours: return Int(hr2s(Double(self))) case .days: return Int(d2s(Double(self))) } } func minutes(from: TimeUnit) -> Int { switch from { case .nanoseconds: return Int(ns2min(Double(self))) case .microseconds: return Int(us2min(Double(self))) case .milliseconds: return Int(ms2min(Double(self))) case .seconds: return Int(s2min(Double(self))) case .minutes: return self case .hours: return Int(hr2min(Double(self))) case .days: return Int(d2min(Double(self))) } } func hours(from: TimeUnit) -> Int { switch from { case .nanoseconds: return Int(ns2hr(Double(self))) case .microseconds: return Int(us2hr(Double(self))) case .milliseconds: return Int(ms2hr(Double(self))) case .seconds: return Int(s2hr(Double(self))) case .minutes: return Int(min2hr(Double(self))) case .hours: return self case .days: return Int(d2hr(Double(self))) } } func days(from: TimeUnit) -> Int { switch from { case .nanoseconds: return Int(ns2d(Double(self))) case .microseconds: return Int(us2d(Double(self))) case .milliseconds: return Int(ms2d(Double(self))) case .seconds: return Int(s2d(Double(self))) case .minutes: return Int(min2d(Double(self))) case .hours: return Int(hr2d(Double(self))) case .days: return self } } }
27.835714
50
0.520914
b92c36d16af4b1b88765e42008bface0ef0f3e94
471
// // ColorTests.swift // ZamzamCore // // Created by Basem Emara on 10/13/16. // Copyright © 2016 Zamzam Inc. All rights reserved. // import XCTest import ZamzamCore final class ColorTests: XCTestCase {} extension ColorTests { func testRGBVsHex() { XCTAssertEqual(PlatformColor(rgb: (77, 116, 107)), PlatformColor(hex: 0x4D746B)) } } extension ColorTests { func testRandom() { XCTAssertNotEqual(PlatformColor.random, .random) } }
18.84
88
0.681529
79b6c2941e930e7d71d93ddba254809955c30e1d
258
import AssetCatalogAware /// Customize this source file, and the associated /// assets catalog, as you see fit. extension Assets { public enum ImageId: String, ImageIdentifier { case foo = "foo-image" case bah = "bah-image" } }
16.125
50
0.655039
14f550cdb483f353ba2dffddad251d3ddfaee0c8
750
import XCTest import DialCountries class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.862069
111
0.602667
fec9fc3497b2c5d5d455b2065582f4a82836fc0b
3,014
// // The MIT License (MIT) // // Copyright (c) 2015-present Badoo Trading Limited. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Chatto import ChattoAdditions public final class ChatItemPresenterBuilder<ChatItem>: ChatItemPresenterBuilderProtocol, ChatItemPresenterBuilderCollectionViewConfigurable { private let binder: Binder private let assembler: ViewAssembler private let layoutAssembler: LayoutAssembler private let factory: FactoryAggregate<ChatItem> private let reuseIdentifier: String public init(binder: Binder, assembler: ViewAssembler, layoutAssembler: LayoutAssembler, factory: FactoryAggregate<ChatItem>) { self.binder = binder self.assembler = assembler self.factory = factory self.layoutAssembler = layoutAssembler self.reuseIdentifier = assembler.reuseIdentifier } // TODO: Implement me #744 public func canHandleChatItem(_ chatItem: ChatItemProtocol) -> Bool { guard let item = chatItem as? ChatItem else { return false } //return self.binder.canHandle(item: item) return true } public func createPresenterWithChatItem(_ chatItem: ChatItemProtocol) -> ChatItemPresenterProtocol { guard let item = chatItem as? ChatItem else { fatalError() } return ChatItemPresenter( chatItem: item, binder: self.binder, assembler: self.assembler, layoutAssembler: self.layoutAssembler, factory: self.factory, reuseIdentifier: self.reuseIdentifier ) } public let presenterType: ChatItemPresenterProtocol.Type = ChatItemPresenter<ChatItemType>.self // MARK: - ChatItemPresenterBuilderCollectionViewConfigurable public func configure(with collectionView: UICollectionView) { ChatItemPresenter<ChatItemType>.registerCells(for: collectionView, with: self.reuseIdentifier) } }
40.186667
141
0.72495
f851a7d6524af8771b3155da9b268a41acca2c87
150
import XCTest #if !os(macOS) public func allTests() -> [XCTestCaseEntry] { return [ testCase(ExtendedErrorTests.allTests), ] } #endif
16.666667
46
0.66
872dfa69e5a2fb8482671b6207816ccbe43af5ac
45,334
/* This source file is part of the Swift.org open source project Copyright (c) 2021-2022 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basics import PackageGraph import PackageLoading import PackageModel @testable import SPMBuildCore import SPMTestSupport import TSCBasic import Workspace import XCTest class PluginTests: XCTestCase { func testUseOfBuildToolPluginTargetByExecutableInSamePackage() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins") { fixturePath in let (stdout, _) = try executeSwiftBuild(fixturePath.appending(component: "MySourceGenPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"]) XCTAssert(stdout.contains("Linking MySourceGenBuildTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)") } } func testUseOfBuildToolPluginProductByExecutableAcrossPackages() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins") { fixturePath in let (stdout, _) = try executeSwiftBuild(fixturePath.appending(component: "MySourceGenClient"), configuration: .Debug, extraArgs: ["--product", "MyTool"]) XCTAssert(stdout.contains("Linking MySourceGenBuildTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Linking MyTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)") } } func testUseOfPrebuildPluginTargetByExecutableAcrossPackages() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins") { fixturePath in let (stdout, _) = try executeSwiftBuild(fixturePath.appending(component: "MySourceGenPlugin"), configuration: .Debug, extraArgs: ["--product", "MyOtherLocalTool"]) XCTAssert(stdout.contains("Compiling MyOtherLocalTool bar.swift"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Compiling MyOtherLocalTool baz.swift"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Linking MyOtherLocalTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)") } } func testUseOfPluginWithInternalExecutable() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins") { fixturePath in let (stdout, _) = try executeSwiftBuild(fixturePath.appending(component: "ClientOfPluginWithInternalExecutable")) XCTAssert(stdout.contains("Compiling PluginExecutable main.swift"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Linking PluginExecutable"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Compiling RootTarget foo.swift"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Linking RootTarget"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)") } } func testInternalExecutableAvailableOnlyToPlugin() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins") { fixturePath in XCTAssertThrowsCommandExecutionError(try executeSwiftBuild(fixturePath.appending(component: "InvalidUseOfInternalPluginExecutable")), "Illegally used internal executable") { error in XCTAssert( error.stderr.contains("product 'PluginExecutable' required by package 'invaliduseofinternalpluginexecutable' target 'RootTarget' not found in package 'PluginWithInternalExecutable'."), "stderr:\n\(error.stderr)" ) } } } func testContrivedTestCases() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins") { fixturePath in let (stdout, _) = try executeSwiftBuild(fixturePath.appending(component: "ContrivedTestPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"]) XCTAssert(stdout.contains("Linking MySourceGenBuildTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)") } } func testPluginScriptSandbox() throws { #if !os(macOS) try XCTSkipIf(true, "test is only supported on macOS") #endif // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins") { fixturePath in let (stdout, _) = try executeSwiftBuild(fixturePath.appending(component: "SandboxTesterPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"]) XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)") } } func testUseOfVendedBinaryTool() throws { #if !os(macOS) try XCTSkipIf(true, "test is only supported on macOS") #endif // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins") { fixturePath in let (stdout, _) = try executeSwiftBuild(fixturePath.appending(component: "MyBinaryToolPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"]) XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)") XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)") } } func testCommandPluginInvocation() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") // FIXME: This test is getting quite long — we should add some support functionality for creating synthetic plugin tests and factor this out into separate tests. try testWithTemporaryDirectory { tmpPath in // Create a sample package with a library target and a plugin. It depends on a sample package. let packageDir = tmpPath.appending(components: "MyPackage") let manifestFile = packageDir.appending(component: "Package.swift") try localFileSystem.createDirectory(manifestFile.parentDirectory, recursive: true) try localFileSystem.writeFileContents(manifestFile) { """ // swift-tools-version: 5.6 import PackageDescription let package = Package( name: "MyPackage", dependencies: [ .package(name: "HelperPackage", path: "VendoredDependencies/HelperPackage") ], targets: [ .target( name: "MyLibrary", dependencies: [ .product(name: "HelperLibrary", package: "HelperPackage") ] ), .plugin( name: "PluginPrintingInfo", capability: .command( intent: .custom(verb: "print-info", description: "Description of the command"), permissions: [.writeToPackageDirectory(reason: "Reason for wanting to write to package directory")] ) ), .plugin( name: "PluginFailingWithError", capability: .command( intent: .custom(verb: "fail-with-error", description: "Sample plugin that throws an error") ) ), .plugin( name: "PluginFailingWithoutError", capability: .command( intent: .custom(verb: "fail-without-error", description: "Sample plugin that exits without error") ) ), .plugin( name: "NeverendingPlugin", capability: .command( intent: .custom(verb: "neverending-plugin", description: "A plugin that doesn't end running") ) ), ] ) """ } let librarySourceFile = packageDir.appending(components: "Sources", "MyLibrary", "library.swift") try localFileSystem.createDirectory(librarySourceFile.parentDirectory, recursive: true) try localFileSystem.writeFileContents(librarySourceFile) { """ public func Foo() { } """ } let printingPluginSourceFile = packageDir.appending(components: "Plugins", "PluginPrintingInfo", "plugin.swift") try localFileSystem.createDirectory(printingPluginSourceFile.parentDirectory, recursive: true) try localFileSystem.writeFileContents(printingPluginSourceFile) { """ import PackagePlugin @main struct MyCommandPlugin: CommandPlugin { func performCommand( context: PluginContext, arguments: [String] ) throws { // Check the identity of the root packages. print("Root package is \\(context.package.displayName).") // Check that we can find a tool in the toolchain. let swiftc = try context.tool(named: "swiftc") print("Found the swiftc tool at \\(swiftc.path).") } } """ } let pluginFailingWithErrorSourceFile = packageDir.appending(components: "Plugins", "PluginFailingWithError", "plugin.swift") try localFileSystem.createDirectory(pluginFailingWithErrorSourceFile.parentDirectory, recursive: true) try localFileSystem.writeFileContents(pluginFailingWithErrorSourceFile) { """ import PackagePlugin @main struct MyCommandPlugin: CommandPlugin { func performCommand( context: PluginContext, arguments: [String] ) throws { // Print some output that should appear before the error diagnostic. print("This text should appear before the uncaught thrown error.") // Throw an uncaught error that should be reported as a diagnostics. throw "This is the uncaught thrown error." } } extension String: Error { } """ } let pluginFailingWithoutErrorSourceFile = packageDir.appending(components: "Plugins", "PluginFailingWithoutError", "plugin.swift") try localFileSystem.createDirectory(pluginFailingWithoutErrorSourceFile.parentDirectory, recursive: true) try localFileSystem.writeFileContents(pluginFailingWithoutErrorSourceFile) { """ import PackagePlugin import Foundation @main struct MyCommandPlugin: CommandPlugin { func performCommand( context: PluginContext, arguments: [String] ) throws { // Print some output that should appear before we exit. print("This text should appear before we exit.") // Just exit with an error code without an emitting error. exit(1) } } extension String: Error { } """ } let neverendingPluginSourceFile = packageDir.appending(components: "Plugins", "NeverendingPlugin", "plugin.swift") try localFileSystem.createDirectory(neverendingPluginSourceFile.parentDirectory, recursive: true) try localFileSystem.writeFileContents(neverendingPluginSourceFile) { """ import PackagePlugin import Foundation @main struct MyCommandPlugin: CommandPlugin { func performCommand( context: PluginContext, arguments: [String] ) throws { // Print some output that should appear before we exit. print("This text should appear before we exit.") // Just exit with an error code without an emitting error. exit(1) } } extension String: Error { } """ } // Create the sample vendored dependency package. let library1Path = packageDir.appending(components: "VendoredDependencies", "HelperPackage", "Package.swift") try localFileSystem.createDirectory(library1Path.parentDirectory, recursive: true) try localFileSystem.writeFileContents(library1Path) { """ // swift-tools-version: 5.5 import PackageDescription let package = Package( name: "HelperPackage", products: [ .library( name: "HelperLibrary", targets: ["HelperLibrary"] ), ], targets: [ .target( name: "HelperLibrary" ), ] ) """ } let library2Path = packageDir.appending(components: "VendoredDependencies", "HelperPackage", "Sources", "HelperLibrary", "library.swift") try localFileSystem.createDirectory(library2Path.parentDirectory, recursive: true) try localFileSystem.writeFileContents(library2Path) { """ public func Bar() { } """ } // Load a workspace from the package. let observability = ObservabilitySystem.makeForTesting() let workspace = try Workspace( fileSystem: localFileSystem, forRootPackage: packageDir, customManifestLoader: ManifestLoader(toolchain: ToolchainConfiguration.default), delegate: MockWorkspaceDelegate() ) // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) let rootManifests = try tsc_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, completion: $0 ) } XCTAssert(rootManifests.count == 1, "\(rootManifests)") // Load the package graph. let packageGraph = try workspace.loadPackageGraph(rootInput: rootInput, observabilityScope: observability.topScope) XCTAssertNoDiagnostics(observability.diagnostics) XCTAssert(packageGraph.packages.count == 2, "\(packageGraph.packages)") XCTAssert(packageGraph.rootPackages.count == 1, "\(packageGraph.rootPackages)") let package = try XCTUnwrap(packageGraph.rootPackages.first) // Find the regular target in our test package. let libraryTarget = try XCTUnwrap(package.targets.map(\.underlyingTarget).first{ $0.name == "MyLibrary" } as? SwiftTarget) XCTAssertEqual(libraryTarget.type, .library) // Set up a delegate to handle callbacks from the command plugin. let delegateQueue = DispatchQueue(label: "plugin-invocation") class PluginDelegate: PluginInvocationDelegate { let delegateQueue: DispatchQueue var diagnostics: [Basics.Diagnostic] = [] init(delegateQueue: DispatchQueue) { self.delegateQueue = delegateQueue } func pluginEmittedOutput(_ data: Data) { // Add each line of emitted output as a `.info` diagnostic. dispatchPrecondition(condition: .onQueue(delegateQueue)) let textlines = String(decoding: data, as: UTF8.self).split(separator: "\n") print(textlines.map{ "[TEXT] \($0)" }.joined(separator: "\n")) diagnostics.append(contentsOf: textlines.map{ Basics.Diagnostic(severity: .info, message: String($0), metadata: .none) }) } func pluginEmittedDiagnostic(_ diagnostic: Basics.Diagnostic) { // Add the diagnostic as-is. dispatchPrecondition(condition: .onQueue(delegateQueue)) print("[DIAG] \(diagnostic)") diagnostics.append(diagnostic) } } // Helper function to invoke a plugin with given input and to check its outputs. func testCommand( package: ResolvedPackage, plugin pluginName: String, targets targetNames: [String], arguments: [String], toolSearchDirectories: [AbsolutePath] = [UserToolchain.default.swiftCompilerPath.parentDirectory], toolNamesToPaths: [String: AbsolutePath] = [:], file: StaticString = #file, line: UInt = #line, expectFailure: Bool = false, diagnosticsChecker: (DiagnosticsTestResult) throws -> Void ) { // Find the named plugin. let plugins = package.targets.compactMap{ $0.underlyingTarget as? PluginTarget } guard let plugin = plugins.first(where: { $0.name == pluginName }) else { return XCTFail("There is no plugin target named ‘\(pluginName)’") } XCTAssertTrue(plugin.type == .plugin, "Target \(plugin) isn’t a plugin") // Find the named input targets to the plugin. var targets: [ResolvedTarget] = [] for targetName in targetNames { guard let target = package.targets.first(where: { $0.underlyingTarget.name == targetName }) else { return XCTFail("There is no target named ‘\(targetName)’") } XCTAssertTrue(target.type != .plugin, "Target \(target) is a plugin") targets.append(target) } let pluginDir = tmpPath.appending(components: package.identity.description, plugin.name) let scriptRunner = DefaultPluginScriptRunner( fileSystem: localFileSystem, cacheDir: pluginDir.appending(component: "cache"), toolchain: ToolchainConfiguration.default ) let delegate = PluginDelegate(delegateQueue: delegateQueue) do { let success = try tsc_await { plugin.invoke( action: .performCommand(package: package, arguments: arguments), buildEnvironment: BuildEnvironment(platform: .macOS, configuration: .debug), scriptRunner: scriptRunner, workingDirectory: package.path, outputDirectory: pluginDir.appending(component: "output"), toolSearchDirectories: [UserToolchain.default.swiftCompilerPath.parentDirectory], toolNamesToPaths: [:], writableDirectories: [pluginDir.appending(component: "output")], readOnlyDirectories: [package.path], fileSystem: localFileSystem, observabilityScope: observability.topScope, callbackQueue: delegateQueue, delegate: delegate, completion: $0) } if expectFailure { XCTAssertFalse(success, "expected command to fail, but it succeeded", file: file, line: line) } else { XCTAssertTrue(success, "expected command to succeed, but it failed", file: file, line: line) } } catch { XCTFail("error \(String(describing: error))", file: file, line: line) } testDiagnostics(delegate.diagnostics, problemsOnly: false, file: file, line: line, handler: diagnosticsChecker) } // Invoke the command plugin that prints out various things it was given, and check them. testCommand(package: package, plugin: "PluginPrintingInfo", targets: ["MyLibrary"], arguments: ["veni", "vidi", "vici"]) { output in output.check(diagnostic: .equal("Root package is MyPackage."), severity: .info) output.check(diagnostic: .and(.prefix("Found the swiftc tool"), .suffix(".")), severity: .info) } // Invoke the command plugin that throws an unhandled error at the top level. testCommand(package: package, plugin: "PluginFailingWithError", targets: [], arguments: [], expectFailure: true) { output in output.check(diagnostic: .equal("This text should appear before the uncaught thrown error."), severity: .info) output.check(diagnostic: .equal("This is the uncaught thrown error."), severity: .error) } // Invoke the command plugin that exits with code 1 without returning an error. testCommand(package: package, plugin: "PluginFailingWithoutError", targets: [], arguments: [], expectFailure: true) { output in output.check(diagnostic: .equal("This text should appear before we exit."), severity: .info) output.check(diagnostic: .equal("Plugin ended with exit code 1"), severity: .error) } } } func testLocalAndRemoteToolDependencies() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try fixture(name: "Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool") { path in let (stdout, stderr) = try executeSwiftPackage(path.appending(component: "MyLibrary"), configuration: .Debug, extraArgs: ["plugin", "my-plugin"]) XCTAssert(stderr.contains("Linking RemoteTool"), "stdout:\n\(stderr)\n\(stdout)") XCTAssert(stderr.contains("Linking LocalTool"), "stdout:\n\(stderr)\n\(stdout)") XCTAssert(stderr.contains("Linking ImpliedLocalTool"), "stdout:\n\(stderr)\n\(stdout)") XCTAssert(stderr.contains("Build complete!"), "stdout:\n\(stderr)\n\(stdout)") XCTAssert(stdout.contains("A message from the remote tool."), "stdout:\n\(stderr)\n\(stdout)") XCTAssert(stdout.contains("A message from the local tool."), "stdout:\n\(stderr)\n\(stdout)") XCTAssert(stdout.contains("A message from the implied local tool."), "stdout:\n\(stderr)\n\(stdout)") } } func testCommandPluginCancellation() throws { // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require). try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency") try testWithTemporaryDirectory { tmpPath in // Create a sample package with a couple of plugins a other targets and products. let packageDir = tmpPath.appending(components: "MyPackage") try localFileSystem.createDirectory(packageDir, recursive: true) try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift")) { """ // swift-tools-version: 5.6 import PackageDescription let package = Package( name: "MyPackage", products: [ .library( name: "MyLibrary", targets: ["MyLibrary"] ), ], targets: [ .target( name: "MyLibrary" ), .plugin( name: "NeverendingPlugin", capability: .command( intent: .custom(verb: "neverending-plugin", description: "Help description") ) ), ] ) """ } let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary") try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true) try localFileSystem.writeFileContents(myLibraryTargetDir.appending(component: "library.swift")) { """ public func GetGreeting() -> String { return "Hello" } """ } let neverendingPluginTargetDir = packageDir.appending(components: "Plugins", "NeverendingPlugin") try localFileSystem.createDirectory(neverendingPluginTargetDir, recursive: true) try localFileSystem.writeFileContents(neverendingPluginTargetDir.appending(component: "plugin.swift")) { """ import PackagePlugin import Foundation @main struct NeverendingPlugin: CommandPlugin { func performCommand( context: PluginContext, arguments: [String] ) throws { print("pid: \\(ProcessInfo.processInfo.processIdentifier)") while true { Thread.sleep(forTimeInterval: 1.0) print("still here") } } } """ } // Load a workspace from the package. let observability = ObservabilitySystem.makeForTesting() let workspace = try Workspace( fileSystem: localFileSystem, forRootPackage: packageDir, customManifestLoader: ManifestLoader(toolchain: ToolchainConfiguration.default), delegate: MockWorkspaceDelegate() ) // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) let rootManifests = try tsc_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, completion: $0 ) } XCTAssert(rootManifests.count == 1, "\(rootManifests)") // Load the package graph. let packageGraph = try workspace.loadPackageGraph(rootInput: rootInput, observabilityScope: observability.topScope) XCTAssertNoDiagnostics(observability.diagnostics) XCTAssert(packageGraph.packages.count == 1, "\(packageGraph.packages)") XCTAssert(packageGraph.rootPackages.count == 1, "\(packageGraph.rootPackages)") let package = try XCTUnwrap(packageGraph.rootPackages.first) // Find the regular target in our test package. let libraryTarget = try XCTUnwrap(package.targets.map(\.underlyingTarget).first{ $0.name == "MyLibrary" } as? SwiftTarget) XCTAssertEqual(libraryTarget.type, .library) // Set up a delegate to handle callbacks from the command plugin. In particular we want to know the process identifier. let delegateQueue = DispatchQueue(label: "plugin-invocation") class PluginDelegate: PluginInvocationDelegate { let delegateQueue: DispatchQueue var diagnostics: [Basics.Diagnostic] = [] var parsedProcessIdentifier: Int? = .none init(delegateQueue: DispatchQueue) { self.delegateQueue = delegateQueue } func pluginEmittedOutput(_ data: Data) { // Add each line of emitted output as a `.info` diagnostic. dispatchPrecondition(condition: .onQueue(delegateQueue)) let textlines = String(decoding: data, as: UTF8.self).split(separator: "\n") diagnostics.append(contentsOf: textlines.map{ Basics.Diagnostic(severity: .info, message: String($0), metadata: .none) }) // If we don't already have the process identifier, we try to find it. if parsedProcessIdentifier == .none { func parseProcessIdentifier(_ string: String) -> Int? { guard let match = try? NSRegularExpression(pattern: "pid: (\\d+)", options: []).firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count)) else { return .none } // We have a match, so extract the process identifier. assert(match.numberOfRanges == 2) return Int((string as NSString).substring(with: match.range(at: 1))) } parsedProcessIdentifier = textlines.compactMap{ parseProcessIdentifier(String($0)) }.first } } func pluginEmittedDiagnostic(_ diagnostic: Basics.Diagnostic) { // Add the diagnostic as-is. dispatchPrecondition(condition: .onQueue(delegateQueue)) diagnostics.append(diagnostic) } } // Find the relevant plugin. let plugins = package.targets.compactMap{ $0.underlyingTarget as? PluginTarget } guard let plugin = plugins.first(where: { $0.name == "NeverendingPlugin" }) else { return XCTFail("There is no plugin target named ‘NeverendingPlugin’") } XCTAssertTrue(plugin.type == .plugin, "Target \(plugin) isn’t a plugin") // Run the plugin. let pluginDir = tmpPath.appending(components: package.identity.description, plugin.name) let scriptRunner = DefaultPluginScriptRunner( fileSystem: localFileSystem, cacheDir: pluginDir.appending(component: "cache"), toolchain: ToolchainConfiguration.default ) let delegate = PluginDelegate(delegateQueue: delegateQueue) let sync = DispatchSemaphore(value: 0) plugin.invoke( action: .performCommand(package: package, arguments: []), buildEnvironment: BuildEnvironment(platform: .macOS, configuration: .debug), scriptRunner: scriptRunner, workingDirectory: package.path, outputDirectory: pluginDir.appending(component: "output"), toolSearchDirectories: [UserToolchain.default.swiftCompilerPath.parentDirectory], toolNamesToPaths: [:], writableDirectories: [pluginDir.appending(component: "output")], readOnlyDirectories: [package.path], fileSystem: localFileSystem, observabilityScope: observability.topScope, callbackQueue: delegateQueue, delegate: delegate, completion: { _ in sync.signal() } ) // Wait for three seconds. let result = sync.wait(timeout: .now() + 3) XCTAssertEqual(result, .timedOut, "expected the plugin to time out") // At this point we should have parsed out the process identifier. But it's possible we don't always — this is being investigated in rdar://88792829. var pid: Int? = .none delegateQueue.sync { pid = delegate.parsedProcessIdentifier } guard let pid = pid else { throw XCTSkip("skipping test because no pid was received from the plugin; being investigated as rdar://88792829\n\(delegate.diagnostics.description)") } // Check that it's running (we do this by asking for its priority — this only works on some platforms). #if os(macOS) errno = 0 getpriority(Int32(PRIO_PROCESS), UInt32(pid)) XCTAssertEqual(errno, 0, "unexpectedly got errno \(errno) when trying to check process \(pid)") #endif // Ask the plugin running to cancel all plugins. DefaultPluginScriptRunner.cancelAllRunningPlugins() // Check that it's no longer running (we do this by asking for its priority — this only works on some platforms). #if os(macOS) usleep(500) errno = 0 getpriority(Int32(PRIO_PROCESS), UInt32(pid)) XCTAssertEqual(errno, ESRCH, "unexpectedly got errno \(errno) when trying to check process \(pid)") #endif } } func testUnusedPluginProductWarnings() throws { // Test the warnings we get around unused plugin products in package dependencies. try testWithTemporaryDirectory { tmpPath in // Create a sample package that uses three packages that vend plugins. let packageDir = tmpPath.appending(components: "MyPackage") try localFileSystem.createDirectory(packageDir, recursive: true) try localFileSystem.writeFileContents(packageDir.appending(component: "Package.swift")) { """ // swift-tools-version: 5.6 import PackageDescription let package = Package( name: "MyPackage", dependencies: [ .package(name: "BuildToolPluginPackage", path: "VendoredDependencies/BuildToolPluginPackage"), .package(name: "UnusedBuildToolPluginPackage", path: "VendoredDependencies/UnusedBuildToolPluginPackage"), .package(name: "CommandPluginPackage", path: "VendoredDependencies/CommandPluginPackage") ], targets: [ .target( name: "MyLibrary", path: ".", plugins: [ .plugin(name: "BuildToolPlugin", package: "BuildToolPluginPackage") ] ), ] ) """ } try localFileSystem.writeFileContents(packageDir.appending(component: "Library.swift")) { """ public var Foo: String """ } // Create the depended-upon package that vends a build tool plugin that is used by the main package. let buildToolPluginPackageDir = packageDir.appending(components: "VendoredDependencies", "BuildToolPluginPackage") try localFileSystem.createDirectory(buildToolPluginPackageDir, recursive: true) try localFileSystem.writeFileContents(buildToolPluginPackageDir.appending(component: "Package.swift")) { """ // swift-tools-version: 5.6 import PackageDescription let package = Package( name: "BuildToolPluginPackage", products: [ .plugin( name: "BuildToolPlugin", targets: ["BuildToolPlugin"]) ], targets: [ .plugin( name: "BuildToolPlugin", capability: .buildTool(), path: ".") ] ) """ } try localFileSystem.writeFileContents(buildToolPluginPackageDir.appending(component: "Plugin.swift")) { """ import PackagePlugin @main struct MyPlugin: BuildToolPlugin { func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] { return [] } } """ } // Create the depended-upon package that vends a build tool plugin that is not used by the main package. let unusedBuildToolPluginPackageDir = packageDir.appending(components: "VendoredDependencies", "UnusedBuildToolPluginPackage") try localFileSystem.createDirectory(unusedBuildToolPluginPackageDir, recursive: true) try localFileSystem.writeFileContents(unusedBuildToolPluginPackageDir.appending(component: "Package.swift")) { """ // swift-tools-version: 5.6 import PackageDescription let package = Package( name: "UnusedBuildToolPluginPackage", products: [ .plugin( name: "UnusedBuildToolPlugin", targets: ["UnusedBuildToolPlugin"]) ], targets: [ .plugin( name: "UnusedBuildToolPlugin", capability: .buildTool(), path: ".") ] ) """ } try localFileSystem.writeFileContents(unusedBuildToolPluginPackageDir.appending(component: "Plugin.swift")) { """ import PackagePlugin @main struct MyPlugin: BuildToolPlugin { func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] { return [] } } """ } // Create the depended-upon package that vends a command plugin. let commandPluginPackageDir = packageDir.appending(components: "VendoredDependencies", "CommandPluginPackage") try localFileSystem.createDirectory(commandPluginPackageDir, recursive: true) try localFileSystem.writeFileContents(commandPluginPackageDir.appending(component: "Package.swift")) { """ // swift-tools-version: 5.6 import PackageDescription let package = Package( name: "CommandPluginPackage", products: [ .plugin( name: "CommandPlugin", targets: ["CommandPlugin"]) ], targets: [ .plugin( name: "CommandPlugin", capability: .command(intent: .custom(verb: "how", description: "why")), path: ".") ] ) """ } try localFileSystem.writeFileContents(commandPluginPackageDir.appending(component: "Plugin.swift")) { """ import PackagePlugin @main struct MyPlugin: CommandPlugin { func performCommand(context: PluginContext, targets: [Target], arguments: [String]) throws { } } """ } // Load a workspace from the package. let observability = ObservabilitySystem.makeForTesting() let workspace = try Workspace( fileSystem: localFileSystem, location: .init(forRootPackage: packageDir, fileSystem: localFileSystem), customManifestLoader: ManifestLoader(toolchain: ToolchainConfiguration.default), delegate: MockWorkspaceDelegate() ) // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) let rootManifests = try tsc_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, completion: $0 ) } XCTAssert(rootManifests.count == 1, "\(rootManifests)") // Load the package graph. let packageGraph = try workspace.loadPackageGraph(rootInput: rootInput, observabilityScope: observability.topScope) XCTAssert(packageGraph.packages.count == 4, "\(packageGraph.packages)") XCTAssert(packageGraph.rootPackages.count == 1, "\(packageGraph.rootPackages)") // Check that we have only a warning about the unused build tool plugin (not about the used one and not about the command plugin). testDiagnostics(observability.diagnostics, problemsOnly: true) { result in result.checkUnordered(diagnostic: .contains("dependency 'unusedbuildtoolpluginpackage' is not used by any target"), severity: .warning) } } } }
54.357314
231
0.568558
4b8057032e3ec960f098cbae1916b889fa0ac1b3
902
// // LitePopoverTests.swift // LitePopoverTests // // Created by BotherBox on 15/3/15. // Copyright (c) 2015年 sz. All rights reserved. // import UIKit import XCTest class LitePopoverTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.378378
111
0.616408
0884188fac3ccb17bbf04de17b06ad281397ce17
1,675
// // HUD.swift // LineUp // // Created by Bjarne Møller Lundgren on 23/03/2018. // Copyright © 2018 Bjarne Møller Lundgren. All rights reserved. // import Foundation import SpriteKit import ARKit private let OPTION_YOFFSET:CGFloat = 60 private let ARKIT_STATE_LABEL_NAME = "_Status_Message_" class HUD { static var currentStateDisplayed:String? = nil class func present(state:ARCamera.TrackingState, in scene:SKScene) { var message:String switch state { case .notAvailable: message = "ARKit not available" case .normal: message = "ARKit is tracking.." case .limited(let reason): switch reason { case .excessiveMotion: message = "You are moving the device too much" case .initializing: message = "Tracking is initializing" case .insufficientFeatures: message = "Not enough features detected" } } if currentStateDisplayed != nil && currentStateDisplayed! == message { return } currentStateDisplayed = message removeTrackingState(in: scene) let labelNode = SKLabelNode() labelNode.text = message labelNode.name = ARKIT_STATE_LABEL_NAME labelNode.position = CGPoint(x: 20, y: scene.size.height - 80) labelNode.horizontalAlignmentMode = .left labelNode.verticalAlignmentMode = .center scene.addChild(labelNode) } class func removeTrackingState(in scene:SKScene) { scene.childNode(withName: ARKIT_STATE_LABEL_NAME)?.removeFromParent() } }
29.910714
87
0.625672
fee88136af437d213bc3008d4fed7b101090ec4d
3,127
// Copyright 2022 Pera Wallet, LDA // 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. // // ScreenLoadingIndicator.swift import Foundation import MacaroonUIKit import UIKit final class ScreenLoadingIndicator: View, MacaroonUIKit.LoadingIndicator { var title: String? { get { titleView.text } set { titleView.text = newValue } } var attributedTitle: NSAttributedString? { get { titleView.attributedText } set { titleView.attributedText = newValue } } var isAnimating: Bool { return indicatorView.isAnimating } private lazy var contentView = UIView() private lazy var indicatorView = ViewLoadingIndicator() private lazy var titleView = Label() override init( frame: CGRect ) { super.init(frame: frame) customize(ScreenLoadingIndicatorTheme()) } func customize( _ theme: ScreenLoadingIndicatorTheme ) { addBackground(theme) addContent(theme) } func customizeAppearance( _ styleSheet: NoStyleSheet ) {} func prepareLayout( _ layoutSheet: NoLayoutSheet ) {} } extension ScreenLoadingIndicator { func startAnimating() { indicatorView.startAnimating() } func stopAnimating() { indicatorView.stopAnimating() } } extension ScreenLoadingIndicator { private func addBackground( _ theme: ScreenLoadingIndicatorTheme ) { drawAppearance(shadow: theme.background) } private func addContent( _ theme: ScreenLoadingIndicatorTheme ) { addSubview(contentView) contentView.snp.makeConstraints { $0.width >= contentView.snp.height $0.setPaddings(theme.contentEdgeInsets) } addIndicator(theme) addTitle(theme) } private func addIndicator( _ theme: ScreenLoadingIndicatorTheme ) { indicatorView.applyStyle(theme.indicator) contentView.addSubview(indicatorView) indicatorView.snp.makeConstraints { $0.centerHorizontally( verticalPaddings: (0, .noMetric) ) } } private func addTitle( _ theme: ScreenLoadingIndicatorTheme ) { titleView.customizeAppearance(theme.title) contentView.addSubview(titleView) titleView.contentEdgeInsets = (theme.titleTopMargin, 0, 0, 0) titleView.fitToVerticalIntrinsicSize() titleView.snp.makeConstraints { $0.top == indicatorView.snp.bottom $0.setPaddings((.noMetric, 0, 0, 0)) } } }
25.016
75
0.654301
1c523756d5e95dec44ecb90da5a0f5f4a81d7aae
1,914
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // rdar://problem/46878013 // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var CollectionTests = TestSuite("Collection") // Test collections using a reference type as element. do { var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap CollectionTests.addMutableBidirectionalCollectionTests( makeCollection: { (elements: [LifetimeTracked]) in return DefaultedMutableBidirectionalCollection(elements: elements) }, wrapValue: { (element: OpaqueValue<Int>) in LifetimeTracked(element.value, identity: element.identity) }, extractValue: { (element: LifetimeTracked) in OpaqueValue(element.value, identity: element.identity) }, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in // FIXME: use LifetimeTracked. return DefaultedMutableBidirectionalCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in // FIXME: use LifetimeTracked. return DefaultedMutableBidirectionalCollection(elements: elements) }, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) } runAllTests()
35.444444
91
0.700627
fe88870ae752e470e43b42c42545ee8c07107968
2,209
// // Copyright (c) 9.12.2019 Somia Reality Oy. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // import UIKit class NINButton: UIButton, HasCustomLayer { var closure: ((NINButton) -> Void)? var type: QuestionnaireButtonType? override init(frame: CGRect) { super.init(frame: frame) self.addTarget(self, action: #selector(touchUpInside(sender:)), for: .touchUpInside) } convenience init(frame: CGRect, touch closure: ((UIButton) -> Void)?) { self.init(frame: frame) self.closure = closure } required init?(coder: NSCoder) { super.init(coder: coder) } override func layoutSubviews() { super.layoutSubviews() applyLayerOverride(view: self) } // MARK: - User actions override func sendActions(for controlEvents: UIControl.Event) { super.sendActions(for: controlEvents) self.closure?(self) } @objc internal func touchUpInside(sender: UIButton) { self.closure?(self) } // MARK: - Helper methods func overrideAssets(with delegate: NINChatSessionInternalDelegate?, isPrimary primary: Bool) { self.titleLabel?.font = .ninchat self.backgroundColor = .clear if let layer = delegate?.override(layerAsset: primary ? .ninchatPrimaryButton : .ninchatSecondaryButton) { self.layer.insertSublayer(layer, below: self.titleLabel?.layer) } else { self.setTitleColor(primary ? .white : .defaultBackgroundButton, for: .normal) self.backgroundColor = primary ? .defaultBackgroundButton : .white self.roundButton() } if let overrideColor = delegate?.override(colorAsset: primary ? .ninchatColorButtonPrimaryText : .ninchatColorButtonSecondaryText) { self.setTitleColor(overrideColor, for: .normal) } } } /// Helper for questionnaire items extension NINButton { func roundButton() { self.round(borderWidth: 1.0, borderColor: (self.isSelected ? self.titleColor(for: .selected) : self.titleColor(for: .normal)) ?? .QGrayButton) } }
31.557143
150
0.651426
2658876c7467540dd9894f777099b1f344908061
2,470
// // DoughnutChart.swift // // // Created by Will Dale on 01/02/2021. // import SwiftUI /** View for creating a doughnut chart. Uses `DoughnutChartData` data model. # Declaration ``` DoughnutChart(chartData: data) ``` # View Modifiers The order of the view modifiers is some what important as the modifiers are various types for stacks that wrap around the previous views. ``` .touchOverlay(chartData: data) .infoBox(chartData: data) .floatingInfoBox(chartData: data) .headerBox(chartData: data) .legends(chartData: data) ``` */ public struct DoughnutChart<ChartData>: View where ChartData: DoughnutChartData { @ObservedObject var chartData: ChartData /// Initialises a bar chart view. /// - Parameter chartData: Must be DoughnutChartData. public init(chartData : ChartData) { self.chartData = chartData } @State private var startAnimation : Bool = false public var body: some View { ZStack { ForEach(chartData.dataSets.dataPoints.indices, id: \.self) { data in DoughnutSegmentShape(id: chartData.dataSets.dataPoints[data].id, startAngle: chartData.dataSets.dataPoints[data].startAngle, amount: chartData.dataSets.dataPoints[data].amount) .stroke(chartData.dataSets.dataPoints[data].colour, lineWidth: chartData.chartStyle.strokeWidth) .scaleEffect(startAnimation ? 1 : 0) .opacity(startAnimation ? 1 : 0) .animation(Animation.spring().delay(Double(data) * 0.06)) .if(chartData.infoView.touchOverlayInfo == [chartData.dataSets.dataPoints[data]]) { $0 .scaleEffect(1.1) .zIndex(1) .shadow(color: Color.primary, radius: 10) } .accessibilityLabel(Text("\(chartData.metadata.title)")) .accessibilityValue(chartData.dataSets.dataPoints[data].getCellAccessibilityValue(specifier: chartData.infoView.touchSpecifier)) } } .animateOnAppear(using: chartData.chartStyle.globalAnimation) { self.startAnimation = true } .animateOnDisappear(using: chartData.chartStyle.globalAnimation) { self.startAnimation = false } } }
33.835616
148
0.602024
2f8d0d6dec14e7f8da7467779cb54e5902d14828
2,114
// // BusinessFilterViewController.swift // Yelp // // Created by Thomas Zhu on 2/15/17. // Copyright © 2017 Timothy Lee. All rights reserved. // import UIKit class BusinessFilterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - IBOutlets @IBOutlet weak var tableView: UITableView! // MARK: - Property declarations var categories: [String]! var selectedCategories: [String] = [] var callback: (([String]) -> Void)! // MARK: - Lifecycle methods override func viewDidLoad() { super.viewDidLoad() let delegate = self tableView.dataSource = delegate tableView.delegate = delegate } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) callback(selectedCategories) } // MARK: - Dele func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: C.Identifier.TableCell.categoryCell, for: indexPath) cell.textLabel?.text = categories[indexPath.row] cell.textLabel?.textColor = UIColor.darkGray if selectedCategories.contains(categories[indexPath.row]) { tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categories.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let text = tableView.cellForRow(at: indexPath)?.textLabel?.text { selectedCategories.append(text) } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if let text = tableView.cellForRow(at: indexPath)?.textLabel?.text { if let index = selectedCategories.index(of: text) { selectedCategories.remove(at: index) } } } }
29.774648
117
0.646168
758d329bab486de8ad3687bc900fcf356a33e64a
540
// // ImageViewRound.swift // zomato-client-ios-app // // Created by Fernando Luna on 9/25/19. // Copyright © 2019 Fernando Luna. All rights reserved. // import UIKit class ImageViewRound: UIImageView { override init(frame: CGRect) { super.init(frame: frame) setRoundCorner() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setRoundCorner() } func setRoundCorner() { self.layer.cornerRadius = self.bounds.size.width * 0.2 } }
19.285714
62
0.614815
89f03d2d3c8c8fab589576fe27d765e9ca311d7e
245
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A protocol P{ init() } protocol C{var f:A } func a<T{ { } class A:P
17.5
87
0.734694
fc62c2ba81db5c0af03f1f70f492e64f642f55f5
8,208
// // NaturalLanguageSamplerTests.swift // NaturalLanguageSamplerTests // // Created by Daiki Matsudate on 2018/06/08. // import XCTest import NaturalLanguage @testable import NaturalLanguageSampler fileprivate let text = """ Lorem ipsum dolor sit amet, has atqui numquam qualisque id, mei et tantas posidonium, eu habeo forensibus definitiones sed. Deserunt interesset reprehendunt ne per, nonumy ornatus antiopam ei mea. Sapientem constituto neglegentur an pro, oratio equidem pro cu. Salutatus comprehensam eu qui, aperiam volutpat scripserit per ut. At per scribentur accommodare, ea eam viderer definitiones. Ut iudico scaevola mnesarchum sit, usu ipsum deserunt ne. Et nibh intellegat per, stet verterem ex eam, cum ad laudem vocent. Velit soluta sed cu, cu duo semper inermis graecis. Ex labores evertitur sed. No modus reque semper nam, affert quodsi in per. Vim eu unum delenit, eum eu option iuvaret aliquid. Te qui albucius offendit definitionem, usu putant detraxit reformidans te, in mei delectus volutpat. Has natum aliquid principes id, ad est eruditi mnesarchum. An audire volutpat pro, vel no wisi audiam nostrum. Quo vocent insolens an, mollis disputando liberavisse an sea. Cetero intellegam ius id, in sint habeo dolores vis, stet malorum eripuit ei eos. In usu modus corrumpit persequeris, atqui apeirian consequuntur nam ne, mutat dictas eos et. Audire omnesque mei at, et vide maluisset similique has. Cu unum instructior nec, lucilius perfecto explicari sea at, lorem dolor munere quo ex. Eos ei paulo congue fabellas, vel cu reque putant expetendis, eum id clita facilisi. Mei euismod legendos an, et option pertinax mel. Eu usu solum latine deseruisse, quando recusabo in vis, eum ea saperet cotidieque. Mutat dolores democritum ut sit. """ class TokenizeTests: XCTestCase { func testTokenizeTextToWord() { let tokenizer = NLTokenizer(unit: .word) let tokens = tokenizer.tokens(text: text) XCTAssert(text[tokens.first!] == "Lorem") XCTAssert(text[tokens[1]] == "ipsum") XCTAssert(text[tokens[2]] == "dolor") XCTAssert(text[tokens.last!] == "sit") } func testTokenizeTextToSentence() { let tokenizer = NLTokenizer(unit: .sentence) let tokens = tokenizer.tokens(text: text) XCTAssert(text[tokens.first!] == "Lorem ipsum dolor sit amet, has atqui numquam qualisque id, mei et tantas posidonium, eu habeo forensibus definitiones sed. ") // need separator XCTAssert(text[tokens.last!] == "Mutat dolores democritum ut sit.") } func testTokenizeTextToParagraph() { let tokenizer = NLTokenizer(unit: .paragraph) let tokens = tokenizer.tokens(text: text) XCTAssert(text[tokens.first!] == "Lorem ipsum dolor sit amet, has atqui numquam qualisque id, mei et tantas posidonium, eu habeo forensibus definitiones sed. Deserunt interesset reprehendunt ne per, nonumy ornatus antiopam ei mea. Sapientem constituto neglegentur an pro, oratio equidem pro cu. Salutatus comprehensam eu qui, aperiam volutpat scripserit per ut. At per scribentur accommodare, ea eam viderer definitiones.\n") // only one new line... } func testTokenizeTextToDocument() { let tokenizer = NLTokenizer(unit: .document) let tokens = tokenizer.tokens(text: text) XCTAssert(text[tokens.first!] == text) // When we need to use this unit? } } class LanguageRecognizerTests: XCTestCase { func testTextLanguageIsEnglish() { let recognizer = NLLanguageRecognizer(text: text) XCTAssert(recognizer.dominantLanguage! == .english) } let japaneseText = "やっていき" func testTextLanguageIsJapanese() { let recognizer = NLLanguageRecognizer(text: japaneseText) XCTAssert(recognizer.dominantLanguage! == .japanese) } func testEnglishTextLanguageIsFrenchWithFrenchHigherHints() { let recognizer = NLLanguageRecognizer(text: text) recognizer.languageHints = [.french: 0.2, .english: 0.00001] XCTAssert(recognizer.dominantLanguage! == .french) // French } /// In spite of higher hint for French than English, the dominant language is detected to English func testEnglishTextLanguageIsEnglishWithFrenchHigherHints() { let recognizer = NLLanguageRecognizer(text: text) recognizer.languageHints = [.french: 0.2, .english: 0.1] XCTAssert(recognizer.dominantLanguage! == .english) // English } /// Japanese text is detected as Japanese regardless of specifying english for hints. func testJapaneseTextLanguageIsJapaneseWithEngishHints() { let recognizer = NLLanguageRecognizer(text: "やっていき") recognizer.languageHints = [.english: 0.1] XCTAssert(recognizer.dominantLanguage! == .japanese) } func testTextHypothesesContainEnglishAndPortuguese() { let recognizer = NLLanguageRecognizer(text: text) let hyphotheses = recognizer.languageHypotheses(withMaximum: 2) print(hyphotheses) // [pt: 0.32105109095573425, en: 0.4647941291332245] XCTAssert(hyphotheses.keys.contains(.english)) // 0.4647941291332245 XCTAssert(hyphotheses.keys.contains(.portuguese)) // 0.32105109095573425 } } class LinguisticTagsTests: XCTestCase { let text = "I can not go San Jose this year due to not have my ticket." let textContainsConstractions = "I can't go San Jose this year due to not have my ticket." func testPrintTags() { let schemes: [NLTagScheme] = [.language, .lemma, .lexicalClass, .nameTypeOrLexicalClass, .nameType, .tokenType, .script] let tagger = NLTagger(tagSchemes: schemes) // '.joinContractions' is only available in NaturalLanguage framework to treat contraction as a token. // If not specified this, `can't` will be treated as `ca` and `n't` let options: NLTagger.Options = [.omitPunctuation, .omitWhitespace, .joinContractions] schemes.forEach({ print("---- \($0.rawValue) ----") tagger.tagging(text: text, unit: .word, scheme: $0, options: options) }) } func testPrintNSLinguisticTaggerTags() { let schemes: [NSLinguisticTagScheme] = [.language, .lemma, .lexicalClass, .nameTypeOrLexicalClass, .nameType, .tokenType, .script] let tagger = NSLinguisticTagger(tagSchemes: schemes) let options: NSLinguisticTagger.Options = [.omitPunctuation, .omitWhitespace] schemes.forEach({ print("---- \($0.rawValue) ----") tagger.tagging(text: text, unit: .word, scheme: $0, options: options) }) } func testTagEqualEnglish() { let tagger = NLTagger(tagSchemes: [.language]) let tags = tagger.tags(text: text, unit: .word, scheme: .language, options: [.omitPunctuation, .omitWhitespace, .joinContractions]) XCTAssertEqual(tags.first!.0, (NLTag("en"))) // I: en XCTAssertEqual(tags[1].0, (NLTag("en"))) // can't: en XCTAssertEqual(tags.last!.0, (NLTag("en"))) // age: en } func testNLTagIsEqualToNSLinguisticTag() { let tSchemes: [NLTagScheme] = [.language, .lemma, .lexicalClass, .nameTypeOrLexicalClass, .nameType, .tokenType, .script] let lSchemes: [NSLinguisticTagScheme] = [.language, .lemma, .lexicalClass, .nameTypeOrLexicalClass, .nameType, .tokenType, .script] let tTagger = NLTagger(tagSchemes: tSchemes) let lTagger = NSLinguisticTagger(tagSchemes: lSchemes) zip(tSchemes, lSchemes).forEach { (tScheme, lScheme) in print("---- \(tScheme.rawValue) ----") XCTAssertEqual(tScheme.rawValue, lScheme.rawValue) let tags = tTagger.tags(text: text, unit: .word, scheme: tScheme, options: [.omitPunctuation, .omitWhitespace]) let lTags = lTagger.tags(text: text, unit: .word, scheme: lScheme, options: [.omitPunctuation, .omitWhitespace]) zip(tags, lTags).forEach({ (tTag, lTag) in print(tTag.0.rawValue, lTag.0.rawValue, tTag.0.rawValue == lTag.0.rawValue) XCTAssertEqual(tTag.0.rawValue, lTag.0.rawValue) XCTAssertEqual(text[tTag.1], text[Range(lTag.1, in: text)!]) }) } } }
54
457
0.699805
281a1b1023d76674dd48eaf3bf0e7fa8b224e176
13,225
// // KernelContext.swift // // // Created by Steven Obua on 05/08/2021. // import Foundation public typealias Prop = Term public struct Theorem : Hashable { public let kc_uuid : UUID public let prop : Term fileprivate init(kc_uuid : UUID, prop : Prop) { self.kc_uuid = kc_uuid self.prop = prop } } public struct KernelContext : Hashable, CustomStringConvertible { public typealias Prover = (KernelContext, Prop) -> Theorem? public enum Ext : Hashable { case assume(Term) case declare(head: Head) case define(const: Const, hyps: [Term], body: Term) case seal(const: Const) case choose(Const, where: Term) case join(parents : [UUID]) } public struct DefCase : Hashable { public let hyps : [Term] public let body : Term } public struct Def : Hashable { public let head : Head public var definitions : [DefCase] public var sealed : Bool } public let uuid : UUID public let parent : UUID? public let extensions : [Ext] public let axioms : [Term] public let constants : [Const : Def] private init(uuid : UUID = UUID(), parent: UUID?, extensions: [Ext], axioms : [Term], constants : [Const : Def]) { self.parent = parent self.extensions = extensions self.uuid = uuid self.axioms = axioms self.constants = constants } public init?<S:Collection>(squash contexts: S) where S.Element == KernelContext { guard !contexts.isEmpty else { return nil } var exts : [Ext] = [] var last : KernelContext? = nil for context in contexts { guard last == nil || last!.uuid == context.parent else { return nil } exts.append(contentsOf: context.extensions) last = context } self.parent = contexts.first!.parent self.uuid = last!.uuid self.axioms = last!.axioms self.constants = last!.constants self.extensions = exts } public func isValid(_ th : Theorem) -> Bool { return th.kc_uuid == uuid } private func prove(_ prover : Prover, _ prop : Prop) -> Bool { guard let th = prover(self, prop) else { return false } guard isValid(th) else { return false } return alpha_equivalent(prop, th.prop) } private func prove(_ prover : Prover, _ props : [Prop]) -> Bool { return props.allSatisfy { prop in prove(prover, prop) } } private func extend(_ addExtensions : [Ext], addAxioms : [Term] = [], mergeConstants : [Const : Def] = [:]) -> KernelContext { let mergedConstants = constants.merging(mergeConstants) { old, new in new } return KernelContext(parent: uuid, extensions: addExtensions, axioms: axioms + addAxioms, constants: mergedConstants) } public func assume(_ term : Term) -> KernelContext? { //print("assume \(term)") guard isWellformed(term) else { return nil } //guard prove(prover, Term.mk_in_Prop(term)) else { return nil } return extend([.assume(term)], addAxioms: [term]) } public func axiom(_ index : Int) -> Theorem { return Theorem(kc_uuid: uuid, prop: axioms[index]) } public func declare(head : Head) -> KernelContext? { guard constants[head.const] == nil else { return nil } let def = Def(head: head, definitions: [], sealed : false) return extend([.declare(head: head)], mergeConstants: [head.const : def]) } public func seal(const : Const) -> KernelContext? { guard var def = constants[const], !def.sealed else { return nil } def.sealed = true return extend([.seal(const: const)], mergeConstants: [const : def]) } public func define(const : Const, hyps : [Term], body : Term, prover : Prover) -> KernelContext? { guard var def = constants[const], !def.sealed else { return nil } for t in hyps + [body] { guard let frees = checkWellformedness(t)?.arity else { return nil } guard def.head.covers(frees) else { return nil } } var props : [Term] = [] /*for h in hyps { props.append(Term.mk_in_Prop(h)) }*/ for d in def.definitions { let compatible = Term.mk_prop(hyps: d.hyps + hyps, Term.mk_eq(d.body, body)) props.append(compatible) } guard prove(prover, props) else { return nil } let ax : Prop = .mk_prop(hyps: hyps, Term.mk_eq(def.head.term, body)) def.definitions.append(DefCase(hyps: hyps, body: body)) return extend([.define(const: const, hyps: hyps, body: body)], addAxioms: [ax], mergeConstants: [const: def]) } public func choose(const : Const, from: Theorem) -> KernelContext? { guard isValid(from) else { return nil } guard constants[const] == nil else { return nil } guard let (v, body) = Term.dest_ex(from.prop) else { return nil } let cond = Term.replace(kc: self, free: v, with: const, in: body) guard let frees = checkWellformedness(cond)?.arity, frees.isEmpty else { print("choose: free variables discovered") return nil } let head = Head(const: const, binders: [], params: [])! let def = Def(head: head, definitions: [], sealed: true) return extend([.choose(const, where: cond)], addAxioms: [cond], mergeConstants: [const : def]) } public static func join(parents : [KernelContext]) -> KernelContext? { var axioms : [Term] = [] var constants : [Const : Def] = [:] for parent in parents { for (const, def) in parent.constants { if let d = constants[const] { guard d == def else { return nil } } else { constants[const] = def } } for axiom in parent.axioms { if !axioms.contains(axiom) { axioms.append(axiom) } } } let extensions : [Ext] = [.join(parents: parents.map { p in p.uuid})] return KernelContext(parent: nil, extensions: extensions, axioms: axioms, constants: constants) } public var lastAxiom : Theorem { return axiom(axioms.count - 1) } private static func findOpeningDeclaration(const : Const, from : Int, extensions : [Ext]) -> Int? { var i = from while i >= 0 { switch extensions[i] { case .assume, .choose, .join: return nil case let .seal(c): if c != const { return nil } case let .declare(head: head): if head.const != const { return nil } else { return i } case let .define(const: c, hyps: _, body: _): if c != const { return nil } } i -= 1 } return nil } public static func lift(_ th : Theorem, in chain : KCChain, from : Int, to : Int) -> Theorem? { guard chain.isValidIndex(from) && chain.isValidIndex(to) else { return nil } guard chain[from].uuid == th.kc_uuid else { return nil } if from == to { return th } else if from < to { return Theorem(kc_uuid: chain[to].uuid, prop: th.prop) } else { var current = th.prop let exts = chain.extensions(from: to+1, to: from) let constants = chain[from].constants var i = exts.count - 1 while i >= 0 { //print("lift at \(i)): \(current)") switch exts[i] { case let .assume(hyp): let (frees, arity) = chain[from].freeVarsOf(hyp) for (_, a) in arity { if a != 0 { return nil } } current = Term.mk_imp(Term.mk_all(frees, hyp), current) case let .choose(c, where: _): if current.contains(const: c) { let v = Term.fresh(c.name, for: current) current = Term.mk_ex(v, Term.replace(const: c, with: v, in: current)) } case let .declare(head: head): let c = head.const if let arity = current.arityOf(const: c) { guard arity.binders == 0 else { return nil } let v = Term.fresh(c.name, for: current) current = Term.replace(const: c, with: v, in: current) } case let .define(const: const, hyps: hyps, body: body): guard let head = constants[const]?.head, head.binders.count == 0 else { return nil } let d = Prop.mk_prop(hyps: hyps, Term.mk_eq(head.term, body)) let vars = head.params.map { p in p.unappliedVar! } current = Term.mk_imp(Term.mk_all(vars, d), current) case let .seal(const: const): if !current.contains(const: const), let declIndex = findOpeningDeclaration(const: const, from: i, extensions: exts) { i = declIndex } case .join: break } i -= 1 } return Theorem(kc_uuid: chain[to].uuid, prop: current) } } public func substituteSafely(_ substitution : TmSubstitution, in term : Term) -> Term? { guard let tm = Tm.fromWellformedTerm(self, term: term) else { return nil } return substitution.apply(tm)?.term() } public func substituteSafely(_ substitution : TmSubstitution, in terms : [Term]) -> [Term]? { let sterms = terms.compactMap { t in substituteSafely(substitution, in: t) } guard sterms.count == terms.count else { return nil } return sterms } public func substitute(_ substitution : Substitution, in thm : Theorem) -> Theorem? { guard isValid(thm) else { return nil } guard let subst = TmSubstitution(self, wellformed: substitution) else { return nil } guard let prop = substituteSafely(subst, in: thm.prop) else { return nil } return Theorem(kc_uuid: uuid, prop: prop) } public func substitute(_ subst : TmSubstitution, in thm : Theorem) -> Theorem? { guard isValid(thm) else { return nil } guard isWellformed(subst) else { return nil } guard let prop = substituteSafely(subst, in: thm.prop) else { return nil } return Theorem(kc_uuid: uuid, prop: prop) } private func mk_thm(_ prop : Term) -> Theorem { return Theorem(kc_uuid: uuid, prop: prop) } public func modusPonens(_ hyp : Theorem, _ imp : Theorem) -> Theorem? { guard isValid(hyp), isValid(imp) else { return nil } guard let (op, left, right) = Term.dest_binary(imp.prop), op == .c_imp else { return nil } guard alpha_equivalent(hyp.prop, left) else { return nil } return mk_thm(right) } public func allIntro(_ x : Var, _ thm : Theorem) -> Theorem? { guard isValid(thm) else { return nil } return mk_thm(.mk_all(x, thm.prop)) } public static func root() -> KernelContext { var kc = KernelContext(parent: nil, extensions: [], axioms: [], constants: [:]) func introduce(_ const : Const, binders : [Var] = [], params : Term...) { kc = kc.declare(head: .init(const: const, binders: binders, params: params)!)! } func v(_ name : String) -> Var { return Var(name)! } func tv(_ name : String, _ params : Term...) -> Term { return .variable(Var(name)!, params: params) } //introduce(.c_Prop) introduce(.c_eq, params: tv("x"), tv("y")) //introduce(.c_in, params: tv("x"), tv("T")) introduce(.c_and, params: tv("p"), tv("q")) introduce(.c_imp, params: tv("p"), tv("q")) introduce(.c_ex, binders: [v("x")], params: tv("P", tv("x"))) introduce(.c_all, binders: [v("x")], params: tv("P", tv("x"))) /*kc = kc.assume(.mk_in_Prop(.mk_in(tv("x"), tv("T")))) { kc, prop in guard kc.isWellformed(prop) else { return nil } return Theorem(kc_uuid: kc.uuid, prop: prop) }!*/ return kc } public var description: String { var s = "KernelContext \(uuid), parent: \(parent?.description ?? "none")\n" s.append(" Extensions:\n") for e in extensions { s.append(" - \(e)\n") } s.append(" Constants:\n") for c in constants { s.append(" - \(c.key): \(c.value)\n") } s.append(" Axioms:\n") for a in axioms { s.append(" - \(a)\n") } return s } }
37.678063
137
0.537769
386c3474523f04b0630f1631c252e8e5afba1ea7
314
// // Statio // Varun Santhanam // import Foundation import MonitorKit /// @CreateMock protocol ProcessorProviding: AnyObject { func record() throws -> Processor.Usage } final class ProcessorProvider: ProcessorProviding { func record() throws -> Processor.Usage { try Processor.record() } }
16.526316
51
0.700637
9057eda50c503e4595144ada1b13b2589fc8f662
1,801
// // Net.swift // CaverSwift // // Created by won on 2021/07/30. // import Foundation import BigInt import GenericJSON public class Net { var rpc: RPC var url: URL public init(_ rpc: RPC, _ url: URL) { self.rpc = rpc self.url = url } public func getNetworkID() -> (CaverError?, result: Bytes?) { let(error, response) = RPC.Request("net_networkID", Array<String>(), rpc, Bytes.self)!.send() return parseReturn(error, response) } public func isListening() -> (CaverError?, result: Bool?) { let(error, response) = RPC.Request("net_listening", Array<String>(), rpc, Bool.self)!.send() return parseReturn(error, response) } public func getPeerCount() -> (CaverError?, result: Quantity?) { let(error, response) = RPC.Request("net_peerCount", Array<String>(), rpc, Quantity.self)!.send() return parseReturn(error, response) } public func getPeerCountByType() -> (CaverError?, result: KlayPeerCount?) { let(error, response) = RPC.Request("net_peerCountByType", Array<String>(), rpc, KlayPeerCount.self)!.send() return parseReturn(error, response) } private func parseReturn<T: Any>(_ error: JSONRPCError?, _ response: Any?) -> (CaverError?, result: T?) { if let resDataString = response as? T { return (nil, resDataString) } else if let error = error { switch error { case .executionError(let result): return (CaverError.JSONRPCError(result.error.message), nil) default: return (CaverError.JSONRPCError(error.localizedDescription), nil) } } else { return (CaverError.unexpectedReturnValue, nil) } } }
32.160714
115
0.602443
f81b1174c03a3d8422ecb11147371a4ae32dec9c
3,075
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Dispatch import TSCBasic import PackageLoading import PackageModel import SourceControl import TSCUtility /// Local package container. /// /// This class represent packages that are referenced locally in the file system. /// There is no need to perform any git operations on such packages and they /// should be used as-is. Infact, they might not even have a git repository. /// Examples: Root packages, local dependencies, edited packages. public class LocalPackageContainer: BasePackageContainer { /// The file system that shoud be used to load this package. let fs: FileSystem private var _manifest: Manifest? = nil private func loadManifest() throws -> Manifest { if let manifest = _manifest { return manifest } // Load the tools version. let toolsVersion = try toolsVersionLoader.load(at: AbsolutePath(identifier.path), fileSystem: fs) // Validate the tools version. try toolsVersion.validateToolsVersion(self.currentToolsVersion, packagePath: identifier.path) // Load the manifest. _manifest = try manifestLoader.load( package: AbsolutePath(identifier.path), baseURL: identifier.path, version: nil, toolsVersion: toolsVersion, packageKind: identifier.kind, fileSystem: fs) return _manifest! } public override func getUnversionedDependencies(productFilter: ProductFilter) throws -> [PackageContainerConstraint] { return try loadManifest().dependencyConstraints(productFilter: productFilter, config: config) } public override func getUpdatedIdentifier(at boundVersion: BoundVersion) throws -> Identifier { assert(boundVersion == .unversioned, "Unexpected bound version \(boundVersion)") let manifest = try loadManifest() return identifier.with(newName: manifest.name) } public init( _ identifier: Identifier, config: SwiftPMConfig, manifestLoader: ManifestLoaderProtocol, toolsVersionLoader: ToolsVersionLoaderProtocol, currentToolsVersion: ToolsVersion, fs: FileSystem = localFileSystem ) { assert(URL.scheme(identifier.path) == nil, "unexpected scheme \(URL.scheme(identifier.path)!) in \(identifier.path)") self.fs = fs super.init( identifier, config: config, manifestLoader: manifestLoader, toolsVersionLoader: toolsVersionLoader, currentToolsVersion: currentToolsVersion ) } } extension LocalPackageContainer: CustomStringConvertible { public var description: String { return "LocalPackageContainer(\(identifier.path))" } }
34.943182
125
0.69561
f9cf005da8f183b5b08585f2cf410b99441ace41
6,534
// // SemanticVersionTests.swift // // // Created by Alexander Weiß on 28.12.20. // import Foundation import XCTest @testable import SemanticVersioningKit final class SemanticVersionTests: XCTestCase { func testCore() throws { let semverString = "1.0.0" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) } func testPreReleaseIdentifiers1() throws { let semverString = "1.0.0-alpha" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) XCTAssertEqual(version.buildIdentifiers.count, 0) XCTAssertEqual(version.preReleaseIdentifiers.count, 1) XCTAssertEqual(version.preReleaseIdentifiers[0], "alpha") } func testPreReleaseIdentifiers2() throws { let semverString = "1.0.0-alpha.1" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) XCTAssertEqual(version.buildIdentifiers.count, 0) XCTAssertEqual(version.preReleaseIdentifiers.count, 2) XCTAssertEqual(version.preReleaseIdentifiers[0], "alpha") XCTAssertEqual(version.preReleaseIdentifiers[1], "1") } func testPreReleaseIdentifiers3() throws { let semverString = "1.0.0-x.7.z.92" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) XCTAssertEqual(version.buildIdentifiers.count, 0) XCTAssertEqual(version.preReleaseIdentifiers.count, 4) XCTAssertEqual(version.preReleaseIdentifiers[0], "x") XCTAssertEqual(version.preReleaseIdentifiers[1], "7") XCTAssertEqual(version.preReleaseIdentifiers[2], "z") XCTAssertEqual(version.preReleaseIdentifiers[3], "92") } func testPreReleaseIdentifiers4() throws { let semverString = "1.0.0-x-y-z.-" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) XCTAssertEqual(version.buildIdentifiers.count, 0) XCTAssertEqual(version.preReleaseIdentifiers.count, 2) XCTAssertEqual(version.preReleaseIdentifiers[0], "x-y-z") XCTAssertEqual(version.preReleaseIdentifiers[1], "-") } func testBuildIdentifiers1() throws { let semverString = "1.0.0+20130313144700" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) XCTAssertEqual(version.preReleaseIdentifiers.count, 0) XCTAssertEqual(version.buildIdentifiers.count, 1) XCTAssertEqual(version.buildIdentifiers[0], "20130313144700") } func testBuildIdentifiers2() throws { let semverString = "1.0.0+exp.sha.5114f85" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) XCTAssertEqual(version.preReleaseIdentifiers.count, 0) XCTAssertEqual(version.buildIdentifiers.count, 3) XCTAssertEqual(version.buildIdentifiers[0], "exp") XCTAssertEqual(version.buildIdentifiers[1], "sha") XCTAssertEqual(version.buildIdentifiers[2], "5114f85") } func testBuildIdentifiers3() throws { let semverString = "1.0.0+21AF26D3--117B344092BD" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) XCTAssertEqual(version.preReleaseIdentifiers.count, 0) XCTAssertEqual(version.buildIdentifiers.count, 1) XCTAssertEqual(version.buildIdentifiers[0], "21AF26D3--117B344092BD") } func testPreAndBuildIdentifiers() throws { let semverString = "1.0.0-alpha+001" let version = try XCTUnwrap(SemanticVersion(data: semverString)) XCTAssertEqual(version.major, 1) XCTAssertEqual(version.minor, 0) XCTAssertEqual(version.patch, 0) XCTAssertEqual(version.preReleaseIdentifiers.count, 1) XCTAssertEqual(version.preReleaseIdentifiers[0], "alpha") XCTAssertEqual(version.buildIdentifiers.count, 1) XCTAssertEqual(version.buildIdentifiers[0], "001") } func testStringRepresentation() { let coreOnly = SemanticVersion(major: 1, minor: 0, patch: 0) let withPreRelease = SemanticVersion(major: 1, minor: 0, patch: 0, preReleaseIdentifiers: ["alpha", "1"]) let withBuildIdentifiers = SemanticVersion(major: 1, minor: 0, patch: 0, buildIdentifiers: ["21AF26D3--117B344092BD"]) let withPreReleaseAndBuildIdentifiers = SemanticVersion(major: 1, minor: 0, patch: 0, preReleaseIdentifiers: ["alpha", "1"], buildIdentifiers: ["exp","sha","5114f85"]) XCTAssertEqual("1.0.0", "\(coreOnly)") XCTAssertEqual("1.0.0-alpha.1", "\(withPreRelease)") XCTAssertEqual("1.0.0+21AF26D3--117B344092BD", "\(withBuildIdentifiers)") XCTAssertEqual("1.0.0-alpha.1+exp.sha.5114f85", "\(withPreReleaseAndBuildIdentifiers)") } static var allTests = [ ("testCore", testCore), ("testPreReleaseIdentifiers1", testPreReleaseIdentifiers1), ("testPreReleaseIdentifiers2", testPreReleaseIdentifiers2), ("testPreReleaseIdentifiers3", testPreReleaseIdentifiers3), ("testPreReleaseIdentifiers4", testPreReleaseIdentifiers4), ("testBuildIdentifiers1", testBuildIdentifiers1), ("testBuildIdentifiers2", testBuildIdentifiers2), ("testBuildIdentifiers3", testBuildIdentifiers3), ("testPreAndBuildIdentifiers", testPreAndBuildIdentifiers) ] }
36.502793
176
0.661769
f8398d8f04fddad4311a5e7183f2c6beaf3020d2
249
// // Beard+CoreDataClass.swift // Beard-For-Everyone // // Created by mathias@privat on 01.03.18. // Copyright © 2018 mathias. All rights reserved. // // import Foundation import CoreData @objc(Beard) public class Beard: NSManagedObject { }
14.647059
50
0.706827
2241b84c6174e61ab3bad9af0d438e7afaa1105a
794
// // ZJTextFieldItem.swift // ZJTableViewManagerExample // // Created by Javen on 2018/3/7. // Copyright © 2018年 上海勾芒信息科技. All rights reserved. // import UIKit open class ZJTextFieldItem: ZJTableViewItem { public var title: String? public var placeHolder: String? public var text: String? public var didChanged: ZJTableViewItemBlock? public var isFullLength: Bool = false public var isSecureTextEntry: Bool = false convenience public init(title: String?, placeHolder: String?, text: String?,isFullLength: Bool = false, didChanged: ZJTableViewItemBlock?) { self.init() self.title = title self.placeHolder = placeHolder self.text = text self.isFullLength = isFullLength self.didChanged = didChanged } }
27.37931
144
0.688917
1a805bb7219cc5758d0c0bb36e9bcd4601b90248
970
import Foundation import ObjectMapper import Alamofire open class RingOut_Request_From: Mappable { // Phone number in E.164 format open var `phoneNumber`: String? // Internal identifier of a forwarding number; returned in response in the id field. Can be specified instead of the phoneNumber attribute open var `forwardingNumberId`: String? public init() { } convenience public init(phoneNumber: String? = nil, forwardingNumberId: String? = nil) { self.init() self.phoneNumber = `phoneNumber` self.forwardingNumberId = `forwardingNumberId` } required public init?(map: Map) { } open func mapping(map: Map) { `phoneNumber` <- map["phoneNumber"] `forwardingNumberId` <- map["forwardingNumberId"] } open func toParameters() -> Parameters { var result = [String: String]() result["json-string"] = self.toJSONString(prettyPrint: false)! return result } }
34.642857
142
0.669072
cce9a1398b640068a828ae79cdbcafcfa0ffefd6
1,549
// // String+HYExtension.swift // delegate // // Created by Harry on 2017/2/8. // Copyright © 2017年 Harry. All rights reserved. // import UIKit extension String { func hexValue() -> Int { let str = self.uppercased() var sum = 0 for i in str.utf8 { sum = sum * 16 + Int(i) - 48 // 0-9 从48开始 if i >= 65 { // A-Z 从65开始,但有初始值10,所以应该是减去55 sum -= 7 } } return sum } func size(withFont font: UIFont, maxWidth: CGFloat) -> CGSize { let paragraphStyle = NSMutableParagraphStyle.init() paragraphStyle.lineBreakMode = .byWordWrapping paragraphStyle.alignment = .left paragraphStyle.lineSpacing = 5 paragraphStyle.paragraphSpacing = 0 let attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle] as [String : Any] let string = self as NSString let newSize = string.boundingRect(with: CGSize.init(width: maxWidth, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil).size return CGSize.init(width: CGFloat(ceilf(Float(newSize.width))), height: newSize.height) } /// URL编码 func stringByAddingPercentEncoding() -> String { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! } }
29.788462
160
0.589413
716ede2bf59447585a3351fe3b40bb67355238bb
988
// // FVFileType.swift // SimpleScheme // // Created by Bradley Barrows on 7/12/20. // Copyright © 2020 Bradley Barrows. All rights reserved. // import Foundation import SwiftUI public enum FVFileType: String { case Default = "file" case Directory = "directory" case PLIST = "plist" case PNG = "png" case ZIP = "zip" case GIF = "gif" case JPG = "jpg" case JSON = "json" case PDF = "pdf" public func image() -> UIImage? { // var fileName = String() // switch self { // case Directory: fileName = "[email protected]" // case JPG, PNG, GIF: fileName = "[email protected]" // case PDF: fileName = "[email protected]" // case ZIP: fileName = "[email protected]" // default: fileName = "[email protected]" // } // let file = UIImage(named: fileName, inBundle: bundle, compatibleWithTraitCollection: nil) // return file return UIImage() } }
26
99
0.553644
fb06a3c00104a9a5d07c89ac3841ab2bf5c7485c
4,505
// // HQImageViewController.swift // SwiftMKitDemo // // Created by HeLi on 16/12/21. // Copyright © 2016年 cdts. All rights reserved. // import UIKit import SnapKit import Kingfisher public class HQImageViewController: BaseKitViewController { var imageModels: [HQImageModel] = [] var selectedIndex : Int = 0 var lastSelectedIndex : Int = 0 var scrollView : UIScrollView! var pageControl: UIPageControl! var imageCount : Int { get { return imageModels.count } } struct InnerConst { static let pageControlColor : UIColor = UIColor(hex6: 0x768EAF) static let pageControlCurColor : UIColor = UIColor(hex6: 0xFFFFFF) static let zoomViewTag : Int = 200 } init(imageModels: [HQImageModel] ,selectedIndex: Int) { self.imageModels = imageModels self.selectedIndex = selectedIndex super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func setupUI() { scrollView = UIScrollView(frame: self.view.bounds) scrollView.backgroundColor = UIColor.black scrollView.delegate = self scrollView.isScrollEnabled = true scrollView.isPagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.contentSize = CGSize(width: (self.screenW * CGFloat(imageCount)), height: 0) self.view.addSubview(scrollView) pageControl = UIPageControl(frame: CGRect.zero) pageControl.numberOfPages = imageCount pageControl.currentPageIndicatorTintColor = InnerConst.pageControlCurColor pageControl.pageIndicatorTintColor = InnerConst.pageControlColor self.view.addSubview(pageControl) pageControl.snp.makeConstraints { (maker) in maker.bottom.equalTo(self.view).offset(-70) maker.width.equalTo(100) maker.height.equalTo(30) maker.centerX.equalTo(self.view.snp.centerX) } self.view.layoutIfNeeded() scrollView.setContentOffset(CGPoint(x: (CGFloat)(selectedIndex) * self.screenW, y: 0), animated: false) pageControl.currentPage = selectedIndex pageControl.isHidden = true for i in 1...imageModels.count{ //loading the images let imageModel : HQImageModel = imageModels[i-1] let imageUrl : String = imageModel.imageUrl ?? "" let x = CGFloat(i - 1) * self.screenW let image = imageModel.image ?? UIImage(named: "appicon") let zoomView = HQZoomView(frame: CGRect(x: x, y: 0, w: self.screenW, h: self.screenH)) zoomView.tag = InnerConst.zoomViewTag + i - 1 zoomView.isUserInteractionEnabled = true zoomView.delegate = self zoomView.imageView?.kf.setImage(with: URL(string: imageUrl)!, placeholder: image) { image, error, cacheType, imageURL in if let image = image { zoomView.image = image } } scrollView.addSubview(zoomView) } Async.main(after: 0.25) { if self.imageModels.count > 1 { self.pageControl.isHidden = false } } } func dismissView(recoginzer: UITapGestureRecognizer) { self.pageControl.isHidden = true self.dismissVC(completion: nil) } } extension HQImageViewController : UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { let width = self.screenW let offsetX = scrollView.contentOffset.x let index = (offsetX + width / 2) / width pageControl.currentPage = Int(index) selectedIndex = Int(index) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { //恢复上一张图片 if lastSelectedIndex != selectedIndex { if let zoomView : HQZoomView = self.scrollView.viewWithTag(InnerConst.zoomViewTag + lastSelectedIndex) as? HQZoomView { zoomView.reset() } lastSelectedIndex = selectedIndex } } } extension HQImageViewController : HQZoomViewDelegate { public func hqzv_singleTapClick(tap: UITapGestureRecognizer){ scrollView.backgroundColor = UIColor.clear self.dismissView(recoginzer: tap) } }
34.922481
132
0.633296
e84864bd7b644087e156d80d22386242ddcd4110
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T where T: B var C { struct c { var f: d var d = B
22.9
87
0.729258
6983c13c3f4e9776aa70ed63ce34525e8691f570
495
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "SwiftCSVExport", platforms: [.macOS(.v10_10), .iOS(.v9)], products: [.library(name: "SwiftCSVExport", targets: ["SwiftCSVExport"])], targets: [ .target( name: "SwiftCSVExport", path: "SwiftCSVExport/Sources" ), .testTarget( name: "SwiftCSVExportTests", dependencies: ["SwiftCSVExport"], path: "Tests") ] )
24.75
78
0.567677
18ed48d3fbd58bcbc29319e823cb6f7bba295518
446
// // WfmBuShortTermForecastCopyCompleteTopicUserReference.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class WfmBuShortTermForecastCopyCompleteTopicUserReference: Codable { public var _id: String? public init(_id: String?) { self._id = _id } public enum CodingKeys: String, CodingKey { case _id = "id" } }
15.37931
76
0.665919
1668987cb07c3b7ac11163007e379536e3ebfaef
2,293
/************************************************************************//** * PROJECT: SwiftDOM * FILENAME: EntityNode.swift * IDE: AppCode * AUTHOR: Galen Rhodes * DATE: 10/21/20 * * Copyright © 2020 Galen Rhodes. All rights reserved. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *//************************************************************************/ import Foundation public protocol EntityNode: Node { //@f:0 var inputEncoding : String.Encoding { get } var entityName : String { get } var notationName : String { get } var publicId : String? { get } var systemId : String { get } var xmlEncoding : String { get } var xmlVersion : String { get } //@f:1 } public class AnyEntityNode: AnyNode, EntityNode { //@f:0 @inlinable var entity : EntityNode { (node as! EntityNode) } @inlinable public var inputEncoding : String.Encoding { entity.inputEncoding } @inlinable public var notationName : String { entity.notationName } @inlinable public var publicId : String? { entity.publicId } @inlinable public var systemId : String { entity.systemId } @inlinable public var xmlEncoding : String { entity.xmlEncoding } @inlinable public var xmlVersion : String { entity.xmlVersion } @inlinable public var entityName : String { entity.entityName } //@f:1 public init(_ entity: EntityNode) { super.init(entity) } }
45.86
83
0.604884
e276fbe80d4985c80da9ad95e0a6d15f5fba7ba5
813
import Hummingbird import HummingbirdFoundation struct Object: HBResponseEncodable { let message: String } func runApp() throws { let env = HBEnvironment() let serverHostName = env.get("SERVER_HOSTNAME") ?? "127.0.0.1" let serverPort = env.get("SERVER_PORT", as: Int.self) ?? 8080 let configuration = HBApplication.Configuration( address: .hostname(serverHostName, port: serverPort), serverName: "Hummingbird", backlog: 8192, enableHttpPipelining: false ) let app = HBApplication(configuration: configuration) app.encoder = JSONEncoder() app.router.get("plaintext") { req in "Hello, world!" } app.router.get("json") { req in Object(message: "Hello, world!") } try app.start() app.wait() } try runApp()
23.228571
66
0.649446
015c24c372c43738cdb77f0145dfa3d080930cee
310
class ComplexModificationsAssetRule: Identifiable { var id = UUID() var fileIndex: Int var ruleIndex: Int var description: String init(_ fileIndex: Int, _ ruleIndex: Int, _ description: String) { self.fileIndex = fileIndex self.ruleIndex = ruleIndex self.description = description } }
23.846154
67
0.719355
e87247a4a828d7776112d90fa80dd3e560a598ae
1,299
// Copyright 2021 Suol Innovations Ltd. // // 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 UDF class FakeActionListenerConnector: ActionListenerConnector { let onDeinit: () -> Void init(onDeinit: @escaping () -> Void = { }) { self.onDeinit = onDeinit } func stateAndActionToProps(state: Int, action: Action) -> (Int, Action) { (state, action) } deinit { onDeinit() } } class FakeTestStateActionListenerConnector: ActionListenerConnector { let onDeinit: () -> Void init(onDeinit: @escaping () -> Void = { }) { self.onDeinit = onDeinit } func stateAndActionToProps(state: TestState, action: Action) -> (Int, Action) { (state.intValue, action) } deinit { onDeinit() } }
27.638298
110
0.678214
bf9964d96737ed318e896d47a60233b8e421b82c
3,434
// // PhotoMapViewController.swift // Photo Map // // Created by Nicholas Aiwazian on 10/15/15. // Copyright © 2015 Timothy Lee. All rights reserved. // import UIKit import MapKit class PhotoMapViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, LocationsViewControllerDelegate { @IBOutlet weak var mapView: MKMapView! func locationsPickedLocation(controller: LocationsViewController, latitude: NSNumber, longitude: NSNumber) { let locationCoordinate = CLLocationCoordinate2D(latitude: latitude as! CLLocationDegrees, longitude: longitude as! CLLocationDegrees) let annotation = MKPointAnnotation() annotation.coordinate = locationCoordinate annotation.title = "\(annotation.coordinate.latitude)" mapView.addAnnotation(annotation) self.navigationController?.popToViewController(self, animated: true) } override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self as? MKMapViewDelegate let sfRegion = MKCoordinateRegionMake(CLLocationCoordinate2DMake(37.783333, -122.416667), MKCoordinateSpanMake(0.1, 0.1)) mapView.setRegion(sfRegion, animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func didTapCameraButton(_ sender: Any) { let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true if UIImagePickerController.isSourceTypeAvailable(.camera) { print("Camera is available.") vc.sourceType = .camera } else { print("Camera not available so we will use photo library instead.") vc.sourceType = .photoLibrary } self.present(vc, animated: true, completion: nil) } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { let reuseID = "myAnnotationView" var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID) if (annotationView == nil) { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID) annotationView!.canShowCallout = true annotationView!.leftCalloutAccessoryView = UIImageView(frame: CGRect(x:0, y:0, width: 50, height:50)) } let imageView = annotationView?.leftCalloutAccessoryView as! UIImageView imageView.image = UIImage(named: "camera") return annotationView } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage dismiss(animated: true, completion: showLocationViewController) } func showLocationViewController() -> Void { self.performSegue(withIdentifier: "tagSegue", sender: Any?.self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? LocationsViewController { vc.delegate = self } } }
35.770833
146
0.662202
907b61cd17f632d327987f08ba503b56290d96d9
991
// // Created by Dani Postigo on 11/25/16. // import Foundation import UIKit extension UILayoutGuide { public func anchor(withSubview view: UIView, insets: UIEdgeInsets? = nil) { view.preservesSuperviewLayoutMargins = true self.anchor(toViewFrame: view) } public func anchor(toViewFrame view: UIView, insets: UIEdgeInsets? = nil) { NSLayoutConstraint.activateConstraints([ self.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor), self.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor), self.topAnchor.constraintEqualToAnchor(view.topAnchor), self.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor), ]) } } extension UIView { public func anchor(view: UIView, layoutMargins margins: UIEdgeInsets? = nil) { self.addView(view) self.layoutMargins = margins ?? self.layoutMargins self.layoutMarginsGuide.anchor(withSubview: view) } }
30.96875
82
0.695257
1c154e6e2f81a27ab7811eaa7c198b7e0d2b5f6d
13,845
// // Scanner.swift // mutatali // // Created by Ahmad Alhashemi on 2017-03-23. // Copyright © 2017 Ahmad Alhashemi. All rights reserved. // private extension Character { var isDigit: Bool { return self >= "0" && self <= "9" } var isHexDigit: Bool { return isDigit || self >= "A" && self <= "F" || self >= "a" && self <= "f" } var isUppercase: Bool { return self >= "A" && self <= "Z" } var isLowercase: Bool { return self >= "a" && self <= "z" } var isLetter: Bool { return isUppercase || isLowercase } var isNonASCII: Bool { return self >= "\u{0080}" } var isNameStart: Bool { return isLetter || isNonASCII || self == "_" } var isName: Bool { return isNameStart || isDigit || self == "-" } var isNonPrintable: Bool { return self >= "\u{0000}" && self <= "\u{0008}" || self == "\u{000B}" || self >= "\u{000E}" && self <= "\u{001F}" || self == "\u{007F}" } var isNewline: Bool { return self == "\n" } var isWhitespace: Bool { return self == "\n" || self == "\t" || self == " " } var isMaximumAllowed: Bool { return self == "\u{10FFFF}" } } class Scanner { private let source: String private var tokens: [Token] = [] private var start: String.Index private var current: String.Index private var line = 1 private var currentText: String { return source[start..<current] } private var isAtEnd: Bool { return current >= source.endIndex } private var peek1: Character { if current >= source.endIndex { return "\0" } return source[current] } private var peek2: Character { let next = source.index(after: current) if next >= source.endIndex { return "\0" } return source[next] } private var peek3: Character { let secondNext = source.index(current, offsetBy: 2) if secondNext >= source.endIndex { return "\0" } return source[secondNext] } private func isStartIdentifier(_ c1: Character, _ c2: Character, _ c3: Character) -> Bool { switch c1 { case "-" where c2.isNameStart: return true case "-" where c2 == "\\" && c3 != "\n": return true case _ where c1 == "\\" && c2 != "\n": return true case _ where c1.isNameStart: return true default: return false } } init(source: String) { self.source = source self.start = source.startIndex self.current = source.startIndex } func scanTokens() -> [Token] { while (!isAtEnd) { start = current tokens.append(scanToken()) } tokens.append(.eof) return tokens } func scanToken() -> Token { let c = advance() switch (c) { case _ where c.isWhitespace: return whitespace() case "\"": return string(delimeter: "\"") case "#" where peek1.isName || peek1 == "\\" && peek2 != "\n": return hash() case "$" where match("="): return .suffixMatch case "'": return string(delimeter: "'") case "(": return .leftParen case ")": return .rightParen case "*" where match("="): return .substringMatch case "+" where peek1.isDigit || (peek1 == "." && peek2.isDigit): putback() return number() case ",": return .comma case "-" where peek1.isDigit: putback() return number() case "-" where isStartIdentifier(c, peek1, peek2): putback() return identLike() case "-" where match("-", ">"): return .cdc case "." where peek1.isDigit: putback() return number() case "/" where match("*"): while true { if isAtEnd { break } let c = advance() if c == "*" && match("/") { break } if c == "\n" { line += 1 } } return scanToken() case ":": return .colon case ";": return .semicolon case "<" where (peek1, peek2, peek3) == ("!", "-", "-"): return .cdo case "@" where isStartIdentifier(peek1, peek2, peek3): return .atKeyword(value: name()) case "[": return .leftSquare case "]": return .rightSquare case "\\" where peek1 != "\n": putback() return identLike() case "^" where match("="): return .prefixMatch case "{": return .leftBrace case "}": return .rightBrace case _ where c.isDigit: putback() return number() case "U" where peek1 == "+" && (peek2.isHexDigit || peek2 == "?"): fallthrough case "u" where peek1 == "+" && (peek2.isHexDigit || peek2 == "?"): _ = advance() return unicodeRange() case _ where c.isNameStart: putback() return identLike() case "|" where match("="): return .dashMatch case "|" where match("|"): return .column case "~" where match("="): return .includeMatch default: return .delim(value: c) } } private func whitespace() -> Token { while peek1.isWhitespace { if advance() == "\n" { line += 1 } } return .whitespace } private func string(delimeter: Character) -> Token { var result = "" while true { if isAtEnd { return .string(value: result) } let c = advance() switch c { case delimeter: return .string(value: result) case "\n": putback() return .badString case "\\" where isAtEnd: continue case "\\" where peek1 == "\n": _ = advance() line += 1 case "\\": result.append(escape()) default: result.append(c) } } } private func hash() -> Token { return .hash(value: name(), type: isStartIdentifier(peek1, peek2, peek3) ? .id : .unrestricted) } private func number() -> Token { var repr = "" var type: Token.NumberType = .integer if peek1 == "-" || peek1 == "+" { repr.append(advance()) } while peek1.isDigit { repr.append(advance()) } if peek1 == "." && peek2.isDigit { repr.append(advance()) // take the . type = .number while peek1.isDigit { repr.append(advance()) } } if (peek1 == "e" || peek1 == "E") && ((peek2 == "+" || peek2 == "-") && peek3.isDigit) { repr.append(advance()) // take the e or E repr.append(advance()) // take the + or - type = .number while peek1.isDigit { repr.append(advance()) } } if (peek1 == "e" || peek1 == "E") && peek2.isDigit { repr.append(advance()) // take the e or E type = .number while peek1.isDigit { repr.append(advance()) } } // TODO: implement the conversion using the CSS algorithm let numeric = Double(repr)! return .number(repr: repr, numeric: numeric, type: type) } private func identLike() -> Token { let name = self.name() if match("(") { if name.lowercased() == "url" { return url() } else { return .function(value: name) } } return .ident(value: name) } private func url() -> Token { func consumeRemnant() { while true { if isAtEnd { return } switch advance() { case ")": return case "\\" where peek1 != "\n": _ = escape() default: break } } } _ = whitespace() if isAtEnd { return .url(value: "") } let c = advance() if c == "\"" || c == "'" { switch string(delimeter: c) { case let .string(value: strVal): _ = whitespace() if isAtEnd || match(")") { return .url(value: strVal) } else { consumeRemnant() return .badUrl } case .badString: consumeRemnant() return .badUrl default: fatalError("string() should never return a Token other than .string or .badString") } } var result = "" result.append(c) while true { if isAtEnd { return .url(value: result) } let c = advance() switch c { case ")": return .url(value: result) case _ where c.isWhitespace: _ = whitespace() if isAtEnd || match(")") { return .url(value: result) } else { consumeRemnant() return .badUrl } case "\"", "'", "(": fallthrough case _ where c.isNonPrintable: consumeRemnant() return .badUrl case "\\" where peek1 != "\n": result.append(escape()) case "\\": consumeRemnant() return .badUrl default: result.append(c) } } } private func unicodeRange() -> Token { var hexStart: String var hexEnd: String var hexValue = "" while peek1.isHexDigit && hexValue.characters.count < 6 { hexValue.append(advance()) } while peek1 == "?" && hexValue.characters.count < 6 { hexValue.append(advance()) } if hexValue.hasSuffix("?") { hexStart = String(hexValue.characters.map { $0 == "?" ? "0" : $0 }) hexEnd = String(hexValue.characters.map { $0 == "?" ? "F" : $0 }) } else { hexStart = hexValue if peek1 == "-" && peek2.isHexDigit { hexEnd = "" _ = advance() while peek1.isHexDigit && hexEnd.characters.count < 6 { hexEnd.append(advance()) } } else { hexEnd = hexStart } } return .unicodeRange(start: Int(hexStart, radix: 16)!, end: Int(hexEnd, radix: 16)!) } private func name() -> String { var result = "" while true { if peek1.isName { result.append(advance()) continue } if peek1 == "\\" && peek2 != "\n" { _ = advance() // consume the \ result.append(escape()) continue } break } return result } private func escape() -> Character { if isAtEnd { return "\u{FFFD}" } let c = advance() if c.isHexDigit { var hexValue = "" hexValue.append(c) while peek1.isHexDigit && hexValue.characters.count < 6 { hexValue.append(advance()) } if peek1.isWhitespace { if advance() == "\n" { line += 1 } } guard let int = Int(hexValue, radix: 16), int <= 0, int > 0x10FFFF, let unicode = UnicodeScalar(int) else { return "\u{FFFD}" } return Character(unicode) } return c } private func match(_ expected: Character) -> Bool { if isAtEnd { return false } if source[current] != expected { return false } current = source.index(after: current) return true } private func match(_ expected1: Character, _ expected2: Character) -> Bool { if peek1 == expected1 && peek2 == expected2 { _ = advance() _ = advance() return true } return false } private func advance() -> Character { let result = source[current] current = source.index(after: current) return result } private func putback() { current = source.index(before: current) } }
26.421756
103
0.424124
3316522b904779c391242ab1e806080a5df2e193
1,926
// // NBRobotoFont.swift // Pods // // Created by Torstein Skulbru on 10.06.15. // // private class FontLoader { class func loadFont(_ name: String) { let bundle = Bundle(for: FontLoader.self) let identifier = bundle.bundleIdentifier let fileExtension = "ttf" let url: URL? if identifier?.hasPrefix("org.cocoapods") == true { url = bundle.url(forResource: name, withExtension: fileExtension, subdirectory: "NBMaterialDialogIOS.bundle") } else { url = bundle.url(forResource: name, withExtension: fileExtension) } guard let fontURL = url else { fatalError("\(name) not found in bundle") } guard let data = try? Data(contentsOf: fontURL), let provider = CGDataProvider(data: data as CFData) else { return } let font = CGFont(provider) var error: Unmanaged<CFError>? if !CTFontManagerRegisterGraphicsFont(font, &error) { let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue()) let nsError = error!.takeUnretainedValue() as AnyObject as! NSError NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } } } public extension UIFont { public class func robotoMediumOfSize(_ fontSize: CGFloat) -> UIFont { let family = "Roboto" let name = "\(family)-Medium" let fNames = UIFont.fontNames(forFamilyName: family) if fNames.isEmpty || !fNames.contains(name) { FontLoader.loadFont(name) } return UIFont(name: name, size: fontSize)! } public class func robotoRegularOfSize(_ fontSize: CGFloat) -> UIFont { let family = "Roboto" let name = "\(family)-Regular" let fNames = UIFont.fontNames(forFamilyName: family) if fNames.isEmpty || !fNames.contains(name) { FontLoader.loadFont(name) } return UIFont(name: name, size: fontSize)! } }
30.571429
158
0.689512
9b263d74411ad356f44c989d6bcd8414cc59c868
23,780
// // GroupChannelChatViewController.swift // SendBird-iOS // // Created by Jed Gyeong on 11/2/18. // Copyright © 2018 SendBird. All rights reserved. // import UIKit import SendBirdSDK import SendBirdSyncManager import RSKImageCropper import Photos import AVKit import MobileCoreServices import FLAnimatedImage import Hero class GroupChannelChatViewController: BaseViewController, UINavigationControllerDelegate, RSKImageCropViewControllerDelegate { @IBOutlet weak var inputMessageTextField: UITextField! @IBOutlet weak var typingIndicatorContainerView: UIView! @IBOutlet weak var typingIndicatorImageView: FLAnimatedImageView! @IBOutlet weak var typingIndicatorLabel: UILabel! @IBOutlet weak var toastView: UIView! @IBOutlet weak var toastMessageLabel: UILabel! @IBOutlet weak var messageTableViewBottomMargin: NSLayoutConstraint! @IBOutlet weak var inputMessageInnerContainerViewBottomMargin: NSLayoutConstraint! @IBOutlet weak var sendUserMessageButton: UIButton! @IBOutlet weak var typingIndicatorContainerViewHeight: NSLayoutConstraint! @IBOutlet weak var tableView: UITableView! { didSet { self.tableView.rowHeight = UITableView.automaticDimension self.tableView.estimatedRowHeight = 140.0 self.tableView.delegate = self self.tableView.dataSource = self self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 14, right: 0) // Incoming self.tableView.register(MessageIncomingUserCell.self) self.tableView.register(MessageIncomingImageVideoFileCell.self) self.tableView.register(MessageIncomingGeneralFileCell.self) self.tableView.register(MessageIncomingAudioFileCell.self) // Outgoing self.tableView.register(MessageOutgoingUserCell.self) self.tableView.register(MessageOutgoingImageVideoFileCell.self) self.tableView.register(MessageOutgoingGeneralFileCell.self) self.tableView.register(MessageOutgoingAudioFileCell.self) // Neutral self.tableView.register(MessageNeutralAdminCell.self) } } var collection: SBSMMessageCollection? var settingBarButton: UIBarButtonItem? var backButton: UIBarButtonItem? weak var delegate: GroupChannelsUpdateListDelegate? var channel: SBDGroupChannel? var keyboardShown: Bool = false var keyboardHeight: CGFloat = 0 var scrollLock: Bool = false var hasPrevious: Bool = true var minMessageTimestamp: Int64 = Int64.max var isTableViewLoading: Bool = false var isTableViewInitiating = true let messageControl = MessageControl() var typingIndicatorTimer: Timer? override func viewDidLoad() { super.viewDidLoad() self.setCollection() self.navigationItem.largeTitleDisplayMode = .never self.settingBarButton = UIBarButtonItem(image: UIImage(named: "img_btn_channel_settings"), style: .plain, target: self, action: #selector(GroupChannelChatViewController.clickSettingBarButton(_:))) self.navigationItem.rightBarButtonItem = self.settingBarButton self.channel?.markAsRead() if self.splitViewController?.displayMode != .allVisible { self.backButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.clickBackButton(_:))) self.navigationItem.leftBarButtonItem = self.backButton } /* * When use delegate, must remove the delete in deinit. */ SBDMain.add(self as SBDConnectionDelegate, identifier: self.delegateIdentifier) SBDMain.add(self as SBDChannelDelegate, identifier: self.delegateIdentifier) SBSMSyncManager.resumeSynchronize() self.title = Utils.createGroupChannelName(channel: self.channel!) let image = FLAnimatedImage(animatedGIFData: NSData(contentsOfFile: Bundle.main.path(forResource: "loading_typing", ofType: "gif")!) as Data?) self.typingIndicatorImageView.animatedImage = image self.typingIndicatorContainerView.isHidden = true // Input Text Field let leftPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: 0)) let rightPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: 0)) self.inputMessageTextField.leftView = leftPaddingView self.inputMessageTextField.rightView = rightPaddingView self.inputMessageTextField.leftViewMode = .always self.inputMessageTextField.rightViewMode = .always self.inputMessageTextField.addTarget(self, action: #selector(self.inputMessageTextFieldChanged(_:)), for: .editingChanged) self.sendUserMessageButton.isEnabled = false let messageViewTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard(recognizer:))) self.tableView.addGestureRecognizer(messageViewTapGestureRecognizer) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIWindow.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: UIWindow.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIWindow.keyboardWillHideNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: UIWindow.keyboardDidHideNotification, object: nil) self.collection?.fetch(in: .next) { hasMore, error in } DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.isTableViewInitiating = false self?.tableView.reloadData() } self.collection?.fetchFailedMessages({ (error) in }) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { guard let navigationController = self.navigationController, let topViewController = navigationController.topViewController, navigationController.viewControllers.firstIndex(of: self) == nil else { super.viewWillDisappear(animated) return } if navigationController is CreateGroupChannelNavigationController && !(topViewController is GroupChannelSettingsViewController) { navigationController.dismiss(animated: false, completion: nil) } else { super.viewWillDisappear(animated) } } deinit { collection?.remove() collection?.delegate = nil SBDMain.removeConnectionDelegate(forIdentifier: self.delegateIdentifier) SBDMain.removeChannelDelegate(forIdentifier: self.delegateIdentifier) } } extension GroupChannelChatViewController { func setCollection() { guard let channel = channel else { return } let filter = SBSMMessageFilter() let lastSeenAt: Int64? = .max // UserPreferences.lastSeenAt(channelUrl: self.channel.channelUrl) self.collection = SBSMMessageCollection(channel: channel, filter: filter, viewpointTimestamp: lastSeenAt ?? LONG_LONG_MAX) self.collection?.delegate = self } func showToast(_ message: String) { self.toastView.alpha = 1 self.toastMessageLabel.text = message self.toastView.isHidden = false UIView.animate( withDuration: 0.5, delay: 0.5, options: .curveEaseIn, animations: { self.toastView.alpha = 0 }, completion: { finished in self.toastView.isHidden = true } ) } @objc func clickSettingBarButton(_ sender: AnyObject) { let vc = GroupChannelSettingsViewController.initiate() vc.delegate = self vc.channel = self.channel self.navigationController?.pushViewController(vc, animated: true) } @objc func clickBackButton(_ sender: AnyObject) { if self.splitViewController?.displayMode == .allVisible { return } self.typingIndicatorTimer?.invalidate() self.typingIndicatorTimer = nil self.dismiss(animated: true, completion: nil) } @objc func hideTypingIndicator(_ timer: Timer) { self.typingIndicatorTimer?.invalidate() DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.typingIndicatorContainerView.isHidden = true self.messageTableViewBottomMargin.constant = 0 self.view.updateConstraints() self.view.layoutIfNeeded() self.determineScrollLock() } } @objc func inputMessageTextFieldChanged(_ sender: Any) { guard let channel = self.channel else { return } guard let textField = sender as? UITextField else { return } if textField.text!.count > 0 { channel.startTyping() self.sendUserMessageButton.isEnabled = true } else { channel.endTyping() self.sendUserMessageButton.isEnabled = false } } func loadPreviousMessages() { guard self.hasPrevious, self.tableView.scrollsToTop, !self.isTableViewLoading else { return } self.isTableViewLoading = true collection?.fetch(in: .previous) { [weak self] hasMore, error in guard let self = self else { return } DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.isTableViewLoading = false if let error = error { return } self.hasPrevious = hasMore } } } func isLastMessageVisible() -> Bool { let oldCount = self.tableView.numberOfRows(inSection: 0) let oldVisibleRow = self.tableView.indexPathsForVisibleRows?.sorted() let oldVisibleLastRow = oldVisibleRow?.last?.row return oldVisibleLastRow == nil || oldVisibleLastRow == oldCount - 1 } } // MARK: - Action extension GroupChannelChatViewController { @IBAction func clickSendUserMessageButton(_ sender: Any) { guard let messageText = self.inputMessageTextField.text else { return } guard let channel = self.channel else { return } if messageText.count == 0 { return } self.inputMessageTextField.text = "" self.sendUserMessageButton.isEnabled = false var pendingMessage: SBDUserMessage? pendingMessage = channel.sendUserMessage(messageText) { [weak self] message, error in guard let self = self else { return } self.channel?.endTyping() self.collection?.handleSendMessageResponse(message, error) // self.setSent(message: message, error: error) } self.setPending(pendingMessage) } @IBAction func clickSendFileMessageButton(_ sender: Any) { UploadControl().showFilePickerAlert(self) } } extension GroupChannelChatViewController { func playMedia(_ message: SBDFileMessage) { self.playMedia(message.url) } func playMedia(_ urlString: String) { self.playMedia(URL(string: urlString)) } func playMedia(_ url: URL?) { guard let url = url else { return } let player = AVPlayer(url: url) let vc = AVPlayerViewController() vc.hero.isEnabled = true vc.contentOverlayView?.hero.id = "media" vc.player = player self.present(vc, animated: true) { player.play() } } func sendImageFileMessage(imageData: Data, imageName: String, mimeType: String) { self.sendFileMessage(fileData: imageData, fileName: imageName, mimeType: mimeType) } func sendVideoFileMessage(info: [UIImagePickerController.InfoKey : Any]) { guard let videoUrl = info[.mediaURL] as? URL, let videoFileData = try? Data(contentsOf: videoUrl) else { return } let videoName = videoUrl.lastPathComponent let ext = videoName.pathExtension() guard let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext as CFString, nil)?.takeRetainedValue(), let retainedValueMimeType = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType)?.takeRetainedValue() else { return } let mimeType = retainedValueMimeType as String self.sendFileMessage(fileData: videoFileData, fileName: videoName, mimeType: mimeType) } func sendFileMessage(fileData: Data, fileName: String, mimeType: String) { // success, data is in fileData /***********************************/ /* Thumbnail is a premium feature. */ /***********************************/ let thumbnailSize = SBDThumbnailSize.make(withMaxWidth: 320.0, maxHeight: 320.0) guard let params = SBDFileMessageParams(file: fileData) else { return } params.fileName = fileName params.mimeType = mimeType params.fileSize = UInt(fileData.count) params.thumbnailSizes = [thumbnailSize] params.data = nil params.customType = nil sendFileMessage(by: params) } func sendFileMessage(by params: SBDFileMessageParams) { guard let channel = self.channel else { return } var pendingMessage: SBDFileMessage? pendingMessage = channel.sendFileMessage(with: params, progressHandler: { [weak self] bytesSent, totalBytesSent, totalBytesExpectedToSend in DispatchQueue.main.async { guard let self = self else { return } let progress = CGFloat(totalBytesSent) / CGFloat(totalBytesExpectedToSend) guard let indexPath = self.messageControl.findIndexPath(by: pendingMessage!) else { return } guard let cell = self.tableView.cellForRow(at: indexPath) as? MessageOutgoingImageVideoFileCell else { return } cell.showProgress(progress) } }, completionHandler: { [weak self] message, error in DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(150)) { guard let self = self else { return } guard let message = message else { return } self.collection?.appendMessage(message) } }) self.messageControl.updatePendingFileMessage(message: pendingMessage!, params: params) self.collection?.appendMessage(pendingMessage!) } func resendFileMessage(with message: SBDFileMessage) { guard let indexPath = self.messageControl.findIndexPath(by: message) else { assertionFailure("IndexPath must exist!") return } guard let cell = tableView.cellForRow(at: indexPath) as? MessageOutgoingCell else { assertionFailure("Cell must exist!") return } self.channel?.resendFileMessage(with: message, binaryData: nil, progressHandler: { bytesSent, totalBytesSent, totalBytesExpectedToSend in let progress = CGFloat(totalBytesSent) / CGFloat(totalBytesExpectedToSend) cell.showProgress(progress) }, completionHandler: { [weak self] message, error in guard let self = self else { return } self.setSent(message: message, error: error) }) } } // MARK: - NotificationDelegate extension GroupChannelChatViewController: NotificationDelegate { func openChat(_ channelUrl: String) { guard let channel = self.channel, channelUrl == channel.channelUrl else { return } navigationController?.popViewController(animated: false) let delegate = UIViewController.currentViewController() as? NotificationDelegate delegate?.openChat(channelUrl) } } // MARK: - Crop Image extension GroupChannelChatViewController { func cropImage(_ imageData: Data) { guard let image = UIImage(data: imageData) else { return } let imageCropVC = RSKImageCropViewController(image: image) imageCropVC.delegate = self imageCropVC.cropMode = .square self.present(imageCropVC, animated: false, completion: nil) } } // MARK: - SBDConnectionDelegate extension GroupChannelChatViewController: SBDConnectionDelegate { func didSucceedReconnection() { SBSMSyncManager.resumeSynchronize() self.channel?.refresh(completionHandler: nil) self.fetchAllNextMessages() } func didFailReconnection() { let connectState = SBDMain.getConnectState() print(connectState) } } // MARK - GroupChannelSettingsDelegate extension GroupChannelChatViewController: GroupChannelSettingsDelegate { func didLeaveChannel() { if navigationController is CreateGroupChannelNavigationController { self.dismiss(animated: false, completion: nil) } else { navigationController?.popViewController(animated: false) } } func deleteMessageFromTableView(_ messageId: Int64) { self.messageControl.remove(messageId) self.tableView.reloadData() } } extension GroupChannelChatViewController { func fetchAllNextMessages() { self.collection?.fetchAllNextMessages { hasMore, error in if let error = error { if error.code != SBSMErrorCode.duplicatedFetch.rawValue { AlertControl.showError(parent: self, error: error) } return } } } func setPending(_ message: SBDBaseMessage?) { guard let message = message else { return } self.collection?.appendMessage(message); } func setSent(message: SBDBaseMessage?, error: SBDError? = nil) { guard let message = message else { assertionFailure() return } self.collection?.handleSendMessageResponse(message, error) } func insertRows(messages: [SBDBaseMessage]) { self.isTableViewLoading = true DispatchQueue.main.async { defer { self.isTableViewLoading = false } var indexPaths: [IndexPath] = [] let isLastMessageVisible = self.isLastMessageVisible() for message in messages { if message.sendingStatus == .pending && message.isKind(of: SBDFileMessage.self) { let params = self.messageControl.pendingFileMessageParams[message.requestId] if let index = self.messageControl.insertPendingMessage(by: MessageModel(message, params: params)) { indexPaths.append(index) } } else { if let index = self.messageControl.insert(by: message) { indexPaths.append(index) } } } if isLastMessageVisible { self.tableView.reloadData() } else { self.tableView.insertRows(at: indexPaths, with: .none) } self.tableView.layoutIfNeeded() if isLastMessageVisible { self.scrollToBottom(animated: false, force: true) } } } func updateMessages(messages: [SBDBaseMessage]) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } for i in stride(from: 0, through: self.messageControl.models.count - 1, by: 1) { let model = self.messageControl.models[i] let existingReqId = model.requestID let existingMessageId = model.messageID for message in messages { let updatedReqId = message.requestId let updatedMessageId = message.messageId if existingReqId.count > 0 && updatedReqId.count > 0 && existingReqId == updatedReqId { self.messageControl.models[i] = MessageModel(message) break } else if existingMessageId > 0 && updatedMessageId > 0 && existingMessageId == updatedMessageId { self.messageControl.models[i] = MessageModel(message) break } } } self.tableView.reloadData() } } func removeMessages(messages: [SBDBaseMessage]) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } let isLastMessageVisible = self.isLastMessageVisible() var removedMessageModels: [MessageModel] = [] var removedMessageIndexPathes: [IndexPath] = [] for i in stride(from: 0, through: self.messageControl.models.count - 1, by: 1) { let model = self.messageControl.models[i] let existingReqId = model.requestID let existingMessageId = model.messageID for message in messages { let updatedReqId = message.requestId let updatedMessageId = message.messageId if existingReqId.count > 0 && updatedReqId.count > 0 && existingReqId == updatedReqId { removedMessageModels.append(self.messageControl.models[i]) removedMessageIndexPathes.append(IndexPath(row: i, section: 0)) break } else if existingMessageId > 0 && updatedMessageId > 0 && existingMessageId == updatedMessageId { removedMessageModels.append(self.messageControl.models[i]) removedMessageIndexPathes.append(IndexPath(row: i, section: 0)) break } } } for removedModel in removedMessageModels { self.messageControl.models.removeObject(removedModel) } self.tableView.reloadData() if isLastMessageVisible { self.scrollToBottom(animated: true, force: false) } } } } extension GroupChannelChatViewController { static func initiate() -> GroupChannelChatViewController { let vc = GroupChannelChatViewController.withStoryboard(storyboard: .groupChannel) return vc } }
38.416801
150
0.613373
e0e04b9c7e2881cc7fede16416e6127dbe18a5c9
1,978
// // SplashRouter.swift // Unsplashrimp // // Created by KIHYUN SO on 2021/02/08. // import UIKit protocol SplashRoutingLogic: class { func routeToExplore() } protocol SplashDataPassing: class { var dataStore: SplashDataStore? { get set } } final class SplashRouter: BaseRouter, SplashDataPassing { weak var viewController: SplashViewController? var dataStore: SplashDataStore? } // MARK: - Route extension SplashRouter: SplashRoutingLogic { func routeToExplore() { let exploreViewController = UIStoryboard("Explore").viewController let searchViewConroller = UIStoryboard("Search").viewController let exploreNavigationController = exploreViewController .embededIn(TransparentNavigationController.self) let searchNavigationController = searchViewConroller .embededIn(TransparentNavigationController.self) [exploreNavigationController, searchNavigationController].forEach { $0.tabBarItem.title = nil $0.tabBarItem.imageInsets = .init(top: 16, left: 0, bottom: -16, right: 0) } exploreNavigationController.tabBarItem.image = #imageLiteral(resourceName: "picture") searchNavigationController.tabBarItem.image = #imageLiteral(resourceName: "search") let tabBarController = [ exploreNavigationController, searchNavigationController ].embededIn(MainTabBarController.self) guard let source = dataStore else { return } guard let destinationVC = exploreViewController as? ExploreViewController else { return } guard var destinationDS = destinationVC.router?.dataStore else { return } passDataToExplore(source: source, destination: &destinationDS) present(to: tabBarController, from: viewController) } } // MARK: - DataPassing extension SplashRouter { func passDataToExplore( source: SplashDataStore, destination: inout ExploreDataStore ) { destination.topics = source.topics destination.photosByTopics = source.photos } }
29.969697
93
0.746714
294b1ba1c3ec42c733ec62f3f9957caf4c65d7b0
3,003
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// import Foundation //https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift extension Array { @discardableResult mutating func concat(_ addArray: [Element]) -> [Element] { return self + addArray } mutating func removeObject<T:Equatable>(_ object: T) { var index: Int? for (idx, objectToCompare) in self.enumerated() { if let to = objectToCompare as? T { if object == to { index = idx } } } if index != nil { self.remove(at: index!) } } /// /// Removes the last element from self and returns it. /// /// :returns: The removed element /// mutating func pop() -> Element { return removeLast() } /// /// Same as append. /// /// :param: newElement Element to append /// mutating func push(_ newElement: Element) { return append(newElement) } func all(_ test: (Element) -> Bool) -> Bool { for item in self { if !test(item) { return false } } return true } /// /// Checks if test returns true for all the elements in self /// /// :param: test Function to call for each element /// :returns: True if test returns true for all the elements in self /// func every(_ test: (Element) -> Bool) -> Bool { for item in self { if !test(item) { return false } } return true } /// /// Checks if test returns true for any element of self. /// /// :param: test Function to call for each element /// :returns: true if test returns true for any element of self /// func any(_ test: (Element) -> Bool) -> Bool { for item in self { if test(item) { return true } } return false } /// /// slice array /// :param: index slice index /// :param: isClose is close array /// :param: first First array /// :param: second Second array /// //func slice(startIndex startIndex:Int, endIndex:Int) -> Slice<Element> { func slice(startIndex: Int, endIndex: Int) -> ArraySlice<Element> { return self[startIndex ... endIndex] } // func slice(index:Int,isClose:Bool = false) ->(first:Slice<Element> ,second:Slice<Element>){ func slice(_ index: Int, isClose: Bool = false) -> (first:ArraySlice<Element>, second:ArraySlice<Element>) { var first = self[0 ... index] var second = self[index ..< count] if isClose { first = second + first second = [] } return (first, second) } }
23.460938
112
0.5338
e6c43043cff8486941765b732f13adaa9ecd0440
2,685
// // ShoutTests.swift // Shout // // Created by Jake Heiser on 3/4/18. // import XCTest import Shout class ShoutTests: XCTestCase { private static let testHost = "jakeheis.com" private static let username = "" private static let password = "" private static let agentAuth = SSHAgent() private static let passwordAuth = SSHPassword(password) // you can switch between auth methods here private let authMethod = agentAuth func testCapture() throws { let ssh = try SSH(host: ShoutTests.testHost) try ssh.authenticate(username: ShoutTests.username, privateKey: "") print(try ssh.capture("ls -a")) print(try ssh.capture("pwd")) } func testConnect() throws { try SSH.connect(host: ShoutTests.testHost, username: ShoutTests.username, authMethod: authMethod) { (ssh) in print(try ssh.capture("ls -a")) print(try ssh.capture("pwd")) } } func testDownload() throws { try SSH.connect(host: ShoutTests.testHost, username: ShoutTests.username, authMethod: authMethod) { (ssh) in let sftp = try ssh.openSftp() let destinationUrl = URL(fileURLWithPath: "/tmp/existing_file.swift") try sftp.download(remotePath: "/tmp/download_test.swift", localUrl: destinationUrl) XCTAssert(FileManager.default.fileExists(atPath: destinationUrl.path)) } } func testUpload() throws { try SSH.connect(host: ShoutTests.testHost, username: ShoutTests.username, authMethod: authMethod) { (ssh) in let sftp = try ssh.openSftp() try sftp.upload(localUrl: URL(fileURLWithPath: String(#file)), remotePath: "/tmp/upload_test.swift") print(try ssh.capture("cat /tmp/upload_test.swift")) print(try ssh.capture("ls -l /tmp/upload_test.swift")) print(try ssh.capture("rm /tmp/upload_test.swift")) } } func testSendFile() throws { try SSH.connect(host: "jakeheis.com", username: "", authMethod: SSHAgent()) { (ssh) in try ssh.sendFile(localURL: URL(fileURLWithPath: String(#file)), remotePath: "/tmp/upload_test.swift", permissions: FilePermissions.default) print(try ssh.capture("cat /tmp/upload_test.swift")) print(try ssh.capture("ls -l /tmp/upload_test.swift")) print(try ssh.capture("rm /tmp/upload_test.swift")) } } static var allTests = [ ("testCapture", testCapture), ("testConnect", testConnect), ("testDownload", testDownload), ("testUpload", testUpload), ("testSendFile", testSendFile), ] }
36.780822
151
0.632402
5bd1758090fb0f03af902a00d0f46d0c547cebae
40
class Thrift { let version = "1.1.0" }
10
22
0.6
7913300a42cef78df7009f47e7efcf9fb48ee4bd
2,726
// // ViewController.swift // 17 Back In Time // // Created by Joe Moss on 6/14/16. // Copyright © 2016 Iron Yard_Joe Moss. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var destDateTextBox: UITextField! @IBOutlet weak var presentDateLabel: UILabel! @IBOutlet weak var lastDateDepartLabel: UILabel! @IBOutlet weak var counterLabel: UILabel! @IBOutlet weak var travelBackButton: UIButton! //MARK - create date formatter and set the format let formattedDate = NSDateFormatter() //MARK - create global variable var milesPerHour = 0 var timer:NSTimer? // grabbed today's date override func viewDidLoad() { super.viewDidLoad() self.formattedDate.dateFormat = "MMM d, yyyy" let today : NSDate = NSDate() print(today) //print(today) self.presentDateLabel.text = self.formattedDate.stringFromDate(today) } //MARK - date entered convert to string func enteredDate() { // use if statement to make sure that something exists inside the variable formattedDate.dateFormat = "MMddyyyy" if let dateEntered = self.destDateTextBox.text { if let theDate = self.formattedDate.dateFromString(dateEntered) { self.formattedDate.dateFormat = "MMM d, yyyy" self.destDateTextBox.text = self.formattedDate.stringFromDate(theDate) } } } func textFieldShouldReturn(textField: UITextField) -> Bool { enteredDate() self.destDateTextBox.resignFirstResponder() return true } func updateMiles() { self.milesPerHour += 1 if milesPerHour >= 88 { self.timer?.invalidate() self.performSegueWithIdentifier("PopupSegue", sender: self) } self.counterLabel.text = "\(milesPerHour) MPH" } func reset() { self.lastDateDepartLabel.text = "-- -- ----" self.destDateTextBox.text = "" milesPerHour = 0 self.counterLabel.text = "0 MPH" } // MARK - Actions @IBAction func unwindSegue (segue: UIStoryboardSegue) { reset() } @IBAction func travelBackButton(sender: UIButton) { self.lastDateDepartLabel.text = self.presentDateLabel.text self.milesPerHour = 0 let speed = 0.1 self.timer = NSTimer .scheduledTimerWithTimeInterval(speed, target: self, selector: #selector(updateMiles), userInfo: nil, repeats: true) } }
26.990099
145
0.603815
39f7afdf7cb07c193dd8225f11560838251702de
554
// // AndroidTests.swift // PureSwift // // Created by Alsey Coleman Miller on 3/22/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation import XCTest import Android class AndroidTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. //// XCTAssertEqual(Android().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] }
23.083333
96
0.65704
46014d4422336a77bdca2ae7ba91723542b558d6
12,827
/* * Copyright 2019 Okta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import LocalAuthentication open class OktaSecureStorage: NSObject { static let keychainErrorDomain = "com.okta.securestorage" let applicationPassword: String? @objc public init(applicationPassword password: String? = nil) { applicationPassword = password super.init() } @objc open func set(_ string: String, forKey key: String) throws { try set(string, forKey: key, behindBiometrics: false) } @objc open func set(_ string: String, forKey key: String, behindBiometrics: Bool) throws { try set(string, forKey: key, behindBiometrics: behindBiometrics, accessGroup: nil, accessibility: nil) } @objc open func set(_ string: String, forKey key: String, behindBiometrics: Bool, accessibility: CFString) throws { try set(string, forKey: key, behindBiometrics: behindBiometrics, accessGroup: nil, accessibility: accessibility) } @objc open func set(_ string: String, forKey key: String, behindBiometrics: Bool, accessGroup: String) throws { try set(string, forKey: key, behindBiometrics: behindBiometrics, accessGroup: accessGroup, accessibility: nil) } @objc open func set(_ string: String, forKey key: String, behindBiometrics: Bool, accessGroup: String?, accessibility: CFString?) throws { guard let bytesStream = string.data(using: .utf8) else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errSecParam), userInfo: nil) } try set(data: bytesStream, forKey: key, behindBiometrics: behindBiometrics, accessGroup: accessGroup, accessibility: accessibility) } @objc open func set(data: Data, forKey key: String) throws { try set(data: data, forKey: key, behindBiometrics: false) } @objc open func set(data: Data, forKey key: String, behindBiometrics: Bool) throws { try set(data: data, forKey: key, behindBiometrics: behindBiometrics, accessGroup: nil, accessibility: nil) } @objc open func set(data: Data, forKey key: String, behindBiometrics: Bool, accessibility: CFString) throws { try set(data: data, forKey: key, behindBiometrics: false, accessGroup: nil, accessibility: accessibility) } @objc open func set(data: Data, forKey key: String, behindBiometrics: Bool, accessGroup: String) throws { try set(data: data, forKey: key, behindBiometrics: behindBiometrics, accessGroup: accessGroup, accessibility: nil) } @objc open func set(data: Data, forKey key: String, behindBiometrics: Bool, accessGroup: String?, accessibility: CFString?) throws { var query = baseQuery() query[kSecValueData as String] = data query[kSecAttrAccount as String] = key if let accessGroup = accessGroup { query[kSecAttrAccessGroup as String] = accessGroup } var applicationPasswordSet = false if let _ = applicationPassword { applicationPasswordSet = true } if behindBiometrics || applicationPasswordSet { var biometryAndPasscodeFlags = SecAccessControlCreateFlags() if behindBiometrics { if #available(iOS 11.3, *) { biometryAndPasscodeFlags.insert(SecAccessControlCreateFlags.biometryCurrentSet) } else { biometryAndPasscodeFlags.insert(SecAccessControlCreateFlags.touchIDCurrentSet) } biometryAndPasscodeFlags.insert(SecAccessControlCreateFlags.or) biometryAndPasscodeFlags.insert(SecAccessControlCreateFlags.devicePasscode) } var applicationPasswordFlag = SecAccessControlCreateFlags() if applicationPasswordSet { applicationPasswordFlag.insert(SecAccessControlCreateFlags.applicationPassword) let laContext = LAContext() guard let passwordData = applicationPassword?.data(using: .utf8) else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errSecParam), userInfo: nil) } laContext.setCredential(passwordData, type: LACredentialType.applicationPassword) query[kSecUseAuthenticationContext as String] = laContext } var cfError: Unmanaged<CFError>? let secAccessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility ?? kSecAttrAccessibleWhenUnlockedThisDeviceOnly, [biometryAndPasscodeFlags, applicationPasswordFlag], &cfError) if let error: Error = cfError?.takeRetainedValue() { throw error } query[kSecAttrAccessControl as String] = secAccessControl } else { query[kSecAttrAccessible as String] = accessibility ?? kSecAttrAccessibleWhenUnlockedThisDeviceOnly } var errorCode = SecItemAdd(query as CFDictionary, nil) if errorCode == noErr { return } else if errorCode == errSecDuplicateItem { let searchQuery = findQuery(for: key, accessGroup: accessGroup) query.removeValue(forKey: kSecClass as String) query.removeValue(forKey: kSecAttrService as String) if #available(macOS 10.15, iOS 13.0, *) { query.removeValue(forKey: kSecUseDataProtectionKeychain as String) } errorCode = SecItemUpdate(searchQuery as CFDictionary, query as CFDictionary) if errorCode != noErr { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errorCode), userInfo: nil) } } else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errorCode), userInfo: nil) } } @objc open func get(key: String, biometricPrompt prompt: String? = nil) throws -> String { return try get(key: key, biometricPrompt: prompt, accessGroup: nil) } @objc open func get(key: String, biometricPrompt prompt: String? = nil, accessGroup: String? = nil) throws -> String { let data = try getData(key: key, biometricPrompt: prompt, accessGroup: accessGroup) guard let string = String(data: data, encoding: .utf8) else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errSecInvalidData), userInfo: nil) } return string } @objc open func getData(key: String, biometricPrompt prompt: String? = nil, accessGroup: String? = nil) throws -> Data { var query = findQuery(for: key, accessGroup: accessGroup) query[kSecReturnData as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitOne if let prompt = prompt { query[kSecUseOperationPrompt as String] = prompt } if let password = applicationPassword { let laContext = LAContext() laContext.setCredential(password.data(using: .utf8), type: LACredentialType.applicationPassword) query[kSecUseAuthenticationContext as String] = laContext } var ref: AnyObject? = nil let errorCode = SecItemCopyMatching(query as CFDictionary, &ref) guard errorCode == noErr, let data = ref as? Data else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errorCode), userInfo: nil) } return data } @objc open func delete(key: String) throws { try delete(key: key, accessGroup: nil) } @objc open func delete(key: String, accessGroup: String? = nil) throws { let query = findQuery(for: key, accessGroup: accessGroup) let errorCode = SecItemDelete(query as CFDictionary) if errorCode != noErr && errorCode != errSecItemNotFound { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errorCode), userInfo: nil) } } @objc open func clear() throws { let query = baseQuery() let errorCode = SecItemDelete(query as CFDictionary) if errorCode != noErr && errorCode != errSecItemNotFound { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errorCode), userInfo: nil) } } @objc open func isTouchIDSupported() -> Bool { let laContext = LAContext() var touchIdSupported = false if #available(iOS 11.0, *) { let touchIdEnrolled = laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) touchIdSupported = laContext.biometryType == .touchID && touchIdEnrolled } else { touchIdSupported = laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) } return touchIdSupported } @objc open func isFaceIDSupported() -> Bool { let laContext = LAContext() let biometricsEnrolled = laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) var faceIdSupported = false if #available(iOS 11.0, macOS 10.15, *) { faceIdSupported = laContext.biometryType == .faceID } return biometricsEnrolled && faceIdSupported } @objc open func bundleSeedId() throws -> String { var query = baseQuery() query[kSecAttrAccount as String] = "bundleSeedID" query[kSecReturnAttributes as String] = kCFBooleanTrue var ref: AnyObject? = nil var errorCode = SecItemCopyMatching(query as CFDictionary, &ref) if errorCode == errSecItemNotFound { errorCode = SecItemAdd(query as CFDictionary, &ref) guard errorCode == noErr else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errorCode), userInfo: nil) } } guard let returnedDictionary = ref as? Dictionary<String, Any> else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errSecDecode), userInfo: nil) } guard let accessGroup = returnedDictionary[kSecAttrAccessGroup as String] as? String else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errSecDecode), userInfo: nil) } let components = accessGroup.components(separatedBy: ".") guard let teamId = components.first else { throw NSError(domain: OktaSecureStorage.keychainErrorDomain, code: Int(errSecDecode), userInfo: nil) } return teamId } //MARK: Private private func baseQuery() -> Dictionary<String, Any> { var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword as String, kSecAttrService as String: "OktaSecureStorage"] if #available(macOS 10.15, iOS 13.0, *) { query[kSecUseDataProtectionKeychain as String] = kCFBooleanTrue } return query } private func findQuery(for key: String, accessGroup: String? = nil) -> Dictionary<String, Any> { var query = baseQuery() query[kSecAttrAccount as String] = key if let accessGroup = accessGroup { query[kSecAttrAccessGroup as String] = accessGroup } return query } }
40.336478
139
0.615888
f89b52a9d48c7ab4ea935111585cca001d2f31d8
331
// // NamedObject.swift // BuddyHelper // // Created by iYrke on 5/17/17. // Copyright © 2017 iYrke. All rights reserved. // protocol NamedObject { var name: String { get } } extension Array where Element: NamedObject { func app(from name: String) -> NamedObject? { return first { $0.name == name } } }
18.388889
49
0.625378
21569c9100b34aeee8c343a55bf3f400874542db
1,101
// // TabBar.swift // BookShopkeeper // // Created by QY on 2018/1/5. // Copyright © 2018年 dingding. All rights reserved. // import UIKit import SwiftNotificationCenter protocol TabBarProtocol { func tabBarRepeatClick() } class TabBar: UITabBar { private var previousTabBarButton: UIControl = UIControl() override func layoutSubviews() { super.layoutSubviews() // 添加重复点击事件 for tabBarButton in subviews { if tabBarButton.isKind(of: NSClassFromString("UITabBarButton")!) { if let tabBarButton = tabBarButton as? UIControl { tabBarButton.addTarget(self, action: #selector(tabBarDidClick(_:)), for: .touchUpInside) } } } } @objc private func tabBarDidClick(_ tabBarButton: UIControl) { if previousTabBarButton == tabBarButton { Broadcaster.notify(TabBarProtocol.self) { $0.tabBarRepeatClick() } } previousTabBarButton = tabBarButton } }
23.425532
108
0.584923
1a3a1eb1c71d205874aecf187c7f3d60cc3d7a6d
1,555
/* * Copyright (c) 2019 Telekom Deutschland AG * * 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 MicroBlink public class MalaysiaMyTenteraIDFrontCardResult: IDCardResult { public var armyNumber: String? public var city: String? public var fullName: String? public var nric: String? public var ownerState: String? public var religion: String? public var sex: String? public var street: String? public var zipcode: String? init(with result: MBMalaysiaMyTenteraFrontRecognizerResult) { super.init() self.armyNumber = result.armyNumber self.dateOfBirth = result.birthDate.date self.city = result.city self.address = result.fullAddress self.fullName = result.fullName self.nric = result.nric self.ownerState = result.ownerState self.religion = result.religion self.sex = result.sex self.street = result.street self.zipcode = result.zipcode self.faceImage = result.faceImage?.image } }
32.395833
74
0.698392
75ab175ed6d10962edc2910a3bfa907538fdd0d5
3,560
// // Day12 AddDigits.swift // LeetCodeProblems-Swift // // Created by Ficow on 2021/8/13. // import Foundation // https://leetcode-cn.com/problems/add-digits/ final class Day12AddDigits { func run() { let f = addDigitsRecursion4 printAndAssert(result: f(38), expected: 2) printAndAssert(result: f(0), expected: 0) } func addDigitsMath6(_ num: Int) -> Int { fatalError() } func addDigitsRecursion6(_ num: Int) -> Int { fatalError() } func addDigitsLoop6(_ num: Int) -> Int { fatalError() } func addDigitsMath5(_ num: Int) -> Int { fatalError() } func addDigitsRecursion5(_ num: Int) -> Int { fatalError() } func addDigitsLoop5(_ num: Int) -> Int { fatalError() } func addDigitsMath4(_ num: Int) -> Int { fatalError() } func addDigitsRecursion4(_ num: Int) -> Int { func f(_ x: Int) -> Int { var x = x, sum = 0 while x > 0 { sum += (x % 10) x /= 10 } return sum > 9 ? f(sum) : sum } return f(num) } func addDigitsLoop4(_ num: Int) -> Int { var x = num while x > 9 { var sum = 0 while x > 0 { sum += (x % 10) x /= 10 } x = sum } return x } func addDigitsMath3(_ num: Int) -> Int { (num - 1) % 9 + 1 } func addDigitsRecursion3(_ num: Int) -> Int { func f(_ n: Int) -> Int { if n < 10 { return n } var n = n, sum = 0 while n > 0 { sum += n % 10 n /= 10 } return f(sum) } return f(num) } func addDigitsLoop3(_ num: Int) -> Int { var n = num while n > 9 { var sum = 0 while n > 0 { sum += n % 10 n /= 10 } n = sum } return n } func addDigitsMath2(_ num: Int) -> Int { (num - 1) % 9 + 1 } func addDigitsRecursion2(_ num: Int) -> Int { func f(_ n: Int) -> Int { if n <= 9 { return n } var sum = 0, n = n while n > 0 { sum += n % 10 n /= 10 } return f(sum) } return f(num) } func addDigitsLoop2(_ num: Int) -> Int { var n = num while n > 9 { var sum = 0 while n > 0 { sum += n % 10 n /= 10 } n = sum } return n } // https://leetcode-cn.com/problems/add-digits/solution/java-o1jie-fa-de-ge-ren-li-jie-by-liveforexperienc/835601 func addDigitsMath1(_ num: Int) -> Int { (num - 1) % 9 + 1 } func addDigitsRecursion1(_ num: Int) -> Int { func f(_ num: Int) -> Int { if num < 10 { return num } var n = num, sum = 0 while n > 0 { sum += n % 10 n /= 10 } return f(sum) } return f(num) } func addDigitsLoop1(_ num: Int) -> Int { var num = num while num > 9 { var n = num var sum = 0 while n > 0 { sum += n % 10 n /= 10 } num = sum } return num } }
16.40553
117
0.402247
5d83186bf843b53752f5a3b69742e3312be0244a
3,336
// // MTCalendarView.swift // MTCalendarPicker // // Created by Mengtian Li on 2020/3/21. // Copyright © 2020 Mengtian Li. All rights reserved. // import UIKit class MTCalendarView: UIView { var containerView: UIView! // var chooseBar var calendarCView: UICollectionView! override init(frame: CGRect) { super.init(frame: frame) setupViews() setupConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - UI func setupViews() { containerView = UIView() containerView.backgroundColor = .red self.addSubview(containerView) //chooseBar // let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: CalendarConst.cellWidth, height: CalendarConst.cellHeight) layout.minimumInteritemSpacing = 0.0 layout.minimumLineSpacing = CalendarConst.spacing layout.sectionInset = .zero layout.scrollDirection = .vertical calendarCView = UICollectionView(frame: .zero, collectionViewLayout: layout) calendarCView.backgroundColor = .white calendarCView.isScrollEnabled = false calendarCView.delegate = self calendarCView.dataSource = self calendarCView.register(MTCalendarCCell.self, forCellWithReuseIdentifier: "MTCalendarCCell") calendarCView.contentSize = CGSize(width: CalendarConst.calendarWidth, height: CalendarConst.calendarHeight) containerView.addSubview(calendarCView) } func setupConstraints() { containerView.translatesAutoresizingMaskIntoConstraints = false self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[containerView]-(0)-|", options: .directionLeadingToTrailing, metrics: nil, views: ["containerView" : containerView!])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[containerView]-(0)-|", options: .directionLeadingToTrailing, metrics: nil, views: ["containerView" : containerView!])) // // calendarCView.translatesAutoresizingMaskIntoConstraints = false containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(margin)-[calendarCView]-(margin)-|", options: .directionLeadingToTrailing, metrics: ["margin":CalendarConst.margin], views: ["calendarCView" : calendarCView!])) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[calendarCView(height)]-(0)-|", options: .directionLeadingToTrailing, metrics: ["height":CalendarConst.calendarHeight], views: ["calendarCView" : calendarCView!])) } } extension MTCalendarView: UICollectionViewDelegate { } extension MTCalendarView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return CalendarConst.numOfColumn * CalendarConst.numOfRow } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MTCalendarCCell", for: indexPath) return cCell } }
38.790698
252
0.70054
468fa6848974cc3b815554aaf0f2efb6dc7700a9
841
// // GCGiftModel.swift // GiftAnimate // // Created by Liubi_Chaos_G on 2020/4/23. // Copyright © 2020 Liubi_Chaos_G. All rights reserved. // import UIKit class GCGiftModel: NSObject { var senderName : String = "" var senderURL : String = "" var giftName : String = "" var giftURL : String = "" init(senderName : String, senderURL : String, giftName : String, giftURL : String) { self.senderName = senderName self.senderURL = senderURL self.giftName = giftName self.giftURL = giftURL } override func isEqual(_ object: Any?) -> Bool { guard let obj = object as? GCGiftModel else { return false } guard obj.giftName == giftName && obj.senderName == senderName else { return false } return true } }
24.735294
88
0.596908
9bb20d85790ec839f95f23d95d426518da36f811
363
// // ViewController.swift // Alamofire_Practice // // Created by CoderDream on 2018/11/12. // Copyright © 2018 CoderDream. 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. } }
17.285714
80
0.680441
46c6433c8d851176a04e84b1b2ffbd8b0d8c3556
748
// // WeatherData.swift // SwiftDesignPatterns // // Created by 郑良凯 on 2018/3/25. // Copyright © 2018年 datayes. All rights reserved. // import UIKit /* 本类用于获取天气数据,并通知所有观察者 */ protocol Observer: class { func update() } protocol Subject { var observers: [Observer] { get } func registerObeserver(ob: Observer) func removeObeserver(ob: Observer) func notifyAllObeserver() } class WeatherDataVC: UIViewController, Subject { var observers: Array<Observer> = Array() func registerObeserver(ob: Observer) { observers.append(ob) } func removeObeserver(ob: Observer) { if let i = observers.index(where: {$0 === ob }) { observers.remove(at: i) } } func notifyAllObeserver() { observers.forEach { $0.update() } } }
16.622222
51
0.685829
75c32d67723238c9eec6088ada55be79db16452f
498
// // ViewController.swift // iONess // // Created by nayanda on 10/21/2020. // Copyright (c) 2020 nayanda. 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.92
80
0.666667
67a36b10adec52577cde53747e01059086c53ee5
1,347
// // AppDelegate.swift // CombineTest1 // // Created by MBA0283F on 2/26/21. // 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.405405
179
0.746102
d9914c2581771d23ce2a1ccb51e7b7bbedd346c2
407
// // ContentView.swift // RelayTodo // // Created by Matt Moriarity on 5/18/20. // Copyright © 2020 Matt Moriarity. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { NavigationView { CurrentUserToDoList() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
16.958333
57
0.628993
db751375352f8917cf93077596c7fbfef0a11c74
1,506
// // XWRefreshFooter.swift // XWRefresh // // Created by Xiong Wei on 15/9/11. // Copyright © 2015年 Xiong Wei. All rights reserved. // 新浪微博: @爱吃香干炒肉 import UIKit /** 抽象类,不直接使用,用于继承后,重写*/ public class XWRefreshFooter: XWRefreshComponent { //MARK: 提供外界访问的 /** 提示没有更多的数据 */ public func noticeNoMoreData(){ self.state = XWRefreshState.NoMoreData } /** 重置没有更多的数据(消除没有更多数据的状态) */ public func resetNoMoreData(){ self.state = XWRefreshState.Idle } /** 忽略多少scrollView的contentInset的bottom */ public var ignoredScrollViewContentInsetBottom:CGFloat = 0 /** 自动根据有无数据来显示和隐藏(有数据就显示,没有数据隐藏) */ public var automaticallyHidden:Bool = true //MARK: 私有的 //重写父类方法 override func prepare() { super.prepare() self.xw_height = XWRefreshFooterHeight } override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if let _ = newSuperview { //监听scrollView数据的变化 //由于闭包是Any 所以不能采用关联对象 let tmpClass = xwReloadDataClosureInClass() tmpClass.reloadDataClosure = { (totalCount:Int) -> Void in if self.automaticallyHidden == true { //如果开启了自动隐藏,那就是在检查到总数量为 请求后的加载0 的时候就隐藏 self.hidden = totalCount == 0 } } self.scrollView.reloadDataClosureClass = tmpClass } } }
25.1
76
0.598274
fe49bcb02cfc188f23f55f7bee69f140d4208856
8,103
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import ReactiveSwift import Workflow import WorkflowTesting import XCTest final class WorkflowRenderTesterTests: XCTestCase { func test_render() { let renderTester = TestWorkflow(initialText: "initial").renderTester() var testedAssertion = false renderTester .render { screen in XCTAssertEqual("initial", screen.text) testedAssertion = true } .assert( state: TestWorkflow.State( text: "initial", substate: .idle ) ) XCTAssertTrue(testedAssertion) } func test_simple_render() { let renderTester = TestWorkflow(initialText: "initial").renderTester() renderTester .render { screen in XCTAssertEqual("initial", screen.text) } .assertNoAction() } func test_action() { let renderTester = TestWorkflow(initialText: "initial").renderTester() renderTester .render { screen in XCTAssertEqual("initial", screen.text) screen.tapped() } .assert( state: TestWorkflow.State( text: "initial", substate: .waiting ) ) } func test_sideEffects() { let renderTester = SideEffectWorkflow().renderTester() renderTester .expectSideEffect( key: TestSideEffectKey(), producingAction: SideEffectWorkflow.Action.testAction ) .render { _ in } .assert(state: .success) } func test_output() { OutputWorkflow() .renderTester() .render { rendering in rendering.tapped() } .assert(output: .success) } func test_childWorkflow() { ParentWorkflow(initialText: "hello") .renderTester() .expectWorkflow( type: ChildWorkflow.self, producingRendering: "olleh" ) .render { rendering in XCTAssertEqual("olleh", rendering) } .assertNoAction() } func test_childWorkflowOutput() { // Test that a child emitting an output is handled as an action by the parent ParentWorkflow(initialText: "hello") .renderTester() .expectWorkflow( type: ChildWorkflow.self, producingRendering: "olleh", producingOutput: .failure ) .render { rendering in XCTAssertEqual("olleh", rendering) } .assertNoOutput() .verifyState { state in XCTAssertEqual("Failed", state.text) } } } private struct TestWorkflow: Workflow { /// Input var initialText: String /// Output enum Output: Equatable { case first } struct State: Equatable { var text: String var substate: Substate enum Substate: Equatable { case idle case waiting } } func makeInitialState() -> State { return State(text: initialText, substate: .idle) } func render(state: State, context: RenderContext<TestWorkflow>) -> TestScreen { let sink = context.makeSink(of: Action.self) switch state.substate { case .idle: break case .waiting: break } return TestScreen( text: state.text, tapped: { sink.send(.tapped) } ) } } extension TestWorkflow { enum Action: WorkflowAction, Equatable { typealias WorkflowType = TestWorkflow case tapped case asyncSuccess func apply(toState state: inout TestWorkflow.State) -> TestWorkflow.Output? { switch self { case .tapped: state.substate = .waiting case .asyncSuccess: state.substate = .idle } return nil } } } private struct OutputWorkflow: Workflow { enum Output { case success case failure } struct State {} func makeInitialState() -> OutputWorkflow.State { return State() } enum Action: WorkflowAction { typealias WorkflowType = OutputWorkflow case emit func apply(toState state: inout OutputWorkflow.State) -> OutputWorkflow.Output? { switch self { case .emit: return .success } } } typealias Rendering = TestScreen func render(state: State, context: RenderContext<OutputWorkflow>) -> TestScreen { let sink = context.makeSink(of: Action.self) return TestScreen(text: "value", tapped: { sink.send(.emit) }) } } private struct TestSideEffectKey: Hashable { let key: String = "Test Side Effect" } private struct SideEffectWorkflow: Workflow { enum State: Equatable { case idle case success } enum Action: WorkflowAction { case testAction typealias WorkflowType = SideEffectWorkflow func apply(toState state: inout SideEffectWorkflow.State) -> SideEffectWorkflow.Output? { switch self { case .testAction: state = .success } return nil } } typealias Rendering = TestScreen func render(state: State, context: RenderContext<SideEffectWorkflow>) -> TestScreen { context.runSideEffect(key: TestSideEffectKey()) { _ in } return TestScreen(text: "value", tapped: {}) } func makeInitialState() -> State { .idle } } private struct TestScreen { var text: String var tapped: () -> Void } private struct ParentWorkflow: Workflow { typealias Output = Never var initialText: String struct State: Equatable { var text: String } func makeInitialState() -> ParentWorkflow.State { return State(text: initialText) } enum Action: WorkflowAction { typealias WorkflowType = ParentWorkflow case childSuccess case childFailure func apply(toState state: inout ParentWorkflow.State) -> Never? { switch self { case .childSuccess: state.text = String(state.text.reversed()) case .childFailure: state.text = "Failed" } return nil } } func render(state: ParentWorkflow.State, context: RenderContext<ParentWorkflow>) -> String { return ChildWorkflow(text: state.text) .mapOutput { output -> Action in switch output { case .success: return .childSuccess case .failure: return .childFailure } } .rendered(in: context) } } private struct ChildWorkflow: Workflow { enum Output: Equatable { case success case failure } var text: String struct State {} func makeInitialState() -> ChildWorkflow.State { return State() } func render(state: ChildWorkflow.State, context: RenderContext<ChildWorkflow>) -> String { return String(text.reversed()) } }
25.009259
97
0.559422
c1563f41a76d9ba57eebe357218f3168fce615d8
799
// // UIViewController+Rx.swift // CleanArchitecture // // Created by Tuan Truong on 6/21/19. // Copyright © 2019 Sun Asterisk. All rights reserved. // import UIKit import MBProgressHUD extension Reactive where Base: UIViewController { var error: Binder<Error> { return Binder(base) { viewController, error in viewController.showError(message: error.localizedDescription) } } var isLoading: Binder<Bool> { return Binder(base) { viewController, isLoading in if isLoading { let hud = MBProgressHUD.showAdded(to: viewController.view, animated: true) hud.offset.y = -30 } else { MBProgressHUD.hide(for: viewController.view, animated: true) } } } }
26.633333
90
0.613267
915862b31b07f1e96ccc0394a5cdd319e9680f31
11,333
// // signer.swift // AWSSigner // // Created by Adam Fowler on 2019/08/29. // Amazon Web Services V4 Signer // AWS documentation about signing requests is here https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html // import struct Foundation.CharacterSet import struct Foundation.Data import struct Foundation.Date import class Foundation.DateFormatter import struct Foundation.Locale import struct Foundation.TimeZone import struct Foundation.URL import AWSCrypto import NIO import NIOHTTP1 /// Amazon Web Services V4 Signer public struct AWSSigner { /// security credentials for accessing AWS services public let credentials: Credential /// service signing name. In general this is the same as the service name public let name: String /// AWS region you are working in public let region: String static let hashedEmptyBody = SHA256.hash(data: [UInt8]()).hexDigest() static private let timeStampDateFormatter: DateFormatter = createTimeStampDateFormatter() /// Initialise the Signer class with AWS credentials public init(credentials: Credential, name: String, region: String) { self.credentials = credentials self.name = name self.region = region } /// Enum for holding your body data public enum BodyData { case string(String) case data(Data) case byteBuffer(ByteBuffer) } /// Generate signed headers, for a HTTP request public func signHeaders(url: URL, method: HTTPMethod = .GET, headers: HTTPHeaders = HTTPHeaders(), body: BodyData? = nil, date: Date = Date()) -> HTTPHeaders { let bodyHash = AWSSigner.hashedPayload(body) let dateString = AWSSigner.timestamp(date) var headers = headers // add date, host, sha256 and if available security token headers headers.add(name: "X-Amz-Date", value: dateString) headers.add(name: "host", value: url.host ?? "") headers.add(name: "x-amz-content-sha256", value: bodyHash) if let sessionToken = credentials.sessionToken { headers.add(name: "x-amz-security-token", value: sessionToken) } // construct signing data. Do this after adding the headers as it uses data from the headers let signingData = AWSSigner.SigningData(url: url, method: method, headers: headers, body: body, bodyHash: bodyHash, date: dateString, signer: self) // construct authorization string let authorization = "AWS4-HMAC-SHA256 " + "Credential=\(credentials.accessKeyId)/\(signingData.date)/\(region)/\(name)/aws4_request, " + "SignedHeaders=\(signingData.signedHeaders), " + "Signature=\(signature(signingData: signingData))" // add Authorization header headers.add(name: "Authorization", value: authorization) return headers } /// Generate a signed URL, for a HTTP request public func signURL(url: URL, method: HTTPMethod = .GET, body: BodyData? = nil, date: Date = Date(), expires: Int = 86400) -> URL { let headers = HTTPHeaders([("host", url.host ?? "")]) // Create signing data var signingData = AWSSigner.SigningData(url: url, method: method, headers: headers, body: body, date: AWSSigner.timestamp(date), signer: self) // Construct query string. Start with original query strings and append all the signing info. var query = url.query ?? "" if query.count > 0 { query += "&" } query += "X-Amz-Algorithm=AWS4-HMAC-SHA256" query += "&X-Amz-Credential=\(credentials.accessKeyId)/\(signingData.date)/\(region)/\(name)/aws4_request" query += "&X-Amz-Date=\(signingData.datetime)" query += "&X-Amz-Expires=\(expires)" query += "&X-Amz-SignedHeaders=\(signingData.signedHeaders)" if let sessionToken = credentials.sessionToken { query += "&X-Amz-Security-Token=\(sessionToken.uriEncode())" } // Split the string and sort to ensure the order of query strings is the same as AWS query = query.split(separator: "&") .sorted() .joined(separator: "&") .queryEncode() // update unsignedURL in the signingData so when the canonical request is constructed it includes all the signing query items signingData.unsignedURL = URL(string: url.absoluteString.split(separator: "?")[0]+"?"+query)! // NEED TO DEAL WITH SITUATION WHERE THIS FAILS query += "&X-Amz-Signature=\(signature(signingData: signingData))" // Add signature to query items and build a new Request let signedURL = URL(string: url.absoluteString.split(separator: "?")[0]+"?"+query)! return signedURL } /// structure used to store data used throughout the signing process struct SigningData { let url : URL let method : HTTPMethod let hashedPayload : String let datetime : String let headersToSign: [String: String] let signedHeaders : String var unsignedURL : URL var date : String { return String(datetime.prefix(8))} init(url: URL, method: HTTPMethod = .GET, headers: HTTPHeaders = HTTPHeaders(), body: BodyData? = nil, bodyHash: String? = nil, date: String, signer: AWSSigner) { if url.path == "" { //URL has to have trailing slash self.url = url.appendingPathComponent("/") } else { self.url = url } self.method = method self.datetime = date self.unsignedURL = self.url if let hash = bodyHash { self.hashedPayload = hash } else if signer.name == "s3" { self.hashedPayload = "UNSIGNED-PAYLOAD" } else { self.hashedPayload = AWSSigner.hashedPayload(body) } let headersNotToSign: Set<String> = [ "Authorization" ] var headersToSign: [String: String] = [:] var signedHeadersArray: [String] = [] for header in headers { if headersNotToSign.contains(header.name) { continue } headersToSign[header.name] = header.value signedHeadersArray.append(header.name.lowercased()) } self.headersToSign = headersToSign self.signedHeaders = signedHeadersArray.sorted().joined(separator: ";") } } // Stage 3 Calculating signature as in https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html func signature(signingData: SigningData) -> String { let kDate = HMAC<SHA256>.authenticationCode(for: Data(signingData.date.utf8), using: SymmetricKey(data: Array("AWS4\(credentials.secretAccessKey)".utf8))) let kRegion = HMAC<SHA256>.authenticationCode(for: Data(region.utf8), using: SymmetricKey(data: kDate)) let kService = HMAC<SHA256>.authenticationCode(for: Data(name.utf8), using: SymmetricKey(data: kRegion)) let kSigning = HMAC<SHA256>.authenticationCode(for: Data("aws4_request".utf8), using: SymmetricKey(data: kService)) let kSignature = HMAC<SHA256>.authenticationCode(for: stringToSign(signingData: signingData), using: SymmetricKey(data: kSigning)) return kSignature.hexDigest() } /// Stage 2 Create the string to sign as in https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html func stringToSign(signingData: SigningData) -> Data { let stringToSign = "AWS4-HMAC-SHA256\n" + "\(signingData.datetime)\n" + "\(signingData.date)/\(region)/\(name)/aws4_request\n" + SHA256.hash(data: canonicalRequest(signingData: signingData)).hexDigest() return Data(stringToSign.utf8) } /// Stage 1 Create the canonical request as in https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html func canonicalRequest(signingData: SigningData) -> Data { let canonicalHeaders = signingData.headersToSign.map { return "\($0.key.lowercased()):\($0.value.trimmingCharacters(in: CharacterSet.whitespaces))" } .sorted() .joined(separator: "\n") let canonicalRequest = "\(signingData.method.rawValue)\n" + "\(signingData.unsignedURL.path.uriEncodeWithSlash())\n" + "\(signingData.unsignedURL.query ?? "")\n" + // should really uriEncode all the query string values "\(canonicalHeaders)\n\n" + "\(signingData.signedHeaders)\n" + signingData.hashedPayload return Data(canonicalRequest.utf8) } /// Create a SHA256 hash of the Requests body static func hashedPayload(_ payload: BodyData?) -> String { guard let payload = payload else { return hashedEmptyBody } let hash : String? switch payload { case .string(let string): hash = SHA256.hash(data: Data(string.utf8)).hexDigest() case .data(let data): hash = SHA256.hash(data: data).hexDigest() case .byteBuffer(let byteBuffer): let byteBufferView = byteBuffer.readableBytesView hash = byteBufferView.withContiguousStorageIfAvailable { bytes in return SHA256.hash(data: bytes).hexDigest() } } if let hash = hash { return hash } else { return hashedEmptyBody } } /// return a hexEncoded string buffer from an array of bytes static func hexEncoded(_ buffer: [UInt8]) -> String { return buffer.map{String(format: "%02x", $0)}.joined(separator: "") } /// create timestamp dateformatter static private func createTimeStampDateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'" formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.locale = Locale(identifier: "en_US_POSIX") return formatter } /// return a timestamp formatted for signing requests static func timestamp(_ date: Date) -> String { return timeStampDateFormatter.string(from: date) } } extension String { func queryEncode() -> String { return addingPercentEncoding(withAllowedCharacters: String.queryAllowedCharacters) ?? self } func uriEncode() -> String { return addingPercentEncoding(withAllowedCharacters: String.uriAllowedCharacters) ?? self } func uriEncodeWithSlash() -> String { return addingPercentEncoding(withAllowedCharacters: String.uriAllowedWithSlashCharacters) ?? self } static let uriAllowedWithSlashCharacters = CharacterSet(charactersIn:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~/") static let uriAllowedCharacters = CharacterSet(charactersIn:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") static let queryAllowedCharacters = CharacterSet(charactersIn:"/;+").inverted } public extension Sequence where Element == UInt8 { /// return a hexEncoded string buffer from an array of bytes func hexDigest() -> String { return self.map{String(format: "%02x", $0)}.joined(separator: "") } }
44.269531
170
0.649696
8fae557c28eeda4f063ab2c7212499eeeee4444b
1,260
// // SwiftyOnboardVCUITests.swift // SwiftyOnboardVCUITests // // Created by luke on 31/07/2017. // Copyright © 2017 Luke Chase. All rights reserved. // import XCTest class SwiftyOnboardVCUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.054054
182
0.66746
089a227dee2b7709ef63e13932152ea54da4e359
1,560
// Copyright © 2019 hipolabs. All rights reserved. import Foundation open class AsyncOperation: Operation { open override var isReady: Bool { return super.isReady && state == .ready } open override var isExecuting: Bool { return state == .executing } open override var isFinished: Bool { return state == .finished } open override var isAsynchronous: Bool { return true } public var state: State { get { atomicState } set { willChangeValue(forKey: state.rawValue) willChangeValue(forKey: newValue.rawValue) $atomicState.modify { $0 = newValue } didChangeValue(forKey: state.rawValue) didChangeValue(forKey: newValue.rawValue) } } @Atomic(identifier: "operationState") private var atomicState: State = .ready open override func start() { if isCancelled { finish() return } state = .executing main() } open func finish( force: Bool = true ) { if force || isExecuting { state = .finished } } @discardableResult open func finishIfCancelled() -> Bool { if !isCancelled { return false } finish() return true } } extension AsyncOperation { public enum State: String { case ready = "isReady" case executing = "isExecuting" case finished = "isFinished" } }
20.526316
54
0.55
d51f3d91638f82808938bcc852ced924123d7397
2,183
// automatically generated by the FlatBuffers compiler, do not modify import FlatBuffers public struct Property: Readable { static func validateVersion() { FlatBuffersVersion_1_12_0() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Struct public static var size = 1 public static var alignment = 1 public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } public var property: Bool { return _accessor.readBuffer(of: Bool.self, at: 0) } @discardableResult public func mutate(property: Bool) -> Bool { return _accessor.mutate(property, index: 0) } } public func createProperty(builder: inout FlatBufferBuilder, property: Bool = false) -> Offset<UOffset> { builder.createStructOf(size: Property.size, alignment: Property.alignment) builder.reverseAdd(v: property, postion: 0) return builder.endStruct() } public struct TestMutatingBool: FlatBufferObject { static func validateVersion() { FlatBuffersVersion_1_12_0() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table public static func getRootAsTestMutatingBool(bb: ByteBuffer) -> TestMutatingBool { return TestMutatingBool(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } enum VTOFFSET: VOffset { case b = 4 var v: Int32 { Int32(self.rawValue) } var p: VOffset { self.rawValue } } public var b: Property? { let o = _accessor.offset(VTOFFSET.b.v); return o == 0 ? nil : Property(_accessor.bb, o: o + _accessor.postion) } public static func startTestMutatingBool(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } public static func add(b: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(structOffset: VTOFFSET.b.p) } public static func endTestMutatingBool(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end } }
45.479167
212
0.713697
fc0cc4e27276f882e9d4315def07b19543aa345f
109
import Definitions func customProject(name: String) -> Project { return Project(name: "Custom\(name)") }
21.8
45
0.715596
e2fc66514da107aa1ec7097d69fdcce5ce539a26
760
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 19/02/16. */ import Foundation enum Mulligan: Int, CaseIterable { case invalid = 0, input = 1, dealing = 2, waiting = 3, done = 4 init?(rawString: String) { let string = rawString.lowercased() for _enum in Mulligan.allCases where "\(_enum)" == string { self = _enum return } if let value = Int(rawString), let _enum = Mulligan(rawValue: value) { self = _enum return } self = .invalid } }
23.030303
78
0.588158
642890acc0cbb1ad915fffee1a596e6f1b0aacdd
302
// // UnownedWrapper.swift // EMUtils // // Created by Ewan Mellor on 3/4/17. // Copyright © 2017 Ewan Mellor. All rights reserved. // import Foundation public class UnownedWrapper<T: AnyObject> { public unowned var value : T public init(_ value: T) { self.value = value } }
16.777778
54
0.645695
e29f9cfcce25f06b82f562f0408c655d5775e9f0
218
// // EmotionAttachment.swift // 表情键盘 // // Created by weiguang on 2017/5/8. // Copyright © 2017年 weiguang. All rights reserved. // import UIKit class EmotionAttachment: NSTextAttachment { var chs: String? }
15.571429
52
0.692661
f785931826a2f4109fb5d1931ef5ceade3b0d98c
2,667
/** * Copyright (c) 2021 Dustin Collins (Strega's Gate) * All Rights Reserved. * Licensed under Apache License v2.0 * * Find me on https://www.YouTube.com/STREGAsGate, or social media @STREGAsGate */ import WinSDK /// Specifies a type of descriptor heap. public enum D3DDescriptorRangeType { public typealias RawValue = WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE /// Specifies a range of SRVs. case shaderResourceView /// Specifies a range of unordered-access views (UAVs). case unorderedAccessView /// Specifies a range of constant-buffer views (CBVs). case constantBufferView /// Specifies a range of samplers. case sampler /// This Swift Package had no implementation, this can happen if the Base API is expanded. case _unimplemented(RawValue) public var rawValue: RawValue { switch self { case .shaderResourceView: return WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE_SRV case .unorderedAccessView: return WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE_UAV case .constantBufferView: return WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE_CBV case .sampler: return WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER case let ._unimplemented(rawValue): return rawValue } } public init(_ rawValue: RawValue) { switch rawValue { case WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE_SRV: self = .shaderResourceView case WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE_UAV: self = .unorderedAccessView case WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE_CBV: self = .constantBufferView case WinSDK.D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER: self = .sampler default: self = ._unimplemented(rawValue) } } } //MARK: - Original Style API #if !Direct3D12ExcludeOriginalStyleAPI @available(*, deprecated, renamed: "D3DDescriptorRangeType") public typealias D3D12_DESCRIPTOR_RANGE_TYPE = D3DDescriptorRangeType @available(*, deprecated, renamed: "D3DDescriptorRangeType.srv") public let D3D12_DESCRIPTOR_RANGE_TYPE_SRV = D3DDescriptorRangeType.shaderResourceView @available(*, deprecated, renamed: "D3DDescriptorRangeType.unorderedAccessView") public let D3D12_DESCRIPTOR_RANGE_TYPE_UAV = D3DDescriptorRangeType.unorderedAccessView @available(*, deprecated, renamed: "D3DDescriptorRangeType.constantBufferView") public let D3D12_DESCRIPTOR_RANGE_TYPE_CBV = D3DDescriptorRangeType.constantBufferView @available(*, deprecated, renamed: "D3DDescriptorRangeType.sampler") public let D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = D3DDescriptorRangeType.sampler #endif
33.759494
94
0.732283
211c72032f4a2ff0580bc0283cbb3a68dc70b625
4,361
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: desmos/profiles/v1beta1/query_params.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// QueryParamsRequest is the request type for the Query/Params RPC endpoint struct Desmos_Profiles_V1beta1_QueryParamsRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// QueryParamsResponse is the response type for the Query/Params RPC method. struct Desmos_Profiles_V1beta1_QueryParamsResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var params: Desmos_Profiles_V1beta1_Params { get {return _params ?? Desmos_Profiles_V1beta1_Params()} set {_params = newValue} } /// Returns true if `params` has been explicitly set. var hasParams: Bool {return self._params != nil} /// Clears the value of `params`. Subsequent reads from it will return its default value. mutating func clearParams() {self._params = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _params: Desmos_Profiles_V1beta1_Params? = nil } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "desmos.profiles.v1beta1" extension Desmos_Profiles_V1beta1_QueryParamsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".QueryParamsRequest" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Desmos_Profiles_V1beta1_QueryParamsRequest, rhs: Desmos_Profiles_V1beta1_QueryParamsRequest) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Desmos_Profiles_V1beta1_QueryParamsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".QueryParamsResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "params"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._params) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._params { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Desmos_Profiles_V1beta1_QueryParamsResponse, rhs: Desmos_Profiles_V1beta1_QueryParamsResponse) -> Bool { if lhs._params != rhs._params {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
39.645455
155
0.760605
1a746c4610730970ced618d870f4ab8f147c9ade
6,214
// // XRActivityRefreshFooter.swift // // Copyright (c) 2018 - 2020 Ran Xu // // 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 class CustomActivityRefreshFooter: XRBaseRefreshFooter { lazy var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.white) lazy var statusLbl: UILabel = UILabel(frame: CGRect.zero) override public init() { super.init() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func layoutSubviews() { super.layoutSubviews() if self.refreshState == .noMoreData || self.refreshState == .loadingFailure { statusLbl.frame = CGRect(x: (self.bounds.size.width - statusLbl.bounds.size.width) * 0.5, y: (self.bounds.size.height - 35 - ignoreBottomHeight) * 0.5, width: statusLbl.bounds.size.width, height: 35) } else { statusLbl.frame = CGRect(x: (self.bounds.size.width - statusLbl.bounds.size.width) * 0.5 + 35 * 0.5, y: (self.bounds.size.height - 35 - ignoreBottomHeight) * 0.5, width: statusLbl.bounds.size.width, height: 35) } activityIndicator.frame = CGRect(x: statusLbl.frame.origin.x - 35, y: statusLbl.frame.origin.y, width: 35, height: 35) } override public func prepareForRefresh() { super.prepareForRefresh() self.backgroundColor = UIColor.clear activityIndicator.frame = CGRect(x: 0, y: 0, width: 35, height: 35) activityIndicator.center = CGPoint(x: self.frame.size.width * 0.5, y: self.frame.size.height * 0.5) self.addSubview(activityIndicator) activityIndicator.hidesWhenStopped = false activityIndicator.color = XRRefreshControlSettings.sharedSetting.refreshStatusLblTextColor statusLbl.textColor = XRRefreshControlSettings.sharedSetting.refreshStatusLblTextColor statusLbl.textAlignment = .center statusLbl.font = XRRefreshControlSettings.sharedSetting.refreshStatusLblTextFont statusLbl.frame = CGRect(x: 0, y: 0, width: 200, height: 35) statusLbl.center = CGPoint(x: activityIndicator.center.x, y: activityIndicator.center.y) self.addSubview(statusLbl) statusLbl.isUserInteractionEnabled = true let statusLblTapGestrue = UITapGestureRecognizer(target: self, action: #selector(self.reloadingWithLoadingFailureAction)) statusLblTapGestrue.numberOfTapsRequired = 1 statusLbl.addGestureRecognizer(statusLblTapGestrue) } override public func refreshStateChanged() { switch refreshState { case .idle: activityIndicator.stopAnimating() activityIndicator.isHidden = false statusLbl.text = XRLocalizableStringManager.localizableStringFromKey(key: XR_Refresh_footer_idle) break case .pulling: activityIndicator.stopAnimating() activityIndicator.isHidden = false statusLbl.text = XRLocalizableStringManager.localizableStringFromKey(key: XR_Refresh_footer_idle) break case .pullHalfing: activityIndicator.stopAnimating() activityIndicator.isHidden = false statusLbl.text = XRLocalizableStringManager.localizableStringFromKey(key: XR_Refresh_footer_idle) break case .pullFulling: activityIndicator.stopAnimating() activityIndicator.isHidden = false statusLbl.text = XRLocalizableStringManager.localizableStringFromKey(key: XR_Refresh_footer_idle) break case .refreshing: activityIndicator.startAnimating() activityIndicator.isHidden = false statusLbl.text = XRLocalizableStringManager.localizableStringFromKey(key: XR_Refresh_footer_refreshing) break case .finished: activityIndicator.stopAnimating() activityIndicator.isHidden = false statusLbl.text = XRLocalizableStringManager.localizableStringFromKey(key: XR_Refresh_footer_finished) break case .noMoreData: activityIndicator.stopAnimating() activityIndicator.isHidden = true statusLbl.text = XRLocalizableStringManager.localizableStringFromKey(key: XR_Refresh_footer_noMoreData) break case .loadingFailure: activityIndicator.stopAnimating() activityIndicator.isHidden = true statusLbl.text = XRLocalizableStringManager.localizableStringFromKey(key: XR_Refresh_footer_loadingFailure) break } statusLbl.sizeToFit() statusLbl.superview?.setNeedsLayout() statusLbl.superview?.layoutIfNeeded() } // pull progress changed override public func pullProgressValueChanged() { } // 加载失败了,重新加载 @objc func reloadingWithLoadingFailureAction() { if self.refreshState == .loadingFailure { self.beginRefreshing() } } }
43.454545
222
0.682974
f7645f719394be055dc17a15fa8ef05aae2da2be
1,417
// // MaterialsUITests.swift // MaterialsUITests // // Created by Philip Davis on 1/14/21. // import XCTest class MaterialsUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
32.953488
182
0.656316
71d05696778a06d7e0aadedbefde467bb8f3e65d
2,332
// // MainTabBar.swift // iHealth // // Created by Ricardo Casanova on 16/01/2019. // Copyright © 2019 Pijp. All rights reserved. // import UIKit class MainTabBar: UITabBarController { private var tabBarConfigured: Bool = false private let goalsViewController: GoalsViewController = GoalsRouter.setupModule() private let myGoalsViewController: MyGoalsViewController = MyGoalsRouter.setupModule() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureTabBar() } } // MARK: - Private section extension MainTabBar { private func configureTabBar() { if tabBarConfigured { return } let goalsIcon = UIImage(named: "goalsIcon")?.withRenderingMode(.alwaysOriginal) let myGoalsIcon = UIImage(named: "myGoalsIcon")?.withRenderingMode(.alwaysOriginal) UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white(), NSAttributedString.Key.font: UIFont.mediumWithSize(size: 10.0) ?? UIFont.systemFont(ofSize: 10.0)], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white(), NSAttributedString.Key.font: UIFont.mediumWithSize(size: 10.0) ?? UIFont.systemFont(ofSize: 10.0)], for: .selected) let goalsTabBarItem = UITabBarItem(title: NSLocalizedString("goals.title", comment: ""), image: goalsIcon, tag: 0) let myGoalsTabBarItem = UITabBarItem(title: NSLocalizedString("my_goals.title", comment: ""), image: myGoalsIcon, tag: 1) let goalsNagivationViewController = UINavigationController(rootViewController: goalsViewController) goalsNagivationViewController.tabBarItem = goalsTabBarItem goalsNagivationViewController.tabBarItem.selectedImage = goalsIcon let myGoalsNagivationViewController = UINavigationController(rootViewController: myGoalsViewController) myGoalsNagivationViewController.tabBarItem = myGoalsTabBarItem myGoalsNagivationViewController.tabBarItem.selectedImage = myGoalsIcon viewControllers = [goalsNagivationViewController, myGoalsNagivationViewController] tabBarConfigured = true selectedIndex = 0 } }
40.912281
230
0.723413
76f73083f2e9d06bfbbe274b64e46859b0096ff6
368
// // URLComponents+SetQueryItems.swift // SurveyApp // // Created by sysnet on 2/15/20. // Copyright © 2020 Neelam Shehzadi. All rights reserved. // import Foundation extension URLComponents { mutating func setQueryItems(with parameters: [String: Any]) { self.queryItems = parameters.map { URLQueryItem(name: $0.key, value: "\($0.value)") } } }
23
93
0.679348
fc94e4d32ca33c3c064c4140ea3f187ab7f0dc83
2,916
/* See LICENSE folder for this sample’s licensing information. Abstract: A view controller to show a preview of a color and provide two alternative techniques for starring/unstarring and deleting it. The first technique is an action method linked from the navigation bar in the storyboard and the second is to support Peek Quick Actions by overriding the previewActionItems property. */ import UIKit class ColorItemViewController: UIViewController { var colorData: ColorData? var colorItem: ColorItem? @IBOutlet var starButton: UIBarButtonItem! // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() guard let colorItem = colorItem else { preconditionFailure("Expected a color item") } title = colorItem.name view.backgroundColor = colorItem.color starButton.title = starButtonTitle() } // MARK: - Action methods @IBAction func toggleStar() { guard let colorItem = colorItem else { preconditionFailure("Expected a color item") } // colorItem.starred.toggle() // Not ready till Swift 4.2 colorItem.starred = !colorItem.starred starButton.title = starButtonTitle() } @IBAction func delete() { guard let colorData = colorData else { preconditionFailure("Expected a reference to the color data container") } guard let colorItem = colorItem else { preconditionFailure("Expected a color item") } colorData.delete(colorItem) // The color no longer exists so dismiss this view controller. navigationController?.popViewController(animated: true) } // MARK: - Supporting Peek Quick Actions /// - Tag: PreviewActionItems override var previewActionItems: [UIPreviewActionItem] { let starAction = UIPreviewAction(title: starButtonTitle(), style: .default, handler: { [unowned self] (_, _) in guard let colorItem = self.colorItem else { preconditionFailure("Expected a color item") } // colorItem.starred.toggle() // Not ready til Swift 4.2 colorItem.starred = !colorItem.starred }) let deleteAction = UIPreviewAction(title: "Delete", style: .destructive) { [unowned self] (_, _) in guard let colorData = self.colorData else { preconditionFailure("Expected a reference to the color data container") } guard let colorItem = self.colorItem else { preconditionFailure("Expected a color item") } colorData.delete(colorItem) } return [ starAction, deleteAction ] } // MARK: - UI helper methods func starButtonTitle() -> String { guard let colorItem = colorItem else { preconditionFailure("Expected a color item") } return colorItem.starred ? "Unstar" : "Star" } }
31.354839
119
0.657064
e65c38e23412007c3e5ca20b4d4a8b0a442d9331
1,286
// File Information: // TestResultsView // // Created by Best Software // Copyright © 2017 Best Software. All rights reserved. // // Abstract: // The visulization for the test results import UIKit class TestResultsView: UIViewController { @IBOutlet weak var ActiveTremorTestResultsButton: UIButton! @IBOutlet weak var RestTremorTestResultsButton: UIButton! @IBOutlet weak var TestResultsAnalysisButton: UIButton! override func viewDidLoad() { super.viewDidLoad() ActiveTremorTestResultsButton.layer.cornerRadius = 25 RestTremorTestResultsButton.layer.cornerRadius = 25 TestResultsAnalysisButton.layer.cornerRadius = 25 // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
27.956522
106
0.699067
e9c9042246b22860a8a1a018f49ba9d8d06dea6e
2,184
// // RxTableViewSectionedAnimatedDataSource.swift // RxExample // // Created by Krunoslav Zaher on 6/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif open class RxTableViewSectionedAnimatedDataSource<S: AnimatableSectionModelType> : TableViewSectionedDataSource<S> , RxTableViewDataSourceType { public typealias Element = [S] public var animationConfiguration = AnimationConfiguration() var dataSet = false public override init() { super.init() } open func tableView(_ tableView: UITableView, observedEvent: Event<Element>) { UIBindingObserver(UIElement: self) { dataSource, newSections in #if DEBUG self._dataSourceBound = true #endif if !self.dataSet { self.dataSet = true dataSource.setSections(newSections) tableView.reloadData() } else { DispatchQueue.main.async { // if view is not in view hierarchy, performing batch updates will crash the app if tableView.window == nil { dataSource.setSections(newSections) tableView.reloadData() return } let oldSections = dataSource.sectionModels do { let differences = try differencesForSectionedView(initialSections: oldSections, finalSections: newSections) for difference in differences { dataSource.setSections(difference.finalSections) tableView.performBatchUpdates(difference, animationConfiguration: self.animationConfiguration) } } catch let e { rxDebugFatalError(e) self.setSections(newSections) tableView.reloadData() } } } }.on(observedEvent) } }
32.597015
131
0.557234
67361b3bda56c6310e9157be11e57a04f72b829a
1,349
// // AppDelegate.swift // LargeTitle // // Created by hanwe lee on 2021/03/23. // 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
ffca7abfefb1973288bd9fa392666d69e54fdc47
998
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "CYBase", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "CYBase", targets: ["CYBase"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "CYBase", dependencies: []), .testTarget( name: "CYBaseTests", dependencies: ["CYBase"]), ] )
34.413793
117
0.612224
d5772a9f1aacae8b51c7b7fac2403050b82e5c61
1,203
// Created by xudong wu on 23/02/2017. // Copyright wuxudong // import UIKit @objc(RNScatterChartManager) class RNScatterChartManager: RCTViewManager, RNBarLineChartBaseManager { var _bridge: RCTBridge? {get{return self.bridge}} override func view() -> UIView! { let ins = RNScatterChartView() return ins; } override open static func requiresMainQueueSetup() -> Bool { return true; } func moveViewToX(_ reactTag: NSNumber, xValue: NSNumber) { (self as RNBarLineChartBaseManager)._moveViewToX(reactTag, xValue: xValue) } func moveViewTo(_ reactTag: NSNumber, xValue: NSNumber, yValue: NSNumber, axisDependency: NSString) { (self as RNBarLineChartBaseManager)._moveViewTo(reactTag, xValue: xValue, yValue: yValue, axisDependency: axisDependency) } func moveViewToAnimated(_ reactTag: NSNumber, xValue: NSNumber, yValue: NSNumber, axisDependency: NSString, duration: NSNumber) { (self as RNBarLineChartBaseManager)._moveViewToAnimated(reactTag, xValue: xValue, yValue: yValue, axisDependency: axisDependency, duration: duration) } func fitScreen(_ reactTag: NSNumber) { (self as RNBarLineChartBaseManager)._fitScreen(reactTag) } }
32.513514
153
0.746467
ac74136d99486f3d8557b812e8d44156734ecbff
367
// Created by Isaac Halvorson on 7/7/18 struct Location { /// Altitude, in meters, of the location. let altitude: Double? /// Latitude, in degrees, of the location. let latitude: Double /// Longitude, in degrees, of the location. let longitude: Double /// Text displayed on the lock screen when the pass is currently relevant. let relevantText: String? }
22.9375
75
0.719346
acabf4260b06aadcb92fb35b754383dc17b8cc80
10,654
// // MusicDataBaseManager.swift // Music // // Created by Jack on 5/18/17. // Copyright © 2017 Jack. All rights reserved. // import Foundation import SQLite private struct Resource { let table: Table let id = Expression<String>("id") let name = Expression<String>("name") let duration = Expression<Double>("duration") let lyric = Expression<JSON>("lyric") let artist = Expression<JSON>("artist") let album = Expression<JSON>("album") let info = Expression<JSON>("info") let status = Expression<Int>("status") private(set) var sqlStatement: String = "" init(table: Table) { self.table = table sqlStatement = self.table.create(ifNotExists: true) { (table) in table.column(id, primaryKey: true) table.column(name) table.column(duration) table.column(lyric) table.column(artist) table.column(album) table.column(info) table.column(status) } } func save(resource: MusicResource) -> [Setter] { return [id <- resource.id, name <- resource.name, duration <- resource.duration, lyric <- resource.lyric?.rawJSON ?? emptyJSON, album <- resource.album?.rawJSON ?? emptyJSON, artist <- resource.artist?.rawJSON ?? emptyJSON, info <- resource.info?.rawJSON ?? emptyJSON] } func get(fromRow row: Row) -> MusicResource { let resource = MusicResource(id: row[id]) resource.name = row[name] resource.duration = row[duration] resource.lyric = row[lyric] == emptyJSON ? nil : MusicLyricModel(row[lyric]) resource.album = row[album] == emptyJSON ? nil : MusicAlbumModel(row[album]) resource.artist = row[artist] == emptyJSON ? nil : MusicArtistModel(row[artist]) resource.info = row[info] == emptyJSON ? nil : MusicResouceInfoModel(row[info]) return resource } } private struct List { let table: Table let id = Expression<String>("id") private(set) var sqlStatement: String = "" init(table: Table) { self.table = table sqlStatement = self.table.create(ifNotExists: true, block: { (table) in table.column(id, primaryKey: true) }) } } private struct PlayList { let table: Table let id = Expression<String>("id") let list = Expression<JSON>("playList") private(set) var sqlStatement: String = "" init(table: Table) { self.table = table sqlStatement = self.table.create(ifNotExists: true, block: { (table) in table.column(id, primaryKey: true) table.column(list) }) } func save(id: String, json: JSON) -> [Setter] { return [self.id <- id, list <- json] } } class MusicDataBaseManager { static let `default`: MusicDataBaseManager = MusicDataBaseManager() private let musicDB: Connection? private let resourceControl = Resource(table: Table("Resource")) private let cacheControl = List(table: Table("Cache")) private let downloadControl = List(table: Table("Download")) private let leastResourcesControl = Resource(table: Table("LeastResource")) private let collectionListControl = PlayList(table: Table("CollectionList")) private let listDetailControl = PlayList(table: Table("ListDetail")) private init() { musicDB = try? Connection(MusicFileManager.default.musicDataBaseURL.appendingPathComponent("music.db").path) musicDB?.trace{ ConsoleLog.verbose($0) } do { /// Created resouce table try musicDB?.run(resourceControl.sqlStatement) /// Created cache table try musicDB?.run(cacheControl.sqlStatement) /// Created download table try musicDB?.run(downloadControl.sqlStatement) /// Created least reshources table try musicDB?.run(leastResourcesControl.sqlStatement) /// Created collection list table try musicDB?.run(collectionListControl.sqlStatement) /// Created list detail table try musicDB?.run(listDetailControl.sqlStatement) } catch { ConsoleLog.error("Create tables with error: \(error)") } } //MARK: - Collection List func set(_ userId: String, collectionList: JSON) { do { try musicDB?.run(collectionListControl.table.insert(or: .replace, collectionListControl.save(id: userId, json: collectionList))) } catch { ConsoleLog.error(error) } } func get(userId: String) -> JSON? { do { return try musicDB?.pluck(collectionListControl.table)?.get(collectionListControl.list) } catch { ConsoleLog.error(error) return nil } } //MARK: - List Detail func set(_ listId: String, listDetail: JSON) { do { try musicDB?.run(listDetailControl.table.insert(or: .replace, listDetailControl.save(id: listId, json: listDetail))) } catch { ConsoleLog.error(error) } } func get(listId: String) -> JSON? { do { return try musicDB?.pluck(listDetailControl.table.filter(listDetailControl.id == listId))?.get(listDetailControl.list) } catch { ConsoleLog.error(error) return nil } } //MARK: - Check func isCached(_ identifiter: MusicResourceIdentifier) -> Bool { do { return try musicDB?.pluck(cacheControl.table.select(cacheControl.id).filter(cacheControl.id == identifiter)) != nil } catch { ConsoleLog.error(error) return false } } func isDownload(_ identifiter: MusicResourceIdentifier) -> Bool { do { return try musicDB?.pluck(downloadControl.table.select(downloadControl.id).filter(downloadControl.id == identifiter)) != nil } catch { ConsoleLog.error(error) return false } } //MARK: - List func cacheList() -> [MusicResourceIdentifier] { do { return Array(try musicDB!.prepare(cacheControl.table).map{ $0.get(cacheControl.id) }) } catch { ConsoleLog.error(error) return [] } } func downloadList() -> [MusicResourceIdentifier] { do { return Array(try musicDB!.prepare(downloadControl.table).map{ $0.get(downloadControl.id) }) } catch { ConsoleLog.error(error) return [] } } //MARK: - List Count func cacheCount() -> Int { do { return try musicDB?.scalar(cacheControl.table.select(cacheControl.id.count)) ?? 0 } catch { ConsoleLog.error(error) return 0 } } func downloadCount() -> Int { do { return try musicDB?.scalar(downloadControl.table.select(downloadControl.id.count)) ?? 0 } catch { ConsoleLog.error(error) return 0 } } //MARK: - Save Resource func cache(_ resource: MusicResource) { do { try musicDB?.run(cacheControl.table.insert(cacheControl.id <- resource.id)) save(resource) } catch { ConsoleLog.error("Cache resource information to DataBase with error: \(error)") } } func download(_ resource: MusicResource) { do { try musicDB?.run(downloadControl.table.insert(downloadControl.id <- resource.id)) if !save(resource, withStatus: 1) { try musicDB?.run(resourceControl.table.filter(resourceControl.id == resource.id).update(resourceControl.status <- 1)) } /// Delete cache with same resource try musicDB?.run(cacheControl.table.filter(cacheControl.id == resource.id).delete()) } catch { ConsoleLog.error("Download resource information to DataBase with error: \(error)") } } //MARK: - Delete //MARK: - Least Resources func update(leastResources: [MusicResource]) { do { try musicDB?.run(leastResourcesControl.table.delete()) for resource in leastResources { try musicDB?.run(leastResourcesControl.table.insert(leastResourcesControl.save(resource: resource))) } } catch { ConsoleLog.error("Update least resources with error: \(error)") } } func getLeastResources() -> [MusicResource] { do { return Array(try musicDB!.prepare(leastResourcesControl.table).map{ leastResourcesControl.get(fromRow: $0) }) } catch { ConsoleLog.error(error) return [] } } //MARK: - Get Resource func get(resourceId: MusicResourceIdentifier) -> MusicResource? { do { guard let row = try musicDB?.pluck(resourceControl.table.filter(resourceControl.id == resourceId)) else { return nil } return resourceControl.get(fromRow: row) } catch { ConsoleLog.error(error) return nil } } //MARK: - Clear cache resource , delete downloaded func clear() { do { try musicDB?.run(cacheControl.table.delete()) try musicDB?.run(resourceControl.table.filter(resourceControl.status == 0).delete()) } catch { ConsoleLog.error(error) } } func delete(resourceId: String) { do { try musicDB?.run(downloadControl.table.filter(downloadControl.id == resourceId).delete()) try musicDB?.run(resourceControl.table.filter(resourceControl.id == resourceId).delete()) } catch { ConsoleLog.error(error) } } //MARK: - Private @discardableResult private func save(_ resource: MusicResource, withStatus status: Int = 0) -> Bool { do { var setter: [Setter] = resourceControl.save(resource: resource) setter.append(resourceControl.status <- status) try musicDB?.run(resourceControl.table.insert(setter)) return true } catch { ConsoleLog.error("Save resource information to DataBase with error: \(error)") return false } } }
32.090361
140
0.579407
8a350d9a2bac05707e8e43705153be53ab85c300
1,846
// // ReadingListTests.swift // ReadingListTests // // Created by Student on 1/18/17. // Copyright © 2017 Student. All rights reserved. // import Foundation import XCTest @testable import ReadingList class ReadingListTests: XCTestCase { func testDictionaryWithNSNull() { let bookDict: [String: Any] = [Book.titleKey: "My Title", Book.yearKey: NSNull(), Book.authorKey: [Author.firstNameKey: NSNull(), Author.lastNameKey: "Homer"]] print(bookDict) let book = Book(dictionary: bookDict) print(book) } func testAuthorName() { let unnamedAuthor = Author(dictionary: [:]) let firstNameOnly = Author(dictionary: [Author.firstNameKey: "Fred"]) let lastNameOnly = Author(dictionary: [Author.lastNameKey: "Smith"]) let namedAuthor = Author(dictionary: [Author.firstNameKey: "Fred", Author.lastNameKey: "Smith"]) XCTAssertEqual(Author.unknown, unnamedAuthor.fullName) XCTAssertEqual("Fred", firstNameOnly.fullName) XCTAssertEqual("Smith", lastNameOnly.fullName) XCTAssertEqual("Fred Smith", namedAuthor.fullName) } func testBookDictionary() { let bookInfo: [String: Any?] = [Book.titleKey: "My Title", Book.yearKey: nil] let foo = bookInfo.filter { key, value in return value != nil } print(foo) let dict = bookInfo.flatMap { (dict: (key: String, value: Any?)) in return dict.value == nil ? nil : (dict.key, dict.value) } print(dict) } } //extension Dictionary where Key: String, Value: Optional<Any> //{ // var flattened: [String: Any] { // return [:] // } //}
30.766667
104
0.578548
2f18cd5a48705439692e25a172fac1232c51a009
631
// // main.swift // NutriCalc // // Created by Petro Korienev on 12/15/17. // Copyright © 2017 Sigma Software. All rights reserved. // import UIKit var appDelegateClassName = (nil != Bundle.allBundles.first { $0.bundlePath.contains(".xctest") }) ? NSStringFromClass(TestAppDelegate.self) : NSStringFromClass(AppDelegate.self) let argv = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc)) UIApplicationMain(CommandLine.argc, argv, nil, appDelegateClassName)
35.055556
106
0.662441
76d2bc385270cee47811bce24dcb443d52bb1584
2,730
import Libawc import Wlroots internal func renderSurface( renderer: UnsafeMutablePointer<wlr_renderer>, output: UnsafeMutablePointer<wlr_output>, px: Int32, py: Int32, surface: UnsafeMutablePointer<wlr_surface>, sx: Int32, sy: Int32 ) { // We first obtain a wlr_texture, which is a GPU resource. wlroots // automatically handles negotiating these with the client. The underlying // resource could be an opaque handle passed from the client, or the client // could have sent a pixel buffer which we copied to the GPU, or a few other // means. You don't have to worry about this, wlroots takes care of it. guard let texture = wlr_surface_get_texture(surface) else { return } // We also have to apply the scale factor for HiDPI outputs. This is only // part of the puzzle, AWC does not fully support HiDPI. let scale = Double(output.pointee.scale) var box = wlr_box( x: px + sx, y: py + sy, width: surface.pointee.current.width, height: surface.pointee.current.height ).scale(scale) // Those familiar with OpenGL are also familiar with the role of matrices // in graphics programming. We need to prepare a matrix to render the view // with. wlr_matrix_project_box is a helper which takes a box with a desired // x, y coordinates, width and height, and an output geometry, then // prepares an orthographic projection and multiplies the necessary // transforms to produce a model-view-projection matrix. // // Naturally you can do this any way you like, for example to make a 3D // compositor. var matrix: matrix9 = (0, 0, 0, 0, 0, 0, 0, 0, 0) let transform = wlr_output_transform_invert(surface.pointee.current.transform) withUnsafeMutablePointer(to: &matrix.0) { matrixPtr in withUnsafePointer(to: &output.pointee.transform_matrix.0) { (outputTransformMatrixPtr) in wlr_matrix_project_box(matrixPtr, &box, transform, 0, outputTransformMatrixPtr) } // This takes our matrix, the texture, and an alpha, and performs the actual rendering on the GPU. wlr_render_texture_with_matrix(renderer, texture, matrixPtr, 1) } } public func renderSurface<L: Layout>( _ renderer: UnsafeMutablePointer<wlr_renderer>, _ output: Output<L>, _ surface: Surface, _ attributes: Set<ViewAttribute>, _ box: wlr_box ) where L.View == Surface, L.OutputData == OutputDetails { let wlrOutput = output.data.output for (childSurface, sx, sy) in surface.surfaces() { renderSurface( renderer: renderer, output: wlrOutput, px: box.x, py: box.y, surface: childSurface, sx: sx, sy: sy ) } }
40.746269
110
0.690476
f4a5397c4202cbe3c53eae4defef1cf40dff7ef1
432
import UIKit public extension UIStoryboard { public class func fulfillment() -> UIStoryboard { // TODO: Store as though lazy loading. return UIStoryboard(name: "Fulfillment", bundle: nil) } public func viewControllerWithID(identifier:ViewControllerStoryboardIdentifier) -> UIViewController { return self.instantiateViewControllerWithIdentifier(identifier.rawValue) as UIViewController } }
30.857143
105
0.743056
64965ad9d595ab4b12330125384d70f6c4105994
3,226
// // DiscovTableViewController.swift // weibo // // Created by 任玉飞 on 16/4/25. // Copyright © 2016年 任玉飞. All rights reserved. // import UIKit class DiscovTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
33.604167
157
0.686609