label
int64
0
1
text
stringlengths
0
2.8M
0
// // UITableView+Exten.swift // sesame-sdk-test-app // // Created by tse on 2019/12/24. // Copyright © 2019 CandyHouse. All rights reserved. // import UIKit extension UITableView { func setEmptyMessage(_ message: String) { let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)) messageLabel.text = message messageLabel.textColor = .black messageLabel.numberOfLines = 0 messageLabel.textAlignment = .center messageLabel.font = UIFont(name: "TrebuchetMS", size: 15) messageLabel.sizeToFit() backgroundView = messageLabel } func restore() { backgroundView = nil } }
0
// // Mappable.swift // ObjectMapper // // Created by Scott Hoyt on 10/25/15. // Copyright © 2015 hearst. All rights reserved. // import Foundation public protocol Mappable { /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point init?(_ map: Map) /// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process. mutating func mapping(map: Map) /// This is an optional function that can be used to: /// 1) provide an existing cached object to be used for mapping /// 2) return an object of another class (which conforms to Mappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping static func objectForMapping(map: Map) -> Mappable? } public extension Mappable { public static func objectForMapping(map: Map) -> Mappable? { return nil } /// Initializes object from a JSON String public init?(JSONString: String) { if let obj: Self = Mapper().map(JSONString) { self = obj } else { return nil } } /// Initializes object from a JSON Dictionary public init?(JSON: [String : AnyObject]) { if let obj: Self = Mapper().map(JSON) { self = obj } else { return nil } } /// Returns the JSON Dictionary for the object public func toJSON() -> [String: AnyObject] { return Mapper().toJSON(self) } /// Returns the JSON String for the object public func toJSONString(prettyPrint: Bool = false) -> String? { return Mapper().toJSONString(self, prettyPrint: prettyPrint) } } public extension Array where Element: Mappable { /// Initialize Array from a JSON String public init?(JSONString: String) { if let obj: [Element] = Mapper().mapArray(JSONString) { self = obj } else { return nil } } /// Initialize Array from a JSON Array public init?(JSONArray: [[String : AnyObject]]) { if let obj: [Element] = Mapper().mapArray(JSONArray) { self = obj } else { return nil } } /// Returns the JSON Array public func toJSON() -> [[String : AnyObject]] { return Mapper().toJSONArray(self) } /// Returns the JSON String for the object public func toJSONString(prettyPrint: Bool = false) -> String? { return Mapper().toJSONString(self, prettyPrint: prettyPrint) } } public extension Set where Element: Mappable { /// Initializes a set from a JSON String public init?(JSONString: String) { if let obj: Set<Element> = Mapper().mapSet(JSONString) { self = obj } else { return nil } } /// Initializes a set from JSON public init?(JSONArray: [[String : AnyObject]]) { if let obj: Set<Element> = Mapper().mapSet(JSONArray) { self = obj } else { return nil } } /// Returns the JSON Set public func toJSON() -> [[String : AnyObject]] { return Mapper().toJSONSet(self) } /// Returns the JSON String for the object public func toJSONString(prettyPrint: Bool = false) -> String? { return Mapper().toJSONString(self, prettyPrint: prettyPrint) } }
0
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // 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 XCTest @testable import EasyPeasy class ReferenceAttributeTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testThatOppositeAttributesAreCorrect() { // given // when // then XCTAssertTrue(ReferenceAttribute.width.opposite == .width) XCTAssertTrue(ReferenceAttribute.height.opposite == .height) XCTAssertTrue(ReferenceAttribute.left.opposite == .right) XCTAssertTrue(ReferenceAttribute.right.opposite == .left) XCTAssertTrue(ReferenceAttribute.top.opposite == .bottom) XCTAssertTrue(ReferenceAttribute.bottom.opposite == .top) XCTAssertTrue(ReferenceAttribute.leading.opposite == .trailing) XCTAssertTrue(ReferenceAttribute.trailing.opposite == .leading) XCTAssertTrue(ReferenceAttribute.centerX.opposite == .centerX) XCTAssertTrue(ReferenceAttribute.centerY.opposite == .centerY) XCTAssertTrue(ReferenceAttribute.lastBaseline.opposite == .lastBaseline) } func testThatOppositeAttributesAreCorrectiOS8AndAbove() { XCTAssertTrue(ReferenceAttribute.firstBaseline.opposite == .firstBaseline) XCTAssertTrue(ReferenceAttribute.leftMargin.opposite == .rightMargin) XCTAssertTrue(ReferenceAttribute.rightMargin.opposite == .leftMargin) XCTAssertTrue(ReferenceAttribute.topMargin.opposite == .bottomMargin) XCTAssertTrue(ReferenceAttribute.bottomMargin.opposite == .topMargin) XCTAssertTrue(ReferenceAttribute.leadingMargin.opposite == .trailingMargin) XCTAssertTrue(ReferenceAttribute.trailingMargin.opposite == .leadingMargin) XCTAssertTrue(ReferenceAttribute.centerXWithinMargins.opposite == .centerXWithinMargins) XCTAssertTrue(ReferenceAttribute.centerYWithinMargins.opposite == .centerYWithinMargins) } func testThatAutoLayoutEquivalentIsTheExpected() { // given // when // then XCTAssertTrue(ReferenceAttribute.width.layoutAttribute == .width) XCTAssertTrue(ReferenceAttribute.height.layoutAttribute == .height) XCTAssertTrue(ReferenceAttribute.left.layoutAttribute == .left) XCTAssertTrue(ReferenceAttribute.right.layoutAttribute == .right) XCTAssertTrue(ReferenceAttribute.top.layoutAttribute == .top) XCTAssertTrue(ReferenceAttribute.bottom.layoutAttribute == .bottom) XCTAssertTrue(ReferenceAttribute.leading.layoutAttribute == .leading) XCTAssertTrue(ReferenceAttribute.trailing.layoutAttribute == .trailing) XCTAssertTrue(ReferenceAttribute.centerX.layoutAttribute == .centerX) XCTAssertTrue(ReferenceAttribute.centerY.layoutAttribute == .centerY) XCTAssertTrue(ReferenceAttribute.lastBaseline.layoutAttribute == .lastBaseline) XCTAssertTrue(ReferenceAttribute.width.layoutAttribute == .width) } func testThatAutoLayoutEquivalentIsTheExpectediOS8AndAbove() { // given // when // then XCTAssertTrue(ReferenceAttribute.firstBaseline.layoutAttribute == .firstBaseline) XCTAssertTrue(ReferenceAttribute.leftMargin.layoutAttribute == .leftMargin) XCTAssertTrue(ReferenceAttribute.rightMargin.layoutAttribute == .rightMargin) XCTAssertTrue(ReferenceAttribute.topMargin.layoutAttribute == .topMargin) XCTAssertTrue(ReferenceAttribute.bottomMargin.layoutAttribute == .bottomMargin) XCTAssertTrue(ReferenceAttribute.leadingMargin.layoutAttribute == .leadingMargin) XCTAssertTrue(ReferenceAttribute.trailingMargin.layoutAttribute == .trailingMargin) XCTAssertTrue(ReferenceAttribute.centerXWithinMargins.layoutAttribute == .centerXWithinMargins) XCTAssertTrue(ReferenceAttribute.centerYWithinMargins.layoutAttribute == .centerYWithinMargins) } }
0
// // HomeMenu.swift // SimpleNeteaseMusic // // Created by shenjie on 2020/11/18. // Copyright © 2020 shenjie. All rights reserved. // import UIKit let JJDragonBallCellId = "JJDragonBallCellId" // 点击cell回调 public typealias MenuDidClickedBlock = (_ currentIndex: Int) -> Void /// 首页圆形按钮 class HomeMenu: UIView, UICollectionViewDelegate, UICollectionViewDataSource{ let margin: CGFloat = 10 // 分割线 lazy var separtor: UIImageView = { let line = UIImageView(frame: CGRect.zero) line.backgroundColor = .separtorColor return line }() // 圆形图标布局 private lazy var menusViewFlowLayout: UICollectionViewFlowLayout = { let collectionFlowLayout = UICollectionViewFlowLayout() collectionFlowLayout.minimumLineSpacing = 0 collectionFlowLayout.minimumInteritemSpacing = 0 collectionFlowLayout.sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0) return collectionFlowLayout }() // 圆形图标入口 private lazy var menusContainer: UICollectionView = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: self.menusViewFlowLayout) collectionView.isPagingEnabled = true collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.delegate = self collectionView.dataSource = self collectionView.bounces = true collectionView.backgroundColor = UIColor.clear collectionView.bounces = false return collectionView }() // 数据源 private var menusArray: [Datum]! { didSet{ if menusArray != nil { self.menusContainer.register(HomeMenuCell.self, forCellWithReuseIdentifier: JJDragonBallCellId) } self.menusContainer.reloadData() self.layoutIfNeeded() } } // 资源数量 private var sourceCount: Int!{ if self.menusArray != nil { return self.menusArray.count } return 0 } override func layoutSubviews() { super.layoutSubviews() self.menusContainer.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height) self.menusViewFlowLayout.itemSize = CGSize(width: 75 * scaleW, height: self.bounds.size.height-20) self.menusViewFlowLayout.scrollDirection = .horizontal self.separtor.snp.makeConstraints { make in make.width.equalToSuperview() make.height.equalTo(0.1) make.left.equalToSuperview() make.bottom.equalToSuperview().offset(-1) } } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.menusContainer) self.addSubview(self.separtor) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { self.menusContainer.delegate = nil self.menusContainer.dataSource = nil } } extension HomeMenu { public func updateUI(data: [Datum]?){ self.menusArray = data } } // MARK: - UICollectionViewDelegate, UICollectionViewDataSource extension HomeMenu { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.menusArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if self.menusArray != nil { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JJDragonBallCellId, for: indexPath) as! HomeMenuCell let model:Datum = self.menusArray[indexPath.row] cell.setupUI(imageUrl: model.iconURL, title: model.name) return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JJDragonBallCellId, for: indexPath) return cell } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){ } }
0
// // AuthViewController.swift // MeetupTweet // // Created by Yoshinori Imajo on 2016/04/10. // Copyright © 2016年 Yoshinori Imajo. All rights reserved. // import Cocoa import RxSwift import RxCocoa import OAuthSwift import TwitterAPI class AuthViewController: NSViewController { let userDefaults = UserDefaults() @IBOutlet weak var consumerKeyTextFeild: NSTextField! { didSet { if let consumerKey = userDefaults.consumerKey() { consumerKeyTextFeild.stringValue = consumerKey.trimmingCharacters(in: .whitespacesAndNewlines) } } } @IBOutlet weak var consumerSecretTextField: NSTextField! { didSet { if let consumerSecret = userDefaults.consumerSecret() { consumerSecretTextField.stringValue = consumerSecret.trimmingCharacters(in: .whitespacesAndNewlines) } } } @IBOutlet weak var authorizeButton: NSButton! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let authViewModel = AuthViewModel( consumerKey: consumerKeyTextFeild.rx.text.orEmpty.asObservable(), consumerSecret: consumerSecretTextField.rx.text.orEmpty.asObservable(), authrorizeTap: authorizeButton.rx.tap.asObservable(), twitterAuth: TwitterAuth.shared, userDefaults: userDefaults ) authViewModel.validated .bind(to: authorizeButton.rx.isEnabled) .disposed(by: disposeBag) authViewModel.authorized .drive(onNext: { [unowned self] _ in self.dismiss(nil) }) .disposed(by: disposeBag) authViewModel.errorMessage .drive(onNext: { [unowned self] in let info = self.configureAlertInfo(from: $0) let alert = NSAlert() alert.messageText = info.title alert.informativeText = info.text alert.addButton(withTitle: "OK") alert.runModal() }) .disposed(by: disposeBag) } @IBAction func tapHelpButton(_ sender: AnyObject) { let url = URL(string: "https://apps.twitter.com/")! NSWorkspace.shared.open(url) } @IBAction func tapCloseButton(_ sender: AnyObject) { dismiss(nil) AppDelegate.shared.quit() } } private extension AuthViewController { func configureAlertInfo(from error: Error) -> (title: String, text: String) { if let error = error as? OAuthSwiftError { switch error { case .requestError(error: _): let title = "API Key, Secretに関するエラー" let text = "存在しないAPI Key, Secretを入力しているか、もしくは、あなたのTwitter DeveloperのApp設定にてCallbackURLに\(TwitterAuth.callBackHost)://が追加されていない可能性があります。CallbackURLはブラウザ認証後にこのアプリを起動するためのURLスキーマです。" return (title: title, text: text) default: return (title: "認証に関するエラー", text: error.description) } } return (title: "原因不明のエラー", text: "このアプリケーションは実行するmacに対応していない可能性があります") } }
0
import Basic import Foundation import TuistCore import TuistGenerator protocol ManifestTargetGenerating { func generateManifestTarget(for project: String, at path: AbsolutePath) throws -> Target } class ManifestTargetGenerator: ManifestTargetGenerating { private let manifestLoader: GraphManifestLoading private let resourceLocator: ResourceLocating init(manifestLoader: GraphManifestLoading, resourceLocator: ResourceLocating) { self.manifestLoader = manifestLoader self.resourceLocator = resourceLocator } func generateManifestTarget(for project: String, at path: AbsolutePath) throws -> Target { let settings = Settings(base: try manifestTargetBuildSettings(), configurations: Settings.default.configurations, defaultSettings: .recommended) let manifests = manifestLoader.manifests(at: path) return Target(name: "\(project)_Manifest", platform: .macOS, product: .staticFramework, productName: "\(project)_Manifest", bundleId: "io.tuist.manifests.${PRODUCT_NAME:rfc1034identifier}", settings: settings, sources: manifests.map { (path: path.appending(component: $0.fileName), compilerFlags: nil) }, filesGroup: .group(name: "Manifest")) } func manifestTargetBuildSettings() throws -> [String: String] { let frameworkParentDirectory = try resourceLocator.projectDescription().parentDirectory var buildSettings = [String: String]() buildSettings["FRAMEWORK_SEARCH_PATHS"] = frameworkParentDirectory.pathString buildSettings["LIBRARY_SEARCH_PATHS"] = frameworkParentDirectory.pathString buildSettings["SWIFT_INCLUDE_PATHS"] = frameworkParentDirectory.pathString buildSettings["SWIFT_VERSION"] = Constants.swiftVersion return buildSettings } }
0
// // OpeningSceneButton.swift // DQ3 // // Created by aship on 2021/01/19. // import SpriteKit extension OpeningScene { func willPress(_ button: ButtonOverlay) { } func didPress(_ button: ButtonOverlay) { } }
0
// // NoLoWindow.swift // PamUIHelper // // Ryan Fitzgerald 11/2/21. // import Foundation import Cocoa class NoLoWindow: NSWindow { private var ctrlPressed:Bool = false; @IBOutlet weak var controller: SignIn! override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing bufferingType: NSWindow.BackingStoreType, defer flag: Bool) { super.init(contentRect: contentRect, styleMask: style, backing: .buffered, defer: false) } override var canBecomeKey: Bool { return true; } override var canBecomeMain: Bool { return true; } }
0
import Foundation public protocol OutputStreamProvider { func createOutputStream() throws -> OutputStream }
0
// // UIColor.swift // Boilerplate // // Created by Jeoffrey Thirot on 21/01/2019. // Copyright © 2019 Jeoffrey Thirot. All rights reserved. // import UIKit extension UIColor { static func random() -> UIColor { return UIColor(red: .random(), green: .random(), blue: .random(), alpha: 1.0) } }
0
// // CKPhotoSession.swift // CameraKit // // Created by Adrian Mateoaea on 08/01/2019. // Copyright © 2019 Wonderkiln. All rights reserved. // import UIKit import AVFoundation extension CKFSession.FlashMode { var captureFlashMode: AVCaptureDevice.FlashMode { switch self { case .off: return .off case .on: return .on case .auto: return .auto } } } @objc public class CKFPhotoSession: CKFSession, AVCapturePhotoCaptureDelegate, AVCaptureMetadataOutputObjectsDelegate { @objc public enum CameraDetection: UInt { case none, faces } @objc public var cameraPosition = CameraPosition.back { didSet { do { let deviceInput = try CKFSession.captureDeviceInput(type: self.cameraPosition.deviceType) self.captureDeviceInput = deviceInput } catch let error { print(error.localizedDescription) } } } @objc public var cameraDetection = CameraDetection.none { didSet { if oldValue == self.cameraDetection { return } for output in self.session.outputs { if output is AVCaptureMetadataOutput { self.session.removeOutput(output) } } self.faceDetectionBoxes.forEach({ $0.removeFromSuperview() }) self.faceDetectionBoxes = [] if self.cameraDetection == .faces { let metadataOutput = AVCaptureMetadataOutput() self.session.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: .main) if metadataOutput.availableMetadataObjectTypes.contains(.face) { metadataOutput.metadataObjectTypes = [.face] } } } } @objc public var flashMode = CKFSession.FlashMode.off @objc public var captureDeviceInput: AVCaptureDeviceInput? { didSet { self.faceDetectionBoxes.forEach({ $0.removeFromSuperview() }) self.faceDetectionBoxes = [] if let oldValue = oldValue { self.session.removeInput(oldValue) } if let captureDeviceInput = self.captureDeviceInput { self.session.addInput(captureDeviceInput) } } } @objc public let photoOutput = AVCapturePhotoOutput() var faceDetectionBoxes: [UIView] = [] @objc public init(position: CameraPosition = .back, detection: CameraDetection = .none) { super.init() defer { self.cameraPosition = position self.cameraDetection = detection } self.session.sessionPreset = .high self.session.addOutput(self.photoOutput) } @objc deinit { self.faceDetectionBoxes.forEach({ $0.removeFromSuperview() }) } var captureCallback: (UIImage, Data?, AVCaptureResolvedPhotoSettings) -> Void = { (_, _, _) in } var errorCallback: (Error) -> Void = { (_) in } @objc public func capture(_ settings: AVCapturePhotoSettings? = AVCapturePhotoSettings(), _ callback: @escaping (UIImage, Data?, AVCaptureResolvedPhotoSettings) -> Void, _ error: @escaping (Error) -> Void) { self.captureCallback = callback self.errorCallback = error guard let settings = settings else { return } settings.flashMode = self.flashMode.captureFlashMode if let connection = self.photoOutput.connection(with: .video) { if self.resolution.width > 0, self.resolution.height > 0 { connection.videoOrientation = .portrait } else { connection.videoOrientation = UIDevice.current.orientation.videoOrientation } } self.photoOutput.capturePhoto(with: settings, delegate: self) } @objc public func togglePosition() { self.cameraPosition = self.cameraPosition == .back ? .front : .back } @objc public override var zoom: Double { didSet { guard let device = self.captureDeviceInput?.device else { return } do { try device.lockForConfiguration() device.videoZoomFactor = CGFloat(self.zoom) device.unlockForConfiguration() } catch { // } if let delegate = self.delegate { delegate.didChangeValue(session: self, value: self.zoom, key: "zoom") } } } @objc public var resolution = CGSize.zero { didSet { guard let deviceInput = self.captureDeviceInput else { return } do { try deviceInput.device.lockForConfiguration() if self.resolution.width > 0, self.resolution.height > 0, let format = CKFSession.deviceInputFormat(input: deviceInput, width: Int(self.resolution.width), height: Int(self.resolution.height)) { deviceInput.device.activeFormat = format } else { self.session.sessionPreset = .high } deviceInput.device.unlockForConfiguration() } catch { // } } } @objc public override func focus(at point: CGPoint) { if let device = self.captureDeviceInput?.device, device.isFocusPointOfInterestSupported { do { try device.lockForConfiguration() device.focusPointOfInterest = point device.focusMode = .continuousAutoFocus device.unlockForConfiguration() } catch let error { print("Error while focusing at point \(point): \(error)") } } } public func photoOutput(_ output: AVCapturePhotoOutput, willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings) { // dispose system shutter sound AudioServicesDisposeSystemSoundID(1108) } var rawPhotoData: Data? = nil @available(iOS 11.0, *) public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { if let error = error { self.errorCallback(error) return } guard let data = photo.fileDataRepresentation() else { self.errorCallback(CKFError.error("Cannot get photo file data representation")) return } if photo.isRawPhoto { rawPhotoData = photo.fileDataRepresentation() } else { self.processPhotoData(rawPhotoData: rawPhotoData, processedPhotoData: data, resolvedSettings: photo.resolvedSettings) } } private func processPhotoData(rawPhotoData: Data?, processedPhotoData: Data, resolvedSettings: AVCaptureResolvedPhotoSettings) { defer { self.captureCallback = { (_, _, _) in } self.errorCallback = { (_) in } } guard let image = UIImage(data: processedPhotoData) else { return } if self.resolution.width > 0, self.resolution.height > 0, let transformedImage = CKUtils.cropAndScale(image, width: Int(self.resolution.width), height: Int(self.resolution.height), orientation: UIDevice.current.orientation, mirrored: self.cameraPosition == .front) { self.captureCallback(transformedImage, rawPhotoData, resolvedSettings) return } self.captureCallback(image, rawPhotoData, resolvedSettings) } public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { let faceMetadataObjects = metadataObjects.filter({ $0.type == .face }) if faceMetadataObjects.count > self.faceDetectionBoxes.count { for _ in 0..<faceMetadataObjects.count - self.faceDetectionBoxes.count { let view = UIView() view.layer.borderColor = UIColor.green.cgColor view.layer.borderWidth = 1 self.overlayView?.addSubview(view) self.faceDetectionBoxes.append(view) } } else if faceMetadataObjects.count < self.faceDetectionBoxes.count { for _ in 0..<self.faceDetectionBoxes.count - faceMetadataObjects.count { self.faceDetectionBoxes.popLast()?.removeFromSuperview() } } for i in 0..<faceMetadataObjects.count { if let transformedMetadataObject = self.previewLayer?.transformedMetadataObject(for: faceMetadataObjects[i]) { self.faceDetectionBoxes[i].frame = transformedMetadataObject.bounds } else { self.faceDetectionBoxes[i].frame = CGRect.zero } } } }
0
//// /// AuthTokenSpec.swift // @testable import Ello import Quick import Nimble class AuthTokenSpec: QuickSpec { override func spec() { describe("AuthToken") { it("returns correct data") { let keychain = FakeKeychain() keychain.authToken = "1234-fake-token" keychain.authTokenType = "fake-refresh-token" keychain.refreshAuthToken = "FakeType" keychain.isPasswordBased = true keychain.isStaff = true var token = AuthToken() token.keychain = keychain expect(token.token).to(equal(keychain.authToken)) expect(token.type).to(equal(keychain.authTokenType)) expect(token.refreshToken).to(equal(keychain.refreshAuthToken)) expect(token.isPasswordBased).to(equal(keychain.isPasswordBased)) expect(token.isStaff).to(equal(keychain.isStaff)) } it("correctly calculates presence of tokens") { let keychain = FakeKeychain() keychain.authToken = "1234-fake-token" keychain.authTokenType = "fake-refresh-token" keychain.refreshAuthToken = "FakeType" keychain.isPasswordBased = true keychain.isStaff = false var token = AuthToken() token.keychain = keychain expect(token.isPresent) == true } it("correctly calculates absence of tokens (token: nil)") { let keychain = FakeKeychain() keychain.authToken = nil keychain.authTokenType = "fake-refresh-token" keychain.refreshAuthToken = "FakeType" keychain.isPasswordBased = true keychain.isStaff = false var token = AuthToken() token.keychain = keychain expect(token.isPresent) == false } it("correctly calculates absence of tokens (token: \"\")") { let keychain = FakeKeychain() keychain.authToken = "" keychain.authTokenType = "fake-refresh-token" keychain.refreshAuthToken = "FakeType" keychain.isPasswordBased = true keychain.isStaff = false var token = AuthToken() token.keychain = keychain expect(token.isPresent) == false } context("storeToken(_:isPasswordBased:email:password:)") { let data = ElloAPI.anonymousCredentials.sampleData var token: AuthToken! beforeEach { AuthToken.reset() token = AuthToken() } it("is reset") { expect(token.token).to(beNil()) expect(token.type).to(beNil()) expect(token.refreshToken).to(beNil()) expect(token.isPresent) == false expect(token.isPasswordBased) == false expect(token.isStaff) == false expect(token.isAnonymous) == false expect(token.username).to(beNil()) expect(token.password).to(beNil()) } it("will store a password based token without user creds") { AuthToken.storeToken(data, isPasswordBased: true) expect(token.token).notTo(beNil()) expect(token.type).notTo(beNil()) expect(token.refreshToken).notTo(beNil()) expect(token.isPresent) == true expect(token.isPasswordBased) == true expect(token.isAnonymous) == false expect(token.isStaff) == false expect(token.username).to(beNil()) expect(token.password).to(beNil()) } it("will store a password based token with user creds") { AuthToken.storeToken( data, isPasswordBased: true, email: "email", password: "password" ) expect(token.token).notTo(beNil()) expect(token.type).notTo(beNil()) expect(token.refreshToken).notTo(beNil()) expect(token.isPresent) == true expect(token.isPasswordBased) == true expect(token.isAnonymous) == false expect(token.isStaff) == false expect(token.username) == "email" expect(token.password) == "password" } it("will store an anonymous token") { AuthToken.storeToken(data, isPasswordBased: false) expect(token.token).notTo(beNil()) expect(token.type).notTo(beNil()) expect(token.refreshToken).notTo(beNil()) expect(token.isPresent) == true expect(token.isPasswordBased) == false expect(token.isAnonymous) == true expect(token.isStaff) == false expect(token.username).to(beNil()) expect(token.password).to(beNil()) } } context("staff credentials") { var token: AuthToken! beforeEach { AuthToken.reset() token = AuthToken() } it("is staff") { let data = stubbedData("jwt-auth-is-staff") AuthToken.storeToken(data, isPasswordBased: true) expect(token.token).notTo(beNil()) expect(token.type).notTo(beNil()) expect(token.refreshToken).notTo(beNil()) expect(token.isPresent) == true expect(token.isPasswordBased) == true expect(token.isAnonymous) == false expect(token.isStaff) == true expect(token.username).to(beNil()) expect(token.password).to(beNil()) } } context("NON staff credentials") { var token: AuthToken! beforeEach { AuthToken.reset() token = AuthToken() } it("is staff") { let data = stubbedData("jwt-auth-no-staff") AuthToken.storeToken(data, isPasswordBased: true) expect(token.token).notTo(beNil()) expect(token.type).notTo(beNil()) expect(token.refreshToken).notTo(beNil()) expect(token.isPresent) == true expect(token.isPasswordBased) == true expect(token.isAnonymous) == false expect(token.isStaff) == false expect(token.username).to(beNil()) expect(token.password).to(beNil()) } } } } }
0
// // EnabledListItem.swift // Demo // // Created by Daniel Saidi on 2021-10-14. // Copyright © 2021 Daniel Saidi. All rights reserved. // import SwiftUI import SwiftUIKit /** This list item view is used to show if a certain feature is enabled or not. */ struct EnabledListItem: View { let isEnabled: Bool let enabledText: String let disabledText: String var body: some View { ListItem { Label( isEnabled ? enabledText : disabledText, image: isEnabled ? .checkmark : .alert) }.foregroundColor(isEnabled ? .green : .orange) } } struct EnabledListItem_Previews: PreviewProvider { static var previews: some View { EnabledListItem(isEnabled: true, enabledText: "Enabled", disabledText: "Disabled") EnabledListItem(isEnabled: false, enabledText: "Enabled", disabledText: "Disabled") } }
0
// // AppAppearanceType.swift // Example // // Created by incetro on 6/3/21. // import Designable // MARK: - AppAppearanceType enum AppAppearanceType: String, AnyAppearanceType { case light case dark case graphite }
0
// // XLSpeechRecognitionDemoTests.swift // XLSpeechRecognitionDemoTests // // Created by xiaoL on 17/1/5. // Copyright © 2017年 xiaolin. All rights reserved. // import XCTest @testable import XLSpeechRecognitionDemo class XLSpeechRecognitionDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
0
// // LaunchScreenViewController.swift // BarberShop // // Created by Daniel Radshun on 26/07/2019. // Copyright © 2019 Neighbors. All rights reserved. // import UIKit class LaunchScreenViewController: UIViewController { @IBOutlet weak var loadingImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() //setting the background color self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!) self.navigationController?.navigationBar.setBackgroundImage(#imageLiteral(resourceName: "background"), for: .default) self.startAnimating() } override func viewDidAppear(_ animated: Bool) { //checks internet connection: if !Reachability.isConnectedToNetwork(){ let alert = AlertService().alert(title: "אין חיבור אינטרנט", body: "אנא בדוק אם הינך מחובר לרשת האינטרנט", btnAmount: 1, positive: "אשר", negative: nil, positiveCompletion: { self.openWifiSettings() }, negativeCompletion: nil) present(alert, animated: true) { [weak self] in self?.loadingImage.layer.removeAllAnimations() } }else{ //load the aboutUs data AboutUs.fetchData() //load descriptionAboveBarbers line DescriptionAboveBarbers.fetchData() //load the barbershop contact details ContactUs.fetchData() //load a message from the barrber if there is one: BarberMessage.fetchData() //load the barbers and the prices let _ = AllBarbers.shared NotificationCenter.default.addObserver(forName: .dataWereLoaded, object: nil, queue: .main) { [weak self] (notification) in guard let isLoaded = notification.userInfo?["isLoaded"] as? Bool else {return} if isLoaded{ self?.performSegue(withIdentifier: "goToApp", sender: nil) } } } } override func viewDidDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self, name: .dataWereLoaded, object: nil) loadingImage.layer.removeAllAnimations() } fileprivate func startAnimating(){ UIView.animate(withDuration: 0.6, delay: 0, options: [.repeat, .autoreverse], animations: { self.loadingImage.transform = CGAffineTransform(scaleX: 1.4, y: 1.4) }) } }
0
import Foundation import ProjectDescription import TSCBasic import TuistCore import TuistGraph import TuistSupport public enum ManifestLoaderError: FatalError, Equatable { case projectDescriptionNotFound(AbsolutePath) case unexpectedOutput(AbsolutePath) case manifestNotFound(Manifest?, AbsolutePath) case manifestCachingFailed(Manifest?, AbsolutePath) case manifestLoadingFailed(path: AbsolutePath, context: String) public static func manifestNotFound(_ path: AbsolutePath) -> ManifestLoaderError { .manifestNotFound(nil, path) } public var description: String { switch self { case let .projectDescriptionNotFound(path): return "Couldn't find ProjectDescription.framework at path \(path.pathString)" case let .unexpectedOutput(path): return "Unexpected output trying to parse the manifest at path \(path.pathString)" case let .manifestNotFound(manifest, path): return "\(manifest?.fileName(path) ?? "Manifest") not found at path \(path.pathString)" case let .manifestCachingFailed(manifest, path): return "Could not cache \(manifest?.fileName(path) ?? "Manifest") at path \(path.pathString)" case let .manifestLoadingFailed(path, context): return """ Unable to load manifest at \(path.pathString.bold()) \(context) """ } } public var type: ErrorType { switch self { case .unexpectedOutput: return .bug case .projectDescriptionNotFound: return .bug case .manifestNotFound: return .abort case .manifestCachingFailed: return .abort case .manifestLoadingFailed: return .abort } } } public protocol ManifestLoading { /// Loads the Config.swift in the given directory. /// /// - Parameter path: Path to the directory that contains the Config.swift file. /// - Returns: Loaded Config.swift file. /// - Throws: An error if the file has a syntax error. func loadConfig(at path: AbsolutePath) throws -> ProjectDescription.Config /// Loads the Project.swift in the given directory. /// - Parameter path: Path to the directory that contains the Project.swift. func loadProject(at path: AbsolutePath) throws -> ProjectDescription.Project /// Loads the Workspace.swift in the given directory. /// - Parameter path: Path to the directory that contains the Workspace.swift func loadWorkspace(at path: AbsolutePath) throws -> ProjectDescription.Workspace /// Loads the name_of_template.swift in the given directory. /// - Parameter path: Path to the directory that contains the name_of_template.swift func loadTemplate(at path: AbsolutePath) throws -> ProjectDescription.Template /// Loads the Dependencies.swift in the given directory /// - Parameters: /// - path: Path to the directory that contains Dependencies.swift func loadDependencies(at path: AbsolutePath) throws -> ProjectDescription.Dependencies /// Loads the Plugin.swift in the given directory. /// - Parameter path: Path to the directory that contains Plugin.swift func loadPlugin(at path: AbsolutePath) throws -> ProjectDescription.Plugin /// List all the manifests in the given directory. /// - Parameter path: Path to the directory whose manifest files will be returend. func manifests(at path: AbsolutePath) -> Set<Manifest> /// Registers plugins that will be used within the manifest loading process. /// - Parameter plugins: The plugins to register. func register(plugins: Plugins) throws } public class ManifestLoader: ManifestLoading { // MARK: - Static static let startManifestToken = "TUIST_MANIFEST_START" static let endManifestToken = "TUIST_MANIFEST_END" // MARK: - Attributes let resourceLocator: ResourceLocating let manifestFilesLocator: ManifestFilesLocating let environment: Environmenting private let decoder: JSONDecoder private var plugins: Plugins = .none private let cacheDirectoryProviderFactory: CacheDirectoriesProviderFactoring private let projectDescriptionHelpersBuilderFactory: ProjectDescriptionHelpersBuilderFactoring // MARK: - Init public convenience init() { self.init( environment: Environment.shared, resourceLocator: ResourceLocator(), cacheDirectoryProviderFactory: CacheDirectoriesProviderFactory(), projectDescriptionHelpersBuilderFactory: ProjectDescriptionHelpersBuilderFactory(), manifestFilesLocator: ManifestFilesLocator() ) } init( environment: Environmenting, resourceLocator: ResourceLocating, cacheDirectoryProviderFactory: CacheDirectoriesProviderFactoring, projectDescriptionHelpersBuilderFactory: ProjectDescriptionHelpersBuilderFactoring, manifestFilesLocator: ManifestFilesLocating ) { self.environment = environment self.resourceLocator = resourceLocator self.cacheDirectoryProviderFactory = cacheDirectoryProviderFactory self.projectDescriptionHelpersBuilderFactory = projectDescriptionHelpersBuilderFactory self.manifestFilesLocator = manifestFilesLocator decoder = JSONDecoder() } public func manifests(at path: AbsolutePath) -> Set<Manifest> { Set(manifestFilesLocator.locateManifests(at: path).map(\.0)) } public func loadConfig(at path: AbsolutePath) throws -> ProjectDescription.Config { try loadManifest(.config, at: path) } public func loadProject(at path: AbsolutePath) throws -> ProjectDescription.Project { try loadManifest(.project, at: path) } public func loadWorkspace(at path: AbsolutePath) throws -> ProjectDescription.Workspace { try loadManifest(.workspace, at: path) } public func loadTemplate(at path: AbsolutePath) throws -> ProjectDescription.Template { try loadManifest(.template, at: path) } public func loadDependencies(at path: AbsolutePath) throws -> ProjectDescription.Dependencies { let dependencyPath = path.appending(components: Constants.tuistDirectoryName) return try loadManifest(.dependencies, at: dependencyPath) } public func loadPlugin(at path: AbsolutePath) throws -> ProjectDescription.Plugin { try loadManifest(.plugin, at: path) } public func register(plugins: Plugins) throws { self.plugins = plugins } // MARK: - Private // swiftlint:disable:next function_body_length private func loadManifest<T: Decodable>( _ manifest: Manifest, at path: AbsolutePath ) throws -> T { let manifestPath = try manifestPath( manifest, at: path ) let data = try loadDataForManifest(manifest, at: manifestPath) do { return try decoder.decode(T.self, from: data) } catch { guard let error = error as? DecodingError else { throw ManifestLoaderError.manifestLoadingFailed( path: manifestPath, context: error.localizedDescription ) } let json = (String(data: data, encoding: .utf8) ?? "nil") switch error { case let .typeMismatch(type, context): throw ManifestLoaderError.manifestLoadingFailed( path: manifestPath, context: """ The content of the manifest did not match the expected type of: \(String(describing: type).bold()) \(context.debugDescription) """ ) case let .valueNotFound(value, _): throw ManifestLoaderError.manifestLoadingFailed( path: manifestPath, context: """ Expected a non-optional value for property of type \(String(describing: value).bold()) but found a nil value. \(json.bold()) """ ) case let .keyNotFound(codingKey, _): throw ManifestLoaderError.manifestLoadingFailed( path: manifestPath, context: """ Did not find property with name \(codingKey.stringValue.bold()) in the JSON represented by: \(json.bold()) """ ) case let .dataCorrupted(context): throw ManifestLoaderError.manifestLoadingFailed( path: manifestPath, context: """ The encoded data for the manifest is corrupted. \(context.debugDescription) """ ) @unknown default: throw ManifestLoaderError.manifestLoadingFailed( path: manifestPath, context: """ Unable to decode the manifest for an unknown reason. \(error.localizedDescription) """ ) } } } private func manifestPath( _ manifest: Manifest, at path: AbsolutePath ) throws -> AbsolutePath { let manifestPath = path.appending(component: manifest.fileName(path)) guard FileHandler.shared.exists(manifestPath) else { throw ManifestLoaderError.manifestNotFound(manifest, path) } return manifestPath } private func loadDataForManifest( _ manifest: Manifest, at path: AbsolutePath ) throws -> Data { let arguments = try buildArguments( manifest, at: path ) + ["--tuist-dump"] do { let string = try System.shared.capture(arguments, verbose: false, environment: environment.manifestLoadingVariables) guard let startTokenRange = string.range(of: ManifestLoader.startManifestToken), let endTokenRange = string.range(of: ManifestLoader.endManifestToken) else { return string.data(using: .utf8)! } let preManifestLogs = String(string[string.startIndex ..< startTokenRange.lowerBound]).chomp() let postManifestLogs = String(string[endTokenRange.upperBound ..< string.endIndex]).chomp() if !preManifestLogs.isEmpty { logger.info("\(path.pathString): \(preManifestLogs)") } if !postManifestLogs.isEmpty { logger.info("\(path.pathString):\(postManifestLogs)") } let manifest = string[startTokenRange.upperBound ..< endTokenRange.lowerBound] return manifest.data(using: .utf8)! } catch { logUnexpectedImportErrorIfNeeded(in: path, error: error, manifest: manifest) logPluginHelperBuildErrorIfNeeded(in: path, error: error, manifest: manifest) throw error } } // swiftlint:disable:next function_body_length private func buildArguments( _ manifest: Manifest, at path: AbsolutePath ) throws -> [String] { let projectDescriptionPath = try resourceLocator.projectDescription() let searchPaths = ProjectDescriptionSearchPaths.paths(for: projectDescriptionPath) let frameworkName: String switch manifest { case .config, .plugin, .dependencies, .project, .template, .workspace: frameworkName = "ProjectDescription" } var arguments = [ "/usr/bin/xcrun", "swift", "-suppress-warnings", "-I", searchPaths.includeSearchPath.pathString, "-L", searchPaths.librarySearchPath.pathString, "-F", searchPaths.frameworkSearchPath.pathString, "-l\(frameworkName)", "-framework", frameworkName, ] let projectDescriptionHelpersCacheDirectory = try cacheDirectoryProviderFactory .cacheDirectories(config: nil) .cacheDirectory(for: .projectDescriptionHelpers) let projectDescriptionHelperArguments: [String] = try { switch manifest { case .config, .plugin: return [] case .dependencies, .project, .template, .workspace: return try projectDescriptionHelpersBuilderFactory.projectDescriptionHelpersBuilder( cacheDirectory: projectDescriptionHelpersCacheDirectory ) .build( at: path, projectDescriptionSearchPaths: searchPaths, projectDescriptionHelperPlugins: plugins.projectDescriptionHelpers ).flatMap { [ "-I", $0.path.parentDirectory.pathString, "-L", $0.path.parentDirectory.pathString, "-F", $0.path.parentDirectory.pathString, "-l\($0.name)", ] } } }() arguments.append(contentsOf: projectDescriptionHelperArguments) arguments.append(path.pathString) return arguments } private func logUnexpectedImportErrorIfNeeded(in path: AbsolutePath, error: Error, manifest: Manifest) { guard case let TuistSupport.SystemError.terminated(command, _, standardError) = error, manifest == .config || manifest == .plugin, command == "swiftc", let errorMessage = String(data: standardError, encoding: .utf8) else { return } let defaultHelpersName = ProjectDescriptionHelpersBuilder.defaultHelpersName if errorMessage.contains(defaultHelpersName) { logger.error("Cannot import \(defaultHelpersName) in \(manifest.fileName(path))") logger.info("Project description helpers that depend on plugins are not allowed in \(manifest.fileName(path))") } else if errorMessage.contains("import") { logger.error("Helper plugins are not allowed in \(manifest.fileName(path))") } } private func logPluginHelperBuildErrorIfNeeded(in _: AbsolutePath, error: Error, manifest _: Manifest) { guard case let TuistSupport.SystemError.terminated(command, _, standardError) = error, command == "swiftc", let errorMessage = String(data: standardError, encoding: .utf8) else { return } let pluginHelpers = plugins.projectDescriptionHelpers guard let pluginHelper = pluginHelpers.first(where: { errorMessage.contains($0.name) }) else { return } logger.error("Unable to build plugin \(pluginHelper.name) located at \(pluginHelper.path)") } }
0
import Mapper import XCTest final class CustomTransformationTests: XCTestCase { func testCustomTransformation() { struct Test: Mappable { let value: Int init(map: Mapper) throws { value = try map.from("value", transformation: { thing in if let a = thing as? Int { return a + 1 } else { return 0 } }) } } let test = try? Test(map: Mapper(JSON: ["value": 1])) XCTAssertTrue(test?.value == 2) } func testCustomTransformationThrows() { struct Test: Mappable { let value: Int init(map: Mapper) throws { try value = map.from("foo", transformation: { _ in throw MapperError.customError(field: nil, message: "") }) } } let test = try? Test(map: Mapper(JSON: [:])) XCTAssertNil(test) } func testOptionalCustomTransformationExists() { struct Test: Mappable { let string: String? init(map: Mapper) { string = map.optionalFrom("string", transformation: { $0 as? String }) } } let test = Test(map: Mapper(JSON: ["string": "hi"])) XCTAssertTrue(test.string == "hi") } func testOptionalCustomTransformationDoesNotExist() { struct Test: Mappable { let string: String? init(map: Mapper) { string = map.optionalFrom("string", transformation: { $0 as? String }) } } let test = Test(map: Mapper(JSON: [:])) XCTAssertNil(test.string) } func testOptionalCustomTransformationThrows() { struct Test: Mappable { let string: String? init(map: Mapper) throws { string = map.optionalFrom("foo", transformation: { _ in throw MapperError.customError(field: nil, message: "") }) } } do { let test = try Test(map: Mapper(JSON: [:])) XCTAssertNil(test.string) } catch { XCTFail("Shouldn't have failed to create Test") } } func testOptionalCustomTransformationArrayOfKeys() { struct Test: Mappable { let value: Int? init(map: Mapper) throws { value = map.optionalFrom(["a", "b"], transformation: { thing in if let a = thing as? Int { return a + 1 } throw MapperError.customError(field: nil, message: "") }) } } do { let test = try Test(map: Mapper(JSON: ["a": "##", "b": 1])) XCTAssertEqual(test.value, 2) } catch { XCTFail("Shouldn't have failed to create Test") } } func testOptionalCustomTransformationArrayOfKeysFails() { struct Test: Mappable { let value: Int? init(map: Mapper) throws { value = map.optionalFrom(["a", "b"], transformation: { _ in throw MapperError.customError(field: nil, message: "") }) } } do { let test = try Test(map: Mapper(JSON: ["a": "##", "b": 1])) XCTAssertNil(test.value) } catch { XCTFail("Shouldn't have failed to create Test") } } func testOptionalCustomTransformationArrayOfKeysReturnsNil() { struct Test: Mappable { let value: Int? init(map: Mapper) throws { value = map.optionalFrom(["a", "b"], transformation: { thing in if let a = thing as? Int { return a + 1 } throw MapperError.customError(field: nil, message: "") }) } } do { let test = try Test(map: Mapper(JSON: [:])) XCTAssertNil(test.value) } catch { XCTFail("Shouldn't have failed to create Test") } } }
0
// // MessageStream.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 07.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** - seealso: `WebimSession.getStream()` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol MessageStream: class { /** - seealso: `VisitSessionState` type. - returns: Current session state. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getVisitSessionState() -> VisitSessionState /** - returns: Current chat state. - seealso: `ChatState` type. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getChatState() -> ChatState /** - returns: Timestamp after which all chat messages are unread by operator (at the moment of last server update recieved). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getUnreadByOperatorTimestamp() -> Date? /** - returns: Timestamp after which all chat messages are unread by visitor (at the moment of last server update recieved) or `nil` if there's no unread by visitor messages. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getUnreadByVisitorTimestamp() -> Date? /** - returns: Count of unread by visitor messages (at the moment of last server update recieved). - author: Nikita Kaberov - copyright: 2018 Webim */ func getUnreadByVisitorMessageCount() -> Int /** - seealso: `Department` protocol. `DepartmentListChangeListener` protocol. - returns: List of departments or `nil` if there're any or department list is not received yet. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getDepartmentList() -> [Department]? /** - returns: Current LocationSettings of the MessageStream. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getLocationSettings() -> LocationSettings /** - returns: Operator of the current chat. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getCurrentOperator() -> Operator? /** - parameter id: ID of the operator. - returns: Previous rating of the operator or 0 if it was not rated before. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getLastRatingOfOperatorWith(id: String) -> Int /** Rates an operator. To get an ID of the current operator call `getCurrentOperator()`. - important: Requires existing chat. - seealso: `RateOperatorCompletionHandler` protocol. - parameter id: ID of the operator to be rated. If passed `nil` current chat operator will be rated. - parameter rate: A number in range (1...5) that represents an operator rating. If the number is out of range, rating will not be sent to a server. - parameter comletionHandler: `RateOperatorCompletionHandler` object. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func rateOperatorWith(id: String?, byRating rating: Int, completionHandler: RateOperatorCompletionHandler?) throws /** Rates an operator. To get an ID of the current operator call `getCurrentOperator()`. - important: Requires existing chat. - seealso: `RateOperatorCompletionHandler` protocol. - parameter id: ID of the operator to be rated. If passed `nil` current chat operator will be rated. - parameter note: A comment for rating. Maximum length is 2000 characters. - parameter rate: A number in range (1...5) that represents an operator rating. If the number is out of range, rating will not be sent to a server. - parameter comletionHandler: `RateOperatorCompletionHandler` object. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2020 Webim */ func rateOperatorWith(id: String?, note: String?, byRating rating: Int, completionHandler: RateOperatorCompletionHandler?) throws /** Respond sentry call - important: Id of redirect to sentry message - parameter id: ID of the operator to be rated. If passed `nil` current chat operator will be rated. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2018 Webim */ func respondSentryCall(id: String) throws /** Changes `ChatState` to `ChatState.queue`. Can cause `VisitSessionState.departmentSelection` session state. It means that chat must be started by `startChat(departmentKey:)` method. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func startChat() throws /** Starts chat and sends first message simultaneously. Changes `ChatState` to `ChatState.queue`. - parameter firstQuestion: First message to send. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func startChat(firstQuestion: String?) throws /** Starts chat with particular department. Changes `ChatState` to `ChatState.queue`. - seealso: `Department` protocol. - parameter departmentKey: Department key (see `getKey()` of `Department` protocol). Calling this method without this parameter passed is the same as `startChat()` method is called. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func startChat(departmentKey: String?) throws /** Starts chat with custom fields. Changes `ChatState` to `ChatState.queue`. - parameter customFields: Custom fields in JSON format. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2018 Webim */ func startChat(customFields:String?) throws /** Starts chat with particular department and sends first message simultaneously. Changes `ChatState` to `ChatState.queue`. - seealso: `Department` protocol. - parameter departmentKey: Department key (see `getKey()` of `Department` protocol). Calling this method without this parameter passed is the same as `startChat()` method is called. - parameter firstQuestion: First message to send. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev - copyright: 2017 Webim */ func startChat(departmentKey: String?, firstQuestion: String?) throws /** Starts chat with custom fields and sends first message simultaneously. Changes `ChatState` to `ChatState.queue`. - parameter firstQuestion: First message to send. - parameter customFields: Custom fields in JSON format. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2018 Webim */ func startChat(firstQuestion:String?, customFields: String?) throws /** Starts chat with particular department and custom fields. Changes `ChatState` to `ChatState.queue`. - seealso: `Department` protocol. - parameter departmentKey: Department key (see `getKey()` of `Department` protocol). Calling this method without this parameter passed is the same as `startChat()` method is called. - parameter customFields: Custom fields in JSON format. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2018 Webim */ func startChat(departmentKey: String?, customFields: String?) throws /** Starts chat with particular department and custom fields and sends first message simultaneously. Changes `ChatState` to `ChatState.queue`. - seealso: `Department` protocol. - parameter departmentKey: Department key (see `getKey()` of `Department` protocol). Calling this method without this parameter passed is the same as `startChat()` method is called. - parameter firstQuestion: First message to send. - parameter customFields: Custom fields in JSON format. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2018 Webim */ func startChat(departmentKey: String?, firstQuestion: String?, customFields: String?) throws /** Changes `ChatState` to `ChatState.closedByVisitor`. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func closeChat() throws /** This method must be called whenever there is a change of the input field of a message transferring current content of a message as a parameter. - parameter draftMessage: Current message content. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func setVisitorTyping(draftMessage: String?) throws /** Sends prechat fields to server. - parameter prechatFields: Custom fields. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2018 Webim */ func set(prechatFields: String) throws /** Sends a text message. When calling this method, if there is an active `MessageTracker` (see newMessageTracker(messageListener:)). `MessageListener.added(message:after:)`) with a message `MessageSendStatus.sending` in the status is also called. - important: Maximum length of message is 32000 characters. Longer messages will be clipped. - parameter message: Text of the message. - returns: ID of the message. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func send(message: String) throws -> String /** Sends a text message. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method). `MessageListener.added(message:after:)`) with a message `MessageSendStatus.SENDING` in the status is also called. - important: Maximum length of message is 32000 characters. Longer messages will be clipped. - parameter message: Text of the message. - parameter completionHandler: Completion handler that executes when operation is done. - returns: ID of the message. - throws: `AccessError.INVALID_THREAD` if the method was called not from the thread the WebimSession was created in. `AccessError.INVALID_SESSION` if WebimSession was destroyed. - author: Yury Vozleev - copyright: 2020 Webim */ func send(message: String, completionHandler: SendMessageCompletionHandler?) throws -> String /** Sends a text message. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method). `MessageListener.added(message:after:)`) with a message `MessageSendStatus.sending` in the status is also called. - important: Maximum length of message is 32000 characters. Longer messages will be clipped. - parameter message: Text of the message. - parameter data: Optional. Custom message parameters dictionary. Note that this functionality does not work as is – server version must support it. - parameter completionHandler: Completion handler that executes when operation is done. - returns: ID of the message. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func send(message: String, data: [String: Any]?, completionHandler: DataMessageCompletionHandler?) throws -> String /** Sends a text message. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method). `MessageListener.added(message:after:)`) with a message `MessageSendStatus.sending` in the status is also called. - important: Maximum length of message is 32000 characters. Longer messages will be clipped. - parameter message: Text of the message. - parameter isHintQuestion: Optional. Shows to server if a visitor chose a hint (true) or wrote his own text (false). - returns: ID of the message. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func send(message: String, isHintQuestion: Bool?) throws -> String /** Sends a message with uploaded files. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method). `MessageListener.added(message:after:)`) with a message `MessageSendStatus.sending` in the status is also called. - seealso: Method could fail. See `SendFilesError`. - important: Maximum count of files is 10. - parameter uploadedFiles: Uploaded files for sending. - parameter completionHandler: Completion handler that executes when operation is done. - returns: ID of the message. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2020 Webim */ func send(uploadedFiles: [UploadedFile], completionHandler: SendFilesCompletionHandler?) throws -> String /** Sends a file message. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method), `MessageListener.added(message:after:)` with a message `MessageSendStatus.sending` in the status is also called. - seealso: Method could fail. See `SendFileError`. - parameter file: File data to send - parameter filename: File name with file extension. - parameter mimeType: MIME type of the file to send. - parameter completionHandler: Completion handler that executes when operation is done. - returns: ID of the message. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func send(file: Data, filename: String, mimeType: String, completionHandler: SendFileCompletionHandler?) throws -> String /** Uploads a file to server. - seealso: Method could fail. See `SendFileError`. - parameter file: File data to send - parameter filename: File name with file extension. - parameter mimeType: MIME type of the file to send. - parameter completionHandler: Completion handler that executes when operation is done. - returns: ID of the message. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2020 Webim */ func uploadFilesToServer(file: Data, filename: String, mimeType: String, completionHandler: UploadFileToServerCompletionHandler?) throws -> String /** Deletes uploaded file from server. - seealso: Method could fail. See `DeleteUploadedFileError`. - parameter fileGuid: GUID of file. - parameter completionHandler: Completion handler that executes when operation is done. - returns: ID of the message. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2020 Webim */ func deleteUploadedFiles(fileGuid: String, completionHandler: DeleteUploadedFileCompletionHandler?) throws /** Send sticker to chat. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method), `MessageListener.added(message:after:)` with a message `MessageSendStatus.sending` in the status is also called. - parameter withId: Contains the id of the sticker to send - parameter completionHandler: Completion handler that executes when operation is done. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Yury Vozleev - copyright: 2020 Webim */ func sendSticker(withId: Int, completionHandler: SendStickerCompletionHandler?) throws /** Send keyboard request with button. - parameter button: Selected button. - parameter message: Message with keyboard. - parameter completionHandler: Completion handler that executes when operation is done. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Kaberov - copyright: 2019 Webim */ func sendKeyboardRequest(button: KeyboardButton, message: Message, completionHandler: SendKeyboardRequestCompletionHandler?) throws /** Send keyboard request with button. - parameter buttonID: ID of selected button. - parameter messageID: Current chat ID of message with keyboard. - parameter completionHandler: Completion handler that executes when operation is done. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Kaberov - copyright: 2020 Webim */ func sendKeyboardRequest(buttonID: String, messageCurrentChatID: String, completionHandler: SendKeyboardRequestCompletionHandler?) throws /** Update widget status. The change is displayed by the operator. - parameter data: JSON string with new widget status. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Nikita Kaberov - copyright: 2019 Webim */ func updateWidgetStatus(data: String) throws /** Reply a message. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method). `MessageListener.added(message:after:)`) with a message `MessageSendStatus.sending` in the status is also called. - important: Maximum length of message is 32000 characters. Longer messages will be clipped. - parameter message: Text of the message. - parameter repliedMessage: Replied message. - returns: ID of the message or nil, if message can't be replied. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Kaberov - copyright: 2019 Webim */ func reply(message: String, repliedMessage: Message) throws -> String? /** Edits a text message. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method). `MessageListener.changed(oldVersion:newVersion:)`) with a message `MessageSendStatus.sending` in the status is also called. - important: Maximum length of message is 32000 characters. Longer messages will be clipped. - parameter message: ID of the message to edit. - parameter text: Text of the message. - parameter completionHandler: Completion handler that executes when operation is done. - returns: True if the message can be edited. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Kaberov - copyright: 2018 Webim */ func edit(message: Message, text: String, completionHandler: EditMessageCompletionHandler?) throws -> Bool /** Deletes a message. When calling this method, if there is an active `MessageTracker` object (see `newMessageTracker(messageListener:)` method). `MessageListener.removed(message:)`) with a message `MessageSendStatus.sent` in the status is also called. - parameter message: The message to delete. - parameter completionHandler: Completion handler that executes when operation is done. - returns: True if the message can be deleted. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Kaberov - copyright: 2018 Webim */ func delete(message: Message, completionHandler: DeleteMessageCompletionHandler?) throws -> Bool /** Set chat has been read by visitor. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Aleksej Lapenok - copyright: 2018 Webim */ func setChatRead() throws /** Send current dialog to email address. - parameter emailAddress: Email addres for sending. - parameter completionHandler: Completion handler that executes when operation is done. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Kaberov - copyright: 2020 Webim */ func sendDialogTo(emailAddress: String, completionHandler: SendDialogToEmailAddressCompletionHandler?) throws /** Send survey answer. - parameter surveyAnswer Answer to survey. If question type is 'stars', answer is var 1-5 that corresponds the rating. If question type is 'radio', answer is index of element in options array beginning with 1. If question type is 'comment', answer is a string. - parameter completionHandler Completion handler that executes when operation is done. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Kaberov - copyright: 2020 Webim */ func send(surveyAnswer: String, completionHandler: SendSurveyAnswerCompletionHandler?) throws /** Method closes current survey. - parameter completionHandler Completion handler that executes when operation is done. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Kaberov - copyright: 2020 Webim */ func closeSurvey(completionHandler: SurveyCloseCompletionHandler?) throws /** Sets `SurveyListener` object. - seealso: `SurveyListener` protocol. - parameter surveyListener: `SurveyListener` object. - author: Nikita Kaberov - copyright: 2020 Webim */ func set(surveyListener: SurveyListener) /** `MessageTracker` (via `MessageTracker.getNextMessages(byLimit:completion:)`) allows to request the messages which are above in the history. Each next call `MessageTracker.getNextMessages(byLimit:completion:)` returns earlier messages in relation to the already requested ones. Changes of user-visible messages (e.g. ever requested from `MessageTracker`) are transmitted to `MessageListener`. That is why `MessageListener` is needed when creating `MessageTracker`. - important: For each `MessageStream` at every single moment can exist the only one active `MessageTracker`. When creating a new one at the previous there will be automatically called `MessageTracker.destroy()`. - parameter messageListener: A listener of message changes in the tracking range. - returns: A new `MessageTracker` for this stream. - throws: `AccessError.invalidThread` if the method was called not from the thread the WebimSession was created in. `AccessError.invalidSession` if WebimSession was destroyed. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func newMessageTracker(messageListener: MessageListener) throws -> MessageTracker /** Sets `VisitSessionStateListener` object. - seealso: `VisitSessionStateListener` protocol. `VisitSessionState` type. - parameter visitSessionStateListener: `VisitSessionStateListener` object. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func set(visitSessionStateListener: VisitSessionStateListener) /** Sets the `ChatState` change listener. - parameter chatStateListener: The `ChatState` change listener. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func set(chatStateListener: ChatStateListener) /** Sets the current `Operator` change listener. - parameter currentOperatorChangeListener: Current `Operator` change listener. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func set(currentOperatorChangeListener: CurrentOperatorChangeListener) /** Sets `DepartmentListChangeListener` object. - seealso: `DepartmentListChangeListener` protocol. `Department` protocol. - parameter departmentListChangeListener: `DepartmentListChangeListener` object. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func set(departmentListChangeListener: DepartmentListChangeListener) /** Sets the listener of the MessageStream LocationSettings changes. - parameter locationSettingsChangeListener: The listener of MessageStream LocationSettings changes. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func set(locationSettingsChangeListener: LocationSettingsChangeListener) /** Sets the listener of the "operator typing" status changes. - parameter operatorTypingListener: The listener of the "operator typing" status changes. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func set(operatorTypingListener: OperatorTypingListener) /** Sets the listener of session status changes. - parameter onlineStatusChangeListener: `OnlineStatusChangeListener` object. - seealso: `OnlineStatusChangeListener` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func set(onlineStatusChangeListener: OnlineStatusChangeListener) /** Sets listener for parameter that is to be returned by `MessageStream.getUnreadByOperatorTimestamp()` method. - parameter unreadByOperatorTimestampChangeListener: `UnreadByOperatorTimestampChangeListener` object. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ func set(unreadByOperatorTimestampChangeListener: UnreadByOperatorTimestampChangeListener) /** Sets listener for parameter that is to be returned by `MessageStream.getUnreadByVisitorMessageCount()` method. - parameter unreadByVisitorMessageCountChangeListener: `UnreadByVisitorMessageCountChangeListener` object. - author: Nikita Kaberov - copyright: 2018 Webim */ func set(unreadByVisitorMessageCountChangeListener: UnreadByVisitorMessageCountChangeListener) /** Sets listener for parameter that is to be returned by `MessageStream.getUnreadByVisitorTimestamp()` method. - parameter unreadByVisitorTimestampChangeListener: `UnreadByVisitorTimestampChangeListener` object. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ func set(unreadByVisitorTimestampChangeListener: UnreadByVisitorTimestampChangeListener) /** Sets listener for hello message. - parameter helloMessageListener: `HelloMessageListener` object. - attention: This method can't be used as is. It requires that client server to support this mechanism. - author: Yury Vozleev - copyright: 2020 Webim */ func set(helloMessageListener: HelloMessageListener) } /** Interface that provides methods for handling MessageStream LocationSettings which are received from server. - seealso: `LocationSettingsChangeListener` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol LocationSettings { /** This method shows to an app if it should show hint questions to visitor. - returns: True if an app should show hint questions to visitor, false otherwise. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func areHintsEnabled() -> Bool } // MARK: - /** - seealso: `MessageStream.send(message:data:completionHandler:)`. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ public protocol DataMessageCompletionHandler: class { /** Executed when operation is done successfully. - parameter messageID: ID of the message. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ func onSuccess(messageID: String) /** Executed when operation is failed. - parameter messageID: ID of the message. - parameter error: Error. - seealso: `DataMessageError`. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ func onFailure(messageID: String, error: DataMessageError) } /** - seealso: `MessageStream.edit(message:messageID:completionHandler:)`. - author: Nikita Kaberov - copyright: 2018 Webim */ public protocol EditMessageCompletionHandler: class { /** Executed when operation is done successfully. - parameter messageID: ID of the message. - author: Nikita Kaberov - copyright: 2018 Webim */ func onSuccess(messageID: String) /** Executed when operation is failed. - parameter messageID: ID of the message. - parameter error: Error. - seealso: `EditMessageError`. - author: Nikita Kaberov - copyright: 2018 Webim */ func onFailure(messageID: String, error: EditMessageError) } /** - seealso: `MessageStream.delete(messageID:completionHandler:)`. - author: Nikita Kaberov - copyright: 2018 Webim */ public protocol DeleteMessageCompletionHandler: class { /** Executed when operation is done successfully. - parameter messageID: ID of the message. - author: Nikita Kaberov - copyright: 2018 Webim */ func onSuccess(messageID: String) /** Executed when operation is failed. - parameter messageID: ID of the message. - parameter error: Error. - seealso: `DeleteMessageError`. - author: Nikita Kaberov - copyright: 2018 Webim */ func onFailure(messageID: String, error: DeleteMessageError) } /** - seealso: `MessageStream.send(message:completionHandler:)` - author: Yury Vozleev - copyright: 2020 Webim */ public protocol SendMessageCompletionHandler: class { func onSuccess(messageID: String) } /** - seealso: `MessageStream.send(file:filename:mimeType:completionHandler:)` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol SendFileCompletionHandler: class { /** Executed when operation is done successfully. - parameter messageID: ID of the message. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func onSuccess(messageID: String) /** Executed when operation is failed. - parameter messageID: ID of the message. - parameter error: Error. - seealso: `SendFileError`. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func onFailure(messageID: String, error: SendFileError) } public protocol SendFilesCompletionHandler: class { /** Executed when operation is done successfully. - parameter messageID: ID of the message. - author: Nikita Kaberov - copyright: 2020 Webim */ func onSuccess(messageID: String) /** Executed when operation is failed. - parameter messageID: ID of the message. - parameter error: Error. - seealso: `SendFileError`. - author: Nikita Kaberov - copyright: 2020 Webim */ func onFailure(messageID: String, error: SendFilesError) } public protocol UploadFileToServerCompletionHandler: class { /** Executed when operation is done successfully. - parameter id: ID of the message. - parameter uploadedFile: Uploaded file from server. - author: Nikita Kaberov - copyright: 2020 Webim */ func onSuccess(id: String, uploadedFile: UploadedFile) /** Executed when operation is failed. - parameter messageID: ID of the message. - parameter error: Error. - seealso: `SendFileError`. - author: Nikita Kaberov - copyright: 2020 Webim */ func onFailure(messageID: String, error: SendFileError) } public protocol DeleteUploadedFileCompletionHandler: class { /** Executed when operation is done successfully. - parameter id: ID of the message. - parameter uploadedFile: Uploaded file from server. - author: Nikita Kaberov - copyright: 2020 Webim */ func onSuccess() /** Executed when operation is failed. - parameter error: Error. - seealso: `SendFileError`. - author: Nikita Kaberov - copyright: 2020 Webim */ func onFailure(error: DeleteUploadedFileError) } /** - seealso: `MessageStream.sendKeyboardRequest(button:message:completionHandler:)` - author: Nikita Kaberov - copyright: 2019 Webim */ public protocol SendKeyboardRequestCompletionHandler: class { /** Executed when operation is done successfully. - parameter messageID: ID of the message. - author: Nikita Kaberov - copyright: 2019 Webim */ func onSuccess(messageID: String) /** Executed when operation is failed. - parameter messageID: ID of the message. - parameter error: Error. - seealso: `KeyboardResponseError`. - author: Nikita Kaberov - copyright: 2019 Webim */ func onFailure(messageID: String, error: KeyboardResponseError) } /** - seealso: `MessageStream.rateOperatorWith(id:byRating:completionHandler:)`. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol RateOperatorCompletionHandler: class { /** Executed when operation is done successfully. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func onSuccess() /** Executed when operation is failed. - parameter error: Error. - seealso: `RateOperatorError`. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func onFailure(error: RateOperatorError) } /** - seealso: `MessageStream.sendDialogTo(emailAddress:completionHandler:)`. - author: Nikita Kaberov - copyright: 2020 Webim */ public protocol SendDialogToEmailAddressCompletionHandler: class { /** Executed when operation is done successfully. - author: Nikita Kaberov - copyright: 2020 Webim */ func onSuccess() /** Executed when operation is failed. - parameter error: Error. - seealso: `SendDialogToEmailAddressError`. - author: Nikita Kaberov - copyright: 2020 Webim */ func onFailure(error: SendDialogToEmailAddressError) } /** - seealso: `MessageStream.sendSticker(withId:completionHandler:)`. - author: Yury Vozleev - copyright: 2020 Webim */ public protocol SendStickerCompletionHandler: class { /** Executed when operation is done successfully. - author: Yury Vozleev - copyright: 2020 Webim */ func onSuccess() /** Executed when operation is failed. - parameter error: Error. - seealso: `SendStickerError`. - author: Yury Vozleev - copyright: 2020 Webim */ func onFailure(error: SendStickerError) } /** - seealso: `MessageStream.send(surveyAnswer:completionHandler:)`. - author: Nikita Kaberov - copyright: 2020 Webim */ public protocol SendSurveyAnswerCompletionHandler { /** Executed when operation is done successfully. - author: Nikita Kaberov - copyright: 2020 Webim */ func onSuccess() /** Executed when operation is failed. - parameter error: Error. - seealso: `SurveyAnswerError`. - author: Nikita Kaberov - copyright: 2020 Webim */ func onFailure(error: SendSurveyAnswerError) } /** - seealso: `MessageStream.closeSurvey(completionHandler:)`. - author: Nikita Kaberov - copyright: 2020 Webim */ public protocol SurveyCloseCompletionHandler { /** Invoked when survey was successfully closed on server. - author: Nikita Kaberov - copyright: 2020 Webim */ func onSuccess() /** Invoked when an error occurred while closing a survey on server. - author: Nikita Kaberov - copyright: 2020 Webim */ func onFailure(error: SurveyCloseError) } /** Provides methods to track changes of `VisitSessionState` status. - seealso: `VisitSessionState` protocol. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol VisitSessionStateListener: class { /** Called when `VisitSessionState` status is changed. - parameter previousState: Previous value of `VisitSessionState` status. - parameter newState: New value of `VisitSessionState` status. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func changed(state previousState: VisitSessionState, to newState: VisitSessionState) } /** Delegate protocol that provides methods to handle changes of chat state. - seealso: `MessageStream.set(chatStateListener:)` `MessageStream.getChatState()` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol ChatStateListener: class { /** Called during `ChatState` transition. - parameter previousState: Previous state. - parameter newState: New state. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func changed(state previousState: ChatState, to newState: ChatState) } /** - seealso: `MessageStream.set(currentOperatorChangeListener:)` `MessageStream.getCurrentOperator()` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol CurrentOperatorChangeListener: class { /** Called when `Operator` of the current chat changed. - parameter previousOperator: Previous operator. - parameter newOperator: New operator or nil if doesn't exist. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func changed(operator previousOperator: Operator?, to newOperator: Operator?) } /** Provides methods to track changes in departments list. - seealso: `Department` protocol. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol DepartmentListChangeListener: class { /** Called when department list is received. - seealso: `Department` protocol. - parameter departmentList: Current department list. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func received(departmentList: [Department]) } /** Interface that provides methods for handling changes in LocationSettings. - seealso: `LocationSettings` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol LocationSettingsChangeListener: class { /** Method called by an app when new LocationSettings object is received. - parameter previousLocationSettings: Previous LocationSettings state. - parameter newLocationSettings: New LocationSettings state. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func changed(locationSettings previousLocationSettings: LocationSettings, to newLocationSettings: LocationSettings) } /** - seealso: `MessageStream.set(operatorTypingListener:)` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol OperatorTypingListener: class { /** Called when operator typing state changed. - parameter isTyping: True if operator is typing, false otherwise. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func onOperatorTypingStateChanged(isTyping: Bool) } /** Interface that provides methods for handling changes of session status. - seealso: `MessageStream.set(onlineStatusChangeListener:)` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol OnlineStatusChangeListener: class { /** Called when new session status is received. - parameter previousOnlineStatus: Previous value. - parameter newOnlineStatus: New value. - seealso: `OnlineStatus` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func changed(onlineStatus previousOnlineStatus: OnlineStatus, to newOnlineStatus: OnlineStatus) } /** Interface that provides methods for handling changes of survey. - seealso: `MessageStream.set(surveyListener:)` - author: Nikita Kaberov - copyright: 2020 Webim */ public protocol SurveyListener: class { /** Method to be called one time when new survey was sent by server. - parameter survey: Survey that was sent. - author: Nikita Kaberov - copyright: 2020 Webim */ func on(survey: Survey) /** Method provide next question in the survey. It is called in one of two ways: survey first received or answer for previous question was successfully sent to server. - parameter nextQuestion: Next question in the survey. - author: Nikita Kaberov - copyright: 2020 Webim */ func on(nextQuestion: SurveyQuestion) /** Method is called when survey timeout expires on server. It means that survey deletes and you can no longer send an answer to the question. - author: Nikita Kaberov - copyright: 2020 Webim */ func onSurveyCancelled() } /** Interface that provides methods for handling changes of parameter that is to be returned by `MessageStream.getUnreadByOperatorTimestamp()` method. - seealso: `MessageStream.set(unreadByOperatorTimestampChangeListener:)`. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ public protocol UnreadByOperatorTimestampChangeListener: class { /** Method to be called when parameter that is to be returned by `MessageStream.getUnreadByOperatorTimestamp()` method is changed. - parameter newValue: New unread by operator timestamp value. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ func changedUnreadByOperatorTimestampTo(newValue: Date?) } /** Interface that provides methods for handling changes of parameter that is to be returned by `MessageStream.getUnreadByVisitorMessageCount()` method. - seealso: `MessageStream.set(unreadByVisitorMessageCountChangeListener:)`. - author: Nikita Kaberov - copyright: 2018 Webim */ public protocol UnreadByVisitorMessageCountChangeListener: class { /** Interface that provides methods for handling changes of parameter that is to be returned by `MessageStream.getUnreadByVisitorMessageCount()` method. - parameter newValue: New unread by visitor message count value. - author: Nikita Kaberov - copyright: 2018 Webim */ func changedUnreadByVisitorMessageCountTo(newValue: Int) } /** Interface that provides methods for handling changes of parameter that is to be returned by `MessageStream.getUnreadByVisitorTimestamp()` method. - seealso: `MessageStream.set(unreadByVisitorTimestampChangeListener:)`. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ public protocol UnreadByVisitorTimestampChangeListener: class { /** Interface that provides methods for handling changes of parameter that is to be returned by `MessageStream.getUnreadByVisitorTimestamp()` method. - parameter newValue: New unread by visitor timestamp value. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ func changedUnreadByVisitorTimestampTo(newValue: Date?) } /** Interface that provides methods for handling Hello messages. - seealso: `MessageStream.set(helloMessageListener:)` - author: Yury Vozleev - copyright: 2020 Webim */ public protocol HelloMessageListener: class { /** Calls at the begining of chat when hello message is available and no messages has been sent yet. - parameter message: Text of the Hello message. - author: Yury Vozleev - copyright: 2020 Webim */ func helloMessage(message: String) } // MARK: - /** A chat is seen in different ways by an operator depending on ChatState. The initial state is `closed`. Then if a visitor sends a message (`MessageStream.send(message:isHintQuestion:)`), the chat changes it's state to `queue`. The chat can be turned into this state by calling `MessageStream.startChat()`. After that, if an operator takes the chat to process, the state changes to `chatting`. The chat is being in this state until the visitor or the operator closes it. When closing a chat by the visitor `MessageStream.closeChat()`, it turns into the state `closedByVisitor`, by the operator - `closedByOperator`. When both the visitor and the operator close the chat, it's state changes to the initial – `closed`. A chat can also automatically turn into the initial state during long-term absence of activity in it. Furthermore, the first message can be sent not only by a visitor but also by an operator. In this case the state will change from the initial to `invitation`, and then, after the first message of the visitor, it changes to `chatting`. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public enum ChatState { /** Means that an operator has taken a chat for processing. From this state a chat can be turned into: * `closedByOperator`, if an operator closes the chat; * `closedByVisitor`, if a visitor closes the chat (`MessageStream.closeChat()`); * `closed`, automatically during long-term absence of activity. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case chatting @available(*, unavailable, renamed: "chatting") case CHATTING /** Means that chat is picked up by a bot. From this state a chat can be turned into: * `chatting`, if an operator intercepted the chat; * `closedByVisitor`, if a visitor closes the chat (`MessageStream.closeChat()`); * `closed`, automatically during long-term absence of activity. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ case chattingWithRobot @available(*, unavailable, renamed: "chattingWithRobot") case CHATTING_WITH_ROBOT /** Means that an operator has closed the chat. From this state a chat can be turned into: * `closed`, if the chat is also closed by a visitor (`MessageStream.closeChat()`), or automatically during long-term absence of activity; * `queue`, if a visitor sends a new message (`MessageStream.send(message:isHintQuestion:)`). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case closedByOperator @available(*, unavailable, renamed: "closedByOperator") case CLOSED_BY_OPERATOR /** Means that a visitor has closed the chat. From this state a chat can be turned into: * `closed`, if the chat is also closed by an operator or automatically during long-term absence of activity; * `queue`, if a visitor sends a new message (`MessageStream.send(message:isHintQuestion:)`). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case closedByVisitor @available(*, unavailable, renamed: "closedByVisitor") case CLOSED_BY_VISITOR /** Means that a chat has been started by an operator and at this moment is waiting for a visitor's response. From this state a chat can be turned into: * `chatting`, if a visitor sends a message (`MessageStream.send(message:isHintQuestion:)`); * `closed`, if an operator or a visitor closes the chat (`MessageStream.closeChat()`). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case invitation @available(*, unavailable, renamed: "invitation") case INVITATION /** Means the absence of a chat as such, e.g. a chat has not been started by a visitor nor by an operator. From this state a chat can be turned into: * `queue`, if the chat is started by a visitor (by the first message or by calling `MessageStream.startChat()`; * `invitation`, if the chat is started by an operator. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case closed @available(*, unavailable, renamed: "closed") case NONE /** Means that a chat has been started by a visitor and at this moment is being in the queue for processing by an operator. From this state a chat can be turned into: * `chatting`, if an operator takes the chat for processing; * `closed`, if a visitor closes the chat (by calling (`MessageStream.closeChat()`) before it is taken for processing; * `closedByOperator`, if an operator closes the chat without taking it for processing. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case queue @available(*, unavailable, renamed: "queue") case QUEUE /** The state is undefined. This state is set as the initial when creating a new session, until the first response of the server containing the actual state is got. This state is also used as a fallback if WebimClientLibrary can not identify the server state (e.g. if the server has been updated to a version that contains new states). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN } /** Online state possible cases. - seealso: `OnlineStatusChangeListener` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public enum OnlineStatus { /** Offline state with chats' count limit exceeded. Means that visitor is not able to send messages at all. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case busyOffline @available(*, unavailable, renamed: "busyOffline") case BUSY_OFFLINE /** Online state with chats' count limit exceeded. Visitor is able send offline messages, but the server can reject it. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case busyOnline @available(*, unavailable, renamed: "busyOnline") case BUSY_ONLINE /** Visitor is able to send offline messages. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case offline @available(*, unavailable, renamed: "offline") case OFFLINE /** Visitor is able to send both online and offline messages. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case online @available(*, unavailable, renamed: "online") case ONLINE /** First status is not recieved yet or status is not supported by this version of the library. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN } /** Session possible states. - seealso: `getVisitSessionState()` method of `MessageStream` protocol. `VisitSessionStateListener` protocol. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public enum VisitSessionState { /** Chat in progress. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case chat @available(*, unavailable, renamed: "chat") case CHAT /** Chat must be started with department selected (there was a try to start chat without department selected). - seealso: `startChat(departmentKey:)` of `MessageStream` protocol. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case departmentSelection @available(*, unavailable, renamed: "departmentSelection") case DEPARTMENT_SELECTION /** Session is active but no chat is occuring (chat was not started yet). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case idle @available(*, unavailable, renamed: "idle") case IDLE /** Session is active but no chat is occuring (chat was closed recently). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case idleAfterChat @available(*, unavailable, renamed: "idleAfterChat") case IDLE_AFTER_CHAT /** Offline state. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case offlineMessage @available(*, unavailable, renamed: "offlineMessage") case OFFLINE_MESSAGE /** First status is not received yet or status is not supported by this version of the library. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN } /** - seealso: `DataMessageCompletionHandler.onFailure(messageID:error:)`. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ public enum DataMessageError: Error { /** Received error is not supported by current WebimClientLibrary version. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN // MARK: Quoted message errors // Note that quoted message mechanism is not a standard feature – it must be implemented by a server. For more information please contact with Webim support service. /** To be raised when quoted message ID belongs to a message without `canBeReplied` flag set to `true` (this flag is to be set on the server-side). - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ case quotedMessageCanNotBeReplied @available(*, unavailable, renamed: "quotedMessageCanNotBeReplied") case QUOTED_MESSAGE_CANNOT_BE_REPLIED /** To be raised when quoted message ID belongs to another visitor's chat. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ case quotedMessageFromAnotherVisitor @available(*, unavailable, renamed: "quotedMessageFromAnotherVisitor") case QUOTED_MESSAGE_FROM_ANOTHER_VISITOR /** To be raised when quoted message ID belongs to multiple messages (server DB error). - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ case quotedMessageMultipleIds @available(*, unavailable, renamed: "quotedMessageMultipleIds") case QUOTED_MESSAGE_MULTIPLE_IDS /** To be raised when one or more required arguments of quoting mechanism are missing. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ case quotedMessageRequiredArgumentsMissing @available(*, unavailable, renamed: "quotedMessageRequiredArgumentsMissing") case QUOTED_MESSAGE_REQUIRED_ARGUMENTS_MISSING /** To be raised when wrong quoted message ID is sent. - author: Nikita Lazarev-Zubov - copyright: 2018 Webim */ case quotedMessageWrongId @available(*, unavailable, renamed: "quotedMessageWrongId") case QUOTED_MESSAGE_WRONG_ID } /** - seealso: `EditMessageCompletionHandler.onFailure(messageID:error:)` - author: Nikita Kaberov - copyright: 2018 Webim */ public enum EditMessageError: Error { /** Received error is not supported by current WebimClientLibrary version. - author: Nikita Kaberov - copyright: 2018 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN /** Editing messages by visitor is turned off on the server. - author: Nikita Kaberov - copyright: 2018 Webim */ case notAllowed @available(*, unavailable, renamed: "notAllowed") case NOT_ALLOWED /** Editing message is empty. - author: Nikita Kaberov - copyright: 2018 Webim */ case messageEmpty @available(*, unavailable, renamed: "messageEmpty") case MESSAGE_EMPTY /** Visitor can edit only his messages. The specified id belongs to someone else's message. - author: Nikita Kaberov - copyright: 2018 Webim */ case messageNotOwned @available(*, unavailable, renamed: "messageNotOwned") case MESSAGE_NOT_OWNED /** The server may deny a request if the message size exceeds a limit. The maximum size of a message is configured on the server. - author: Nikita Kaberov - copyright: 2018 Webim */ case maxLengthExceeded @available(*, unavailable, renamed: "maxLengthExceeded") case MAX_LENGTH_EXCEEDED /** Visitor can edit only text messages. - author: Nikita Kaberov - copyright: 2018 Webim */ case wrongMesageKind @available(*, unavailable, renamed: "wrongMesageKind") case WRONG_MESSAGE_KIND } /** - seealso: `DeleteMessageCompletionHandler.onFailure(messageID:error:)` - author: Nikita Kaberov - copyright: 2018 Webim */ public enum DeleteMessageError: Error { /** Received error is not supported by current WebimClientLibrary version. - author: Nikita Kaberov - copyright: 2018 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN /** Deleting messages by visitor is turned off on the server. - author: Nikita Kaberov - copyright: 2018 Webim */ case notAllowed @available(*, unavailable, renamed: "notAllowed") case NOT_ALLOWED /** Visitor can delete only his messages. The specified id belongs to someone else's message. - author: Nikita Kaberov - copyright: 2018 Webim */ case messageNotOwned @available(*, unavailable, renamed: "messageNotOwned") case MESSAGE_NOT_OWNED /** Message with the specified id is not found in history. - author: Nikita Kaberov - copyright: 2018 Webim */ case messageNotFound @available(*, unavailable, renamed: "messageNotFound") case MESSAGE_NOT_FOUND } /** - seealso: `SendFileCompletionHandler.onFailure(messageID:error:)` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public enum SendFileError: Error { /** The server may deny a request if the file size exceeds a limit. The maximum size of a file is configured on the server. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case fileSizeExceeded @available(*, unavailable, renamed: "fileSizeExceeded") case FILE_SIZE_EXCEEDED case fileSizeTooSmall /** The server may deny a request if the file type is not allowed. The list of allowed file types is configured on the server. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case fileTypeNotAllowed @available(*, unavailable, renamed: "fileTypeNotAllowed") case FILE_TYPE_NOT_ALLOWED case maxFilesCountPerChatExceeded /** Sending files in body is not supported. Use multipart form only. - author: Nikita Kaberov - copyright: 2018 Webim */ case uploadedFileNotFound @available(*, unavailable, renamed: "uploadedFileNotFound") case UPLOADED_FILE_NOT_FOUND /** Received error is not supported by current WebimClientLibrary version. - author: Nikita Kaberov - copyright: 2018 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN /** Visitor authorization error on the server. - author: Nikita Kaberov - copyright: 2020 Webim */ case unauthorized } public enum SendFilesError: Error { case fileNotFound case maxFilesCountPerMessage case unknown } public enum DeleteUploadedFileError: Error { case fileNotFound case fileHasBeenSent case unknown } /** - seealso: `KeyboardResponseCompletionHandler.onFailure(error:)`. - author: Nikita Kaberov - copyright: 2019 Webim */ public enum KeyboardResponseError: Error { /** Received error is not supported by current WebimClientLibrary version. - author: Nikita Kaberov - copyright: 2019 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN /** Arised when trying to response if no chat is exists. - author: Nikita Kaberov - copyright: 2019 Webim */ case noChat @available(*, unavailable, renamed: "noChat") case NO_CHAT /** Arised when trying to response without button id. - author: Nikita Kaberov - copyright: 2019 Webim */ case buttonIdNotSet @available(*, unavailable, renamed: "buttonIdNotSet") case BUTTON_ID_NOT_SET /** Arised when trying to response without request message id. - author: Nikita Kaberov - copyright: 2019 Webim */ case requestMessageIdNotSet @available(*, unavailable, renamed: "requestMessageIdNotSet") case REQUEST_MESSAGE_ID_NOT_SET /** Arised when trying to response with wrong data. - author: Nikita Kaberov - copyright: 2019 Webim */ case canNotCreateResponse @available(*, unavailable, renamed: "canNotCreateResponse") case CAN_NOT_CREATE_RESPONSE } /** - seealso: `RateOperatorCompletionHandler.onFailure(error:)` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public enum RateOperatorError: Error { /** Arised when trying to send operator rating request if no chat is exists. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case noChat @available(*, unavailable, renamed: "noChat") case NO_CHAT /** Arised when trying to send operator rating request if passed operator ID doesn't belong to existing chat operator (or, in the same place, chat doesn't have an operator at all). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case wrongOperatorId @available(*, unavailable, renamed: "wrongOperatorId") case WRONG_OPERATOR_ID /** Note length is more than 2000 characters. - author: Nikita Kaberov - copyright: 2020 Webim */ case noteIsTooLong @available(*, unavailable, renamed: "noteIsTooLong") case NOTE_IS_TOO_LONG } /** - seealso: `SendDialogToEmailAddressCompletionHandler.onFailure(error:)` - author: Nikita Kaberov - copyright: 2020 Webim */ public enum SendDialogToEmailAddressError: Error { /** There is no chat to send it to the email address. - author: Nikita Kaberov - copyright: 2020 Webim */ case noChat @available(*, unavailable, renamed: "noChat") case NO_CHAT /** Exceeded sending attempts. - author: Nikita Kaberov - copyright: 2020 Webim */ case sentTooManyTimes @available(*, unavailable, renamed: "sentTooManyTimes") case SENT_TOO_MANY_TIMES /** An unexpected error occurred while sending. - author: Nikita Kaberov - copyright: 2020 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN } /** - seealso: `SendStickerCompletionHandler.onFailure(error:)` - author: Yury Vozleev - copyright: 2020 Webim */ public enum SendStickerError: Error { /** There is no chat to send it to the sticker. - author: Yury Vozleev - copyright: 2020 Webim */ case noChat /** Not set sticker id - author: Yury Vozleev - copyright: 2020 Webim */ case noStickerId } /** - seealso: `SendSurveyAnswerCompletionHandler.onFailure(error:)` - author: Nikita Kaberov - copyright: 2020 Webim */ public enum SendSurveyAnswerError { /** Incorrect value for question type 'radio'. - author: Nikita Kaberov - copyright: 2020 Webim */ case incorrectRadioValue /** Incorrect value for question type 'stars'. - author: Nikita Kaberov - copyright: 2020 Webim */ case incorrectStarsValue /** Incorrect survey ID. - author: Nikita Kaberov - copyright: 2020 Webim */ case incorrectSurveyID /** Max comment length was exceeded for question type 'comment'. - author: Nikita Kaberov - copyright: 2020 Webim */ case maxCommentLength_exceeded /** No current survey on server. - author: Nikita Kaberov - copyright: 2020 Webim */ case noCurrentSurvey /** Question was not found. - author: Nikita Kaberov - copyright: 2020 Webim */ case questionNotFound /** Survey is disabled on server. - author: Nikita Kaberov - copyright: 2020 Webim */ case surveyDisabled /** Received error is not supported by current WebimClientLibrary version. - author: Nikita Kaberov - copyright: 2020 Webim */ case unknown } /** - seealso: `SurveyCloseCompletionHandler.onFailure(error:)` - author: Nikita Kaberov - copyright: 2020 Webim */ public enum SurveyCloseError { /** Incorrect survey ID. - author: Nikita Kaberov - copyright: 2020 Webim */ case incorrectSurveyID /** No current survey on server. - author: Nikita Kaberov - copyright: 2020 Webim */ case noCurrentSurvey /** Survey is disabled on server. - author: Nikita Kaberov - copyright: 2020 Webim */ case surveyDisabled /** Received error is not supported by current WebimClientLibrary version. - author: Nikita Kaberov - copyright: 2020 Webim */ case unknown }
0
// // CameraViewController.swift // NextLevel (http://nextlevel.engineering/) // // Copyright (c) 2016-present patrick piemonte (http://patrickpiemonte.com) // // 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 AVFoundation //import NextLevel class CameraViewController: UIViewController { // MARK: - UIViewController override public var prefersStatusBarHidden: Bool { return true } // MARK: - properties internal var previewView: UIView? internal var gestureView: UIView? internal var controlDockView: UIView? internal var recordButton: UIButton? internal var flipButton: UIButton? internal var flashButton: UIButton? internal var saveButton: UIButton? internal var focusTapGestureRecognizer: UITapGestureRecognizer? internal var zoomPanGestureRecognizer: UIPanGestureRecognizer? internal var flipDoubleTapGestureRecognizer: UITapGestureRecognizer? // MARK: - object lifecycle public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { } // MARK: - view lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black self.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] let screenBounds = UIScreen.main.bounds // preview self.previewView = UIView(frame: screenBounds) if let previewView = self.previewView { previewView.autoresizingMask = [.flexibleWidth, .flexibleHeight] previewView.backgroundColor = UIColor.black NextLevel.sharedInstance.previewLayer.frame = previewView.bounds previewView.layer.addSublayer(NextLevel.sharedInstance.previewLayer) self.view.addSubview(previewView) } // buttons self.recordButton = UIButton(type: .custom) if let recordButton = self.recordButton { recordButton.setImage(UIImage(named: "record_button"), for: .normal) recordButton.sizeToFit() recordButton.addTarget(self, action: #selector(handleRecordButton(_:)), for: .touchUpInside) } self.flipButton = UIButton(type: .custom) if let flipButton = self.flipButton { flipButton.setImage(UIImage(named: "flip_button"), for: .normal) flipButton.sizeToFit() flipButton.addTarget(self, action: #selector(handleFlipButton(_:)), for: .touchUpInside) } // capture control "dock" let controlDockHeight = screenBounds.height * 0.2 self.controlDockView = UIView(frame: CGRect(x: 0, y: screenBounds.height - controlDockHeight, width: screenBounds.width, height: controlDockHeight)) if let controlDockView = self.controlDockView { controlDockView.backgroundColor = UIColor.clear controlDockView.autoresizingMask = [.flexibleTopMargin] self.view.addSubview(controlDockView) if let recordButton = self.recordButton { recordButton.center = CGPoint(x: controlDockView.bounds.midX, y: controlDockView.bounds.midY) controlDockView.addSubview(recordButton) } if let flipButton = self.flipButton, let recordButton = self.recordButton { flipButton.center = CGPoint(x: recordButton.center.x + controlDockView.bounds.width * 0.25 + flipButton.bounds.width * 0.5, y: recordButton.center.y) controlDockView.addSubview(flipButton) } } // gestures self.gestureView = UIView(frame: screenBounds) if let gestureView = self.gestureView, let controlDockView = self.controlDockView { gestureView.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin] gestureView.frame.size.height -= controlDockView.frame.height gestureView.backgroundColor = .clear self.view.addSubview(gestureView) self.focusTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleFocusTapGestureRecognizer(_:))) if let focusTapGestureRecognizer = self.focusTapGestureRecognizer { focusTapGestureRecognizer.delegate = self focusTapGestureRecognizer.numberOfTapsRequired = 1 gestureView.addGestureRecognizer(focusTapGestureRecognizer) } } // Configure NextLevel by modifying the configuration ivars NextLevel.sharedInstance.delegate = self //NextLevel.sharedInstance.videoConfiguration //NextLevel.sharedInstance.audioConfiguration } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let nextLevel = NextLevel.sharedInstance if nextLevel.authorizationStatus(forMediaType: AVMediaTypeVideo) == .authorized && nextLevel.authorizationStatus(forMediaType: AVMediaTypeAudio) == .authorized { do { try nextLevel.start() } catch { print("NextLevel, failed to start camera session") } } else { nextLevel.requestAuthorization(forMediaType: AVMediaTypeVideo) nextLevel.requestAuthorization(forMediaType: AVMediaTypeAudio) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NextLevel.sharedInstance.stop() } } // MARK: - UIButton extension CameraViewController { internal func handleFlipButton(_ button: UIButton) { NextLevel.sharedInstance.flipCaptureDevicePosition() } internal func handleFlashModeButton(_ button: UIButton) { } internal func handleRecordButton(_ button: UIButton) { } internal func handleDoneButton(_ button: UIButton) { NextLevel.sharedInstance.session?.mergeClips(usingPreset: AVAssetExportPresetHighestQuality, completionHandler: { (url: URL?, error: Error?) in if let _ = url { // } else if let _ = error { // } }) } } // MARK: - UIGestureRecognizerDelegate extension CameraViewController: UIGestureRecognizerDelegate { internal func handleLongPressGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { } internal func handleFocusTapGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { let tapPoint = gestureRecognizer.location(in: self.previewView) // TODO: create focus view and animate let previewLayer = NextLevel.sharedInstance.previewLayer let adjustedPoint = previewLayer.captureDevicePointOfInterest(for: tapPoint) NextLevel.sharedInstance.focusExposeAndAdjustWhiteBalance(atAdjustedPoint: adjustedPoint) } } // MARK: - NextLevelDelegate extension CameraViewController: NextLevelDelegate { // permission func nextLevel(_ nextLevel: NextLevel, didUpdateAuthorizationStatus status: NextLevelAuthorizationStatus, forMediaType mediaType: String!) { if nextLevel.authorizationStatus(forMediaType: AVMediaTypeVideo) == .authorized && nextLevel.authorizationStatus(forMediaType: AVMediaTypeAudio) == .authorized { do { try nextLevel.start() } catch { print("NextLevel, failed to start camera session") } } else if status == .notAuthorized { // gracefully handle when audio/video is not authorized print("NextLevel doesn't have authorization for audio or video") } } // configuration func nextLevel(_ nextLevel: NextLevel, didUpdateVideoConfiguration videoConfiguration: NextLevelVideoConfiguration) { } func nextLevel(_ nextLevel: NextLevel, didUpdateAudioConfiguration audioConfiguration: NextLevelAudioConfiguration) { } // session func nextLevelSessionWillStart(_ nextLevel: NextLevel) { } func nextLevelSessionDidStart(_ nextLevel: NextLevel) { } func nextLevelSessionDidStop(_ nextLevel: NextLevel) { } // device, mode, orientation func nextLevelDevicePositionWillChange(_ nextLevel: NextLevel) { } func nextLevelDevicePositionDidChange(_ nextLevel: NextLevel) { } func nextLevelCaptureModeWillChange(_ nextLevel: NextLevel) { } func nextLevelCaptureModeDidChange(_ nextLevel: NextLevel) { } func nextLevel(_ nextLevel: NextLevel, didChangeDeviceOrientation deviceOrientation: NextLevelDeviceOrientation) { } // aperture func nextLevel(_ nextLevel: NextLevel, didChangeCleanAperture cleanAperture: CGRect) { } // focus, exposure, white balance func nextLevelWillStartFocus(_ nextLevel: NextLevel) { } func nextLevelDidStopFocus(_ nextLevel: NextLevel) { } func nextLevelWillChangeExposure(_ nextLevel: NextLevel) { } func nextLevelDidChangeExposure(_ nextLevel: NextLevel) { } func nextLevelWillChangeWhiteBalance(_ nextLevel: NextLevel) { } func nextLevelDidChangeWhiteBalance(_ nextLevel: NextLevel) { } // torch, flash func nextLevelDidChangeFlashMode(_ nextLevel: NextLevel) { } func nextLevelDidChangeTorchMode(_ nextLevel: NextLevel) { } func nextLevelFlashActiveChanged(_ nextLevel: NextLevel) { } func nextLevelTorchActiveChanged(_ nextLevel: NextLevel) { } func nextLevelFlashAndTorchAvailabilityChanged(_ nextLevel: NextLevel) { } // zoom func nextLevel(_ nextLevel: NextLevel, didUpdateVideoZoomFactor videoZoomFactor: Float) { } // preview func nextLevelWillStartPreview(_ nextLevel: NextLevel) { } func nextLevelDidStopPreview(_ nextLevel: NextLevel) { } // video frame processing func nextLevel(_ nextLevel: NextLevel, willProcessRawVideoSampleBuffer sampleBuffer: CMSampleBuffer) { } // enabled by isCustomContextVideoRenderingEnabled func nextLevel(_ nextLevel: NextLevel, renderToCustomContextWithImageBuffer imageBuffer: CVPixelBuffer, onQueue queue: DispatchQueue) { } // video recording session func nextLevel(_ nextLevel: NextLevel, didSetupVideoInSession session: NextLevelSession) { } func nextLevel(_ nextLevel: NextLevel, didSetupAudioInSession session: NextLevelSession) { } func nextLevel(_ nextLevel: NextLevel, didStartClipInSession session: NextLevelSession) { } func nextLevel(_ nextLevel: NextLevel, didCompleteClip clip: NextLevelClip, inSession session: NextLevelSession) { } func nextLevel(_ nextLevel: NextLevel, didAppendVideoSampleBuffer sampleBuffer: CMSampleBuffer, inSession session: NextLevelSession) { } func nextLevel(_ nextLevel: NextLevel, didAppendAudioSampleBuffer sampleBuffer: CMSampleBuffer, inSession session: NextLevelSession) { } func nextLevel(_ nextLevel: NextLevel, didSkipVideoSampleBuffer sampleBuffer: CMSampleBuffer, inSession session: NextLevelSession) { } func nextLevel(_ nextLevel: NextLevel, didSkipAudioSampleBuffer sampleBuffer: CMSampleBuffer, inSession session: NextLevelSession) { } func nextLevel(_ nextLevel: NextLevel, didCompleteSession session: NextLevelSession) { } // video frame photo func nextLevel(_ nextLevel: NextLevel, didCompletePhotoCaptureFromVideoFrame photoDict: [String : Any]?) { } // photo func nextLevel(_ nextLevel: NextLevel, willCapturePhotoWithConfiguration photoConfiguration: NextLevelPhotoConfiguration) { } func nextLevel(_ nextLevel: NextLevel, didCapturePhotoWithConfiguration photoConfiguration: NextLevelPhotoConfiguration) { } func nextLevel(_ nextLevel: NextLevel, didProcessPhotoCaptureWith photoDictionary: [String : Any]?, photoConfiguration: NextLevelPhotoConfiguration) { } func nextLevel(_ nextLevel: NextLevel, didProcessRawPhotoCaptureWith photoDictionary: [String : Any]?, photoConfiguration: NextLevelPhotoConfiguration) { } func nextLevelDidCompletePhotoCapture(_ nextLevel: NextLevel) { } }
0
// // ViewController.swift // SimplestViewExamples // // Created by YS on 4/10/19. // Copyright © 2019 YS. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
0
import CakeWalletLib import CakeWalletCore public struct BalanceState: StateType { public static func == (lhs: BalanceState, rhs: BalanceState) -> Bool { return lhs.balance.compare(with: rhs.balance) && lhs.unlockedBalance.compare(with: rhs.unlockedBalance) && lhs.unlockedFiatBalance.compare(with: rhs.unlockedFiatBalance) && lhs.price == rhs.price && lhs.rate == rhs.rate } public enum Action: AnyAction { case changedBalance(Amount) case changedUnlockedBalance(Amount) case changedPrice(Double) case changedUnlockedFiatBalance(Amount) case changedFullFiatBalance(Amount) case changedRate(Double) } public let balance: Amount public let unlockedBalance: Amount public let price: Double public let unlockedFiatBalance: Amount public let fullFiatBalance: Amount public let rate: Double public init(balance: Amount, unlockedBalance: Amount, price: Double, fiatBalance: Amount, fullFiatBalance: Amount, rate: Double) { self.balance = balance self.unlockedBalance = unlockedBalance self.fullFiatBalance = fullFiatBalance self.price = price self.unlockedFiatBalance = fiatBalance self.rate = rate } public func reduce(_ action: BalanceState.Action) -> BalanceState { switch action { case let .changedBalance(balance): return BalanceState(balance: balance, unlockedBalance: unlockedBalance, price: price, fiatBalance: unlockedFiatBalance, fullFiatBalance: fullFiatBalance, rate: rate) case let .changedUnlockedFiatBalance(fiatBalance): return BalanceState(balance: balance, unlockedBalance: unlockedBalance, price: price, fiatBalance: fiatBalance, fullFiatBalance: fullFiatBalance, rate: rate) case let .changedFullFiatBalance(fullFiatBalance): return BalanceState(balance: balance, unlockedBalance: unlockedBalance, price: price, fiatBalance: unlockedFiatBalance, fullFiatBalance: fullFiatBalance, rate: rate) case let .changedPrice(price): return BalanceState(balance: balance, unlockedBalance: unlockedBalance, price: price, fiatBalance: unlockedFiatBalance, fullFiatBalance: fullFiatBalance, rate: rate) case let .changedUnlockedBalance(unlockedBalance): return BalanceState(balance: balance, unlockedBalance: unlockedBalance, price: price, fiatBalance: unlockedFiatBalance, fullFiatBalance: fullFiatBalance, rate: rate) case let .changedRate(rate): return BalanceState(balance: balance, unlockedBalance: unlockedBalance, price: price, fiatBalance: unlockedFiatBalance, fullFiatBalance: fullFiatBalance, rate: rate) } } }
0
import XCTest import Overture final class ZipTests: XCTestCase { func testZipOptional() { guard let (a, b, c, d, e, f, g, h, i, j) = zip( Int?.some(1), Int?.some(2), Int?.some(3), Int?.some(4), Int?.some(5), Int?.some(6), Int?.some(7), Int?.some(8), Int?.some(9), Int?.some(10) ) else { return XCTFail() } XCTAssertEqual(1, a) XCTAssertEqual(2, b) XCTAssertEqual(3, c) XCTAssertEqual(4, d) XCTAssertEqual(5, e) XCTAssertEqual(6, f) XCTAssertEqual(7, g) XCTAssertEqual(8, h) XCTAssertEqual(9, i) XCTAssertEqual(10, j) } func testZipSequence() { let zipped = zip( [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16], [17, 18], [19, 20] ) let array = Array(zipped) let fst = array[0] XCTAssertEqual(1, fst.0) XCTAssertEqual(3, fst.1) XCTAssertEqual(5, fst.2) XCTAssertEqual(7, fst.3) XCTAssertEqual(9, fst.4) XCTAssertEqual(11, fst.5) XCTAssertEqual(13, fst.6) XCTAssertEqual(15, fst.7) XCTAssertEqual(17, fst.8) XCTAssertEqual(19, fst.9) let snd = array[1] XCTAssertEqual(2, snd.0) XCTAssertEqual(4, snd.1) XCTAssertEqual(6, snd.2) XCTAssertEqual(8, snd.3) XCTAssertEqual(10, snd.4) XCTAssertEqual(12, snd.5) XCTAssertEqual(14, snd.6) XCTAssertEqual(16, snd.7) XCTAssertEqual(18, snd.8) XCTAssertEqual(20, snd.9) } }
0
// // LicenseContainer.swift // r2-lcp-swift // // Created by Mickaël Menu on 05.02.19. // // Copyright 2019 Readium Foundation. All rights reserved. // Use of this source code is governed by a BSD-style license which is detailed // in the LICENSE file present in the project repository where this source code is maintained. // import Foundation import R2Shared /// Encapsulates the read/write access to the packaged License Document (eg. in an EPUB container, or a standalone LCPL file) protocol LicenseContainer { /// Returns whether this container currently contains a License Document. /// /// For example, when fulfilling an EPUB publication, it initially doesn't contain the license. func containsLicense() -> Bool func read() throws -> Data func write(_ license: LicenseDocument) throws } func makeLicenseContainer(for file: URL, mimetypes: [String] = []) -> Deferred<LicenseContainer?, LCPError> { return deferred(on: .global(qos: .background)) { success, _, _ in success(makeLicenseContainerSync(for: file, mimetypes: mimetypes)) } } func makeLicenseContainerSync(for file: URL, mimetypes: [String] = []) -> LicenseContainer? { guard let mediaType = MediaType.of(file, mediaTypes: mimetypes, fileExtensions: []) else { return nil } switch mediaType { case .lcpLicenseDocument: return LCPLLicenseContainer(lcpl: file) case .lcpProtectedPDF, .lcpProtectedAudiobook, .readiumAudiobook, .readiumWebPub, .divina: return ReadiumLicenseContainer(path: file) case .epub: return EPUBLicenseContainer(epub: file) default: return nil } }
0
import Foundation extension SlackLogHandler { /// An icon for a Slack integration. public enum Icon { /// An [emoji code](https://webpagefx.com/tools/emoji-cheat-sheet) string to use in place of the default icon. /// /// .emoji("smile") case emoji(String) /// An icon image URL to use in place of the default icon. case url(URL) internal var emoji: String? { switch self { case let .emoji(emoji): return emoji default: return nil } } internal var url: URL? { switch self { case let .url(url): return url default: return nil } } } }
0
// // AssociatedObject.swift // Reactant // // Created by Filip Dolnik on 21.11.16. // Copyright © 2016 Brightify. All rights reserved. // import Foundation public func associatedObject<T>(_ base: AnyObject, key: UnsafePointer<UInt8>, defaultValue: T) -> T { if let associated = objc_getAssociatedObject(base, key) as? T { return associated } else { associateObject(base, key: key, value: defaultValue) return defaultValue } } public func associatedObject<T>(_ base: AnyObject, key: UnsafePointer<UInt8>, initializer: () -> T) -> T { if let associated = objc_getAssociatedObject(base, key) as? T { return associated } else { let defaultValue = initializer() associateObject(base, key: key, value: defaultValue) return defaultValue } } public func associateObject<T>(_ base: AnyObject, key: UnsafePointer<UInt8>, value: T) { objc_setAssociatedObject(base, key, value, .OBJC_ASSOCIATION_RETAIN) }
0
// // MainColorView.swift // SwiftColorPicker // // Created by cstad on 12/15/14. // import UIKit extension UIView { func getLimitXCoordinate(_ coord:CGFloat)->CGFloat { if coord < 0 { return 0 } else if coord > frame.width { return frame.width } return coord } func getLimitYCoordinate(_ coord:CGFloat)->CGFloat { if coord < 0 { return 0 } else if coord > frame.height { return frame.height } return coord } } public class HueView: UIView { var color: UIColor! var point: CGPoint! var knob:UIView! weak var delegate: ColorPicker? init(frame: CGRect, color: UIColor) { super.init(frame: frame) } var width:CGFloat! var width_2:CGFloat! var hasLayouted = false override public func layoutSubviews() { super.layoutSubviews() if !hasLayouted { backgroundColor = UIColor.clear width = frame.height width_2 = width*0.5 let colorLayer = CAGradientLayer() colorLayer.colors = [ UIColor(hue: 0.0, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.1, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.2, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.3, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.4, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.5, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.6, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.7, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.8, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.9, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 1.0, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor ] //colorLayer.locations = [0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95] colorLayer.locations = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.75, 0.8, 0.9,1.0] colorLayer.startPoint = CGPoint(x: 0, y: 0.5) colorLayer.endPoint = CGPoint(x: 1, y: 0.5) colorLayer.frame = frame colorLayer.frame.origin = CGPoint.zero // Insert the colorLayer into this views layer as a sublayer self.layer.insertSublayer(colorLayer, below: layer) self.color = UIColor.black point = getPointFromColor(color) knob = UIView(frame: CGRect(x: -3, y: -2, width: 6, height: width+4)) knob.layer.cornerRadius = 3 knob.layer.borderWidth = 1 knob.layer.borderColor = UIColor.lightGray.cgColor knob.backgroundColor = UIColor.white knob.layer.shadowColor = UIColor.black.cgColor // knob.layer.shadowOffset = CGSize(width: 0, height: -3) hasLayouted = true addSubview(knob) layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowOpacity = 0.8 } } override public func awakeFromNib() { } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // Set reference to the location of the touch in member point let touch = touches.first moveKnob(touch!,duration: 0.5) /* point = touch!.locationInView(self) point.x = getLimitXCoordinate(point.x) point.y = width_2 DLog("\(point)") // Notify delegate of the new new color selection let color = getColorFromPoint(point) delegate?.mainColorSelected(color, point: point) // Update display when possible UIView.animateWithDuration(0.5, animations: { self.knob.layer.transform = CATransform3DMakeTranslation(self.point.x-self.width_2, 0, 0) self.knob.backgroundColor = color }) */ } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // Set reference to the location of the touchesMoved in member point let touch = touches.first moveKnob(touch!,duration: 0.1) } func moveKnob(_ touch:UITouch,duration:TimeInterval) { point = touch.location(in: self) point.x = getLimitXCoordinate(point.x) point.y = width_2 // Notify delegate of the new new color selection let color = getColorFromPoint(point) delegate?.mainColorSelected(color, point: point) UIView.animate(withDuration: duration, animations: { self.knob.layer.transform = CATransform3DMakeTranslation(self.point.x, 0, 0) }) } func getColorFromPoint(_ point: CGPoint) -> UIColor { return UIColor(hue: point.x/frame.width, saturation: 1, brightness: 1, alpha: 1) } override public func draw(_ rect: CGRect) { /* if (point != nil) { let context = UIGraphicsGetCurrentContext() // Drawing properties: // Set line width to 1 CGContextSetLineWidth(context, 1) // Set color to black CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor) // Draw selector CGContextBeginPath(context) CGContextMoveToPoint(context, 1, getYCoordinate(point.y) - 4) CGContextAddLineToPoint(context, 9, getYCoordinate(point.y)) CGContextAddLineToPoint(context, 1, getYCoordinate(point.y) + 4) CGContextStrokePath(context) CGContextBeginPath(context) CGContextMoveToPoint(context, 29, getYCoordinate(point.y) - 4) CGContextAddLineToPoint(context, 21, getYCoordinate(point.y)) CGContextAddLineToPoint(context, 29, getYCoordinate(point.y) + 4) CGContextStrokePath(context) } */ } // Determine crosshair coordinates from a color func getPointFromColor(_ color: UIColor) -> CGPoint { var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) if (!ok) { print("ColorPicker: exception <The color provided to ColorPicker is not convertible to HSB>", terminator: "") } return CGPoint(x: 15, y: frame.height - (hue * frame.height)) } // Thanks to mbanasiewicz for this method // https://gist.github.com/mbanasiewicz/940677042f5f293caf57 }
1
#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities #endif extension TreeSet: Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Two persistent sets are considered equal if they contain the same /// elements, but not necessarily in the same order. /// /// - Note: This simply forwards to the ``isEqualSet(to:)-4bc1i`` method. /// That method has additional overloads that can be used to compare /// persistent sets with additional types. /// /// - Complexity: O(`min(left.count, right.count)`) @inlinable @inline(__always) public static func == (left: Self, right: Self) -> Bool { left.isEqualSet(to: right) } }
0
// // SpeakerTableViewCell.swift // Mopcon // // Created by EthanLin on 2018/7/2. // Copyright © 2018 EthanLin. All rights reserved. // import UIKit import Kingfisher class SpeakerTableViewCell: UITableViewCell { @IBOutlet weak var baseView: UIView! @IBOutlet weak var speakerAvatarImageView: UIImageView! { didSet { self.speakerAvatarImageView.makeCircle() } } @IBOutlet weak var speakerNameLabel: UILabel! @IBOutlet weak var speakerJobLabel: UILabel! @IBOutlet weak var tagView: MPTagView! { didSet { tagView.dataSource = self } } var tags: [Tag] = [] func updateUI(speaker: Speaker) { speakerAvatarImageView.kf.setImage( with: URL(string: speaker.img.mobile), placeholder: UIImage.asset(.fieldGameProfile) ) let language = CurrentLanguage.getLanguage() switch language { case Language.chinese.rawValue: self.speakerJobLabel.text = speaker.jobTitle self.speakerNameLabel.text = speaker.name case Language.english.rawValue: self.speakerJobLabel.text = speaker.jobTitleEn self.speakerNameLabel.text = speaker.nameEn default: break } tags = speaker.tags tagView.reloadData() } override func awakeFromNib() { super.awakeFromNib() // Initialization code baseView.layer.borderColor = UIColor.azure?.cgColor baseView.layer.borderWidth = 1.0 baseView.layer.cornerRadius = 6.0 baseView.clipsToBounds = true selectionStyle = .none } } extension SpeakerTableViewCell: MPTagViewDataSource { func numberOfTags(_ tagView: MPTagView) -> Int { return tags.count } func titleForTags(_ tagView: MPTagView, index: Int) -> String { return tags[index].name } func colorForTags(_ tagView: MPTagView, index: Int) -> UIColor? { return UIColor(hex: tags[index].color) } }
0
// // ViewController.swift // GitYourFeedback // // Created by Gabe Kangas on 09/11/2016. // Copyright (c) 2016 Gabe Kangas. All rights reserved. // import UIKit import GitYourFeedback class ViewController: UIViewController { var feedback: FeedbackManager! override func viewDidLoad() { super.viewDidLoad() feedback = FeedbackManager(githubApiToken: Config.githubApiToken, githubUser: Config.githubUser, repo: Config.githubRepo, feedbackRemoteStorageDelegate: self, issueLabels: ["Feedback", "Bugs"]) view.backgroundColor = UIColor.white view.addSubview(button) button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true button.widthAnchor.constraint(equalToConstant: 150).isActive = true button.heightAnchor.constraint(equalToConstant: 45).isActive = true button.addTarget(self, action: #selector(display), for: .touchUpInside) view.addSubview(label) label.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true label.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true label.bottomAnchor.constraint(equalTo: button.topAnchor, constant: -50).isActive = true } func display() { feedback.display(viewController: self) } private let button: UIButton = { let button = UIButton(type: UIButtonType.roundedRect) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Provide Feedback", for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.backgroundColor = UIColor.blue return button }() private let label: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Take a screenshot or press button to provide feedback" label.numberOfLines = 0 label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 14) return label }() } extension ViewController: FeedbackManagerDatasource { public func uploadUrl(_ completionHandler: (String) -> Void) { let filename = String(Date().timeIntervalSince1970) + ".jpg" let url = "https://www.googleapis.com/upload/storage/v1/b/\(Config.googleStorageBucket)/o?name=\(filename)" completionHandler(url) } public func additionalData() -> String? { return "This is additional data that was added via the FeedbackManagerDatasource.\n\nYou can put whatever you want here." } }
0
// // ConfigModelProtocol.swift // PaiBaoTang // // Created by ZJaDe on 2017/9/27. // Copyright © 2017年 Z_JaDe. All rights reserved. // import Foundation public protocol ConfigModelProtocol: AnyObject { associatedtype ModelType var model: ModelType {get set} /// 不能通过直接调用的方式,应该使用设置model的方式 func configData(with model: ModelType) func updateWithModel() func update(with model: ModelType) } public extension ConfigModelProtocol { func updateWithModel() { self.update(with: self.model) } func update(with model: ModelType) { self.model = model } } public protocol ConfigOptionModelProtocol: AnyObject { associatedtype ModelType var model: ModelType? {get set} /// 不能通过直接调用的方式,应该使用设置model的方式 func configData(with model: ModelType?) func updateWithModel() func update(with model: ModelType?) } public extension ConfigOptionModelProtocol { func updateWithModel() { self.update(with: self.model) } func update(with model: ModelType?) { self.model = model } } public protocol ConfigViewModelProtocol: AnyObject { associatedtype ViewModelType var viewModel: ViewModelType! {get set} /// 不能通过直接调用的方式,应该使用设置model的方式 func config(viewModel: ViewModelType) } extension ConfigViewModelProtocol { func updateWithViewModel() { if let viewModel = self.viewModel { self.update(viewModel: viewModel) } } func update(viewModel: ViewModelType) { self.viewModel = viewModel } }
0
import Foundation enum Spell: UInt16 { case armor = 1 // + case teleport = 2 // + case bless = 3 // + case blindness = 4 // + case burningHands = 5 // + case callLightning = 6 // + case charmPerson = 7 // + case chillTouch = 8 // + case continualLight = 9 // + case colorSpray = 10 // + case stormCall = 11 // + case createFood = 12 // + case createWater = 13 // + case cureBlind = 14 // + case cureCritic = 15 // + case cureLight = 16 // + case curse = 17 // + case detectAlign = 18 // + case detectInvisible = 19 // + case detectMagic = 20 // + case detectPoison = 21 // + case dispelEvil = 22 // + case earthquake = 23 // + case enchantWeapon = 24 // + case energyDrain = 25 // + case fireball = 26 // + case harm = 27 // + case heal = 28 // + case invisible = 29 // + case lightningBolt = 30 // + case locateObject = 31 // + case magicMissile = 32 // + case poison = 33 // + case protectionFromEvil = 34 // + case removeCurse = 35 // + case sanctuary = 36 // + case clearSkies = 37 // + case sleep = 38 // + case strength = 39 // + case summon = 40 // + case clairvoyance = 41 // + case wordOfRecall = 42 // + case removePoison = 43 // + case senseLife = 44 // + case animateDead = 45 // +! case dispelGood = 46 // + case holyAura = 47 // + case healingMist = 48 // +! case holdUndead = 49 // + case infravision = 50 // + case waterbreath = 51 // + case acidBlast = 52 // + case aid = 53 // + case charmMonster = 54 // + case coneOfCold = 55 // + case fly = 56 // + case massCharm = 57 // +! case holdPerson = 58 // + case holdMonster = 59 // + case createLight = 60 // + case fistOfStone = 61 // + case message = 62 // + case rayOfEnfeeblement = 63 // + case dispelMagic = 64 // + case haste = 65 // +! case stinkingСloud = 66 // +! case delayDeath = 67 // + case enlarge = 68 // + case grease = 69 // +! case identify = 70 // + case reduce = 71 // + case slow = 72 // +! case calm = 73 // + case confusion = 74 // +! case distanceDistortion = 75 // +! case enchantArmor = 76 // + case monsterSummoning = 77 // +! case vampiricTouch = 78 // +! case antimagicShell = 79 // +! case clawUmberHulk = 80 // + case cloudkill = 81 // +! case feeblemind = 82 // +! case fireshield = 83 // + case improvedInvisibility = 84 // +! case rot = 85 // +! case stoneSkin = 86 // +! case conjureElemental = 87 // +! case deathSpell = 88 // +! case delayedBlastFireball = 89 // + case disjunction = 90 // + case powerWordBlind = 91 // + case prismaticSpray = 92 // +! case relocate = 93 // + case spellTurning = 94 // +! case trueSeeing = 95 // +! case gate = 96 // +! case globeOfInvulnerability = 97 // +! case powerWordStun = 98 // + case recharge = 99 case crushingHand = 100 case duplicate = 101 case legendLore = 102 case spell103 = 103 // НОМЕР СВОБОДЕН! case acceleratedHealing = 104 // + case powerWordKill = 105 // + case heatMetal = 106 // +! case timeStop = 107 case causeLight = 108 // + case detectEvil = 109 // + case detectGood = 110 // + case dispelFatigue = 111 // + case silence = 112 // + case causeSerious = 113 // + case cureSerious = 114 // + case fright = 115 // + case protectionFromGood = 116 // + case darkness = 117 // +! case negativePlaneProt = 118 case nightvision = 119 case protectionFromAcid = 120 // + case prayer = 121 // + case protectionFromCold = 122 // + case protectionFromFire = 123 // + case protectionFromLightning = 124 // + case removeParalysis = 125 // + case causeCritical = 126 // + case flameStrike = 127 // + case bladeBarrier = 128 case freeAction = 129 // + case restoration = 130 // + case fireStorm = 131 case holyWord = 132 case sunray = 133 // + case unholyWord = 134 case shield = 135 // + case elvenMind = 136 case ironBody = 137 // + case awareness = 138 // + case warCry = 139 case dimensionalAnchor = 140 case heroesFeast = 141 case wish = 142 case floatingDisc = 143 case gustOfWind = 144 case mending = 145 case alarm = 146 case mount = 147 case deeppockets = 148 case fireStormXxx = 149 case dimensionDoor = 150 // + case knock = 151 case mirrorImage = 152 case blink = 153 case iceStorm = 154 // + case illusionaryWall = 155 case secureShelter = 156 case wizardEye = 157 case wallOfForce = 158 case chainLightning = 159 case findThePath = 160 case transformation = 161 case banishment = 162 case massInvisibility = 163 case deceleratedHealing = 164 case passWithoutTrace = 165 // + case barkskin = 166 // + case charmAnimal = 167 // + case flameBlade = 168 case magicalVestment = 169 // + case unholyAura = 170 // + case healingRadiance = 171 // + case graniteCrag = 172 // + case catsGrace = 173 // + case cloakOfPain = 174 // + case fortify = 175 // + case mortify = 176 // + case frostshield = 177 // + case cureDisease = 178 // + case unquenchableHunger = 179 // + case fatigue = 180 // + case ailment = 181 // case bravery = 182 // 1/2 case giantHand = 183 // + case leprosy = 184 // 1/2 case plague = 185 case cholera = 186 case pestilence = 187 case fierySquall = 188 // только на "огненный кристалл" и т.п. case battleRage = 189 //case wildRage = 190 case silveryMantle = 191 // ? а может всё-таки "радужная"? case shillelagh = 192 // + case thorns = 193 // + case handOfFate = 194 // + case surgeOfMight = 195 // + //case regeneration = 195 case fearlessness = 196 // + case blur = 197 // + case disruptUndead = 198 // + case ramStrike = 199 // + case estimateWear = 200 // + case ennui = 201 // + case panic = 202 case firebreathing = 203 // только для эффектов case flameArrow = 204 static let aliases = ["заклинания", "заучивание", "закл1", "закл2", "закл3", "заклинание", "спец.заклинание", "свиток.заклинания", "палочка.заклинания", "посох.заклинания", "зелье.заклинания", "книга.заклинания"] var info: SpellInfo { return spells.getSpellInfo(for: self) } static var definitions: Enumerations.EnumSpec.NamesByValue = [ 1: "доспех", 2: "искривление_пространства", 3: "благословение", 4: "слепота", 5: "жгущие_руки", 6: "вызов_молнии", 7: "очарование_человека", 8: "ледяное_прикосновение", 9: "вечный_свет", 10: "цветные_брызги", 11: "вызов_бури", 12: "создание_пищи", 13: "создание_воды", 14: "снятие_слепоты", 15: "лечение_смертельных_ран", 16: "лечение_легких_ран", 17: "проклятие", 18: "знание_наклонностей", 19: "определение_невидимости", 20: "определение_магии", 21: "определение_яда", 22: "изгнание_зла", 23: "землетрясение", 24: "заклятие_оружия", 25: "истощение_жизни", 26: "огненный_шар", 27: "вред", 28: "исцеление", 29: "невидимость", 30: "удар_молнии", 31: "поиск_предмета", 32: "магическая_стрела", 33: "яд", 34: "защита_от_зла", 35: "снятие_проклятия", 36: "убежище", 37: "разгон_туч", 38: "сон", 39: "сила", 40: "призыв", 41: "ясновидение", 42: "слово_возвращения", 43: "снятие_яда", 44: "определение_жизни", 45: "оживление_мертвого", 46: "изгнание_добра", 47: "священная_аура", 48: "целительный_туман", 49: "паралич_нежити", 50: "инфравидение", 51: "подводное_дыхание", 52: "кислотный_всплеск", 53: "поддержка", 54: "очарование_существа", 55: "конус_холода", 56: "полет", 57: "благоговение", 58: "паралич_человека", 59: "паралич_существа", 60: "свет", 61: "каменный_кулак", 62: "сообщение", 63: "ослабляющий_луч", 64: "рассеяние_магии", 65: "ускорение", 66: "едкое_облако", 67: "порог_смерти", 68: "увеличение", 69: "скольжение", 70: "знание_свойств", 71: "уменьшение", 72: "замедление", 73: "спокойствие", 74: "ошеломление", 75: "сокращение_расстояний", 76: "заклятие_доспеха", 77: "вызов_существа", 78: "прикосновение_смерти", 79: "магический_барьер", 80: "стальные_когти", 81: "облако_смерти", 82: "слабоумие", 83: "огненный_щит", 84: "улучшенная_невидимость", 85: "гниение", 86: "каменная_кожа", 87: "вызов_элементаля", 88: "заклятие_смерти", 89: "огненный_кристалл", 90: "расторжение", 91: "слово_силы_ослепить", 92: "радужные_брызги", 93: "перемещение", 94: "отражение_заклинаний", 95: "истинное_зрение", 96: "врата", 97: "сфера_неуязвимости", 98: "слово_силы_оглушить", 99: "перезарядка", 100: "кулак_великана", 101: "воссоздание", 102: "легенда", //103: "порог_смерти", 104: "ускоренное_восстановление", 105: "слово_силы_убить", 106: "раскаление_металла", 107: "остановка_времени", 108: "нанесение_легких_ран", 109: "определение_зла", 110: "определение_добра", 111: "снятие_усталости", 112: "молчание", 113: "нанесение_тяжелых_ран", 114: "лечение_тяжелых_ран", 115: "испуг", 116: "защита_от_добра", 117: "темнота", 118: "защита_жизни", 119: "ночное_зрение", 120: "защита_от_кислоты", 121: "молитва", 122: "защита_от_холода", 123: "защита_от_огня", 124: "защита_от_электричества", 125: "снятие_паралича", 126: "нанесение_смертельных_ран", 127: "вспышка_пламени", 128: "стена_клинков", 129: "свобода_действий", 130: "реабилитация", 131: "огненная_буря", 132: "святое_слово", 133: "луч_солнца", 134: "нечистое_слово", 135: "щит", 136: "эльфийский_разум", 137: "железное_тело", 138: "внимание", 139: "боевой_клич", 140: "пространственный_якорь", 141: "пир_героев", 142: "желание", 143: "летающий_диск", 144: "порыв_ветра", 145: "починка", 146: "охрана", 147: "скакун", 148: "глубокие_карманы", 149: "огненный_шторм", 150: "пространственная_дверь", 151: "стук", 152: "отражения", 153: "мигание", 154: "ледяной_шторм", 155: "иллюзорная_стена", 156: "безопасное_убежище", 157: "магический_глаз", 158: "магическая_стена", 159: "цепь_молний", 160: "истинный_путь", 161: "превращение", 162: "изгнание", 163: "иллюзорная_завеса", 164: "астральное_тело", 165: "проход_без_следа", 166: "кора", 167: "очарование_животного", 168: "пламенный_клинок", 169: "волшебное_облачение", 170: "нечистая_аура", 171: "живительное_сияние", 172: "гранитный_утес", 173: "кошачья_грация", 174: "плащ_боли", 175: "сила_жизни", 176: "мертвенная_длань", 177: "щит_мороза", 178: "лечение_болезней", 179: "неутолимый_голод", 180: "усталость", 181: "хворь", 182: "отвага", 183: "рука_великана", 184: "проказа", 185: "чума", 186: "холера", 187: "мор", 188: "огненный_шквал", 189: "ярость", // - не готово 190: "безумная_ярость", // - не готово 191: "серебряная_мантия", 192: "чудесная_дубина", 193: "колючки", 194: "рука_судьбы", 195: "прилив_сил", 196: "бесстрашие", 197: "марево", 198: "разрушение_нежити", 199: "бараний_лоб", 200: "взгляд_мастера", 201: "уныние", 202: "паника", // - не готово 203: "огненное_дыхание", 204: "стрела_огня", ] static func registerDefinitions(in e: Enumerations) { e.add(aliases: aliases, namesByValue: definitions) } }
0
// // EthereumCallParamsTests.swift // Web3_Tests // // Created by Koray Koska on 11.02.18. // Copyright © 2018 Boilertalk. All rights reserved. // import XCTest import Foundation @testable import EthereumWeb3 #if !COCOAPODS @testable import PKEthereumWeb3 #endif class CallParamsTests: XCTestCase { var encoder: JSONEncoder = JSONEncoder() var decoder: JSONDecoder = JSONDecoder() func assignEncoderAndDecoder() { self.encoder = JSONEncoder() self.decoder = JSONDecoder() } func testEncoding() { self.assignEncoderAndDecoder() let e = try? CallParams( from: Address(hex: "0x52bc44d5378309EE2abF1539BF71dE1b7d7bE3b5", eip55: true), to: Address(hex: "0x829BD824B016326A401d083B33D092293333A830", eip55: true), gas: 21000, gasPrice: Quantity(21 * BigUInt(10).power(9)), value: 10, data: EthData([0x00, 0xff]), block: .latest ) XCTAssertNotNil(e, "should not be nil") guard let call = e else { return } let newCall = try? self.decoder.decode(CallParams.self, from: self.encoder.encode(call)) XCTAssertNotNil(newCall, "should not be nil") XCTAssertEqual(newCall?.from?.hex(eip55: true), "0x52bc44d5378309EE2abF1539BF71dE1b7d7bE3b5", "should be equal") XCTAssertEqual(newCall?.to.hex(eip55: true), "0x829BD824B016326A401d083B33D092293333A830", "should be equal") XCTAssertEqual(newCall?.gas?.quantity, 21000, "should be equal") XCTAssertEqual(newCall?.gasPrice?.quantity, 21 * BigUInt(10).power(9), "should be equal") XCTAssertEqual(newCall?.value?.quantity, 10, "should be equal") XCTAssertEqual(newCall?.data?.data.bytes, [0x00, 0xff], "should be equal") XCTAssertEqual(newCall?.block.tagType, .latest, "should be equal") XCTAssertEqual(call == newCall, true, "should be equatable") XCTAssertEqual(call.hashValue, newCall?.hashValue, "should produce correct hashValues") } func testDecoding() { self.assignEncoderAndDecoder() let str = "[{\"value\":\"0xa\",\"to\":\"0x829bd824b016326a401d083b33d092293333a830\",\"gas\":\"0x5208\",\"data\":\"0x00ff\",\"gasPrice\":\"0x4e3b29200\",\"from\":\"0x52bc44d5378309ee2abf1539bf71de1b7d7be3b5\"},\"latest\"]" let e = try? self.decoder.decode(CallParams.self, from: Data(str.bytes)) XCTAssertNotNil(e, "should not be nil") XCTAssertEqual(e?.block.tagType, QuantityTag._Type.latest, "should be equal") XCTAssertEqual(e?.from?.hex(eip55: true), "0x52bc44d5378309EE2abF1539BF71dE1b7d7bE3b5", "should be equal") XCTAssertEqual(e?.to.hex(eip55: true), "0x829BD824B016326A401d083B33D092293333A830", "should be equal") XCTAssertEqual(e?.gas?.quantity, BigUInt(21000), "should be equal") XCTAssertEqual(e?.gasPrice?.quantity, 21 * BigUInt(10).power(9), "should be equal") XCTAssertEqual(e?.value?.quantity, BigUInt(10), "should be equal") XCTAssertEqual(e?.data?.data.bytes, [0x00, 0xff], "should be equal") } }
0
// // Created by Giancarlo Pacheco on 8/21/20. // import UIKit class CustomButton: UIButton { @IBInspectable var borderColor: UIColor = .clear { didSet { layer.borderColor = borderColor.withAlphaComponent(0.5).cgColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } override open var isEnabled: Bool { didSet { backgroundColor = isEnabled ? Theme.color(.accent) : UIColor.gray } } override open var isHighlighted: Bool { didSet { backgroundColor = isHighlighted ? UIColor.blue : Theme.color(.accent) } } }
0
// // LoginViewController.swift // Twitter // // Created by Fatama on 2/24/16. // Copyright © 2016 Fatama. All rights reserved. // import UIKit import BDBOAuth1Manager class LoginViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onLoginButton(sender: AnyObject) { TwitterClient.sharedInstance.login({ () -> () in self.performSegueWithIdentifier("loginSegue", sender: nil) }) { (error: NSError) -> () in print ("Error: \(error.localizedDescription)") } } /* // 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. } */ }
0
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/soto/blob/main/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. @_exported import SotoCore /* Client object for interacting with AWS MarketplaceCatalog service. Catalog API actions allow you to manage your entities through list, describe, and update capabilities. An entity can be a product or an offer on AWS Marketplace. You can automate your entity update process by integrating the AWS Marketplace Catalog API with your AWS Marketplace product build or deployment pipelines. You can also create your own applications on top of the Catalog API to manage your products on AWS Marketplace. */ public struct MarketplaceCatalog: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the MarketplaceCatalog client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: SotoCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, service: "catalog.marketplace", signingName: "aws-marketplace", serviceProtocol: .restjson, apiVersion: "2018-09-17", endpoint: endpoint, possibleErrorTypes: [MarketplaceCatalogErrorType.self], timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// Used to cancel an open change request. Must be sent before the status of the request changes to APPLYING, the final stage of completing your change request. You can describe a change during the 60-day request history retention period for API calls. public func cancelChangeSet(_ input: CancelChangeSetRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CancelChangeSetResponse> { return self.client.execute(operation: "CancelChangeSet", path: "/CancelChangeSet", httpMethod: .PATCH, serviceConfig: self.config, input: input, on: eventLoop, logger: logger) } /// Provides information about a given change set. public func describeChangeSet(_ input: DescribeChangeSetRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeChangeSetResponse> { return self.client.execute(operation: "DescribeChangeSet", path: "/DescribeChangeSet", httpMethod: .GET, serviceConfig: self.config, input: input, on: eventLoop, logger: logger) } /// Returns the metadata and content of the entity. public func describeEntity(_ input: DescribeEntityRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeEntityResponse> { return self.client.execute(operation: "DescribeEntity", path: "/DescribeEntity", httpMethod: .GET, serviceConfig: self.config, input: input, on: eventLoop, logger: logger) } /// Returns the list of change sets owned by the account being used to make the call. You can filter this list by providing any combination of entityId, ChangeSetName, and status. If you provide more than one filter, the API operation applies a logical AND between the filters. You can describe a change during the 60-day request history retention period for API calls. public func listChangeSets(_ input: ListChangeSetsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListChangeSetsResponse> { return self.client.execute(operation: "ListChangeSets", path: "/ListChangeSets", httpMethod: .POST, serviceConfig: self.config, input: input, on: eventLoop, logger: logger) } /// Provides the list of entities of a given type. public func listEntities(_ input: ListEntitiesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<ListEntitiesResponse> { return self.client.execute(operation: "ListEntities", path: "/ListEntities", httpMethod: .POST, serviceConfig: self.config, input: input, on: eventLoop, logger: logger) } /// This operation allows you to request changes for your entities. Within a single ChangeSet, you cannot start the same change type against the same entity multiple times. Additionally, when a ChangeSet is running, all the entities targeted by the different changes are locked until the ChangeSet has completed (either succeeded, cancelled, or failed). If you try to start a ChangeSet containing a change against an entity that is already locked, you will receive a ResourceInUseException. For example, you cannot start the ChangeSet described in the example below because it contains two changes to execute the same change type (AddRevisions) against the same entity (entity-id@1). public func startChangeSet(_ input: StartChangeSetRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<StartChangeSetResponse> { return self.client.execute(operation: "StartChangeSet", path: "/StartChangeSet", httpMethod: .POST, serviceConfig: self.config, input: input, on: eventLoop, logger: logger) } }
0
// // AppDelegate.swift // ToDo // // Created by Lourdes Zekkani on 5/26/21. // import UIKit import CoreData @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. } lazy var persistentContainer : NSPersistentCloudKitContainer = { let container = NSPersistentCloudKitContainer(name: "InfoStorage") container.loadPersistentStores { storeDescription, error in guard error == nil else { fatalError("Could not load persistent stores. \(error!)") } } container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return container }() func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Error: \(nserror), \(nserror.userInfo)") } } } }
0
// // OauthSession.swift // Yoshinani // // Created by 石部達也 on 2016/04/13. // Copyright © 2016年 石部達也. All rights reserved. // import UIKit import Unbox class OauthSession: NSObject { func create (thirdPartyId :String,complition :(error :ErrorHandring, message: String?, user :User?) ->Void) { let request = NSMutableURLRequest(URL: NSURL(string: Const().urlDomain + "/oauth_registrations")!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10.0) request.HTTPMethod = "POST" request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") let userDict:Dictionary<String,AnyObject> = [ "third_party_id":thirdPartyId, "oauth_id":1, "sns_hash_id": StringUtil.md5(string: thirdPartyId + SortWord) ] let params = ["oauth_registration":userDict] print(params) do { // Dict -> JSON let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted) //(*)options?? request.HTTPBody = jsonData } catch { print("Error!: \(error)") } let session = NSURLSession.sharedSession() let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) if error!.code != NSURLError.Cancelled.rawValue { complition(error: .NetworkError, message: nil, user: nil) } } else { guard let notNilResponse = response else { complition(error: .ServerError, message: nil, user: nil) return } let httpResponse = notNilResponse as! NSHTTPURLResponse if httpResponse.statusCode == 401 { let error :Error = Unbox(data!)! guard let message = error.errors?.password else { complition(error: .UnauthorizedError,message: error.message, user: nil) return } complition(error: .UnauthorizedError,message: message[0], user: nil) return }else if httpResponse.statusCode != 200 { let error :Error = Unbox(data!)! guard let message = error.errors?.password else { complition(error: .ServerError,message: error.message, user: nil) return } complition(error: .ServerError,message: message[0], user: nil) return } let user :User = Unbox(data!)! complition(error: .Success, message: nil, user: user) } }) dataTask.resume() } }
0
// // AppDelegate.swift // JXWebViewController // // Created by swordray on 01/17/2018. // Copyright (c) 2018 swordray. All rights reserved. // import JXWebViewController import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let url = URL(string: "https://example.com/")! let webViewController = JXWebViewController() webViewController.webView.load(URLRequest(url: url)) window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = webViewController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
0
import SwiftUI import Combine final class Store<State, Action>: BindableObject { typealias Reducer = (State, Action) -> State let didChange = PassthroughSubject<State, Never>() var state: State { lock.lock() defer { lock.unlock() } return _state } private let lock = NSLock() private let reducer: Reducer private var _state: State init(initial state: State, reducer: @escaping Reducer) { _state = state self.reducer = reducer } func dispatch(action: Action) { lock.lock() let newState = reducer(_state, action) _state = newState lock.unlock() didChange.send(newState) } }
0
// // ViewController.swift // DWSwitchDemo // // Created by di wu on 1/18/15. // Copyright (c) 2015 di wu. All rights reserved. // import UIKit import DWSwitch class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let mySwitch1 = DWSwitch(frame: CGRectMake(0, 0, 100, 50)) mySwitch1.center = CGPointMake(self.view.bounds.size.width * 0.5, self.view.bounds.size.height * 0.5 - 80) mySwitch1.addTarget(self, action: "switchChanged:", forControlEvents: UIControlEvents.ValueChanged) mySwitch1.offImage = UIImage(named: "cross") mySwitch1.onImage = UIImage(named: "check") mySwitch1.onTintColor = UIColor.blueColor() mySwitch1.isRounded = false; self.view.addSubview(mySwitch1) } func switchChanged(sender: DWSwitch) { println("Changed value to: \(sender.on)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
0
// // Dislike.swift // InformME // // Created by Amal Ibrahim on 2/4/16. // Copyright © 2016 King Saud University. All rights reserved. // import Foundation class Dislike { var attendees:[Attendee] = [] var counter: Int = 0 func createDislike() {} }
0
// // GuidanceColors.swift // LoopKitUI // // Created by Nathaniel Hamming on 2020-07-31. // Copyright © 2020 LoopKit Authors. All rights reserved. // import SwiftUI public struct GuidanceColors { public var acceptable: Color public var warning: Color public var critical: Color public init(acceptable: Color, warning: Color, critical: Color) { self.acceptable = acceptable self.warning = warning self.critical = critical } public init() { self.acceptable = .primary self.warning = .yellow self.critical = .red } }
1
// RUN: not %target-swift-frontend %s -typecheck func>{{}func b<T>([T:b func b
0
// // CovalentToNativeTransactionMapper.swift // AlphaWallet // // Created by Vladyslav Shepitko on 30.03.2022. // import Foundation import BigInt extension Covalent { struct ToNativeTransactionMapper { private static let formatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" return dateFormatter }() func mapToNativeTransactions(transactions: [Covalent.Transaction], server: RPCServer) -> [TransactionInstance] { transactions.compactMap { covalentTxToNativeTx(tx: $0, server: server) } } private func covalentTxToNativeTx(tx: Covalent.Transaction, server: RPCServer) -> TransactionInstance? { let gas = tx.gasOffered.flatMap { String($0) } ?? "" let gasPrice = tx.gasPrice.flatMap { String($0) } ?? "" let gasSpent = tx.gasSpent.flatMap { String($0) } ?? "" guard let date = ToNativeTransactionMapper.formatter.date(from: tx.blockSignedAt) else { return nil } let operations: [LocalizedOperationObjectInstance] = tx .logEvents .compactMap { logEvent -> LocalizedOperationObjectInstance? in guard let contractAddress = AlphaWallet.Address(uncheckedAgainstNullAddress: logEvent.senderAddress) else { return nil } var params = logEvent.params //TODO: Improve with adding more transaction types, approve and other guard let from = AlphaWallet.Address(uncheckedAgainstNullAddress: params["from"]?.value ?? "") else { return nil } guard let to = AlphaWallet.Address(uncheckedAgainstNullAddress: params["to"]?.value ?? "") else { return nil } let tokenId = logEvent.senderContractDecimals == 0 ? (params["tokenId"]?.value ?? "") : "" params.removeValue(forKey: "from") params.removeValue(forKey: "to") let value = params["value"]?.value let operationType: OperationType //TODO check have tokenID + no "value", cos those might be ERC1155? if tokenId.nonEmpty { operationType = .erc721TokenTransfer } else { operationType = .erc20TokenTransfer } return .init(from: from.eip55String, to: to.eip55String, contract: contractAddress, type: operationType.rawValue, value: value ?? "", tokenId: tokenId, symbol: logEvent.senderContractTickerSymbol, name: logEvent.senderName, decimals: logEvent.senderContractDecimals) } let transactionIndex = tx.logEvents.first?.txOffset ?? 0 return TransactionInstance(id: tx.txHash, server: server, blockNumber: tx.blockHeight, transactionIndex: transactionIndex, from: tx.from, to: tx.to, value: tx.value, gas: gas, gasPrice: gasPrice, gasUsed: gasSpent, nonce: "0", date: date, localizedOperations: operations, state: .completed, isErc20Interaction: true) } } }
0
// // PropertyListHelper.swift // UpcomingMovies // // Created by Rotimi Joshua on 10/04/2021. // import Foundation struct PropertyListHelper { /** Decodes a property list to a specific type. - Parameters: - resourceName: Name of the property list to be decoded. - Returns: The already decoded type. */ static func decode<T: Decodable>(resourceName: String = "Info") -> T { guard let url = Bundle.main.url(forResource: resourceName, withExtension: ".plist") else { fatalError() } do { let baseParameters: T = try url.decodePropertyList() return baseParameters } catch { fatalError() } } }
0
// // YQNavigationControllerSwiftUITests.swift // YQNavigationControllerSwiftUITests // // Created by 杨雯德 on 16/3/2. // Copyright © 2016年 杨雯德. All rights reserved. // import XCTest class YQNavigationControllerSwiftUITests: 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. } }
0
// // AppDelegate.swift // APControllers-Example // // Created by Anton Plebanovich on 01/12/2020. // Copyright © 2020 Anton Plebanovich. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { static let shared = UIApplication.shared.delegate as! AppDelegate var window: UIWindow? }
0
// // PhoneConfirmation.swift // falcon // // Created by Manu Herrera on 24/08/2018. // Copyright © 2018 muun. All rights reserved. // struct PhoneConfirmation { let verificationCode: String let signedUp: Bool? let hasPasswordChallengeKey: Bool? let hasRecoveryCodeChallengeKey: Bool? }
0
// // ChangeListViewController.swift // SimpleReminders // // Created by Andrew Grant on 5/25/15. // Copyright (c) Andrew Grant. All rights reserved. // import UIKit import EventKit class ChangeListViewController : BaseListsViewController { var reminder : EKReminder! override func listWasSelected(calendar : EKCalendar) { reminder.calendar = calendar self.navigationController?.popViewControllerAnimated(true) } }
0
import UIKit import ThemeKit protocol ICoinSelectDelegate { func didSelect(coin: SwapModule.CoinBalanceItem) } struct CoinBalanceViewItem { let coin: Coin let balance: String? } struct CoinSelectModule { static func instance(coins: [SwapModule.CoinBalanceItem], delegate: ICoinSelectDelegate) -> UIViewController { let viewModel = CoinSelectViewModel(coins: coins) return ThemeNavigationController(rootViewController: CoinSelectViewController(viewModel: viewModel, delegate: delegate)) } }
0
// // TabViewController.swift // UIKitDemos // // Created by Jonathan Rasmusson (Contractor) on 2020-01-27. // Copyright © 2020 Jonathan Rasmusson. All rights reserved. // import UIKit class TabBarViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupViews() } func setupViews() { navigationItem.title = "TabBar Container" let firstViewController = TabBarViewController1() firstViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0) let secondViewController = TabBarViewController2() secondViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .more, tag: 1) viewControllers = [firstViewController, secondViewController] } } class TabBarViewController1: UIViewController { override func viewDidLoad() { view.backgroundColor = .systemGreen } } class TabBarViewController2: UIViewController { override func viewDidLoad() { view.backgroundColor = .systemBlue } }
0
// // AddressSettingsTVC.swift // crychat // // Created by Жека on 22/01/2018. // Copyright © 2018 Жека. All rights reserved. // import UIKit class AddressSettingsTVC: UITableViewController { @IBOutlet weak var publicKeyTV: UITextView! @IBOutlet weak var privateKeyTV: UITextView! @IBOutlet weak var identIcon: UIImageView! @IBAction func generateAction(_ sender: Any) { let (publicKey, privateKey) = generateKeyPair() setKeys(privateKey, publicKey) } @IBAction func adress_1(_ sender: Any) { setKeys("pdf4e5t91gj07huoqn6540s6wx0szxei","g203hdtf7d1be19gj7dcp7ww8kqopjcu") } @IBAction func address_2(_ sender: Any) { setKeys("i1vunfr6z5i2fkw7g93n0x7edj78d5kx","w2aogwzgogkutmwrnohdqj3rqnxfj4u9") } @IBAction func address_3(_ sender: Any) { setKeys("g203hdtf7d1be19gj7dcp7ww8kqopjcu","i1vunfr6z5i2fkw7g93n0x7edj78d5kx") } func setKeys(_ privateKey: String, _ publicKey: String){ publicKeyTV.text = publicKey privateKeyTV.text = privateKey update() } @IBAction func saveAction(_ sender: Any) { newAddressDelegate.onAddressGenerated(privateKeyTV.text ?? "", publicKeyTV.text ?? "") navigationController?.popViewController(animated: true) } var newAddressDelegate : NewAddressDelegate! override func viewDidLoad() { super.viewDidLoad() publicKeyTV.delegate = self privateKeyTV.delegate = self generateAction(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } protocol NewAddressDelegate { func onAddressGenerated(_ privateKey: String, _ publicKey: String) }
0
// // StateCoordinator.swift // CVGenericDataSourceExample // // Created by Stephan Schulz on 11.04.17. // Copyright © 2017 Stephan Schulz. All rights reserved. // import Foundation import UIKit import CVGenericDataSource class StateCoordinator: NSObject, CoordinatorProtocol { // MARK: - Variables <CoordinatorProtocol> var parentCoordinator: CoordinatorProtocol? var childCoordinators: [CoordinatorProtocol] = [] // MARK: - Variables var navigationController: UINavigationController! var stateViewController: StateViewController! // MARK: - Init init(parentCoordinator: CoordinatorProtocol?, navigationController: UINavigationController) { super.init() self.parentCoordinator = parentCoordinator self.navigationController = navigationController } // MARK: - CoordinatorProtocol func start() { stateViewController = StateViewController(nibName: String(describing: StateViewController.self), bundle: nil) stateViewController.viewModel = StateViewModel(coordinator: self) navigationController.pushViewController(stateViewController, animated: true) } }
0
// // ImageViewController.swift // PixPic // // Created by Illya on 1/26/16. // Copyright © 2016 Yalantis. All rights reserved. // import UIKit class ImageViewController: UIViewController { var model: ImageViewModel! fileprivate weak var locator: ServiceLocator! fileprivate var stickers = [StickerEditorView]() fileprivate var isControlsVisible = true @IBOutlet fileprivate weak var rawImageView: UIImageView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() rawImageView.image = model.originalImage() addHideControlsGestureRecognizer() } // MARK: - Setup methods func setLocator(_ locator: ServiceLocator) { self.locator = locator } @objc fileprivate func toggleControlsState() { isControlsVisible = !isControlsVisible for sticker in stickers { sticker.switchControls(toState: isControlsVisible, animated: true) } } fileprivate func addHideControlsGestureRecognizer() { let singleTap = UITapGestureRecognizer(target: self, action: #selector(toggleControlsState)) singleTap.delegate = self rawImageView.addGestureRecognizer(singleTap) } } extension ImageViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { for sticker in stickers { let touchLocation = touch.location(in: sticker) if sticker.bounds.contains(touchLocation) { return false } } return true } } // MARK: - PhotoEditorDelegate methods extension ImageViewController: PhotoEditorDelegate { func photoEditor(_ photoEditor: PhotoEditorViewController, didChooseSticker: UIImage) { let userResizableView = StickerEditorView(image: didChooseSticker) userResizableView.center = rawImageView.center rawImageView.addSubview(userResizableView) stickers.append(userResizableView) } func imageForPhotoEditor(_ photoEditor: PhotoEditorViewController, withStickers: Bool) -> UIImage { guard withStickers else { return rawImageView.image! } for sticker in stickers { sticker.switchControls(toState: false) } let rect = rawImageView.bounds UIGraphicsBeginImageContextWithOptions(rect.size, view.isOpaque, 0) rawImageView.drawHierarchy(in: rect, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() for sticker in stickers { sticker.switchControls(toState: true) } return image! } func removeAllStickers(_ photoEditor: PhotoEditorViewController) { for sticker in stickers { sticker.removeFromSuperview() } } }
0
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func f: ExtensibleCollectionType>(a)) -> d.join() protocol a { typealias A { " typealias e : A.e = b,
0
// // APODData.swift // DesktopAPOD // // Created by Richard Ash on 5/18/17. // Copyright © 2017 Richard. All rights reserved. // import Foundation struct APODData { let imageURL: URL let title: String }
0
// // AppDelegateTest.swift // PhantomTests // // Created by Alberto Cantallops on 05/09/2017. // Copyright © 2017 Alberto Cantallops. All rights reserved. // import XCTest @testable import Phantom class AppDelegateTest: XCTestCase { // swiftlint:disable:next weak_delegate fileprivate var appDelegate: AppDelegate! fileprivate var firstFakeService: FakeAppDelegateService! fileprivate var secondFakeService: FakeAppDelegateService! override func setUp() { super.setUp() appDelegate = AppDelegate() appDelegate.checkRunningTest = false firstFakeService = FakeAppDelegateService() secondFakeService = FakeAppDelegateService() appDelegate.services = [firstFakeService, secondFakeService] } override func tearDown() { super.tearDown() } func testExecuteDidFinishLaunchingShouldExecuteAllOfServices() { _ = appDelegate.application(UIApplication.shared, didFinishLaunchingWithOptions: nil) XCTAssertTrue(firstFakeService.executedDidFinishLaunchingWithOptions) XCTAssertTrue(secondFakeService.executedDidFinishLaunchingWithOptions) } func testExecuteDidFinishLaunchingShouldReturnFalseIfOneOfTheServicesDoes() { secondFakeService.didFinishLaunchingWithOptionsResult = false let result = appDelegate.application(UIApplication.shared, didFinishLaunchingWithOptions: nil) XCTAssertTrue(firstFakeService.executedDidFinishLaunchingWithOptions) XCTAssertTrue(secondFakeService.executedDidFinishLaunchingWithOptions) XCTAssertFalse(result) } func testExecuteDidFinishLaunchingShouldNotExecuteFollowingServiceIfOneReturnFalse() { secondFakeService.didFinishLaunchingWithOptionsResult = false let thirdFakeService = FakeAppDelegateService() appDelegate.services = [firstFakeService, secondFakeService, thirdFakeService] _ = appDelegate.application(UIApplication.shared, didFinishLaunchingWithOptions: nil) XCTAssertTrue(firstFakeService.executedDidFinishLaunchingWithOptions) XCTAssertTrue(secondFakeService.executedDidFinishLaunchingWithOptions) XCTAssertFalse(thirdFakeService.executedDidFinishLaunchingWithOptions) } } private class FakeAppDelegateService: NSObject, UIApplicationDelegate { var executedDidFinishLaunchingWithOptions: Bool = false var didFinishLaunchingWithOptionsResult: Bool = true override init() { } func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil ) -> Bool { executedDidFinishLaunchingWithOptions = true return didFinishLaunchingWithOptionsResult } }
0
/* * -------------------------------------------------------------------------------- * <copyright company="Aspose" file="GetRangeTextOnlineRequest.swift"> * Copyright (c) 2022 Aspose.Words for Cloud * </copyright> * <summary> * 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. * </summary> * -------------------------------------------------------------------------------- */ import Foundation // Request model for getRangeTextOnline operation. @available(macOS 10.12, iOS 10.3, watchOS 3.3, tvOS 12.0, *) public class GetRangeTextOnlineRequest : WordsApiRequest { private let document : InputStream; private let rangeStartIdentifier : String; private let rangeEndIdentifier : String?; private let loadEncoding : String?; private let password : String?; private let encryptedPassword : String?; private enum CodingKeys: String, CodingKey { case document; case rangeStartIdentifier; case rangeEndIdentifier; case loadEncoding; case password; case encryptedPassword; case invalidCodingKey; } // Initializes a new instance of the GetRangeTextOnlineRequest class. public init(document : InputStream, rangeStartIdentifier : String, rangeEndIdentifier : String? = nil, loadEncoding : String? = nil, password : String? = nil, encryptedPassword : String? = nil) { self.document = document; self.rangeStartIdentifier = rangeStartIdentifier; self.rangeEndIdentifier = rangeEndIdentifier; self.loadEncoding = loadEncoding; self.password = password; self.encryptedPassword = encryptedPassword; } // The document. public func getDocument() -> InputStream { return self.document; } // The range start identifier. public func getRangeStartIdentifier() -> String { return self.rangeStartIdentifier; } // The range end identifier. public func getRangeEndIdentifier() -> String? { return self.rangeEndIdentifier; } // Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML. public func getLoadEncoding() -> String? { return self.loadEncoding; } // Password of protected Word document. Use the parameter to pass a password via SDK. SDK encrypts it automatically. We don't recommend to use the parameter to pass a plain password for direct call of API. public func getPassword() -> String? { return self.password; } // Password of protected Word document. Use the parameter to pass an encrypted password for direct calls of API. See SDK code for encyption details. public func getEncryptedPassword() -> String? { return self.encryptedPassword; } // Creates the api request data public func createApiRequestData(apiInvoker : ApiInvoker, configuration : Configuration) throws -> WordsApiRequestData { var rawPath = "/words/online/get/range/{rangeStartIdentifier}/{rangeEndIdentifier}"; rawPath = rawPath.replacingOccurrences(of: "{rangeStartIdentifier}", with: try ObjectSerializer.serializeToString(value: self.getRangeStartIdentifier())); if (self.getRangeEndIdentifier() != nil) { rawPath = rawPath.replacingOccurrences(of: "{rangeEndIdentifier}", with: try ObjectSerializer.serializeToString(value: self.getRangeEndIdentifier()!)); } else { rawPath = rawPath.replacingOccurrences(of: "{rangeEndIdentifier}", with: ""); } rawPath = rawPath.replacingOccurrences(of: "//", with: "/"); let urlPath = (try configuration.getApiRootUrl()).appendingPathComponent(rawPath); var urlBuilder = URLComponents(url: urlPath, resolvingAgainstBaseURL: false)!; var queryItems : [URLQueryItem] = []; if (self.getLoadEncoding() != nil) { #if os(Linux) queryItems.append(URLQueryItem(name: "loadEncoding", value: try ObjectSerializer.serializeToString(value: self.getLoadEncoding()!))); #else queryItems.append(URLQueryItem(name: "loadEncoding", value: try ObjectSerializer.serializeToString(value: self.getLoadEncoding()!))); #endif } if (self.getPassword() != nil) { #if os(Linux) queryItems.append(URLQueryItem(name: "password", value: try ObjectSerializer.serializeToString(value: self.getPassword()!))); #else queryItems.append(URLQueryItem(name: "encryptedPassword", value: try apiInvoker.encryptString(value: self.getPassword()!))); #endif } if (self.getEncryptedPassword() != nil) { #if os(Linux) queryItems.append(URLQueryItem(name: "encryptedPassword", value: try ObjectSerializer.serializeToString(value: self.getEncryptedPassword()!))); #else queryItems.append(URLQueryItem(name: "encryptedPassword", value: try ObjectSerializer.serializeToString(value: self.getEncryptedPassword()!))); #endif } if (queryItems.count > 0) { urlBuilder.queryItems = queryItems; } var formParams = [RequestFormParam](); var requestFilesContent = [FileReference](); apiInvoker.prepareFilesContent(&requestFilesContent); formParams.append(RequestFormParam(name: "document", body: try ObjectSerializer.serializeFile(value: self.getDocument()), contentType: "application/octet-stream")); for requestFileReference in requestFilesContent { formParams.append(RequestFormParam(name: requestFileReference.reference, body: try ObjectSerializer.serializeFile(value: requestFileReference.content), contentType: "application/octet-stream")); } var result = WordsApiRequestData(url: urlBuilder.url!, method: "PUT"); if (formParams.count > 0) { result.setBody(formParams: formParams); } return result; } // Deserialize response of this request public func deserializeResponse(data : Data, headers : [String: String]) throws -> Any? { return try ObjectSerializer.deserialize(type: RangeTextResponse.self, from: data); } }
0
import Foundation protocol RawBindable { associatedtype Binding: Decodable init(data: [String: Any], binding: Binding) }
0
// // Album.swift // audiobook // // Created by Dang Huy on 5/25/17. // Copyright © 2017 ayanne. All rights reserved. // import SwiftyJSON class Album { var id = Int() var album_title = String() var is_hot = String() var genre = [Genre]() var artist = Artist() var count_songs = Int() var create_date = String() var album_intro = String() var album_logo = String() var update_date = String() var view_count = Int() init(jsonObject: JSON){ self.id = jsonObject["id"].intValue self.album_title = jsonObject["album_title"].stringValue self.is_hot = jsonObject["is_hot"].stringValue self.view_count = jsonObject["view_count"].intValue self.count_songs = jsonObject["count_songs"].intValue self.album_intro = jsonObject["album_intro"].stringValue self.album_logo = jsonObject["album_logo"].stringValue self.create_date = jsonObject["create_date"].stringValue self.update_date = jsonObject["update_date"].stringValue self.artist = Artist(jsonObject: jsonObject["artist"]) var genreList = [Genre]() for item in jsonObject["genre"].arrayValue{ let genre = Genre(jsonObject: item) genreList.append(genre) } self.genre = genreList } }
0
// // Keys.swift // GordianSigner // // Created by Peter on 9/29/20. // Copyright © 2020 Blockchain Commons. All rights reserved. // import Foundation import LibWally enum Keys { static var coinType = UserDefaults.standard.object(forKey: "coinType") as? String ?? "1" static var chain:Network { coinType = UserDefaults.standard.object(forKey: "coinType") as? String ?? "1" if coinType == "0" { return .mainnet } else { return .testnet } } static func accountXprv(_ masterKey: String) -> String? { guard let hdkey = try? HDKey(base58: masterKey), let path = try? BIP32Path(string: "m/48h/\(coinType)h/0h/2h"), let accountXprv = try? hdkey.derive(using: path) else { return nil } return accountXprv.xpriv } static func accountXpub(_ masterKey: String) -> String? { guard let hdkey = try? HDKey(base58: masterKey), let path = try? BIP32Path(string: "m/48h/\(coinType)h/0h/2h"), let accountXpub = try? hdkey.derive(using: path) else { return nil } return accountXpub.xpub } static func masterKey(_ words: [String], _ passphrase: String) -> String? { guard let mnemonic = try? BIP39Mnemonic(words: words) else { return nil } let seedHex = mnemonic.seedHex(passphrase: passphrase) guard let hdMasterKey = try? HDKey(seed: seedHex, network: chain) else { return nil } return hdMasterKey.xpriv } static func masterXprv(_ words: String, _ passphrase: String) -> String? { guard let mnemonic = try? BIP39Mnemonic(words: words) else { return nil } let seedHex = mnemonic.seedHex(passphrase: passphrase) guard let hdMasterKey = try? HDKey(seed: seedHex, network: chain) else { return nil } return hdMasterKey.xpriv } static func masterXpub(_ words: [String], _ passphrase: String) -> String? { guard let mnemonic = try? BIP39Mnemonic(words: words) else { return nil } let seedHex = mnemonic.seedHex(passphrase: passphrase) guard let hdMasterKey = try? HDKey(seed: seedHex, network: chain) else { return nil } return hdMasterKey.xpub } static func fingerprint(_ masterKey: String) -> String? { guard let hdMasterKey = try? HDKey(base58: masterKey) else { return nil } return hdMasterKey.fingerprint.hexString } static func psbtValid(_ string: String) -> Bool { guard let _ = try? PSBT(psbt: string, network: chain) else { guard let _ = try? PSBT(psbt: string, network: chain) else { return false } return true } return true } static func validMnemonicArray(_ words: [String]) -> Bool { guard let _ = try? BIP39Mnemonic(words: words) else { return false } return true } static func validMnemonicString(_ words: String) -> Bool { guard let _ = try? BIP39Mnemonic(words: words) else { return false } return true } static func entropy(_ words: [String]) -> Data? { guard let mnemonic = try? BIP39Mnemonic(words: words) else { return nil } return mnemonic.entropy.data } static func entropy(_ words: String) -> Data? { guard let mnemonic = try? BIP39Mnemonic(words: words) else { return nil } return mnemonic.entropy.data } static func seed() -> String? { var words: String? let bytesCount = 16 var randomBytes = [UInt8](repeating: 0, count: bytesCount) let status = SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomBytes) if status == errSecSuccess { let data = Data(randomBytes) let entropy = BIP39Mnemonic.Entropy(data) if let mnemonic = try? BIP39Mnemonic(entropy: entropy) { words = mnemonic.description } } return words } static func mnemonic(_ entropy: Data) -> String? { let bip39entropy = BIP39Mnemonic.Entropy(entropy) return try? BIP39Mnemonic(entropy: bip39entropy).description } static func psbt(_ psbt: String) -> PSBT? { return try? PSBT(psbt: psbt, network: chain) } static func psbt(_ psbt: Data) -> PSBT? { return try? PSBT(psbt: psbt, network: chain) } static func bip48SegwitAccount(_ masterKey: String) -> String? { guard let hdKey = try? HDKey(base58: masterKey), let bip48SegwitDeriv = try? BIP32Path(string: "m/48'/\(coinType)'/0'/2'"), let account = try? hdKey.derive(using: bip48SegwitDeriv) else { return nil } return "[\(hdKey.fingerprint.hexString)/48h/\(coinType)h/0h/2h]\(account.xpub)" } static func bip48SegwitAccountXprv(_ masterKey: String) -> String? { guard let hdKey = try? HDKey(base58: masterKey), let bip48SegwitDeriv = try? BIP32Path(string: "m/48'/\(coinType)'/0'/2'"), let account = try? hdKey.derive(using: bip48SegwitDeriv), let xprv = account.xpriv else { return nil } return "[\(hdKey.fingerprint.hexString)/48h/\(coinType)h/0h/2h]\(xprv)" } }
0
// // CallEngineResponse.swift // MaduraCallKit // // Created by qiscus on 1/17/17. // Copyright © 2017 qiscus. All rights reserved. // import Foundation public protocol CallEngineResponse{ func userDidLeave() func userDidOffline() func localVideoDidLoad(any: Any?) func remoteVideoDidLoad(any: Any?) }
0
import SwiftUI struct SearchView: View { @ObservedObject var state: SearchState var interceptor: SearchInterceptor var body: some View { VStack { SearchTextField(text: $state.search) .frame(height: 40) .padding([.trailing, .leading], 16) List(state.rows) { row in SearchRowView(row: row) } } .navigationBarTitle("Search") .onAppear(perform: interceptor.setup) } } //struct SearchView_Previews: PreviewProvider { // static var previews: some View { // // let city = CityDTO( // city: "1", // title: "city1", // lat: "0", // lng: "0" // ) // let church = ChurchDTO( // church: "church1", // title: "church1", // city: "city1", // lat: "0", // lng: "0", // desc: "desc", // image: nil, // thumbnail: nil, // alias: "alias" // ) // // let repo = Repo() // repo.churches = [Church(churchDTO: church)] // repo.cities = [City(cityDTO: city)] // // let viewModel = SearchViewModel(repo: repo) // let view = SearchView(viewModel: viewModel) // // // Search `c` // viewModel.search = "c" // return view // } //}
0
import Foundation public class EmptyRouter: Router { public enum Target: Destination { public typealias Container = EmptyRouter public static var presentFrom: EmptyRouter.Target? { return nil } } public func navigate(to destination: EmptyRouter.Target, animated: Bool, completion: ((UIResponder) -> Void)?) { fatalError("It should be impossible to navigate to an empty router") } }
0
// // CartesianCoordinate2D.swift // TrigKit // // Created by Andrew McKnight on 3/4/17. // Copyright © 2017 Andrew McKnight. All rights reserved. // import Foundation public struct CartesianCoordinate2D { public let x: Double public let y: Double public init(x: Double, y: Double) { self.x = x self.y = y } init(x: CGFloat, y: CGFloat) { self.x = Double(x) self.y = Double(y) } } public extension CartesianCoordinate2D { func distance(to coordinate: CartesianCoordinate2D) -> Double { return sqrt(pow(x - coordinate.x, 2) + pow(y - coordinate.y, 2)) } func angle(to b: CartesianCoordinate2D) -> Angle { let xDist = x - b.x let yDist = y - b.y let angle = atan2(yDist, xDist) + .pi return Angle(radians: angle) } } // MARK: CGPoint conversions extension CartesianCoordinate2D { public init(cgPoint: CGPoint, size: CGSize) { let x = cgPoint.x - size.width / 2 let y = size.height / 2 - cgPoint.y self = CartesianCoordinate2D(x: x, y: y) } public func cgPoint(_ canvasSize: CGSize) -> CGPoint { let x = CGFloat(self.x) + canvasSize.width / 2 let y = canvasSize.height / 2 - CGFloat(self.y) return CGPoint(x: x, y: y); } }
0
// swiftlint:disable force_unwrapping // // HMACTests.swift // Tests // // Created by Carol Capek on 05.12.17. // // --------------------------------------------------------------------------- // Copyright 2019 Airside Mobile Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // --------------------------------------------------------------------------- // import XCTest @testable import JOSESwift class HMACTests: HMACCryptoTestCase { func testHMAC256Calculation() { let hmacOutput = try! HMAC.calculate(from: testData, with: testKey, using: .SHA256) XCTAssertEqual(hmacOutput, hmac256TestOutput) } func testHMAC256CalculationWithFalseKey() { let falseKey = "abcdefg".hexadecimalToData()! let hmacOutput = try! HMAC.calculate(from: testData, with: falseKey, using: .SHA256) XCTAssertNotEqual(hmacOutput, hmac256TestOutput) } func testHMAC256CalculationWithFalseData() { let falseData = "abcdefg".hexadecimalToData()! let hmacOutput = try! HMAC.calculate(from: falseData, with: testKey, using: .SHA256) XCTAssertNotEqual(hmacOutput, hmac256TestOutput) } func testHMAC384Calculation() { let hmacOutput = try! HMAC.calculate(from: testData, with: testKey, using: .SHA384) XCTAssertEqual(hmacOutput, hmac384TestOutput) } func testHMAC384CalculationWithFalseKey() { let falseKey = "abcdefg".hexadecimalToData()! let hmacOutput = try! HMAC.calculate(from: testData, with: falseKey, using: .SHA384) XCTAssertNotEqual(hmacOutput, hmac384TestOutput) } func testHMAC384CalculationWithFalseData() { let falseData = "abcdefg".hexadecimalToData()! let hmacOutput = try! HMAC.calculate(from: falseData, with: testKey, using: .SHA384) XCTAssertNotEqual(hmacOutput, hmac384TestOutput) } func testHMAC512Calculation() { let hmacOutput = try! HMAC.calculate(from: testData, with: testKey, using: .SHA512) XCTAssertEqual(hmacOutput, hmac512TestOutput) } func testHMAC512CalculationWithFalseKey() { let falseKey = "abcdefg".hexadecimalToData()! let hmacOutput = try! HMAC.calculate(from: testData, with: falseKey, using: .SHA512) XCTAssertNotEqual(hmacOutput, hmac512TestOutput) } func testHMAC512CalculationWithFalseData() { let falseData = "abcdefg".hexadecimalToData()! let hmacOutput = try! HMAC.calculate(from: falseData, with: testKey, using: .SHA512) XCTAssertNotEqual(hmacOutput, hmac512TestOutput) } }
0
// // DetailView.swift // WeatherApp // // Created by Margiett Gil on 2/5/20. // Copyright © 2020 David Rifkin. All rights reserved. // import UIKit class DetailView: UIView { public lazy var dayLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12, weight: .medium) label.textColor = .gray label.textAlignment = .center return label }() public lazy var imageView: UIImageView = { let image = UIImageView() image.contentMode = .scaleAspectFill return image }() public lazy var summaryLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.textColor = .blue label.font = UIFont.systemFont(ofSize: 12, weight: .medium) label.textAlignment = .center return label }() public lazy var lowTempLabel: UILabel = { let label = UILabel() label.textColor = .systemTeal label.textAlignment = .center return label }() public lazy var highTempLabel: UILabel = { let label = UILabel() label.textColor = .red label.textAlignment = .center return label }() public lazy var sunriseLabel: UILabel = { let label = UILabel() label.textColor = .orange label.textAlignment = .center return label }() public lazy var sunsetLabel: UILabel = { let label = UILabel() label.textColor = .blue label.textAlignment = .center return label }() public lazy var precipitationLabel: UILabel = { let label = UILabel() label.textColor = .purple label.textAlignment = .center return label }() public lazy var windspeedLabel: UILabel = { let label = UILabel() label.textColor = .green label.textAlignment = .center return label }() override init(frame: CGRect) { super.init(frame: UIScreen.main.bounds) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } private func commonInit() { dayLabelConstraints() imageViewConstraints() summaryLabelConstraints() lowTempLabelConstraints() highTempLabelConstraints() sunriseLabelConstraints() sunsetLabelConstraints() precipitationLabelConstraints() windspeedLabelConstraints() } private func dayLabelConstraints() { addSubview(dayLabel) dayLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ dayLabel.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 10), dayLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), dayLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) } private func imageViewConstraints() { addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ imageView.topAnchor.constraint(equalTo: dayLabel.bottomAnchor, constant: 10), imageView.leadingAnchor.constraint(equalTo: leadingAnchor), imageView.trailingAnchor.constraint(equalTo: trailingAnchor), imageView.heightAnchor.constraint(equalToConstant: 400) ]) } private func summaryLabelConstraints() { addSubview(summaryLabel) summaryLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ summaryLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 10), summaryLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), summaryLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) } private func lowTempLabelConstraints() { addSubview(lowTempLabel) lowTempLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ lowTempLabel.topAnchor.constraint(equalTo: summaryLabel.bottomAnchor, constant: 10), lowTempLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), lowTempLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) } private func highTempLabelConstraints() { addSubview(highTempLabel) highTempLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ highTempLabel.topAnchor.constraint(equalTo: lowTempLabel.bottomAnchor, constant: 10), highTempLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), highTempLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) } private func sunriseLabelConstraints() { addSubview(sunriseLabel) sunriseLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ sunriseLabel.topAnchor.constraint(equalTo: highTempLabel.bottomAnchor, constant: 10), sunriseLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), sunriseLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) } private func sunsetLabelConstraints() { addSubview(sunsetLabel) sunsetLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ sunsetLabel.topAnchor.constraint(equalTo: sunriseLabel.bottomAnchor, constant: 10), sunsetLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), sunsetLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) } private func precipitationLabelConstraints() { addSubview(precipitationLabel) precipitationLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ precipitationLabel.topAnchor.constraint(equalTo: sunsetLabel.bottomAnchor, constant: 10), precipitationLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), precipitationLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) } private func windspeedLabelConstraints() { addSubview(windspeedLabel) windspeedLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ windspeedLabel.topAnchor.constraint(equalTo: precipitationLabel.bottomAnchor, constant: 10), windspeedLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), windspeedLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) } }
0
// // ViewController.swift // StarredRepositories // // Created by Gustavo Tiago on 16/08/19. // Copyright © 2019 Tiago. All rights reserved. // import UIKit class RepositoriesViewController: UIViewController { private let viewModel = RepositoriesVM() override var preferredStatusBarStyle: UIStatusBarStyle { return .default } var repositoryView: RepositoryView { return self.view as! RepositoryView } override func loadView() { view = RepositoryView() } override func viewDidLoad() { super.viewDidLoad() bindContent() } // MARK: - Bind private func bindContent() { repositoryView.bindTable(viewModel.repositoryObservable) repositoryView.bindModelState(viewModel.stateDriver) viewModel.bindViewState(repositoryView.stateObservable) } }
0
// // Created by Krzysztof Zablocki on 11/09/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation /// Defines Swift Type class Type: NSObject { internal var isExtension: Bool var accessLevel: AccessLevel /// Name in global scope var name: String { guard let parentName = parentName else { return localName } return "\(parentName).\(localName)" } /// Name in parent scope var localName: String /// All type static variables var staticVariables: [Variable] /// All instance variables var variables: [Variable] /// Only computed instance variables var computedVariables: [Variable] { return variables.filter { $0.isComputed } } /// Only stored instance variables var storedVariables: [Variable] { return variables.filter { !$0.isComputed } } /// Types / Protocols we inherit from var inheritedTypes: [String] /// Contained types var containedTypes: [Type] { didSet { containedTypes.forEach { $0.parentName = self.name } } } /// Parent type name in global scope var parentName: String? /// Underlying parser data, never to be used by anything else internal var __parserData: Any? init(name: String, parentName: String? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, variables: [Variable] = [], staticVariables: [Variable] = [], inheritedTypes: [String] = [], containedTypes: [Type] = []) { self.localName = name self.accessLevel = accessLevel self.isExtension = isExtension self.variables = variables self.staticVariables = staticVariables self.inheritedTypes = inheritedTypes self.containedTypes = containedTypes self.parentName = parentName super.init() containedTypes.forEach { $0.parentName = self.name } } /// Extends this type with an extension /// /// - Parameter type: Extension of this type func extend(_ type: Type) { self.variables += type.variables } }
0
// // RowingStrokeData.swift // // // Created by Chris Hinkle on 10/3/20. // import Foundation import CBGATT public struct RowingStrokeData:CharacteristicModel { public static let dataLength:Int = 20 public let elapsedTime:C2TimeInterval public let distance:C2Distance public let driveLength:C2DriveLength public let driveTime:C2DriveTime public let strokeRecoveryTime:C2TimeInterval public let strokeDistance:C2Distance public let peakDriveForce:C2DriveForce public let averageDriveForce:C2DriveForce public let workPerStroke:C2Work public let strokeCount:C2StrokeCount public init( bytes:[UInt8] ) { elapsedTime = C2TimeInterval( timeWithLow:UInt32( bytes[ 0 ] ), mid:UInt32( bytes[ 1 ] ), high:UInt32( bytes[ 2 ] ) ) distance = C2Distance( distanceWithLow:UInt32( bytes[ 3 ] ), mid:UInt32( bytes[ 4 ] ), high:UInt32( bytes[ 5 ] ) ) driveLength = C2DriveLength( driveLengthWithLow:bytes[6 ] ) driveTime = C2DriveTime( timeWithLow:UInt32( bytes[ 7 ] ), mid:0, high:0 ) strokeRecoveryTime = C2TimeInterval( timeWithLow:UInt32( bytes[ 8 ] ), mid:UInt32( bytes[ 9 ] ), high:0 ) strokeDistance = C2Distance( distanceWithLow:UInt32( bytes[ 10 ] ), mid:UInt32( bytes[ 11 ] ), high:0 ) peakDriveForce = C2DriveForce( driveForceWithLow:UInt16( bytes[ 12 ] ), high:UInt16( bytes[ 13 ] ) ) averageDriveForce = C2DriveForce( driveForceWithLow:UInt16( bytes[ 14 ] ), high:UInt16( bytes[ 15 ] ) ) workPerStroke = C2Work( workWithLow:UInt16( bytes[ 16 ] ), high:UInt16( bytes[ 17 ] ) ) strokeCount = C2StrokeCount( strokeCountWithLow:UInt16( bytes[ 18 ] ), high:UInt16( bytes[ 19 ] ) ) } }
0
// // ContentViewController.swift // SwiftWeather // // Created by CB on 1/02/2016. // Copyright © 2016 Jake Lin. All rights reserved. // import UIKit class ContentViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! var pageIndex: Int! var titleText: String! var imageFile: String! override func viewDidLoad() { super.viewDidLoad() self.imageView.image = UIImage(named: self.imageFile) self.titleLabel.text = self.titleText } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
0
// // AppDelegate.swift // NTPExample // // Created by Michael Sanders on 7/9/16. // Copyright © 2016 Instacart. All rights reserved. // import UIKit import Result import TrueTime @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { TrueTimeClient.sharedInstance.start() window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = .white window?.makeKeyAndVisible() window?.rootViewController = ExampleViewController() return true } }
0
// Copyright © 2015 George King. Permission to use this file is granted in ploy/license.txt. class Pub: ActFormBase, ActForm { // public modifier: `pub expr;`. let def: Def init(_ syn: Syn, def: Def) { self.def = def super.init(syn) } static var expDesc: String { return "`pub`" } var textTreeChildren: [Any] { return [def] } }
0
// // QQdetailVC.swift // QQMusic // // Created by LCY on 16/8/15. // Copyright © 2016年 lincuiyuan. All rights reserved. // import UIKit class QQdetailVC: UIViewController { // 当歌曲切换时, 控件的更新频率 /// 歌词的占位scrollView @IBOutlet weak var lrcBackView: UIScrollView! /// 进度条 (n) @IBOutlet weak var progressSlider: UISlider! /// 歌词label(n) @IBOutlet weak var lrcLabel: QQLrcLabel! /// 播放/暂停按钮() @IBOutlet weak var playOrPauseBtn: UIButton! /// 播放时长(n) @IBOutlet weak var costTimeLabel: UILabel! /// 前景小图片 (1) @IBOutlet weak var singerIconIMV: UIImageView! /// 大的背景(1) @IBOutlet weak var backIMV: UIImageView! /// 歌曲名称(1) @IBOutlet weak var songNameLabel: UILabel! /// 歌手名称(1) @IBOutlet weak var singerNameLabel: UILabel! /// 总时长(1) @IBOutlet weak var totalTimeLabel: UILabel! //歌词视图 var lrcTableView = UITableView?() override func viewDidLoad() { super.viewDidLoad() // layoutViews() } func layoutViews() { lrcTableView?.frame = lrcBackView.bounds lrcTableView?.x = lrcBackView.width lrcBackView.contentSize = CGSize(width: lrcBackView.width * 2, height: 0) singerIconIMV.layer.cornerRadius = singerIconIMV.width * 0.5 singerIconIMV.layer.masksToBounds = true } @IBAction func blackBtnClick(sender: AnyObject) { navigationController?.popViewControllerAnimated(true) } //暂停,播放 @IBAction func playPauseBtn(sender: AnyObject) { playOrPauseBtn.selected = !playOrPauseBtn.selected if playOrPauseBtn.selected { QQMusicSwitchNext.shareInstance.play() }else{ QQMusicSwitchNext.shareInstance.pause() } } //上一首 @IBAction func preMusicBtn(sender: AnyObject) { } //下一首 @IBAction func nextMusicBtn(sender: AnyObject) { } }
0
// // CalenderViewController.swift // MyAirbnb // // Created by 행복한 개발자 on 15/07/2019. // Copyright © 2019 Alex Lee. All rights reserved. // import UIKit import Kingfisher import NVActivityIndicatorView class CalenderViewController: UIViewController { // MARK: - UI Properties let backgroundView = UIView() let containerView = UIView() let topTextLabel = UILabel() let refreshBtn = UIButton() var weekdayLabel = UILabel() let seperateLineViewTop = UIView() let seperateLineViewBottom = UIView() let resultBtn = UIButtonWithHighlightEffect() private weak var calendar: FSCalendar! let indicator = NVActivityIndicatorView(frame: .zero) // MARK: - Properties var useCase: UseCase = .inMainVC var inController: UIViewController = UIViewController() let currentDate = Date() let dateFormatter = DateFormatter() let notiCenter = NotificationCenter.default let netWork = NetworkCommunicator() let jsonDecoder = JSONDecoder() let kingfisher = ImageDownloader.default var beginDatesArray = [Date]() { didSet { print("🔵🔵🔵 beginDatesArray didSet") selectedDatesArray = beginDatesArray // guard beginDatesArray.count > 1 else { // calendar.select(beginDatesArray.first!) // return // } // print(selectedDatesArray) // selectDateCells() } } var selectedDatesArray = [Date]() { didSet { guard selectedDatesArray.count > 0 else { return } selectedDatesString = setTextFromDate(datesArray: selectedDatesArray) } } var selectedDatesString = "날짜 선택" { didSet { guard selectedDatesString != "날짜 선택" else { topTextLabel.text = "날짜 선택" return } topTextLabel.text = selectedDatesString } } override func viewDidLoad() { super.viewDidLoad() setBackgroundView() setCalendar() setAutoLayout() configureViewsOptions() setIndicatorView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setAnimation() guard beginDatesArray.count > 0 else { return } calendar.select(beginDatesArray.first!) refreshBtn.isEnabled = true refreshBtn.layer.opacity = 1 if beginDatesArray.count > 1 { print(" 😘 ", selectedDatesArray) selectDateCells() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) dismiss(animated: false, completion: nil) } private func setBackgroundView() { view.addSubview(backgroundView) backgroundView.frame = view.frame backgroundView.backgroundColor = .white backgroundView.alpha = 0 } private func setAutoLayout() { let safeGuide = view.safeAreaLayoutGuide view.addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false containerView.topAnchor.constraint(equalTo: safeGuide.topAnchor, constant: 80).isActive = true containerView.leadingAnchor.constraint(equalTo: safeGuide.leadingAnchor, constant: 15).isActive = true containerView.trailingAnchor.constraint(equalTo: safeGuide.trailingAnchor, constant: -15).isActive = true // containerView.bottomAnchor.constraint(equalTo: safeGuide.bottomAnchor, constant: -200).isActive = true containerView.heightAnchor.constraint(equalToConstant: 430).isActive = true containerView.addSubview(topTextLabel) topTextLabel.translatesAutoresizingMaskIntoConstraints = false topTextLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 15).isActive = true topTextLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true containerView.addSubview(refreshBtn) refreshBtn.translatesAutoresizingMaskIntoConstraints = false refreshBtn.centerYAnchor.constraint(equalTo: topTextLabel.centerYAnchor).isActive = true refreshBtn.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -3).isActive = true refreshBtn.widthAnchor.constraint(equalToConstant: 60).isActive = true refreshBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true let weekDays = ["일", "월", "화", "수", "목", "금", "토"] var leadingConst: CGFloat = 20 let letterWidth = "가".size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)]).width let letterPadding = (UIScreen.main.bounds.width - 30 - leadingConst*2 - letterWidth ) / 6 for i in 0...6 { let label = UILabel() containerView.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false label.topAnchor.constraint(equalTo: topTextLabel.bottomAnchor, constant: 15).isActive = true label.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: leadingConst).isActive = true label.text = weekDays[i] label.textColor = #colorLiteral(red: 0.1990053952, green: 0.1978290677, blue: 0.1999138892, alpha: 0.8544252997) label.font = .systemFont(ofSize: 11, weight: .regular) leadingConst += letterPadding ( i == 6 ) ? (weekdayLabel = label) : () } containerView.addSubview(seperateLineViewTop) seperateLineViewTop.translatesAutoresizingMaskIntoConstraints = false seperateLineViewTop.topAnchor.constraint(equalTo: weekdayLabel.bottomAnchor, constant: 5).isActive = true seperateLineViewTop.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true seperateLineViewTop.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true seperateLineViewTop.heightAnchor.constraint(equalToConstant: 1).isActive = true containerView.addSubview(resultBtn) resultBtn.translatesAutoresizingMaskIntoConstraints = false resultBtn.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true resultBtn.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0).isActive = true resultBtn.widthAnchor.constraint(equalTo: containerView.widthAnchor, multiplier: 1).isActive = true resultBtn.heightAnchor.constraint(equalToConstant: 43).isActive = true containerView.addSubview(seperateLineViewBottom) seperateLineViewBottom.translatesAutoresizingMaskIntoConstraints = false seperateLineViewBottom.bottomAnchor.constraint(equalTo: resultBtn.topAnchor, constant: 0).isActive = true seperateLineViewBottom.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true seperateLineViewBottom.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true seperateLineViewBottom.heightAnchor.constraint(equalToConstant: 1).isActive = true containerView.addSubview(calendar) calendar.translatesAutoresizingMaskIntoConstraints = false calendar.topAnchor.constraint(equalTo: seperateLineViewTop.bottomAnchor, constant: 0).isActive = true calendar.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true calendar.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true calendar.bottomAnchor.constraint(equalTo: seperateLineViewBottom.topAnchor, constant: 0).isActive = true } private func configureViewsOptions() { containerView.backgroundColor = .white containerView.layer.cornerRadius = 5 containerView.alpha = 0 containerView.layer.masksToBounds = false containerView.layer.shadowColor = UIColor.gray.cgColor containerView.layer.shadowOpacity = 0.6 containerView.layer.shadowOffset = CGSize(width: 0, height: 0) containerView.layer.shadowRadius = 5 topTextLabel.text = selectedDatesString topTextLabel.textAlignment = .center topTextLabel.font = .systemFont(ofSize: 15, weight: .semibold) topTextLabel.textColor = #colorLiteral(red: 0.1990053952, green: 0.1978290677, blue: 0.1999138892, alpha: 0.8544252997) refreshBtn.setTitle("지우기", for: .normal) refreshBtn.setTitleColor(UIColor(red:0.09, green:0.51, blue:0.54, alpha:1.0), for: .normal) refreshBtn.titleLabel?.font = .systemFont(ofSize: 13, weight: .semibold) refreshBtn.addTarget(self, action: #selector(refreshBtnDidTap(_:)), for: .touchUpInside) refreshBtn.isEnabled = false refreshBtn.layer.opacity = 0.5 resultBtn.addTarget(self, action: #selector(resultBtnDidTap(_:)), for: .touchUpInside) seperateLineViewTop.backgroundColor = #colorLiteral(red: 0.5761868954, green: 0.5727648139, blue: 0.5788194537, alpha: 0.4162831764) seperateLineViewBottom.backgroundColor = #colorLiteral(red: 0.5761868954, green: 0.5727648139, blue: 0.5788194537, alpha: 0.4162831764) resultBtn.setTitle("결과 보기", for: .normal) resultBtn.setTitleColor(UIColor(red:0.09, green:0.51, blue:0.54, alpha:1.0), for: .normal) resultBtn.titleLabel?.font = .systemFont(ofSize: 13, weight: .semibold) } private func setCalendar() { let calendar = FSCalendar(frame: .zero) calendar.dataSource = self calendar.delegate = self calendar.pagingEnabled = false calendar.scrollDirection = .vertical calendar.allowsMultipleSelection = true calendar.today = nil calendar.placeholderType = .none calendar.appearance.headerDateFormat = "M" calendar.headerHeight = 35 calendar.appearance.headerTitleFont = .systemFont(ofSize: 13, weight: .semibold) calendar.appearance.headerTitleColor = .black calendar.weekdayHeight = 15 calendar.appearance.weekdayTextColor = .clear calendar.appearance.titleFont = .systemFont(ofSize: 13, weight: .semibold) calendar.appearance.titleDefaultColor = #colorLiteral(red: 0.1990053952, green: 0.1978290677, blue: 0.1999138892, alpha: 0.8544252997) calendar.appearance.titlePlaceholderColor = #colorLiteral(red: 0.7327679992, green: 0.7284137607, blue: 0.7361161113, alpha: 0.4171660959) calendar.appearance.selectionColor = UIColor(red:0.09, green:0.51, blue:0.54, alpha:1.0) view.addSubview(calendar) self.calendar = calendar } private func setAnimation() { UIView.animate(withDuration: 0.2) { self.backgroundView.alpha = 0.5 self.containerView.transform = CGAffineTransform(translationX: 0, y: -10) self.containerView.alpha = 1 } } private func setIndicatorView() { let centerX = UIScreen.main.bounds.width/2 let centerY = UIScreen.main.bounds.height/2 resultBtn.addSubview(indicator) indicator.frame = CGRect(x: centerX-23, y: 9, width: 23, height: 23) indicator.type = .ballBeat indicator.color = StandardUIValue.shared.colorBlueGreen } @objc func refreshBtnDidTap(_ sender: UIButton) { print("didTap") selectedDatesString = "날짜 선택" selectedDatesArray.forEach{ calendar.deselect($0) } selectedDatesArray.removeAll() sender.isEnabled = false sender.layer.opacity = 0.5 } @objc func resultBtnDidTap(_ sender: UIButton) { print("--------------------------[resultBtnDidTap]--------------------------") print(selectedDatesString) switch useCase { case .inMainVC: guard let mainVC = inController as? MainViewController else { print("‼️ : "); return } if self.selectedDatesString == "날짜 선택" { mainVC.searchBarView.selectedDatesArray.removeAll() mainVC.searchBarView.selectedDateString = "날짜" dismissWithAnimation() } else { resultBtn.setTitle("", for: .normal) indicator.startAnimating() mainVC.searchBarView.selectedDateString = selectedDatesString mainVC.searchBarView.selectedDatesArray = selectedDatesArray } case .inHouseVC: guard let houseVC = inController as? HouseViewController else { print("‼️ : "); return } if self.selectedDatesString == "날짜 선택" { houseVC.searchBarView.selectedDatesArray.removeAll() houseVC.searchBarView.selectedDateString = "날짜" dismissWithAnimation() } else { resultBtn.setTitle("", for: .normal) indicator.startAnimating() houseVC.searchBarView.selectedDateString = selectedDatesString houseVC.searchBarView.selectedDatesArray = selectedDatesArray } case .inTripVC: () } var houseViewDataArray = [HouseViewData]() getServerDataWithDate { (houseDataArray, success) in DispatchQueue.main.asyncAfter(deadline: .now() + 1) { switch success { case true: print("--------------------------[CalendarVC serfverData Success]--------------------------") let houseviewDataIntroLabel = HouseViewData( data: [HouseIntroLabelDataInList(intro: "여행 날짜와 게스트 인원수를 입력하면 1박당 총 요금을 확인할 수 있습니다. 관광세가 추가로 부과될 수 있습니다.")], cellStyle: .introLabel) let houseviewDataTitleLabel = HouseViewData( data: [HouseTitleLabelDataInList(title: "300개 이상의 숙소 모두 둘러보기")], cellStyle: .titleLabel) let houseviewDataNormal = HouseViewData(data: houseDataArray!, cellStyle: .normalHouse) houseViewDataArray = [houseviewDataIntroLabel, houseviewDataTitleLabel, houseviewDataNormal] case false: print("--------------------------[CalendarVC serfverData False]--------------------------") let houseviewDataIntroLabel = HouseViewData( data: [HouseIntroLabelDataInList(intro: "숙소 결과가 없습니다.")], cellStyle: .introLabel) houseViewDataArray = [houseviewDataIntroLabel] } self.notiCenter.post(name: .searchBarDateResultBtnDidTap, object: nil, userInfo: ["houseViewDataArray": houseViewDataArray, SingletonCommonData.notiKeySearchBarUseCase: self.useCase, SingletonCommonData.notiKeySearchBarInController: self.inController]) self.dismissWithAnimation() } } } private func lastDayOfMonth(date: Date) -> Date { let calendar = Calendar.current var components = calendar.dateComponents([.year, .month, .day], from: date) let range = calendar.range(of: .day, in: .month, for: date)! components.day = range.upperBound - 1 return calendar.date(from: components)! } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touchLocation = touches.first!.location(in: view) print(touchLocation) guard !containerView.frame.contains(touchLocation) else { return } UIView.animate(withDuration: 0.2, animations: { self.backgroundView.alpha = 0 self.containerView.transform = CGAffineTransform.identity self.containerView.alpha = 0 }) { (_) in self.dismiss(animated: false, completion: nil) } } private func dismissWithAnimation() { UIView.animate(withDuration: 0.2, animations: { self.backgroundView.alpha = 0 self.containerView.transform = CGAffineTransform.identity self.containerView.alpha = 0 }) { (_) in self.dismiss(animated: false, completion: nil) } } private func getServerDataWithDate(completion: @escaping ([HouseDataInList]?, Bool) -> ()) { let startDate = selectedDatesArray.first?.getDateStringFormatYearMonthDay(dateFormat: "yyyy-MM-dd") ?? "" let endDate = selectedDatesArray.last?.getDateStringFormatYearMonthDay(dateFormat: "yyyy-MM-dd") ?? "" let urlString = netWork.basicUrlString + "/rooms/?search=korea&ordering=-total_rating&page_size=10&page=1" + "&start_date=\(startDate)&end_date=\(endDate)" netWork.getJsonObjectFromAPI(urlString: urlString, urlForSpecificProcessing: nil) { (json, success) in guard success else { return } guard let object = json as? [String: Any] , let resultArray = object["results"] as? [[String: Any]] else { print("object convert error"); return } guard let data = try? JSONSerialization.data(withJSONObject: resultArray) else { print("‼️ CalendarVC data convert error") return } guard var houseArray = try? self.jsonDecoder.decode([HouseDataInList].self, from: data) , houseArray.count > 0 else { print("‼️ CalendarVC result decoding convert error") completion(nil, false) return } for i in 0..<houseArray.count { guard let url = URL(string: houseArray[i].image) else { print("‼️ CalendarVC kingfisher url "); return } self.kingfisher.downloadImage(with: url, completionHandler: { (result) in switch result { case .success(let value): houseArray[i].imageArray.append(value.image) case .failure(let error): print("‼️ LaunchVC kinfisher: ", error.localizedDescription) } (i == houseArray.count - 1) ? completion(houseArray, true) : () }) } } } } extension CalenderViewController: FSCalendarDelegate, FSCalendarDataSource { func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool { print("--------------------------[ShouldSelect]--------------------------") guard calendar.cell(for: date, at: monthPosition)?.isPlaceholder == false else { print("placeholder cell") return false } dateFormatter.dateFormat = "yyyy-MM-dd hh:mm" let selectDateString = dateFormatter.string(from: date) print("selectDateString: ", selectDateString) dateFormatter.dateFormat = "MM.dd" let currentDay = dateFormatter.string(from: currentDate) let selectDay = dateFormatter.string(from: date) print("currentDay: ", currentDay) print("selectDay: ", selectDay) return true } func minimumDate(for calendar: FSCalendar) -> Date { return currentDate } func maximumDate(for calendar: FSCalendar) -> Date { let laterDate = Calendar.current.date(byAdding: .month, value: 2, to: currentDate)! let lastDayMonth = lastDayOfMonth(date: laterDate) return lastDayMonth } func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) { print("--------------------------[DidSelect]--------------------------") refreshBtn.isEnabled = true refreshBtn.layer.opacity = 1 switch selectedDatesArray.count { case 0: print("currentCount: ", selectedDatesArray.count) selectedDatesArray.append(date) print(selectedDatesArray) case 1: // 이미 1개가 선택되어있을때 print("currentCount: ", selectedDatesArray.count) selectedDatesArray.append(date) selectedDatesArray.sort() selectDateCells() selectedDatesArray.sort() print(selectedDatesArray) case 2...: // 눌렀을때 이미 2개이상이 선택되있는 상황일때 print("currentCount: ", selectedDatesArray.count) selectedDatesArray.forEach{ calendar.deselect($0) } selectedDatesArray.removeAll() selectedDatesArray.append(date) print(selectedDatesArray) default : break } } func calendar(_ calendar: FSCalendar, didDeselect date: Date, at monthPosition: FSCalendarMonthPosition) { print("--------------------------[DidDeselect]--------------------------") if selectedDatesArray.contains(date) { selectedDatesArray.forEach{ calendar.deselect($0) } selectedDatesArray.removeAll() calendar.select(date) selectedDatesArray.append(date) // topTextLabel.text = setTextFromDate() } print(selectedDatesArray) } private func selectDateCells() { let timeGap = selectedDatesArray.last!.timeIntervalSince(selectedDatesArray.first!) let oneDayValue: TimeInterval = 3600 * 24 let daysGap = Int(timeGap / oneDayValue) for i in 1...daysGap { let day = Calendar.current.date(byAdding: .day, value: i, to: selectedDatesArray.first!)! calendar.select(day) guard !selectedDatesArray.contains(day) else { continue } selectedDatesArray.append(day) } // selectedDatesArray.removeLast() } private func setTextFromDate(datesArray: [Date]) -> String{ var dayString = "" let componentsStartDay = Calendar.current.dateComponents([.month, .day], from: selectedDatesArray.first!) if datesArray.count > 1 { let componentsEndDay = Calendar.current.dateComponents([.month, .day], from: selectedDatesArray.last!) dayString = "\(componentsStartDay.month!)월 \(componentsStartDay.day!)일 ~ \(componentsEndDay.month!)월 \(componentsEndDay.day!)일" return dayString } dayString = "\(componentsStartDay.month!)월 \(componentsStartDay.day!)일" return dayString } }
0
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // import UIKit struct UserListItem { let user: User let action: ((UserListItem) -> Void)? } extension UserListItem: CellModel { var cellClass: UITableViewCell.Type { return UserListCell.self } var reuseID: String { return UserListCell.reuseID } }
0
// // Location.swift // SortMyGroceries // // Created by Thomas Smith on 4/18/20. // Copyright © 2020 Thomas Smith. All rights reserved. // import Foundation struct Location: Comparable, Hashable { var text: String init(_ text: String) { self.text = text.localizedCapitalized } static func < (lhs: Location, rhs: Location) -> Bool { return lhs.text < rhs.text } }
0
// // KeynotedexTests.swift // KeynotedexTests // // Created by Guillermo Orellana on 27/04/2019. // Copyright © 2019 Guillermo Orellana. All rights reserved. // import XCTest @testable import Keynotedex class KeynotedexTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
0
// // OxygenMonitorController.swift // Oxygen // // Created by Andrew Madsen on 7/21/15. // Copyright (c) 2015 Open Reel Software. All rights reserved. // import Foundation import ORSSerial import Observable struct PulseOxMeasurement { var oxygen: Int var heartRate: Int var timestamp: NSDate init?(serialPacket: NSData) { self.oxygen = 0; self.heartRate = 0; self.timestamp = NSDate() if let string = String(asciiData: serialPacket) as NSString? where string.length >= 15 { let oxygenString = string.substringWithRange(NSRange(location: 5, length: 3)).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let heartRateString = string.substringWithRange(NSRange(location: 12, length: 3)).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) if let oxygen = oxygenString.toInt(), let heartRate = heartRateString.toInt() { self.oxygen = oxygen self.heartRate = heartRate self.timestamp = NSDate() } else { return nil } } else { return nil } } var csvLineRepresentation: String { let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" let dateString = dateFormatter.stringFromDate(timestamp) return "\(dateString), \(String(oxygen)), \(String(heartRate))\n" } } class OxygenMonitorController: NSObject, ORSSerialPortDelegate { init(_ serialPort: ORSSerialPort) { self.serialPort = serialPort let desktop = NSURL(fileURLWithPath: "~/Desktop/".stringByExpandingTildeInPath)! let dataFileURL = desktop.URLByAppendingPathComponent(NSUUID().UUIDString).URLByAppendingPathExtension("o2d") NSFileManager.defaultManager().createFileAtPath(dataFileURL.path!, contents: NSData(), attributes: nil) var error: NSError? self.dataFileHandle = NSFileHandle(forWritingToURL: dataFileURL, error: &error) if self.dataFileHandle == nil { println("Unable to open file handle to \(dataFileURL): \(error)") } super.init() self.writeFileHeader() self.configureSerialPort() } deinit { self.serialPort = nil self.dataFileHandle?.closeFile() } // MARK: - ORSSerialPortDelegate func serialPortWasRemovedFromSystem(serialPort: ORSSerialPort) { self.serialPort = nil } func serialPortWasOpened(serialPort: ORSSerialPort) { println("\(serialPort) was opened.") } func serialPort(serialPort: ORSSerialPort, didReceivePacket packetData: NSData, matchingDescriptor descriptor: ORSSerialPacketDescriptor) { if let reading = PulseOxMeasurement(serialPacket: packetData) { self.mostRecentReading.value = reading self.allReadings.value.append(reading) self.dataFileHandle?.writeData(reading.csvLineRepresentation.asciiData) } } // MARK: - Private func configureSerialPort() { self.serialPort?.delegate = self self.serialPort?.baudRate = 9600 self.serialPort?.numberOfStopBits = 2 self.serialPort?.open() self.installPacketListener() } func installPacketListener() { if let port = self.serialPort { let prefix = NSData(asciiString: "Sp") let suffix = NSData(asciiString: "\r\n") let descriptor = ORSSerialPacketDescriptor(prefix: prefix, suffix: suffix, userInfo: nil) port.startListeningForPacketsMatchingDescriptor(descriptor) } } func writeFileHeader() { let data = NSData(asciiString: "Date, O2, HeartRate\n") self.dataFileHandle?.writeData(data) } // MARK: - Properties private(set) var mostRecentReading = Observable<PulseOxMeasurement?>(nil) private(set) var allReadings = Observable(Array<PulseOxMeasurement>()) private(set) var serialPort: ORSSerialPort? { willSet { self.serialPort?.delegate = nil self.serialPort?.close() } didSet { self.configureSerialPort() } } private let dataFileHandle: NSFileHandle? } extension NSData { convenience init!(asciiString: String) { if let data = asciiString.dataUsingEncoding(NSASCIIStringEncoding) { self.init(data: data) } else { self.init() return nil } } var asciiString: String { return NSString(data: self, encoding: NSASCIIStringEncoding)! as String } } extension String { init!(asciiData: NSData) { if let string = NSString(data: asciiData, encoding: NSASCIIStringEncoding) { self.init(string) } else { self.init() return nil } } var asciiData: NSData { return self.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)! } }
0
// // JFMusicPlayerView.swift // EnglishCommunity-swift // // Created by zhoujianfeng on 9/18/16. // Copyright © 2016 zhoujianfeng. All rights reserved. // import UIKit protocol JFMusicPlayerViewDelegate: NSObjectProtocol { func didTappedPlayButton(button: UIButton) } class JFMusicPlayerView: UIView { @IBOutlet weak var currentTimeLabel: UILabel! @IBOutlet weak var totalTimeLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var playButton: UIButton! weak var delegate: JFMusicPlayerViewDelegate? /** 点击了播放按钮 */ @IBAction func didTappedPlayButton(sender: UIButton) { delegate?.didTappedPlayButton(sender) } }
0
// // Bundle+Extensions.swift // Indicate // // Created by Jan Krukowski on 2021-09-29. // Copyright © 2021 Philip Kluz. All rights reserved. // import Foundation extension Bundle { internal static var indicate: Bundle = { let podBundle = Bundle(for: Indicate.View.self) guard let url = podBundle.url(forResource: "IndicateKit", withExtension: "bundle"), let bundle = Bundle(url: url) else { return podBundle } return bundle }() }
0
// // SeniorWillDetailViewController.swift // devils-advocate // // Created by Isabella Hochschild on 5/4/20. // Copyright © 2020 Isabella Hochschild. All rights reserved. // import UIKit class SeniorWillDetailViewController: UIViewController { var previousVC : UITableViewController? var selectedSeniorWill : SeniorWill? var willContents : String? @IBOutlet weak var contents: UITextView! @IBOutlet weak var testLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.title = selectedSeniorWill!.name testLabel.text = selectedSeniorWill!.name willContents = "" if(selectedSeniorWill!.cause_of_death != "?") { willContents=willContents!+"<br><br><strong>Cause of death</strong>: \(selectedSeniorWill!.cause_of_death)" } if(selectedSeniorWill!.statement != "?") { willContents=willContents!+"<br><br><strong>Statement</strong>: \(selectedSeniorWill!.statement)" } if(!(selectedSeniorWill!.freshmen.isEmpty)) { willContents=willContents!+"<br><br><strong>Freshmen</strong>:" for (key,val) in selectedSeniorWill!.freshmen { willContents=willContents!+"<br>\(key): \(val)" } } if(!(selectedSeniorWill!.sophomores.isEmpty)) { willContents=willContents!+"<br><br><strong>Sophomors</strong>:" for (key,val) in selectedSeniorWill!.sophomores { willContents=willContents!+"<br>\(key): \(val)" } } if(!(selectedSeniorWill!.juniors.isEmpty)) { willContents=willContents!+"<br><br><strong>Juniors</strong>:" for (key,val) in selectedSeniorWill!.juniors { willContents=willContents!+"<br>\(key): \(val)" } } if(!(selectedSeniorWill!.faculty.isEmpty)) { willContents=willContents!+"<br><br><strong>Faculty</strong>:" for (key,val) in selectedSeniorWill!.faculty { willContents=willContents!+"<br>\(key): \(val)" } } if(!(selectedSeniorWill!.miscellaneous.isEmpty)) { willContents=willContents!+"<br><br><strong>Miscellaneous</strong>:" for (key,val) in selectedSeniorWill!.miscellaneous { willContents=willContents!+"<br>\(key): \(val)" } } contents.attributedText = willContents?.htmlToAttributedString let btnShare = UIBarButtonItem(barButtonSystemItem:.action, target: self, action: #selector(btnShare_clicked)) self.navigationItem.rightBarButtonItem = btnShare } @objc func btnShare_clicked() { var seniorName = selectedSeniorWill!.name let textToShare = "\(seniorName)'s Senior Will from the Devils' Advocate" if let myWebsite = NSURL(string: "http://devils-advocate.herokuapp.com/2020-senior-wills/"+selectedSeniorWill!.will_id) { let objectsToShare: [Any] = [textToShare, myWebsite] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = self.view self.present(activityVC, animated: true, completion: nil) } } /* // 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.destination. // Pass the selected object to the new view controller. } */ }
0
import XCTest import Firebase @testable import Tripfinger class StringUtilsTest: XCTestCase { func testSplitStringInParagraphs() { let string = "<p>One paragraph.</p>" let paragraphs = string.splitInParagraphs() XCTAssertEqual(1, paragraphs.count) } }
0
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // NetworkOperation.swift // // Created by Joshua Liebowitz on 11/18/21. import Foundation class CacheableNetworkOperation: NetworkOperation, CacheKeyProviding { var cacheKey: String { "\(type(of: self)) \(individualizedCacheKeyPart)" } let individualizedCacheKeyPart: String /** - Parameter individualizedCacheKeyPart: The part of the cacheKey that makes it unique from other operations of the same type. Example: If you posted receipts two times in a row you'd have 2 operations. The cache key would be PostOperation + individualizedCacheKeyPart where individualizedCacheKeyPart is whatever you determine to be unique. */ init(configuration: NetworkConfiguration, individualizedCacheKeyPart: String) { self.individualizedCacheKeyPart = individualizedCacheKeyPart super.init(configuration: configuration) } } class NetworkOperation: Operation { let httpClient: HTTPClient private var _isExecuting: Atomic<Bool> = .init(false) private(set) override final var isExecuting: Bool { get { return self._isExecuting.value } set { self.willChangeValue(for: \.isExecuting) self._isExecuting.value = newValue self.didChangeValue(for: \.isExecuting) } } private var _isFinished: Atomic<Bool> = .init(false) private(set) override final var isFinished: Bool { get { return self._isFinished.value } set { self.willChangeValue(for: \.isFinished) self._isFinished.value = newValue self.didChangeValue(for: \.isFinished) } } private var _isCancelled: Atomic<Bool> = .init(false) private(set) override final var isCancelled: Bool { get { return self._isCancelled.value } set { self.willChangeValue(for: \.isCancelled) self._isCancelled.value = newValue self.didChangeValue(for: \.isCancelled) } } init(configuration: NetworkConfiguration) { self.httpClient = configuration.httpClient super.init() } override final func main() { if self.isCancelled { self.isFinished = true return } self.isExecuting = true self.log("Started") self.begin { self.finish() } } override final func cancel() { self.isCancelled = true self.isExecuting = false self.isFinished = true self.log("Cancelled") } /// Overriden by subclasses to define the body of the operation /// - Important: this method may be called from any thread so it must be thread-safe. /// - Parameter completion: must be called when the operation has finished. func begin(completion: @escaping () -> Void) { fatalError("Subclasses must override this method") } private final func finish() { assert(!self.isFinished, "Operation \(type(of: self)) (\(self)) was already finished") self.log("Finished") self.isExecuting = false self.isFinished = true } // MARK: - final override var isAsynchronous: Bool { return true } // MARK: - private func log(_ message: String) { Logger.debug("\(type(of: self)): \(message)") } // MARK: - struct Configuration: NetworkConfiguration { let httpClient: HTTPClient } struct UserSpecificConfiguration: AppUserConfiguration, NetworkConfiguration { let httpClient: HTTPClient let appUserID: String } } protocol AppUserConfiguration { var appUserID: String { get } } protocol NetworkConfiguration { var httpClient: HTTPClient { get } }
0
// // PostTableViewCell.swift // CeibaUser // // Created by Nestor Moya Yepes on 15/03/20. // Copyright © 2020 Nestor Moya Yepes. All rights reserved. // import UIKit class PostTableViewCell: UITableViewCell { @IBOutlet weak var txtContent: UITextView! @IBOutlet weak var txtTitle: UITextView! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
0
// // SwiftAsyncUDPSocketSendFilter.swift // SwiftAsyncSocket // // Created by chouheiwa on 2019/1/11. // Copyright © 2019 chouheiwa. All rights reserved. // import Foundation /// This struct can help you to filter send data /// A filter can provide several interesting possibilities: /// /// 1. Optional caching of resolved addresses for domain names. /// The cache could later be consulted, resulting in fewer system calls to getaddrinfo. /// /// 2. Reusable modules of code for bandwidth monitoring. /// /// 3. Sometimes traffic shapers are needed to simulate real world environments. /// A filter allows you to write custom code to simulate such environments. /// The ability to code this yourself is especially helpful when your simulated environment /// is more complicated than simple traffic shaping (e.g. simulating a cone port restricted router), /// or the system tools to handle this aren't available (e.g. on a mobile device). public struct SwiftAsyncUDPSocketSendFilter: SwiftAsyncUDPSocketFilter { /// - Parameters: /// - $0: the packet that was sent /// - $1: The address of the data sent to /// - $2: The tag of the sent data /// - Returns: /// - $0: true if the received packet should be passed onto the delegate. /// false if the received packet should be discarded, and not reported to the delegete. public typealias BlockType = (Data, SwiftAsyncUDPSocketAddress, Int) -> Bool public var filterBlock: BlockType public var queue: DispatchQueue /// If we should use async public var async: Bool public init(filterBlock: @escaping BlockType, queue: DispatchQueue, async: Bool) { self.filterBlock = filterBlock self.queue = queue self.async = async } }
0
// // Users.swift // import Foundation struct User { var name: String var email: String var password: String }
0
// // MainView.swift // CheapHunt // // Created by Furkan Hanci on 5/30/21. // import SwiftUI struct MainView: View { @ObservedObject private var userName = UserName() @State private var dat : [Deal] = [] @State private var isWorking : Bool = true private let second : Double = 4.0 @State private var isString = "" @State private var isActive : Bool = false @State private var settingsActive : Bool = false @State private var emptyAlert : Bool = false @StateObject private var getData = GetData() init() { UITableView.appearance().backgroundColor = .clear UITableView.appearance().separatorStyle = .none UITableViewCell.appearance().backgroundColor = .clear } var body: some View { NavigationView { ZStack { LinearGradient(gradient: Gradient(colors: [Color.bg2, Color.bg3 , Color.bg4 , Color.bg1]), startPoint: .topLeading, endPoint: .bottomTrailing) .edgesIgnoringSafeArea(.all) VStack { TextField(Constants.Texts.enterAmount, text: $isString) .textFieldStyle(OvalTextField()) Button(Constants.Texts.fetch) { switch self.isString.isEmpty { case .BooleanLiteralType(true): self.emptyAlert = true default: getData.getData(price: Int((isString))) { data in self.dat = data } } } .alert(isPresented: $emptyAlert , content: { Alert(title: Text(Constants.Texts.underDollar), message: Text(Constants.Texts.again), dismissButton: .default(Text(Constants.Error.ok))) }) .buttonStyle(OvalButton()) Text("Welcome \(userName.name), enter your amount for matched games!") .font(.system(size: 15)) .fontWeight(.semibold) Spacer() }.padding(.bottom , 30) .frame(width: UIScreen.main.bounds.size.width * 0.7, height: UIScreen.main.bounds.size.height * 0.8) Spacer() ZStack { VStack { Spacer() List(dat) { data in VStack { HStack { Text(data.title!) .font(.system(size: 20)) Spacer() } HStack { NavigationLink(destination: GameDetailView(games: data)) { Text("Saled Price \(data.salePrice!)") .font(.system(size: 15)) .fontWeight(.light) Text("Normal Price \(data.normalPrice!)") .font(.system(size: 10)) .fontWeight(.medium) .foregroundColor(.red) Spacer() Text("Rating \(data.dealRating!)⭐️") .font(.system(size: 15)) .fontWeight(.regular) .foregroundColor(.green) } } } } .cornerRadius(15) } .padding(.top , 60) .frame(height: UIScreen.main.bounds.width / 1.2) VStack { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .opacity(isWorking ? 1 : 0) .foregroundColor(.black) .animation(.easeIn) Text(Constants.Texts.loading) .font(.system(size: 25)) .fontWeight(.light) .foregroundColor(.black) .opacity(isWorking ? 1 : 0) .animation(.easeIn) } .navigationBarBackButtonHidden(true) }.onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + second) { getData.getData(price: Int(isString) ) { data in self.dat = data } self.isWorking = false } } } .toolbar { ToolbarItemGroup(placement: .navigationBarTrailing) { Button(action: { print("Favorites tapped") self.isActive = true }) { Image(systemName: Constants.Style.Image.heart) .font(.system(size: 30)) .foregroundColor(Color.heart) } .background( NavigationLink( destination: FavoritesView(), isActive : $isActive) { FavoritesView() } .hidden() ) } ToolbarItemGroup(placement: .navigationBarLeading) { Button(action: { print("settings tapped") self.settingsActive = true }) { Image(systemName: Constants.Style.Image.gear) .font(.system(size: 30)) .foregroundColor(Color.gear) }.background( NavigationLink(destination: SettingsView(), isActive: $settingsActive) { SettingsView() } .hidden() ) } } } .navigationBarBackButtonHidden(true) } } struct MainView_Previews: PreviewProvider { static var previews: some View { MainView().preferredColorScheme(.light) } }
0
// // EmailManager.swift // DuckDuckGo // // Copyright © 2021 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public protocol EmailManagerStorage: AnyObject { func getUsername() -> String? func getToken() -> String? func getAlias() -> String? func getCohort() -> String? func getLastUseDate() -> String? func store(token: String, username: String, cohort: String?) func store(alias: String) func store(lastUseDate: String) func deleteAlias() func deleteAuthenticationState() // Waitlist: func getWaitlistToken() -> String? func getWaitlistTimestamp() -> Int? func getWaitlistInviteCode() -> String? func store(waitlistToken: String) func store(waitlistTimestamp: Int) func store(inviteCode: String) func deleteWaitlistState() } public enum EmailManagerPermittedAddressType { case user case generated case none } public enum EmailManagerWaitlistState { case notJoinedQueue case joinedQueue case inBeta } // swiftlint:disable identifier_name public protocol EmailManagerAliasPermissionDelegate: AnyObject { func emailManager(_ emailManager: EmailManager, didRequestPermissionToProvideAliasWithCompletion: @escaping (EmailManagerPermittedAddressType) -> Void) } // swiftlint:enable identifier_name // swiftlint:disable function_parameter_count public protocol EmailManagerRequestDelegate: AnyObject { func emailManager(_ emailManager: EmailManager, requested url: URL, method: String, headers: [String: String], parameters: [String: String]?, httpBody: Data?, timeoutInterval: TimeInterval, completion: @escaping (Data?, Error?) -> Void) } // swiftlint:enable function_parameter_count public extension Notification.Name { static let emailDidSignIn = Notification.Name("com.duckduckgo.browserServicesKit.EmailDidSignIn") static let emailDidSignOut = Notification.Name("com.duckduckgo.browserServicesKit.EmailDidSignOut") static let emailDidGenerateAlias = Notification.Name("com.duckduckgo.browserServicesKit.EmailDidGenerateAlias") } public enum AliasRequestError: Error { case noDataError case signedOut case invalidResponse case userRefused case permissionDelegateNil } public struct EmailUrls { struct Url { static let emailAlias = "https://quack.duckduckgo.com/api/email/addresses" static let joinWaitlist = "https://quack.duckduckgo.com/api/auth/waitlist/join" static let waitlistStatus = "https://quack.duckduckgo.com/api/auth/waitlist/status" static let getInviteCode = "https://quack.duckduckgo.com/api/auth/waitlist/code" } var emailAliasAPI: URL { return URL(string: Url.emailAlias)! } var joinWaitlistAPI: URL { return URL(string: Url.joinWaitlist)! } var waitlistStatusAPI: URL { return URL(string: Url.waitlistStatus)! } var getInviteCodeAPI: URL { return URL(string: Url.getInviteCode)! } public init() { } } public typealias AliasCompletion = (String?, AliasRequestError?) -> Void public typealias UsernameAndAliasCompletion = (_ username: String?, _ alias: String?, AliasRequestError?) -> Void public class EmailManager { private static let emailDomain = "duck.com" private let storage: EmailManagerStorage public weak var aliasPermissionDelegate: EmailManagerAliasPermissionDelegate? public weak var requestDelegate: EmailManagerRequestDelegate? private lazy var emailUrls = EmailUrls() private lazy var aliasAPIURL = emailUrls.emailAliasAPI private var dateFormatter = ISO8601DateFormatter() private var username: String? { storage.getUsername() } private var token: String? { storage.getToken() } private var alias: String? { storage.getAlias() } private var hasExistingInviteCode: Bool { return storage.getWaitlistInviteCode() != nil } public var cohort: String? { storage.getCohort() } public var lastUseDate: String { storage.getLastUseDate() ?? "" } public func updateLastUseDate() { let dateString = dateFormatter.string(from: Date()) storage.store(lastUseDate: dateString) } public var inviteCode: String? { storage.getWaitlistInviteCode() } public var isSignedIn: Bool { return token != nil && username != nil } public var eligibleToJoinWaitlist: Bool { return waitlistState == .notJoinedQueue } public var isInWaitlist: Bool { return waitlistState == .joinedQueue && !isSignedIn } public var waitlistState: EmailManagerWaitlistState { if storage.getWaitlistTimestamp() != nil, storage.getWaitlistInviteCode() == nil { return .joinedQueue } if storage.getWaitlistInviteCode() != nil { return .inBeta } return .notJoinedQueue } public var userEmail: String? { guard let username = username else { return nil } return username + "@" + EmailManager.emailDomain } public init(storage: EmailManagerStorage = EmailKeychainManager()) { self.storage = storage dateFormatter.formatOptions = [.withFullDate, .withDashSeparatorInDate] dateFormatter.timeZone = TimeZone(identifier: "America/New_York") // Use ET time zone } public func signOut() { storage.deleteAuthenticationState() NotificationCenter.default.post(name: .emailDidSignOut, object: self) } public func emailAddressFor(_ alias: String) -> String { return alias + "@" + Self.emailDomain } public func getAliasIfNeededAndConsume(timeoutInterval: TimeInterval = 4.0, completionHandler: @escaping AliasCompletion) { getAliasIfNeeded(timeoutInterval: timeoutInterval) { [weak self] newAlias, error in completionHandler(newAlias, error) if error == nil { self?.consumeAliasAndReplace() } } } } extension EmailManager: AutofillEmailDelegate { public func autofillUserScriptDidRequestSignedInStatus(_: AutofillUserScript) -> Bool { return isSignedIn } public func autofillUserScriptDidRequestUsernameAndAlias(_: AutofillUserScript, completionHandler: @escaping UsernameAndAliasCompletion) { getAliasIfNeeded { [weak self] alias, error in guard let alias = alias, error == nil, let self = self else { completionHandler(nil, nil, error) return } completionHandler(self.username, alias, nil) } } public func autofillUserScript(_: AutofillUserScript, didRequestAliasAndRequiresUserPermission requiresUserPermission: Bool, shouldConsumeAliasIfProvided: Bool, completionHandler: @escaping AliasCompletion) { getAliasIfNeeded { [weak self] newAlias, error in guard let newAlias = newAlias, error == nil, let self = self else { completionHandler(nil, error) return } if requiresUserPermission { guard let delegate = self.aliasPermissionDelegate else { assertionFailure("EmailUserScript requires permission to provide Alias") completionHandler(nil, .permissionDelegateNil) return } delegate.emailManager(self, didRequestPermissionToProvideAliasWithCompletion: { [weak self] permissionType in switch permissionType { case .user: if let username = self?.username { completionHandler(username, nil) } else { completionHandler(nil, .userRefused) } case .generated: completionHandler(newAlias, nil) if shouldConsumeAliasIfProvided { self?.consumeAliasAndReplace() } case .none: completionHandler(nil, .userRefused) } }) } else { completionHandler(newAlias, nil) if shouldConsumeAliasIfProvided { self.consumeAliasAndReplace() } } } } public func autofillUserScriptDidRequestRefreshAlias(_: AutofillUserScript) { self.consumeAliasAndReplace() } public func autofillUserScript(_ : AutofillUserScript, didRequestStoreToken token: String, username: String, cohort: String?) { storeToken(token, username: username, cohort: cohort) NotificationCenter.default.post(name: .emailDidSignIn, object: self) } } // MARK: - Token Management private extension EmailManager { func storeToken(_ token: String, username: String, cohort: String?) { storage.store(token: token, username: username, cohort: cohort) fetchAndStoreAlias() } } // MARK: - Alias Management private extension EmailManager { struct EmailAliasResponse: Decodable { let address: String } typealias HTTPHeaders = [String: String] var emailHeaders: HTTPHeaders { guard let token = token else { return [:] } return ["Authorization": "Bearer " + token] } func consumeAliasAndReplace() { storage.deleteAlias() fetchAndStoreAlias() } func getAliasIfNeeded(timeoutInterval: TimeInterval = 4.0, completionHandler: @escaping AliasCompletion) { if let alias = alias { completionHandler(alias, nil) return } fetchAndStoreAlias(timeoutInterval: timeoutInterval) { newAlias, error in guard let newAlias = newAlias, error == nil else { completionHandler(nil, error) return } completionHandler(newAlias, nil) } } func fetchAndStoreAlias(timeoutInterval: TimeInterval = 60.0, completionHandler: AliasCompletion? = nil) { fetchAlias(timeoutInterval: timeoutInterval) { [weak self] alias, error in guard let alias = alias, error == nil else { completionHandler?(nil, error) return } // Check we haven't signed out whilst waiting // if so we don't want to save sensitive data guard let self = self, self.isSignedIn else { completionHandler?(nil, .signedOut) return } self.storage.store(alias: alias) completionHandler?(alias, nil) } } func fetchAlias(timeoutInterval: TimeInterval = 60.0, completionHandler: AliasCompletion? = nil) { guard isSignedIn else { completionHandler?(nil, .signedOut) return } requestDelegate?.emailManager(self, requested: aliasAPIURL, method: "POST", headers: emailHeaders, parameters: [:], httpBody: nil, timeoutInterval: timeoutInterval) { data, error in guard let data = data, error == nil else { completionHandler?(nil, .noDataError) return } do { let decoder = JSONDecoder() let alias = try decoder.decode(EmailAliasResponse.self, from: data).address NotificationCenter.default.post(name: .emailDidGenerateAlias, object: self) completionHandler?(alias, nil) } catch { completionHandler?(nil, .invalidResponse) } } } } // MARK: - Waitlist Management extension EmailManager { public typealias WaitlistRequestCompletion<T> = (Result<T, WaitlistRequestError>) -> Void public typealias JoinWaitlistCompletion = WaitlistRequestCompletion<WaitlistResponse> public typealias FetchInviteCodeCompletion = WaitlistRequestCompletion<EmailInviteCodeResponse> private typealias FetchWaitlistStatusCompletion = WaitlistRequestCompletion<WaitlistStatusResponse> public struct WaitlistResponse: Decodable { let token: String let timestamp: Int } struct WaitlistStatusResponse: Decodable { let timestamp: Int } public struct EmailInviteCodeResponse: Decodable { let code: String } public enum WaitlistRequestError: Error { case noDataError case invalidResponse case codeAlreadyExists case noCodeAvailable case notOnWaitlist } public func joinWaitlist(timeoutInterval: TimeInterval = 60.0, completionHandler: JoinWaitlistCompletion? = nil) { requestDelegate?.emailManager(self, requested: emailUrls.joinWaitlistAPI, method: "POST", headers: emailHeaders, parameters: nil, httpBody: nil, timeoutInterval: timeoutInterval) { [weak self] data, error in guard let self = self else { return } guard let data = data, error == nil else { DispatchQueue.main.async { completionHandler?(.failure(.noDataError)) } return } do { let decoder = JSONDecoder() let response = try decoder.decode(WaitlistResponse.self, from: data) self.storage.store(waitlistToken: response.token) self.storage.store(waitlistTimestamp: response.timestamp) DispatchQueue.main.async { completionHandler?(.success(response)) } } catch { DispatchQueue.main.async { completionHandler?(.failure(.noDataError)) } } } } /// Fetches the invite code for users who have joined the waitlist. There are two steps required: /// /// 1. Query the waitlist status API to determine the status of the queue, which returns a timestamp /// 2. Compare the waitlist status timestamp against the locally persisted value, and status timestamp > local timestamp, then fetch the waitlist code using the saved token public func fetchInviteCodeIfAvailable(timeoutInterval: TimeInterval = 60.0, completionHandler: FetchInviteCodeCompletion? = nil) { guard storage.getWaitlistInviteCode() == nil else { completionHandler?(.failure(.codeAlreadyExists)) return } // Verify that the waitlist has already been joined before checking the status. guard storage.getWaitlistToken() != nil, let storedTimestamp = storage.getWaitlistTimestamp() else { completionHandler?(.failure(.notOnWaitlist)) return } fetchWaitlistStatus(timeoutInterval: timeoutInterval) { waitlistResult in switch waitlistResult { case .success(let statusResponse): if statusResponse.timestamp >= storedTimestamp { self.fetchInviteCode(timeoutInterval: timeoutInterval, completionHandler: completionHandler) } else { // If the user is still in the waitlist, no code is available. completionHandler?(.failure(.noCodeAvailable)) } case .failure(let error): completionHandler?(.failure(error)) } } } private func fetchWaitlistStatus(timeoutInterval: TimeInterval = 60.0, completionHandler: FetchWaitlistStatusCompletion? = nil) { guard storage.getWaitlistInviteCode() == nil else { completionHandler?(.failure(.codeAlreadyExists)) return } // Verify that the waitlist has already been joined before checking the status. guard storage.getWaitlistToken() != nil, storage.getWaitlistTimestamp() != nil else { completionHandler?(.failure(.notOnWaitlist)) return } requestDelegate?.emailManager(self, requested: emailUrls.waitlistStatusAPI, method: "GET", headers: emailHeaders, parameters: nil, httpBody: nil, timeoutInterval: timeoutInterval) { data, error in guard let data = data, error == nil else { DispatchQueue.main.async { completionHandler?(.failure(.noDataError)) } return } do { let decoder = JSONDecoder() let waitlistStatus = try decoder.decode(WaitlistStatusResponse.self, from: data) DispatchQueue.main.async { completionHandler?(.success(waitlistStatus)) } } catch { DispatchQueue.main.async { completionHandler?(.failure(.noDataError)) } } } } private func fetchInviteCode(timeoutInterval: TimeInterval = 60.0, completionHandler: FetchInviteCodeCompletion? = nil) { guard storage.getWaitlistInviteCode() == nil else { completionHandler?(.failure(.codeAlreadyExists)) return } // Verify that the waitlist has already been joined before checking the status. guard let token = storage.getWaitlistToken(), storage.getWaitlistTimestamp() != nil else { completionHandler?(.failure(.notOnWaitlist)) return } var components = URLComponents() components.queryItems = [URLQueryItem(name: "token", value: token)] let componentData = components.query?.data(using: .utf8) requestDelegate?.emailManager(self, requested: emailUrls.getInviteCodeAPI, method: "POST", headers: emailHeaders, parameters: nil, httpBody: componentData, timeoutInterval: timeoutInterval) { [weak self] data, error in guard let data = data, error == nil else { DispatchQueue.main.async { completionHandler?(.failure(.noDataError)) } return } do { let decoder = JSONDecoder() let inviteCodeResponse = try decoder.decode(EmailInviteCodeResponse.self, from: data) self?.storage.store(inviteCode: inviteCodeResponse.code) DispatchQueue.main.async { completionHandler?(.success(inviteCodeResponse)) } } catch { DispatchQueue.main.async { completionHandler?(.failure(.noDataError)) } } } } }
0
// AppDelegate.h // Copyright (c) 2017; Electric Bolt Limited. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } }
0
// // ConversationViewController-macOS.swift // Resolve // // Created by David Mitchell // Copyright © 2017 The App Studio 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 Cocoa import ResolveKit import Foundation extension ConversationViewController { // MARK: - NSViewController overrides override func viewDidAppear() { super.viewDidAppear() startConversationConnection() } } extension ConversationViewController: InputSheetViewControllerDelegate { func inputSheetViewControllerDidFinish(_ inputSheetViewController: InputSheetViewController) { if inputSheetViewController.inputText.count > 0 { settingsService.peerID = MCPeerID(displayName: inputSheetViewController.inputText) } dismiss(inputSheetViewController) startConversationConnection() } }
0
// // Formatter.swift // XCPretty // // Created by Steven Choi on 2020/2/29. // Copyright © 2020 Steven Choi. All rights reserved. // import Foundation protocol FormatterProtocol : AnyObject { func format_note(_ message: String) -> String func format_analyze(_ file_name: String, _ file_path: String) -> String func format_build_target(_ target: String, _ project: String, _ configuration: String) -> String func format_aggregate_target(_ target: String, _ project: String, _ configuration: String) -> String func format_analyze_target(_ target: String, _ project: String, _ configuration: String) -> String func format_check_dependencies() -> String func format_clean(_ project: String, _ target: String, _ configuration: String) -> String func format_clean_target(_ target: String, _ project: String, _ configuration: String) -> String func format_clean_remove() -> String func format_compile(_ file_name: String, _ file_path: String) -> String func format_compile_command(_ compiler_command: String, _ file_path: String) -> String func format_compile_storyboard(_ file_name: String, _ file_path: String) -> String func format_compile_xib(_ file_name: String, _ file_path: String) -> String func format_copy_header_file(_ source: String, _ target: String) -> String func format_copy_plist_file(_ source: String, _ target: String) -> String func format_copy_strings_file(_ file_name: String) -> String func format_cpresource(_ file: String) -> String func format_generate_dsym(_ dsym: String) -> String func format_linking(_ file: String, _ build_variant: String, _ arch: String) -> String func format_libtool(_ library: String) -> String func format_passing_test(_ suite: String, _ test: String, _ time: String) -> String func format_pending_test(_ suite: String, _ test: String) -> String func format_measuring_test(_ suite: String, _ test: String, _ time: String) -> String func format_failing_test(_ suite: String, _ test: String, _ reason: String, _ file_path: String) -> String func format_process_pch(_ file: String) -> String func format_process_pch_command(_ file_path: String) -> String func format_phase_success(_ phase_name: String) -> String func format_phase_script_execution(_ script_name: String) -> String func format_process_info_plist(_ file_name: String, _ file_path: String) -> String func format_codesign(_ file: String) -> String func format_preprocess(_ file: String) -> String func format_pbxcp(_ file: String) -> String func format_shell_command(_ command: String, _ arguments: String) -> String func format_test_run_started(_ name: String) -> String func format_test_run_finished(_ name: String, _ time: String) -> String func format_test_suite_started(_ name: String) -> String func format_test_summary(_ message: String, _ failures_per_suite: [String:[Parser.Issue]]) -> String func format_touch(_ file_path: String, _ file_name: String) -> String func format_tiffutil(_ file: String) -> String func format_write_file(_ file: String) -> String func format_write_auxiliary_files()->String func format_other(_ text: String) -> String // COMPILER / LINKER ERRORS AND WARNINGS func format_compile_error(_ file_name: String, _ file_path: String, _ reason: String, _ line: String, _ cursor: String) -> String func format_error(_ message: String) -> String func format_file_missing_error(_ error: String, _ file_path: String) -> String func format_ld_warning(_ message: String) -> String func format_undefined_symbols(_ message: String, _ symbol: String, _ reference: String) -> String func format_duplicate_symbols(_ message: String, _ file_paths: [String]) -> String func format_warning(_ message: String) -> String // TODO: see how we can unify format_error and _ format_compile_error: String // the same for warnings func format_compile_warning(_ file_name: String, _ file_path: String, _ reason: String, _ line: String, _ cursor: String) -> String func format_will_not_be_code_signed(_ message:String) -> String } public class Formatter : FormatterProtocol { static let NOTE = "🗒 " static let ASCII_NOTE = "[#] " static let ERROR = "❌ " static let ASCII_ERROR = "[x]" static let WARNING = "⚠️ " static let ASCII_WARNING = "[!]" let ansi = ANSI() var useUnicode = true var parser : Parser var error_symbol: String { self.useUnicode ? Formatter.ERROR : Formatter.ASCII_ERROR } var warning_symbol : String { self.useUnicode ? Formatter.WARNING : Formatter.ASCII_WARNING } func format_note(_ message: String) -> String { return "\(self.useUnicode ? Formatter.NOTE : Formatter.ASCII_NOTE) \(message)" } func format_error(_ message: String) -> String { return "\n\(red(error_symbol + " " + message))\n\n" } func format_compile_error(file: String, file_path: String, reason: String, line: String, cursor: String) -> String { return """ \n\(red(error_symbol + " "))\(file_path): \(red(reason))\n\n \(line)\n\(cyan(cursor))\n\n """ } func format_file_missing_error(_ reason: String, _ file_path: String) -> String { return "\n\(red(error_symbol + " " + reason)) \(file_path)\n\n" } func format_compile_warning(_ file: String, _ file_path: String, _ reason: String, line: String, cursor: String) -> String { """ \n\(yellow(warning_symbol + " "))\(file_path): \(yellow(reason))\n\n\(line)\n \(cyan(cursor))\n\n """ } func format_ld_warning(_ reason: String) -> String { "\(yellow(warning_symbol + " " + reason))" } func format_undefined_symbols(_ message: String, _ symbol: String, _ reference: String) -> String { """ \n\(red(error_symbol + " " + message))\n "> Symbol: \(symbol)\n "> Referenced from: \(reference)\n\n """ } func format_duplicate_symbols(_ message: String, _ file_paths: [String]) -> String { let formattedFilePath: String = file_paths.map { $0.split(separator:"/").last ?? $0[$0.startIndex..<$0.endIndex] }.joined(separator: "\n> ") return """ \n\(red(error_symbol + " " + message))\n > \(formattedFilePath)\n """ } func format_will_not_be_code_signed(_ message: String) -> String { "\(yellow(warning_symbol + " " + message))" } func format_other(_:String)-> String { "" } public init() { self.parser = Parser() self.parser.formatter = self } public func prettyFormat(_ text: String) -> String? { return parser.parse(text) } func format_analyze(_ file_name: String, _ file_path: String) -> String { return "" } func format_build_target(_ target: String, _ project: String, _ configuration: String) -> String { return "" } func format_aggregate_target(_ target: String, _ project: String, _ configuration: String) -> String { "" } func format_analyze_target(_ target: String, _ project: String, _ configuration: String) -> String { "" } func format_check_dependencies()->String { "" } func format_clean(_ project: String, _ target: String, _ configuration: String) -> String { "" } func format_clean_target(_ target: String, _ project: String, _ configuration: String) -> String { "" } func format_clean_remove()->String { "" } func format_compile(_ file_name: String, _ file_path: String) -> String { "" } func format_compile_command(_ compiler_command: String, _ file_path: String) -> String { "" } func format_compile_storyboard(_ file_name: String, _ file_path: String) -> String { "" } func format_compile_xib(_ file_name: String, _ file_path: String) -> String { "" } func format_copy_header_file(_ source: String, _ target: String) -> String { "" } func format_copy_plist_file(_ source: String, _ target: String) -> String { "" } func format_copy_strings_file(_ file_name: String) -> String { "" } func format_cpresource(_ file: String) -> String { "" } func format_generate_dsym(_ dsym: String) -> String { "" } func format_linking(_ file: String, _ build_variant: String, _ arch: String) -> String { "" } func format_libtool(_ library: String) -> String { "" } func format_passing_test(_ suite: String, _ test: String, _ time: String) -> String { "" } func format_pending_test(_ suite: String, _ test: String) -> String { "" } func format_measuring_test(_ suite: String, _ test: String, _ time: String) -> String { "" } func format_failing_test(_ suite: String, _ test: String, _ reason: String, _ file_path: String) -> String { "" } func format_process_pch(_ file: String) -> String { "" } func format_process_pch_command(_ file_path: String) -> String { "" } func format_phase_success(_ phase_name: String) -> String { "" } func format_phase_script_execution(_ script_name: String) -> String { "" } func format_process_info_plist(_ file_name: String, _ file_path: String) -> String { "" } func format_codesign(_ file: String) -> String { "" } func format_preprocess(_ file: String) -> String { "" } func format_pbxcp(_ file: String) -> String { "" } func format_shell_command(_ command: String, _ arguments: String) -> String { "" } func format_test_run_started(_ name: String) -> String { "" } func format_test_run_finished(_ name: String, _ time: String) -> String { "" } func format_test_suite_started(_ name: String) -> String { "" } func format_test_summary(_ message: String, _ failures_per_suite: [String: [Parser.Issue]]) -> String { "" } func format_touch(_ file_path: String, _ file_name: String) -> String { "" } func format_tiffutil(_ file: String) -> String { "" } func format_write_file(_ file: String) -> String { "" } func format_write_auxiliary_files() -> String {""} // func format_other(_ text: String) -> String { "" } // COMPILER / LINKER ERRORS AND WARNINGS func format_compile_error(_ file_name: String, _ file_path: String, _ reason: String, _ line: String, _ cursor: String) -> String { "" } // func format_error(_ message: String) -> String { "" } // func format_file_missing_error(_ error: String, _ file_path: String) -> String { "" } // func format_ld_warning(_ message: String) -> String { "" } // func format_undefined_symbols(_ message: String, _ symbol: String, _ reference: String) -> String { "" } // func format_duplicate_symbols(_ message: String, _ file_paths: [String]) -> String { "" } func format_warning(_ message: String) -> String { message; } // TODO: see how we can unify format_error and _ format_compile_error: String // the same for warnings func format_compile_warning(_ file_name: String, _ file_path: String, _ reason: String, _ line: String, _ cursor: String) -> String { "" } } extension Formatter { var red:(String)-> String { get{ ansi.red } } var cyan:(String)-> String { get{ ansi.cyan } } var yellow:(String)-> String { get{ ansi.yellow } } var green:(String)-> String { get {ansi.green }} var white:(String)-> String { get{ ansi.white } } // var red:(String)-> String { get{ ansi.red } } }
0
// // XMLPrettier.swift // SourcefulPrettier // // Created by Raghav Ahuja on 11/12/20. // import Foundation import JavaScriptCore public final class XMLPrettier { private var vkBeautifier: JSValue? public init() { let jsContext = JSContext()! let window = JSValue(newObjectIn: jsContext) jsContext.setObject(window, forKeyedSubscript: "window" as NSString) do { if let vkBeautifierPath = Bundle.module.path(forResource: "vkbeautify", ofType: "js") { let vkBeautifierJs = try String(contentsOfFile: vkBeautifierPath) let vkValue = jsContext.evaluateScript(vkBeautifierJs) if vkValue?.toBool() == true, let vkBeautifierJS = window?.objectForKeyedSubscript("vkbeautify") { vkBeautifier = vkBeautifierJS } else { vkBeautifier = nil } } else { vkBeautifier = nil } } catch let error as NSError { print(error) vkBeautifier = nil } } public func prettify(_ code: String) -> String? { #if os(macOS) do { let doc = try XMLDocument(xmlString: code) try doc.validate() let data = doc.xmlData(options: .nodePrettyPrint) let xmlPretty = String(data: data, encoding: .utf8) return xmlPretty } catch { print(error as NSError) return nil } #else guard let result = vkBeautifier?.invokeMethod("xml", withArguments: [code])?.toString(), result != "undefined" else { return nil } return result #endif } }
0
// // ViewController.swift // MetalSquare // // Created by Hanson on 16/6/2. // Copyright © 2016年 Hanson. All rights reserved. // import UIKit import simd // 旋转矩阵 struct Uniforms { var rotation_matrix: matrix_float4x4 } class ViewController: UIViewController { // 设置metal var device: MTLDevice! = nil var metalLayer: CAMetalLayer! = nil var pipelineState: MTLRenderPipelineState! = nil var vertexBuffer: MTLBuffer! = nil var commandQueue: MTLCommandQueue! = nil // 渲染图形 var timer: CADisplayLink! = nil // 用于旋转辅助变量 var uniformBuffer: MTLBuffer! = nil // 旋转矩阵缓冲区 var uniforms: Uniforms! // 旋转矩阵 var rotationAngle: Float = 0.0 // 旋转角度 // 数据源[x,y,z,w, r,g,b,a] //前四个数字代表了每一个顶点的 x,y,z 和 w 元素。后四个数字代表每个顶点的红色,绿色,蓝色和透明值元素。 //第四个顶点位置元素,w,是一个数学上的便利,使我们能以一种统一的方式描述 3D 转换 (旋转,平移,缩放 let vertexData: [Float] = [ 0.5, -0.5, 0.0,1.0, 1.0, 0.0, 0.0, 1.0, -0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, -0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.5, 0.5, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.5, -0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, -0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, ] override func viewDidLoad() { super.viewDidLoad() // 初始化Metal setupMetal() // 渲染图形 displayContent() } /************************** 七步设置Metal ****************************/ // MARK: - 七步设置Metal private func setupMetal() { // 1.0 创建一个MTLDevice device = MTLCreateSystemDefaultDevice() // 1.1 创建一个CAMetalLayer metalLayer = CAMetalLayer() metalLayer.device = device metalLayer.pixelFormat = .BGRA8Unorm metalLayer.framebufferOnly = true metalLayer.frame = view.layer.frame view.layer.addSublayer(metalLayer) // 1.2 创建一个Vertex Buffer let dataSize = vertexData.count * sizeofValue(vertexData[0]) vertexBuffer = device.newBufferWithBytes(vertexData, length: dataSize, options: MTLResourceOptions.OptionCPUCacheModeDefault) // 旋转缓冲区内容时刻变化,这里通过长度创建 uniformBuffer = device.newBufferWithLength(sizeof(Uniforms), options: MTLResourceOptions.OptionCPUCacheModeDefault) let defaultLibrary = device.newDefaultLibrary() // 1.3 创建一个Vertex Shader let vertexProgram = defaultLibrary?.newFunctionWithName("basic_vertex") // 1.4 创建一个Fragment Shader let fragmentProgram = defaultLibrary?.newFunctionWithName("basic_fragment") // 1.5 创建一个Render Pipeline let pipelineStateDescriptor = MTLRenderPipelineDescriptor() pipelineStateDescriptor.vertexFunction = vertexProgram pipelineStateDescriptor.fragmentFunction = fragmentProgram pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm pipelineState = try! device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor) // 1.6 创建一个Command Queue commandQueue = device.newCommandQueue() } /************************** 五步完成渲染 ****************************/ // MARK: - 五步完成渲染 private func displayContent() { // 2.0 创建一个Display link timer = CADisplayLink(target: self, selector: #selector(ViewController.gameloop)) timer.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) } func render() { let drawable = metalLayer.nextDrawable() // 2.1 创建一个Render Pass Descriptor let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = drawable?.texture renderPassDescriptor.colorAttachments[0].loadAction = .Clear renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 104.0/255.0, blue: 5.0/255.0, alpha: 1.0) renderPassDescriptor.colorAttachments[0].storeAction = .Store // 2.2 创建一个Command Buffer let commandBuffer = commandQueue.commandBuffer() // 2.3 创建一个Render Command Encoder let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor) renderEncoder.setRenderPipelineState(pipelineState) // 将vertexBuffer添加到第0个缓冲区(等下metal着色器要取出值) renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0) // 将uniformBuffer添加到第1个缓冲区(等下metal着色器要取出值) renderEncoder.setVertexBuffer(uniformBuffer, offset: 0, atIndex: 1) renderEncoder.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: 6) renderEncoder.endEncoding() // 2.4 提交你Command Buffer的内容 commandBuffer.presentDrawable(drawable!) commandBuffer.commit() } // MARK: - 其他 // 循环执行 func gameloop() { autoreleasepool { update() render() } } // 将图层改为正方形 override func viewDidLayoutSubviews() { let parentSize = view.bounds.size let minSize = min(parentSize.width,parentSize.height) let frame = CGRectMake((parentSize.width - minSize) * 0.5, (parentSize.height - minSize) * 0.5, minSize, minSize) metalLayer.frame = frame } } // 旋转相关--修改缓冲区(需要修改着色器的顶点) extension ViewController { /************************** 旋转相关 ****************************/ // MARK: - 设置旋转矩阵 func update() { // 创建旋转矩阵 uniforms = Uniforms(rotation_matrix: rotation_matrix_2d(rotationAngle)) // 获取旋转缓冲区 let bufferPointer = uniformBuffer.contents() // 将旋转矩阵拷贝到旋转缓冲区 memcpy(bufferPointer, &uniforms, sizeof(Uniforms)) // 变换角度 rotationAngle += 0.01 } // 旋转矩阵计算 func rotation_matrix_2d(radians: Float) -> matrix_float4x4 { let cos = cosf(radians) let sin = sinf(radians) let columns0 = vector_float4([ cos, sin, 0, 0]) let columns1 = vector_float4([-sin, cos, 0, 0]) let columns2 = vector_float4([ 0, 0, 1, 0]) let columns3 = vector_float4([ 0, 0, 0, 1]) return matrix_float4x4(columns: (columns0, columns1, columns2, columns3)) } }
0
// // ViewController.swift // SoundSampler // // Created by 工藤征生 on 2016/03/26. // Copyright © 2016年 Aquaware. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let url = NSBundle.mainBundle().URLForResource("M1F1int16", withExtension: "aif")! let resource = SoundSampler(url: url) let size = resource.data.length / sizeof(Int16) var data: [Int16] = [Int16](count: size, repeatedValue: 0) resource.data.getBytes(&data, length: resource.data.length) for var i = 1000; i < 1100; i++ { print("\(data[i]) ") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
0
// // DetailViewController.swift // PNChartSwift // // Created by YiChen Zhou on 8/14/17. // import UIKit class DetailViewController: UIViewController { var chartName: String? override func viewDidLoad() { super.viewDidLoad() guard let _chartName = self.chartName else { print("Invalid Chart Name") return } self.title = _chartName switch _chartName { case "Pie Chart": let pieChart = self.setPieChart() self.view.addSubview(pieChart) case "Bar Chart": let barChart = self.setBarChart() self.view.addSubview(barChart) case "Line Chart": let lineChart = self.setLineChart() self.view.addSubview(lineChart) default: break } } // override func viewWillAppear(_ animated: Bool) { // for view in self.view.subviews { // view.removeFromSuperview() // } // } private func setPieChart() -> PNPieChart { let item1 = PNPieChartDataItem(dateValue: 20, dateColor: PNLightGreen, description: "Build") let item2 = PNPieChartDataItem(dateValue: 20, dateColor: PNFreshGreen, description: "I/O") let item3 = PNPieChartDataItem(dateValue: 45, dateColor: PNDeepGreen, description: "WWDC") let frame = CGRect(x: 40, y: 155, width: 240, height: 240) let items: [PNPieChartDataItem] = [item1, item2, item3] let pieChart = PNPieChart(frame: frame, items: items) pieChart.descriptionTextColor = UIColor.white pieChart.descriptionTextFont = UIFont(name: "Avenir-Medium", size: 14)! pieChart.center = self.view.center return pieChart } private func setBarChart() -> PNBarChart { let barChart = PNBarChart(frame: CGRect(x: 0, y: 135, width: 320, height: 200)) barChart.backgroundColor = UIColor.clear barChart.animationType = .Waterfall barChart.labelMarginTop = 5.0 barChart.xLabels = ["Sep 1", "Sep 2", "Sep 3", "Sep 4", "Sep 5", "Sep 6", "Sep 7"] barChart.yValues = [1, 23, 12, 18, 30, 12, 21] barChart.strokeChart() barChart.center = self.view.center return barChart } private func setLineChart() -> PNLineChart { let lineChart = PNLineChart(frame: CGRect(x: 0, y: 135, width: 320, height: 250)) lineChart.yLabelFormat = "%1.1f" lineChart.showLabel = true lineChart.backgroundColor = UIColor.clear lineChart.xLabels = ["Sep 1", "Sep 2", "Sep 3", "Sep 4", "Sep 5", "Sep 6", "Sep 7"] lineChart.showCoordinateAxis = true lineChart.center = self.view.center let dataArr = [60.1, 160.1, 126.4, 232.2, 186.2, 127.2, 176.2] let data = PNLineChartData() data.color = PNGreen data.itemCount = dataArr.count data.inflexPointStyle = .None data.getData = ({ (index: Int) -> PNLineChartDataItem in let yValue = CGFloat(dataArr[index]) let item = PNLineChartDataItem(y: yValue) return item }) lineChart.chartData = [data] lineChart.strokeChart() return lineChart } }
0
// // TableViewController.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // 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 class TableViewController : UIViewController { var tableViewStyle: UITableViewStyle var tableView: UITableView! init(style: UITableViewStyle) { self.tableViewStyle = style super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { self.tableViewStyle = .Plain super.init(coder: aDecoder) } deinit { tableView.delegate = nil tableView.dataSource = nil NSNotificationCenter.defaultCenter().removeObserver(self) } func registerForKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver( self, selector: "keyboardDidShowNotification:", name: UIKeyboardDidShowNotification, object: nil ) NSNotificationCenter.defaultCenter().addObserver( self, selector: "keyboardWillHideNotification:", name: UIKeyboardWillHideNotification, object: nil ) } func keyboardDidShowNotification(notification: NSNotification) { let userInfo = notification.userInfo ?? [:] if let rectValue = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue { let keyboardSize = rectValue.CGRectValue().size var contentInset = tableView.contentInset contentInset.bottom = keyboardSize.height tableView.contentInset = contentInset tableView.scrollIndicatorInsets = contentInset } } func keyboardWillHideNotification(notification: NSNotification) { var contentInset = tableView.contentInset contentInset.bottom = 0.0 tableView.contentInset = contentInset tableView.scrollIndicatorInsets = contentInset } override func loadView() { tableView = UITableView(frame: CGRect.zero, style: tableViewStyle) view = tableView } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self registerForKeyboardNotifications() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let selectedIndexPath = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(selectedIndexPath, animated: true) } } } extension TableViewController : UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } } extension TableViewController : UITableViewDelegate { }
0
// // Bonefile.swift // MurrayKit // // Created by Stefano Mondino on 04/01/2019. // import Foundation import Files class BoneFile { let contents: String var repositories: [Repository] = [] init(fileContents: String) { self.contents = fileContents repositories = parseRepositories() } init (repositories: [Repository]) { self.contents = "" self.repositories = Array(Set(repositories)) } private func parseRepositories() -> [Repository] { let set = Set( self.contents.components(separatedBy: "\n") .map {$0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)} .filter { $0.count > 0} .compactMap { string -> String? in let strings = string.components(separatedBy: " ") guard let command = strings.first, strings.count == 2, command == "bone" else { return nil } return strings.last?.replacingOccurrences(of: "\"", with: "") } .compactMap { $0 } // .map { try Part(string: $0) } ) return set.map { Repository(package: $0)} } }
0
// // ReplaceWindowContentSegue.swift // CustomSegue /* The MIT License (MIT) Copyright (c) 2016 Eric Marchand (phimage) 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 Cocoa // Replace contentViewController of sourceController parent NSWindow by destinationController open class ReplaceWindowContentSegue: NSStoryboardSegue { open var copyFrame = false open override func perform() { guard let fromController = self.sourceController as? NSViewController, let toController = self.destinationController as? NSViewController, let window = fromController.view.window else { return } if copyFrame { toController.view.frame = fromController.view.frame } window.contentViewController = toController } // In prepareForSegue of sourceController, store this segue into destinationController // Then you can call this method to dismiss the destinationController open func unperform() { guard let fromController = self.sourceController as? NSViewController, let toController = self.destinationController as? NSViewController, let window = toController.view.window else { return } if copyFrame { fromController.view.frame = toController.view.frame } window.contentViewController = fromController } }